I’m touching up a game engine I wrote in Java a while back. I have a master Arraylist that holds Sprite objects. The Sprite class holds an X and Y location of the specified sprite by the type float.
I’m trying to sort the list based on their relative distance to a specific sprite (the player). I have a method that calculates the distance between 2 sprites.
/**Retrieve a double value that represents the distance between 2 sprites*/
public static double getSpriteDistance(Sprite s1, Sprite s2) {
return Math.hypot((s1.getX() - s2.getX()), (s1.getY() - s2.getY()));
}
I have another method that I pass the Sprite used to sort based on its position as well as the master list of all the sprites (will be about 500-700 Sprites on the list depending on the map)
/**Sort a Sprite list relatively based on a specific sprite's location*/
public static ArrayList<Sprite> relativeSort(Sprite s1, ArrayList<Sprite> list) {
//Sort
return list;
}
This is where I generally get stuck as far as how to do it, and looking into the future as far as efficiency and speed. I have a method to measure the distance between 2 sprites, now I just need the to sort the list so the specific sprite to be sorted is the first item on the list, and the sprite that’s the farthest away is the last.
I’ve thought of a using a recursive method to sort, or a while loop, but I feel as if there are better ways. I read about using Comparators and Collection’s sort() method. But the examples i’ve seen are very basic.
Thanks for any help, if you have any questions you need answered to better assist me, i’ll be glad to answer them.
EDIT:
I have a feeling someone will link this to me, so I’ll just clarify that I know about it, but have trouble understanding how to implement what I specified above using this:
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
You’ll need to create a
Comparatorthat follows this signature:The method
compareshould return a positive number ifobj1is to be sorted first in the list, and a negative number otherwise.Then you can pass it into
Collections.sort().You can create a class on-the-fly like that pretty easily, actually: