I am making a game where I can spawn soldiers with a button click. All of these soldiers will be added in an ArrayList named entity_walking_right_array
. I also have another ArrayList for the entities which are walking left.
I have another class where the x, y position, the animation etc. of the soldier is determined or drawn. All soldiers have a random Y value between the screen height and 450 pixels.
When I spawn the soldiers some of them will logically have a higher y value or y position than others but when those are created later, than soldiers with a lower y value, they will be rendered above them. That leads to soldiers being rendered above soldiers when they logically would be behind them. (For example the feets are in the face of the lower y value soldier)
I then render the soldiers like that:
for (entity_walking_right blue : entity_walking_right_array) {
blue.render(game.batch);
}
I figured out that when I use the y value of those soldiers ( entity_walking_right.getY();
is a float) to sort the ArrayList then they should be rendered in the right order. At least I am hoping that is the right way to do it.
I have already tried using entity_walking_right_array,sort(...)
, Collections.sort
or some of those Lambda
functions which are completely new to me. I've also tried using compareTo
(I unfortionatly cannot find the question anymore) but it gave me an error which basically said that compareTo
just does not exist as a function.
Any code that I've found did not really help me and I am trying to get this problem solved for 2 days now which is the reason why I am writing the question.
Edit:
I have found the question.
Sort ArrayList of custom Objects by property
When I try to use
Collections.sort(entity_walking_right_array,
(o1, o2) -> o1.getY().compareTo(o2.getY()));
it simply says "Cannot resolve method 'compareTo(float)'.