#Getting the nearest Vector2 point

5 messages · Page 1 of 1 (latest)

dusky vigil
#

Hello! If I have a value like Vector2(4,4) and I want to check it against an array of Vector2s (see something like: [Vector2(3,3), Vector2(6,7), Vector2(9,2)]) - would assume it would return Vector2(3,3)

Is there a method for something like this? Example:

var vectors = [Vector2(3,3), Vector2(6,7), Vector2(9,2)]

get_nearest_vector(Vector(3,3), vectors)

Context: I am using this to move an enemy closer to the player based on Nathan’s wonderful tactical RPG movement series 😍😀😉

hidden axle
#

I won't claim this is the best solution for what you are trying to achieve but when I was faced with a similar task I did this.

There is a built in Godot method called distance_to(Vector2, to) which returns a float for the distance.

So I ran a loop over each of the vectors I wanted to calculate the distance to and then stored the shortest value. After the loop finished I had the closest Vector2 from the array of Vector2s

#

This is the method from the Godot 4 documentation but I think it's called the same in Godot 3.x if you are using those versions

dusky vigil
#

Thank you so much @hidden axle I had a very similar thought since you cannot directly compare Vector2s in gdscript. So this basically achieves a similar result, but instead comparing the float that is returned from distance_to. Fantastic!