I’m making a top down game and needed a way to render objects in the correct order based on their y-axis position. After a day of trying to hard code it, I ended up using Collections.sort() and it works perfectly, but I don’t understand why it does. The docs say it sorts by “natural ordering”, but I don’t understand what that actually is. Here is the code:
public static void sortAndRenderObjectsInYPositionOrder(
ArrayList<GameObject> gameObjectList,
SpriteBatch batch,
ShapeRenderer shapeRenderer,
ImageLoader imageLoader
) {
Collections.sort(gameObjectList);
for (int i = 0; i < gameObjectList.size(); i++) {
if (playerPositionIsWithinBoundsToRenderGameObjects(
gameObjectList.get(0).getX(),
gameObjectList.get(0).getY(),
gameObjectList.get(i).getX(),
gameObjectList.get(i).getY(),
gameObjectList.get(i).getHeight(),
gameObjectList.get(i).getWidth()
)) {
gameObjectList.get(i).renderObject(batch, shapeRenderer, imageLoader);
}
}
}
My question is, how is the gameObjectList actually being sorted, and since each object has an x, y, width, and height, how is it seemingly sorting by the y-position of the objects without my specifying to sort that way?