So I decided to restructure my collision code to be general and flexible to something like this:
This code restructure single-handily eliminates my original code that had multiple instanceof check inside the for each loop.
Now the only issue I can see is if when I want to add different audio for the monster death upon collision with a projectile.
// detect collision detection on all monsters on screen
public void checkMonsterCollision(ArrayList<GameComponent> gameObjects) {
// check for Monsters in the ArrayList
for(GameComponent component: gameObjects)
{
if(component instanceof Monster)
{
/* check the intersection of the laser's rectangle and the OneEye monster
* rectangle. If both rectangles intersects, it is a collision
*/
if(rectangle.intersects(((Monster) component).getRectangle()))
{
// uncomment code to play the
//playDeathSound();
// remove laser upon monster contact
Game.getInstance().remove(this);
// remove the monster upon contact of the laser
Game.getInstance().remove(component);
}
}
}
}
import java.awt.Rectangle;
public abstract class Monster extends Sprite{
private Rectangle rectangle;
public Rectangle getRectangle()
{
return rectangle;
}
}