Game Development Reference
In-Depth Information
Gravity Game, a Timer object is used to slow the game down. The GameUpdater class is a user-
defined class that declares a method that the Timer object will call. We'll discuss this method in
more detail in a little bit.
// These elements are used to control the execution
// speed of the game. Without them, the game would
// run too quickly.
private GameUpdater gameUpdater;
private Timer gameTimer;
The GravityGame constructor initializes the box and ball fields, creates and initializes the
Timer object, and creates and initializes the GUI components. The GUI initialization code
isn't shown.
public GravityGame() {
// Set box, ball, and time parameters.
boxLocation = 0.0;
boxWidth = 40;
initialAltitude = 120.0;
ballAltitude = initialAltitude;
ballLocation = 210.0;
time = 0.0;
dropTime = 0.0;
dropped = false;
// Create a Timer object that will be used
// to slow the action down and an ActionListener
// that the Timer will call. The timeDelay variable
// is the time delay in milliseconds.
gameUpdater = new GameUpdater();
int timeDelay = 50;
gameTimer = new Timer(timeDelay, gameUpdater);
// GUI initialization code not shown …
The GravityGame class declares a method called actionPerformed that is called when the
Start button is pressed. The method obtains the box velocity and planet selection values from
the GUI components. The value of the gravitational acceleration is set according to which
planet is selected. The start method is then called on the Timer object to start the simulation.
// The actionPerformed() method is called when
// the "Start" button is pressed.
public void actionPerformed(ActionEvent event) {
// Get the box velocity from the textfield
boxVelocity = Double.parseDouble(velocityTextField.getText());
Search WWH ::




Custom Search