CHAPTER 12 ■ VIDEO GAMES
// Provide a way to get the value
// (used when the target is hit)
public int getValue() {
return value;
}
}
The ShootingGalleryTarget class is a very simple object that keeps track of a target's position, its
value (if it gets hit), and the way in which it draw itself within its row. To make collision detection easier,
I implemented the target as a Polygon object, because the Polygon class has a handy method called
contains that lets us know whether a point is in the polygon. I could have used the properties of the
image itself, but doing so would require more code and more math, which would neither perform better
nor be more readable.
Collision detection usually means two objects end up in the same space and the game has to figure
out what to do about it (such as draw an explosion, or open a door, or any other number of possibilities
that are determined by the nature of the game). In this case, I elected to simplify the game by not
drawing a bullet (or laser beam or whatever) going from the cursor to the target area. However, we still
have to determine whether a target has been hit when the player shoots. So I make the shooter class see
whether a target has the same vertical position as the center of the player's cursor and (working from the
right-most row to the left-most row) remove the first target that matches the vertical location.
An excellent exercise would be to add an animation for the shot. You could either add a bullet object
(use another class) and move it across the screen or just draw a line from the cursor to the first target it
touches (an expansion of the ShootingGalleryShooter class will do this trick).
Speaking of the shooter class, let's look at it a little more closely. As you read the class, notice that it
implements both the MouseListener and the MouseMotionListener interfaces. No other object in the
game needs to listen for mouse clicks and mouse motion, so only the ShootingGalleryShooter class
implements those interfaces. You might also want to study the paintComponent method to see how it
changes the color of the bar after a player shoots and enforces a one-second delay between shots.
Finally, take a close look at the analyzeShot and analyzeShotForRow methods. Those two contain the
logic for determining whether a shot hit a target.
Listing 12-9. The ShootingGalleryShooter class
package com.bryantcs.examples.videogames;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class ShootingGalleryShooter extends JPanel implements MouseListener,
MouseMotionListener {
private static final long serialVersionUID = 1L;
// We need to know where the cursor is
private int xPosition, yPosition;