I am making an explosion. The explosion is supposed to hit all the enemys within it’s rectangle (x, y, x + w, y + h). Both the explosion and the enemies inherits from a Sprite class that has a getBounds() method that returns their rectangle. When I create the explosion item I in the constructor loops trough the enemies to check if the rectangles intersects with rectangle.intersects(rectangle2). But seemingly when there are multiple targets that are SUPPOSED to be intersected sometimes the check ignores some of them…
Here’s som code:
In the constructor of the class Explosion, inherits class Sprite
List<Zombie> zombies = mGamePlay.getZombieHandeler().getZombies();
Rect r = getBounds();
for(int i = 0; i < zombies.size(); i++)
{
Rect zR = zombies.get(i).getAnimation().getBounds();
if(!zombies.get(i).isDead() && r.intersect(zR))
zombies.get(i).doDamage(new int[]{damage, 0, 0});
}
Inside class Sprite:
public Rect getBounds()
{
return new Rect(mPosX, mPosY, mPosX + mWidth, mPosY + mHeight);
}
Rect.intersect()will modify the source rectangle and set it to the intersection of the two rectangles if they intersect. This is mentioned in the javadoc. This means that after the first successful intersection test, subsequent intersection tests will likely fail (they will pass only for zombies that intersect each other with the original intersection rectangle.)Instead you should use the
Rect.intersects()(with an ‘s’ at the end.)