Let's just say that you have a collection (Set, List, whatever) of GameObject:
Collection<GameObject> gameObjects = ...;
You also have, somewhere, a method used to compute the distance of one GameObject to the player. I'll assume it returns an int:
public int computeDistanceToPlayer(GameObject gameObject) {
...
}
You want to sort these GameObjects by their distance to the player, in order to get the nth closer object. The easiest way to do that is to sort the objects. For example:
List<GameObject> sortedGameObjects =
gameObjects.stream()
.sorted(Comparator.comparingInt(gameObject -> computeDistanceToPlayer(gameObject)))
.collect(Collectors.toList());
You can then get the nth element from that list.
You can even get the nth element from the stream directly:
GameObject nthCloserGameObject =
gameObjects.stream()
.sorted(Comparator.comparingInt(gameObject -> computeDistanceToPlayer(gameObject)))
.skip(n - 1)
.findFirst()
.orElse(null);
That is all you need, but, if the distance computation is costly (requires a long, costly computation), then it's not really optimal because it computes the distance of the same GameObject several times: each time it's compared to another GameObject during the sorting. So, if you want to avoid that, you can just compute all the distances first and associate them with the GameObjects, and then sort the resulting results:
public class GameObjectWithDistance {
private final GameObject gameObject;
private final int distance;
// constructor, getters omitted for brevity
}
Now you just need to wrap every GameObject inside a GameObjectWithDistance, and sort the result:
GameObject nthCloserGameObject =
gameObjects.stream()
.map(gameObject -> new GameObjectWithDistance(gameObject, computeDistanceToPlayer(gameObject)))
.sorted(Comparator.comparingInt(GameObjectWithDistance::getDistance))
.skip(n - 1)
.findFirst()
.map(GameObjectWithDistance::getGameObject)
.orElse(null);
Now, if you're unfamiliar with streams and lambdas, you can do that with loops, lists and a comparator class, it doesn't matter. What matters is the logic, and the realization that you don't need any 2D list of anything like that.