Game Development Reference
In-Depth Information
for(j=0; j<numEqns; ++j) {
q[j] = q[j] + (dq1[j] + 2.0*dq2[j] + 2.0*dq3[j] + dq4[j])/6.0;
ode.setQ(q[j], j);
}
return;
}
}
The rungeKutta4 method is quite simple and takes only 38 lines of code including comment
statements. To apply the Runge-Kutta solver to a specific problem requires one more step—an
ODE subclass must be written that models the equations to be solved. We'll look at an example
of that in the next section where the Runge-Kutta solver will be used to model the motion of
a spring.
Example: Spring Motion
Let's demonstrate the Runge-Kutta ODE solver by applying it to the problem of predicting the
motion of a spring. The equations that describe the change in the location and velocity as a
function of time for the spring are shown in Equations (4.25) and (4.26). They consist of two
first-order ODEs. The spring problem is a good test case for the ODE solver because there is an
exact solution to the governing equations that can be compared against the values predicted
by the ODE solver.
In order to compute the motion of the spring, it is necessary to write a class that represents
the spring motion ODEs. The class, called SpringODE , is written as a subclass of ODE so the code
written in the ODE class can be reused. The first thing the SpringODE class does is to declare fields
that represent spring-specific data such as the spring constant and damping coefficient. Since
the motion of the spring will be computed as a function of time, the independent variable for this
problem is time.
public class SpringODE extends ODE
{
private double mass; // mass at end of spring
private double mu; // damping coefficient
private double k; // spring constant
private double x0; // initial spring deflection
private double time; // independent variable
The SpringODE class declares a constructor that is used to define the initial state of the
spring. The first thing the constructor does is to call the ODE class constructor to initialize the
values of the fields declared in the ODE class. The fields declared in the SpringODE class are then
initialized according to the arguments passed to the SpringODE constructor. The last thing the
constructor does is to set the initial conditions for the spring. The initial velocity of the spring
is set to zero and the initial location of the spring is set according to the x 0 argument passed to
the constructor.
Search WWH ::




Custom Search