Game Development Reference
In-Depth Information
When the Start button is pressed, the actionPerformed method declared in the
SphereCollision class is called. The values in the text fields are used to update the velocity,
mass, and coefficient of restitution values. As with the other programs presented in this topic,
the SphereCollision class uses a Timer object to control the execution of the simulation. When
the start method is called on the Timer , the simulation begins.
// The actionPerformed() method is called when
// the Start button is pressed.
public void actionPerformed(ActionEvent event) {
// Get the initial quantities from the text fields.
vx1 = Double.parseDouble(vx1TextField.getText());
mass1 = Double.parseDouble(mass1TextField.getText());
vx2 = Double.parseDouble(vx2TextField.getText());
mass2 = Double.parseDouble(mass2TextField.getText());
e = Double.parseDouble(eTextField.getText());
// Update the display.
updateDisplay();
// Start the box sliding using a Timer object.
// to slow down the action.
gameTimer.start();
}
The SphereCollision class declares an inner class named GameUpdater that declares its own
version of the actionPerformed method. The Timer is set up to call this actionPerformed method
every 0.05 seconds. The first thing done in the method is to determine whether the spheres
have collided. A collision is defined to occur if the distance between the centers of the spheres
is less than or equal to the sum of the radii of the spheres.
class GameUpdater implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Determine if a collision occurs and if it
// does, change the velocities of the spheres.
// A collision occurs if the distance between the
// centers of the spheres is less than twice their
// radii.
double distance = Math.abs(x1 - x2);
double tmp = 1.0/(mass1 + mass2);
If a collision occurs, the velocities of the spheres are updated according to Equation (6.14).
Since the spheres only move in the x-direction in this simulation, only the x-direction compo-
nents of velocity need to be updated.
Search WWH ::




Custom Search