Game Development Reference
In-Depth Information
When designing the
SimpleProjectile
class, we need to think a little bit about the future.
One of the central goals of object-oriented programming in a language such as Java is to reuse
as much code as possible. The equations of motion for the gravity-only model can be solved
directly using simple algebraic equations. However, later in this chapter when we add effects
like aerodynamic drag and spin to the projectile model, the equations of motion will have to be
solved with an ODE solver. At the same time, when we build the more complicated models, we
will want to reuse as much code as possible from the
SimpleProjectile
class.
The answer to satisfying these objectives is to make the
SimpleProjectile
class a subclass
of
ODE
. The
ODE
class, if you remember from Chapter 4, defines the data structure and methods
needed to use the
rungeKutta4
ODE solver method declared in the
ODESolver
class. Any subclass
of
ODE
will inherit this data structure and can therefore make use of the ODE solver. When more
sophisticated effects are added to the projectile model, those classes will be written as subclasses
of
SimpleProjectile
. By setting up this type of class hierarchy, the sophisticated projectile
classes will have access to all of the code from the
SimpleProjectile
class and the data structure
from the
ODE
class and will be able to use the ODE solver without any further modifications. The
SimpleProjectile
class may seem more complicated than it needs to be, but creating it in this
manner will make things much easier when we code up the more complicated projectile classes
a little later in the chapter. As a reminder, the
ODE
class code listing is shown in its entirety in
Chapter 4.
The
SimpleProjectile
class only declares one field representing the gravitational acceler-
ation. The class will make use of the fields declared in the
ODE
class to store the location and
velocity of the projectile. The
SimpleProjectile
class constructor calls the
ODE
constructor and
then loads the initial values of time, location, and velocity into the
s
field and
q[]
array of the
ODE
class using the
setS
and
setQ
methods.
public class SimpleProjectile extends ODE
{
// Gravitational acceleration.
public final static double G = -9.81;
public SimpleProjectile(double x0, double y0, double z0,
double vx0, double vy0, double vz0,
double time) {
// Call the ODE class constructor.
super(6);
// Load the initial position, velocity, and time
// values into the s field and q array from the
// ODE class.
setS(time);
setQ(vx0,0);
setQ(x0, 1);
setQ(vy0,2);
setQ(y0, 3);
setQ(vz0,4);
setQ(z0, 5);
}