Skip to content
Advertisement

Java – How to dynamically sort an Arraylist of objects based on distance from player

I’m building a small game in java where i have an Arraylist of Zombie objects that is used to select the next target for the player. The zombies are comprised of an x and y variable which dictates their initial position.

JavaScript

I have written this method which selects the next zombie in the array in which the player automatically targets, but I’m stuck trying to figure out how to dynamically sort the Arraylist so the player targets the closest zombie by distance, rather than the one next in the list.

JavaScript

tl:dr I want to dynamically sort an Arraylist of zombies by shortest distance to the player.

Advertisement

Answer

Here I would use a custom ZombieSort class, which implements Comparator, that sorts the Zombies by comparing their distance from the player’s coordinates.

Here is ZombieSort.java

JavaScript

And here would be your implementation for zombieSpawn(), which basically sorts the list of Zombies every time it is called.:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement