# Find object nearest to a point

Is there a simple way to find the nearest object of a given type to a point (eg the mouse)?
Even more useful would be a simple way to step through the objects in order of distance from the point, one after another.

In this case the player has several bases and I want the closest to the target cursor to shoot, rather than all of them or a random one.
Unless that one has just fired in which case the next closest will fire, etc.

One solution would be too do a loop on the objects :

[code]Conditions : None
Actions: Do =99999 to variable “Nearest”

For each objects “Base”
Conditions : Distance between Base and Target is < Variable(Nearest)
Actions : Do =Base.Distance(Target) to variable “Nearest”.

Conditions : Distance between Base and Target = Variable(Nearest)
Actions: Do what you want with the Base[/code]

That nearly works but I needed to modify the last clause to:

Conditions :
AND
Distance between Base and Target >= Variable(Nearest)-1
Distance between Base and Target <= Variable(Nearest)+1

Actions: Do what you want with the Base

It looks like the distance condition returns a slightly different value to the distance action.

I’ve checked the code, in fact the distance condition is comparing the square of the distance against the square of the length indicated ( so as to avoid computing the square root of the distance ). Mathematically, the result should be the same, but in computer science and its floating point number representation, the numbers can be slighty different, so that is why you’ve to use an extra condition as you did.