Friday, December 13, 2019

java - How can I remove enemies from my ArrayList after they have died?




Possible Duplicate:

How do I best remove an entity from my game loop when it is dead?



Right now, I have an ArrayList like this:


List enemies = new ArrayList();

When an enemy dies, how can I remove it? Should I use a different type of list, array, or set?



Answer



Please, don't use a set, you don't need it. There's a simple trick that can help improve @Jake-Woods' answer.


From my experience, if you keep a lot of enemies (or other entities) in an array, you don't really care about the order in the array. The trick is, it's possible to remove an object from an array with a small and constant amount of operations (O(1)), if you allow for the order to change. The algorithm is as follows:




  • Iterate over the entities in your array

    • If you find an item that needs to be removed

      • Swap it with the last element

      • Remove the last element from the array







It's quite easy to write, but takes some work to understand that this works properly for corner cases (like removing the last element from the array). Here's a code sample from my project:


   public void update(int dt) {
for (int i = 0; i < entities.size(); /* conditional incr */){
Entity entity = entities.get(i);
entity.update(dt);

if (entity.isToBeDestroyed()){
int lastEntity = entities.size()-1;
entities.set(i, entities.get(lastEntity));

entities.remove(lastEntity);
} else {
i++;
}
}
}

This particular variant uses update and remove in a single loop, but depending on your context you might want to split those into separate loops (so that entities don't disappear during the update phase).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...