Collision Detection List

I have a sprite control class and two other classes, one is the players class, the other is the enemies class. Both are child classes of my sprite manager. I figured out how to make collision detection for a player and an adversary class. However, since my enemies are created on the list, I cannot figure out how to check for collision detection for enemies when they collide with each other. I was thinking about duplicating my lists, but how would I update them, right? I saw an example of creating nested foreach loops for two lists and then comparing objects, but I'm not sure if this is correct. Is there an easy way to compare two items in a list?

+4
source share
1 answer

In short, yes. Think that as soon as you compare the enemy with any other enemy, he no longer needs to be compared. You can minimize the number of checks in this way.

Example (pseudo code):

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 note - do not try to remove the enemy from the list in these loops, because you do not want to change the state of the list during iteration ( foreach actually throws an exception if you try to change the list during replay). Instead, save it in a different list or iterate in the reverse order.

+6
source

Source: https://habr.com/ru/post/1443304/


All Articles