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

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) {

In the image below, green circle is the observer while the red circle is the observables.

enter image description here


1 Answer 1


If you are precomputing this sorted array once only, then this is perfectly fine (even doing an actual distance calculation with square roots is probably ok in that case).

If your entities are moving around and you have to resort this array every frame then you will probably want to implement an acceleration structure of some sort, like a Quadtree in order to get away with only sorting a subset of all your entities.

Without knowing more detail about your intended use case its hard to provide any more specific advice.

  • \$\begingroup\$ you're right, the entities are moving and need to be sort every sec. \$\endgroup\$
    – ronscript
    Commented Sep 27, 2016 at 7:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .