Finding the distance from entity A to entity B is often useful. Sometimes options could be available only within a certain distance, or only outside a certain distance. Calculating the distance from point a to point b is easy. The method below shows how.

public static double getDistance(double x1, double y1, double x2, double y2)
{
return Math.sqrt( ( (x2-x1)*(x2-x1) ) + ( (y2-y1)*(y2-y1) ) );
}

The method finds the distance between the point (x1,y1) -> (x2,y2).

Now, sometimes you are not really interested in the distance itself. Sometimes, the relationship between several distances is more interesting. Let’s say you want to look at a group of entities, and you want to find the entity with the shortest distance from a source point. In this case, the method above is unneccessary slow. Math.sqrt() is not a particularely efficient method, so leaving it out would be good. And we can. Since we’re not interested in the real distance values (only the relationship between distances), we can use the following method:

public static double getUnsquaredDistance(double x1, double y1, double x2, double y2)
{
return ( (x2-x1)*(x2-x1) ) + ( (y2-y1)*(y2-y1) );
}

if getDistance(a,b) > getDistance(a,c) then the same holds true for getUnsquaredDistance. a,b will be larger than a,c.

With this method, we can more efficiently compare distances. If used in combination with what I wrote in the previous post, we can design a way to find entities efficiently.

We’re currently adding weapons that should fire some kind of “heat-seeking” bullets. These bullets should lock on to the closest enemy entity. To achieve this, we iterate over our collection of entities (either filtered on a category, or not), calculate the distance(relative) to each entity by using the method defined above, and return the entity with the lowest distance.