Game Development Reference
In-Depth Information
Take a look now at the other new function, ApplyImpulse :
void ApplyImpulse(pRigidBody2D body1, pRigidBody2D body2)
{
float j;
j = (-(1+fCr) * (vRelativeVelocity*vCollisionNormal)) /
( (vCollisionNormal*vCollisionNormal) *
(1/body1->fMass + 1/body2->fMass) );
body1->vVelocity += (j * vCollisionNormal) / body1->fMass;
body2->vVelocity -= (j * vCollisionNormal) / body2->fMass;
}
This is a simple but crucial function for collision response. What it does is calculate the
linear collision impulse as a function of the colliding hovercraft's relative normal ve‐
locity, masses, and coefficient of restitution, using the formula that we showed you in
Chapter 5 . Further, it applies this impulse to each hovercraft, effectively changing their
velocities in response to the collision. Note that the impulse is applied to one hovercraft
and then the negative impulse applied to the other.
With those two new functions complete, it's now time to revise UpdateSimulation to
handle collision detection and response as the simulation steps through time. Here's
what the new UpdateSimulation function looks like:
{
float dtime = dt;
bool tryAgain = true;
int check=0;
RigidBody2D craft1Copy, craft2Copy;
bool didPen = false;
int count = 0;
Craft.SetThrusters(false, false);
if (IsKeyDown(VK_UP))
Craft.ModulateThrust(true);
if (IsKeyDown(VK_DOWN))
Craft.ModulateThrust(false);
if (IsKeyDown(VK_RIGHT))
Craft.SetThrusters(true, false);
if (IsKeyDown(VK_LEFT))
Craft.SetThrusters(false, true);
while(tryAgain && dtime > tol)