Firstly, I apologise if this belongs in gamedev and not here, secondly, Im still learning java so sorry if the answer is very simple or if I'm not going about it the right way.
I'm making a game using the slick2d framework, with help from people on here I've managed to put all of my characters into to an array, sort this array based on Y axis value, and draw them in that order, to create the illusion of a zaxis. Now though, I want to add a new sorting algorithm so that after it sorts normally, it pushes any dead characters to the bottom of the array, for gameplay reason.
I've made an algorithm that looks like it should work to me, but what actually happens is that when a character dies it just totally removes one random character from the screen, no crash, no null pointer exception, one character just stops rendering, though the rest of gameplay works fine, their actions and movements still work as if they're not invisible.
I've stared at this code for so long that I can't seem to see whats wrong with it, help would be very much appreciated.
If necessary I can post my original sorting algorithm or the code that draws the sorted array, but I don't think the fault is there, they've always worked fine.
//this is what I have
Creature temp = null;
for(int i=0; i<drawArray.length; i++) {
if(drawArray[i].isDead){
temp = drawArray[0];
drawArray[0] = drawArray[i];
int k = i
for(int j=0; j < (i-1); j++){
drawArray[k-1] = drawArray[k];
k -=1;
}
drawArray[1] = temp;
}
}
First you need to get the index of the dead guy:
int indexOfDeadGuy = -1;
for (int i=0; i<drawArray.length; i++) {
if (drawArray[i].isDead) {
indexOfDeadGuy = i;
break;
}
}
Then you need to move everyone below that up one position so you can put that guy at the bottom:
if (indexOfDeadGuy > -1) {
Creature deadGuy = drawArray[indexOfDeadGuy];
for (int i = indexOfDeadGuy; i > 0; i--) {
drawArray[i] = drawArray[i - 1];
}
drawArray[0] = deadGuy;
}
Edit: If you needed to handle when more than one creature is dead, you need to rethink the approach. One way to do it is to copy the array (in this case into a List), then repopulate the original array in two passes:
// first, copy the array (in this case into a list)
List<Creature> tempList = new ArrayList<>(Arrays.asList(drawArray));
// the index of the next position in the array to insert a creature
int targetIndex = 0;
// fill the array with dead things
for (Creature creature : tempList) {
if (creature.isDead) {
drawArray[targetIndex] = creature;
targetIndex++;
}
}
// continue filling the array with non-dead things
for (Creature creature : tempList) {
if (!creature.isDead) {
drawArray[targetIndex] = creature;
targetIndex++;
}
}
This will stack all the dead creatures at the start of the list and all the non-dead creatures after that in their same relative order.