I have created a comparator class called DistanceSquaredComparator
and implements it with Comparator<Entity>
. Then in the override compare method, I get the distance square of each nearby position to owner position, then get the signum int value to return. Now the problem is I don't know if this is the efficient way of sorting the array by nearest distance.
Entity owner
@Override
public int compare(Entity o1, Entity o2) {
Vector2 ownerPosition = Mapper.transform.get(owner);
Vector2 nearby1 = Mapper.transform.get(o1).position;
Vector2 nearby2 = Mapper.transform.get(o2).position;
return (int) Math.signum(nearby2.dst2(ownerPosition) - nearby1.dst2(ownerPosition));
}
// usage
DistanceSquaredComparator comparator = new DistanceSquredComparator();
ImmutableArray<Entity> players = ...
ImmutableArray<Entity> enemies = ...
Array<Entity> sortedEnemies = ...
... // fill sortedEnemies
for(Entity player: players) {
comparator.setOwner(player);
sortedEnemies.sort(comparator);
}
In the image below, green circle is the observer while the red circle is the observables.