4
votes

I have a sprite managing class and two other classes, one is a player class, the other is an enemy class. Both are child classes of my sprite manager. I have figured out how to do the collision detection for the player and enemy class. However, since my enemies are instantiated in a list i am not able to figure out how to check the collision detection for the enemies when they run into each other. I thought about duplicating my lists, but how would i update them, properly? I saw an example of creating nested foreach loops for the two lists and then compare objects, but i'm not sure if this is right. Is there an easy way to compare two items within a list?

1
Show us the relevant part of the code you tried so far. ;)vdbuilder

1 Answers

6
votes

In short, yes. Consider that once you compare an enemy to every other enemy, it no longer needs to be compared. You can minimize the number of checks this way

Example (pseudocode):

for (int i=0; i < list.length; i++){
    // compare list[i] to everything subsequent enemy
    // we don't have to compare to enemies < i, because we've already
    // compared those to all other enemies
    for (int j=i+1; j < list.length; j++){
        checkcollision(list[i], list[j])
    }
}

Just a note -- don't try to remove an enemy from the list in these loops because you don't want to change the state of the list while you're iterating (foreach will actually throw an exception if you try to modify a list while you're iterating). Instead, save it in another list or iterate in reverse.