Game Development Reference

In-Depth Information

Here
y
is a function of
t
, and
y
' is the derivative as a function of
t
and possibly of
y

depending on the equations you're trying to solve, and ∆
t
the step size.

To make this clearer for you, we'll show these formulas in terms of the ship example

equation of motion of
Chapter 4
, the same example that we discussed in the previous

section. In this case, velocity is approximated by the following formulas:

k
1
= ∆t [1/m (T - C v
t
)]

k
2
= ∆t [1/m (T - C (v
t
+ k
1
))]

v
t+∆t
= v
t
+ ½(k
1
+ k
2
)

where
v
t
is the velocity at time
t
, and
v
t+∆t
is the new velocity at time
t
+∆
t
.

Here is the revised
StepSimulation
function showing how to implement this method

in code:

// This function progresses the simulation by dt seconds using

// the "improved" Euler method

void StepSimulation(float dt)

{

float F; // total force

float A; // acceleration

float Vnew; // new velocity at time t + dt

float Snew; // new position at time t + dt

float k1, k2;

F = (T - (C * V));

A = F/M;

k1 = dt * A;

F = (T - (C * (V + k1)));

A = F/M;

k2 = dt * A;

// Calculate the new velocity at time t + dt

// where V is the velocity at time t

Vnew = V + (k1 + k2) / 2;

// Calculate the new displacement at time t + dt

// where S is the displacement at time t

Snew = S + Vnew * dt;

// Update old velocity and displacement with the new ones

V = Vnew;

S = Snew;

}