Comparing Vectors

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

For example,

print(Vector2(5,6)>Vector2(1,56))

Prints True

According to vector2.h it’s correct,

bool operator<(const Vector2 &p_vec2) const { return (x == p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); }

But I think it should be like this,

bool operator<(const Vector2 &p_vec2) const { return (x < p_vec2.x) && (y < p_vec2.y) ); }

I also found this issue in GitHub #9284 and is closed. There are 2 comments describing the the issue but I can’t understand it. Can anyone explain it in detail?

:bust_in_silhouette: Reply From: xPheRe

Vectors can be used as keys in dictionaries, so the following is valid code:

var grid = {}
var direction = Vector2(0.0, 0.0)
grid[direction] = 1.0

To allow this, keys must fulfill some conditions, one of them is that if a > b == true then b > a == false (also if a >= b and b >= a then a == b)

With your suggestion, two vectors like (2, 3) and (3, 2) would return false when compared, no matter in what order you do.

Hope this helps a bit.

You mean (2, 3) < (3, 2) and (3, 2) < (2, 3) both returns false?

Afsar Pasha | 2018-09-27 18:32

:bust_in_silhouette: Reply From: MysteryGM

The example you give is True, because a vector isn’t just a size, it is also a direction.

Instead if you want to compare only the size use:

print(Vector2(5,6).length() > Vector2(1,56).length())

To compare direction use dot product.