Game Development Reference
In-Depth Information
shots.remove(i);
i--;
len--;
}
}
}
}
The checkShotCollisions() method is a little bit more complex. It loops through each Shot
instance and checks for overlap between it and a shield block, an invader, or the ship. Shield
blocks can be hit by shots fired by the ship or by an invader. An invader can only be hit by a
shot fired by the ship. And the ship can only be hit by a shot fired by an invader. To distinguish
whether a shot was fired by a ship or an invader, all we need to do is look at its z velocity. If it is
positive, it moves toward the ship, and was therefore fired by an invader. If it is negative, it was
fired by the ship.
public boolean isGameOver() {
return ship.lives == 0;
}
The isGameOver() method simply tells an outside party if the ship has lost all its lives.
public void shoot() {
if (ship.state == Ship. SHIP_EXPLODING )
return ;
int friendlyShots = 0;
int len = shots.size();
for ( int i = 0; i < len; i++) {
if (shots.get(i).velocity.z < 0)
friendlyShots++;
}
if (System. nanoTime () - lastShotTime > 1000000000 || friendlyShots == 0) {
shots.add( new Shot(ship.position.x, ship.position.y,
ship.position.z, -Shot. SHOT_VELOCITY ));
lastShotTime = System. nanoTime ();
listener.shot();
}
}
}
Finally, the shoot() method will be called from outside each time the Fire button is pressed
by the user. As noted in the “Core Game Mechanics� section, a shot can be fired by the
ship every second, or it can be fired if no ship has been shot on the field yet. The ship can't
fire if it explodes, of course, so that's the first thing we check. Next, we run through all the
Shot instances and check if one of them is a ship shot. If that's not the case, we can shoot
immediately. Otherwise, we check when the last shot was fired. If more than a second has
passed since the last shot, we fire a new one. This time, we set the velocity to - Shot.SHOT_
VELOCITY so that the shot moves in the direction of the negative z axis toward the invaders.
As always, we invoke the listener to inform it of the event.
 
Search WWH ::




Custom Search