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.
public Zombie(double positionX, double positionY){ this.image = new Image("res/images/zombie.png"); this.Position = new Point(positionX, positionY); this.visible = true; }
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.
public void zombieSpawn(){ for(int i = 0; i < zombies.size(); i++){ zombie = zombies.get(i); if(!zombie.isVisible()){ removeZombie(zombie); } if(zombies.size() != 0){ this.zombie = zombies.get(0); } } }
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
public class ZombieSort implements Comparator<Zombie> { private final double playerX, playerY; public ZombieSort(double playerX, double playerY) { this.playerX = playerX; this.playerY = playerY; } @Override public int compare(Zombie z1, Zombie z2) { return Double.compare(getDistance(z1), getDistance(z2)); } public double getDistance(Zombie zombie) { return Math.sqrt( Math.pow(zombie.x - playerX, 2) + Math.pow(zombie.y - playerY, 2) ); } }
And here would be your implementation for zombieSpawn(), which basically sorts the list of Zombies every time it is called.:
public void zombieSpawn(){ sortZombies(zombies, player); for(int i = 0; i < zombies.size(); i++){ zombie = zombies.get(i); if(!zombie.isVisible()){ removeZombie(zombie); } if(zombies.size() != 0){ this.zombie = zombies.get(0); } } } public void sortZombies(List<Zombie> zombies, Player player) { Collections.sort(zombies, new ZombieSort(player.getX(), player.getY())); }