Game Development Reference
In-Depth Information
The Gravity Game is implemented in a class called GravityGame . Most of the program involves
setting up the GUI elements of the game. We won't cover the GUI aspects of the code in any
detail. The first thing the program does is to declare the fields used in the class. The first group
of fields declared in the class are the GUI components.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.BevelBorder;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;
public class GravityGame extends JFrame implements ActionListener
{
private JTextField resultsTextField;
private JTextField velocityTextField;
private JComboBox planetComboBox;
private JLabel planetLabel;
private JLabel velocityLabel;
private JLabel resultsLabel;
private JButton startButton;
private JButton dropButton;
private JButton resetButton;
private JPanel drawingPanel;
private GridBagConstraints gbc;
Additional fields are declared that describe the position and characteristics of the box
and ball.
private double boxLocation; // horizontal location of box
private double boxVelocity;
private int boxWidth; // width of box in pixels
private double ballAltitude; // vertical location of ball
private double ballLocation; // horizontal location of ball
private double initialAltitude; // initial ball altitude
private double g; // gravitational acceleration
private double time; // time since box begins to move
private double dropTime; // time since ball was dropped
private boolean dropped; // true if the ball has been dropped
As mentioned in Chapter 1, in many cases the physics models are computed so quickly
that the games actually have to be slowed down so they will simulate more or less real-time
behavior. Since the program has been artificially slowed down, the time it will take the ball to
drop 120 m on the screen is close to the time it would actually take. If the program was allowed
to run at full speed, then the ball would appear to drop in a fraction of a second. This kind of
behavior would not convince anyone using the game that it was simulating reality! In the
Search WWH ::




Custom Search