Reputation: 197
In the game that I am currently making I need to check if two enemies collide with each other, if they collide only those two enemies should get affected and not every enemy that exist. Therefor I need to get the two enemies from the ArrayList when they collide so that only they will get affected. How would I go about doing so?
This is the code that adds the enemies to the ArrayList
zombie.add(new Zombie(randomXSpawn,randomYSpawn));
To check if the enemies colided with each other I currently use this code
Zombie z = (Zombie) zombie.get(i);
Rectangle r2 = z.getBounds();
if(r2.intersects(r2)){
//Code goes here
}
Upvotes: 0
Views: 137
Reputation: 13
Also if you haven't done so, you may want to create boundaries around where the zombies CANNOT be (houses, obstacles, etc.)
Rob's answers is really good though.
Upvotes: 0
Reputation: 7146
You're going to need to check each pair of zombies to see if they have collided. The simplest way to do this check is like this:
for (int i = 0; i < zombie.size(); i++) {
Rectangle r1 = zombie.get(i).getBounds();
for (int j = i+1; j < zombie.size(); j++) {
if (r1.intersects(zombie.get(j).getBounds())) {
// Code goes here
}
}
}
Note that j
is not starting from zero each time. This makes it so that as long as each zombie is in the list only once you will never check the same pair twice, and you won't check a zombie against itself.
Also, as a general programming tip, change the name of the list to zombies
. It's a little bit clearer, and getting in the habit of using good names for your variables will save you headaches later on.
Upvotes: 2