0 votes

I'm writing a function to test the position of a kinematicbody2d (which has a sprite attached) and execute another line of code if it is at x270 (y does not change from 0).
The code goes as follows:

func _process(delta) :
     var pos = get_global_position()
     if pos == 270:

And gives the error in the title (Invalid operands 'Vector2' and 'int' in operator '==')
I assume this is because "pos" contains 2 numbers, the x and y coordinate, but I'm only testing for x. How can I remove the y coordinate from "pos" or otherwise test for x270 and y0?

asked Jul 22 in Engine by zorua98741 (15 points)

1 Answer

+2 votes
Best answer

The error is because you can't compare a vector and a number. You can access the individual components of a vector with .x and .y, for example:

if pos.x >= 270

A couple of other points to consider:

1) You don't need to fetch the position into its own variable. It's already a property:

if global_position.x >= 270:

2) A Vector2's components are floats, not ints. You should never compare floats using == because of imprecision (ie, the value may be 270.00001 or 269.997).

answered Jul 22 by kidscancode (12,138 points)
selected Jul 22 by zorua98741
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.