How to fix error (Invalid operands 'Vector2' and 'int' in operator '==')

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zorua98741

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?

:bust_in_silhouette: Reply From: kidscancode

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:
  1. 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).