Game Development Reference

In-Depth Information

if(s <= 0.0)

{

d.Normalize();

n = d;

vr = p->vVelocity - Obstacles[i].vVelocity;

vrn = vr*n;

if(vrn < 0.0)

{

J = -(vr*n) * (_RESTITUTION + 1) /

(1/p->fMass + 1/Obstacles[i].fMass);

Fi = n;

Fi *= J/_TIMESTEP;

p->vImpactForces += Fi;

p->vPosition -= n*s;

hasCollision = true;

}

}

}

.

.

.

}

The new code is nearly the same as the code that checks for and handles particle-to-

ground collisions. The only major differences are in how we compute the distance be‐

tween the particle and the obstacle and how we adjust the colliding particle's position

to prevent it from penetrating an obstacle, since the unit normal vector may not be

straight up as it was before. The rest of the code is the same, so let's focus on the differ‐

ences.

As explained earlier and illustrated in
Figure 8-6
, we need to compute the separation,

s
, between the particle and the obstacle. So to get
s
, we declare a variable
r
and equate

it to the sum of radii of the particle and the obstacle against which we're checking for a

collision. We define
d
, a
Vector
, as the difference between the positions of the particle

and obstacle. The magnitude of
d
minus
r
yields
s
.

If
s
is less than 0, then we make the relative velocity check. Now, in this case the collision

normal vector is along the line connecting the centers of the two circles representing

the particle and the obstacle. Well, that's just the vector
d
we already calculated. To get

the unit normal vector, we simply normalize
d
. The relative velocity vector is simply the

difference in velocities of the particle and the obstacle. Since the obstacles are static, the

relative velocity is just the particle's velocity. But we calculated the relative velocity by

taking the vector difference
vr = p->vVelocity - Obstacles[i].vVelocity
, because

in a more advanced scenario, you might have moving obstacles.