Using operators with vectors (?)

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

Hello,

I’m sorry I have to ask for this (which is probably stupid) but I really cant figure out how to fix that right now.
I have a variable which stores a position in a Vector2(). Now I want to check if this position is equal to some Vectors I’m defining in an if-statement.

if position == Vector2(254, 320)
   print "is there"

This works fine. However, I want to write multiple possible Vectors in there, but as soon as I write two or more, he prints “is there” every time, even if the Vector2/position doesnt fit, and I’m assuming it’s got to do with the operators.

if position == Vector2(254,105) or Vector2(390, 216):
   print "is there"

Like this for example. I’m probably missing something obvious, but idk what it is. Could someone please help? (Also I dont know if Vector-Arrays are possible, and if so, with which format, so I’m stuck at this right now since I dont want to write an if-statement for every single vector I need)

:bust_in_silhouette: Reply From: kidscancode

Your problem is order of operations. The == is evaluated first so it’s as if you wrote:

if (position == Vector2(254,105)) or Vector2(390, 216):

To check both vectors for equality with position you would need to write:

if position == Vector2(254,105) or position == Vector2(390, 216):

You can use arrays of vectors:

var position_list = [Vector2(254,105), Vector2(390, 216)]
if position in position_list:
    print("is there")

However, you’re going to run into a problem when comparing equality of floating point numbers. Your position may be (254.0231, 105.00035) or some other non-integer value. You can use floor() to solve that:

var position_list = [Vector2(254,105), Vector2(390, 216)]
if position.floor() in position_list:
    print("is there")

I won’t have floats as I’m creating exact Vectors which aren’t going to change, so that wouldn’t be a problem, but thanks a lot, the other stuff should fix it. (And while I’m at it, thanks for your tutorials too, they’re helpful!)

Cherep | 2018-10-27 15:43