Game Development Reference
In-Depth Information
As with the games in the earlier chapters of this topic, when the Start button is pressed, the
actionPerformed method declared in the PaddleGame class is called. The method is quite simple.
The horizontal and vertical components of the ball velocity are set according to the values
inside the text fields. The GUI display is updated, and then the start method is called on a
Timer object to start the ball moving.
// The actionPerformed() method is called when
// the Start button is pressed.
public void actionPerformed(ActionEvent event) {
// Get the initial quantities from the text fields.
ballVx = Double.parseDouble(vxTextField.getText());
ballVz = Double.parseDouble(vzTextField.getText());
// Update the display.
updateDisplay();
// Start the box sliding using a Timer object
// to slow down the action.
gameTimer.start();
}
The PaddleGame class declares an inner class named GameUpdater that declares its own
actionPerformed method. The Timer is set up to call this method every 0.05 seconds. The first
thing the method does is to determine if a collision has occurred between the ball and either
one of the walls or the paddle. The collision determination logic is pretty simple. For example,
the ball collides with the right-hand wall if the x-velocity of the ball is positive and the distance
from the center of the ball to the wall is less than or equal to the ball radius. The other potential
collisions are determined in a similar manner. If a collision occurs, the post-collision velocity
along the line of action is determined by Equation (6.15).
// This ActionListener is called by the Timer.
class GameUpdater implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Get dimensions of drawing area.
Graphics g = drawingPanel.getGraphics();
int width = drawingPanel.getWidth() - 1;
int height = drawingPanel.getHeight() - 1;
// Determine if ball collides with right wall.
// If it does, change the x-velocity of the ball.
if ( ballVx > 0.0 && ballX + ballRadius >= width ) {
ballVx = -ballVx;
}
Search WWH ::




Custom Search