Collision Management


If a projectile collides with an alien, both objects are marked inactive. If an alien collides with the rocketship, both are marked inactive. Inactive objects are removed from the game so they are no longer drawn.

GameObject

1. In your GameObject class, create an object of the Rectangle class in your member variables. Call this object collisionBox and DO NOT INITIALIZE IT YET.


2. Initialize the collision box in the constructor. It takes four parameters. Use its x, y, width, and height variables.


3. In the update method, update the collision box with the x, y, width, and height variables so it keeps moving with the GameObject (Alien, Projectile, or Rocketship).

        collisionBox.setBounds(x, y, width, height);

4. Add a call to the GameObject update method in both the Alien and Projectile update methods as follows:

        super.update();

ObjectManager

5. Create a method called checkCollision. Add code that iterates through every alien and checks if it collides with any "enemy" (Rocket or Projectile). If they collide, set the Alien AND "enemy's" isActive variables to false. NOTE: you will need nested for loops! Collision can be checked using the Rectangle intersects() method - see example below:

rocket.collisionBox.intersects(alien.collisionBox)


6. In the update() method call the checkCollision() and the purgeObjects() methods after you have updated all the game objects. Note: If the rocket is marked inActive, you can skip all the remaining updates and purging because the game is over.


GamePanel

7. In the updateGameState method, create an if statement that checks the isActive variable of your Rocketship object. If it is false, set the currentState to END.


TESTING

8. Run the program. Do the aliens and projectiles disappear when they are supposed to?