Game Development Reference
In-Depth Information
// Determine which planet is selected and set
// the gravitational acceleration accordingly.
String planet = (String)planetComboBox.getSelectedItem();
if ( planet.equals("Earth") ) {
g = 9.81;
}
else if ( planet.equals("Moon") ) {
g = 1.624;
}
else {
g = 24.8; // Jupiter
}
// Start the box sliding using a Timer object
// to slow down the action.
gameTimer.start();
}
The Timer object itself calls an actionPerformed method that is declared inside the GameUpdater
class (an inner class of the GravityGame class). The Timer object is set up to call this method
every 0.05 seconds. This actionPerformed method updates the location of the box and ball. The
box moves to the right by a constant amount every time the method is called. If the ball has
been dropped, it begins to accelerate due to gravity. Because the velocity of the ball increases
over time, it will drop further and further each time the actionPerformed method is called.
When the ball hits the ground, the method determines if it landed inside the box or not and
displays the appropriate message.
class GameUpdater implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Update the time and compute the new position
// of the box and ball.
double timeIncrement = 0.05;
time += timeIncrement;
boxLocation = boxVelocity*time;
if ( dropped ) {
dropTime += timeIncrement;
ballAltitude =
initialAltitude - 0.5*g*dropTime*dropTime;
}
// Update the display
updateDisplay();
Search WWH ::




Custom Search