Game Development Reference
In-Depth Information
Now that the Car and BoxsterS classes are defined, they can be incorporated into the Car
Simulator GUI. The class that implements the GUI is named CarSimulator . As with the other
GUIs in this topic, we will not go over every detail of the CarSimulator class, but you are encour-
aged to download the source code from the Apress website. As with most of the other sample
games in this topic, the CarSimulator class makes use of a Timer object to control the execution
speed of the game. Among the fields declared in the CarSimulator class is a BoxsterS object that
represents the car being modeled in the simulation.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.BevelBorder;
import java.awt.event.*;
import javax.swing.Timer;
public class CarSimulator extends JFrame implements ActionListener
{
// Other field declarations not shown ...
private BoxsterS car;
When the Start button is pressed, the start method is called on the Timer object to start the
simulation. The Timer object is set up to call the actionPerformed method every 0.05 seconds. The
first thing the actionPerformed method does is to determine whether the car is accelerating,
cruising at a constant speed, or braking, and sets the value of the mode field accordingly.
// This ActionListener is called by the Timer
class GameUpdater implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Figure out if the car is accelerating,
// cruising, or braking, and set the mode of
// the car accordingly.
if ( accelButton.isSelected() == true ) {
car.setMode("accelerating");
}
else if ( cruiseButton.isSelected() == true ) {
car.setMode("cruising");
}
else {
car.setMode("braking");
}
The updateLocationAndVelocity method is called to update the location and velocity of
the car. This method is implemented in the DragProjectile class, but since the BoxsterS class
is a subclass of DragProjectile , the method can be accessed inside the BoxsterS class.
// Update the car velocity and position at the next
// time increment.
double timeIncrement = 0.06;
car.updateLocationAndVelocity(timeIncrement);
Search WWH ::




Custom Search