This section of the archives stores flipcode's complete Developer Toolbox collection,
featuring a variety of mini-articles and source code contributions from our readers.

3D Pong Collision & Response
Submitted by

Here is an example / inspiration on how to handle a 3D pong / breakout game. It handles
AABBox / Sphere collision tests, and perform some simple collision physics, based on
an extended 'velocity reflection' model (does friction / restitution and handles difference in
object mass). Thanks to the physics, Objects don't get squashed on walls, and react pretty
well to multiple simultaneous collision. The code is unoptimised, but should be already quite
fast already. SInce the collision detection routines work on overlaps, you have to be careful
with the velocity of the objects, and their relative size (relative to their velocity). Swept
tests would solve the problem of both accuracy and stability on thin&fast moving objects, but
that's for another COTD....
Other goodies are,

returntrue;
}
//------------------------------------------------------
// sphere centre not in the box. This is the general case
//------------------------------------------------------
else
{
//------------------------------------------------------
// find the closest plane on the box to the sphere
// (could be a corner, an edge or a face of the box).
//------------------------------------------------------
pBox = pDiff;
if (outx) pBox.x = sgn(pDiff.x) * pExt.x;
if (outy) pBox.y = sgn(pDiff.y) * pExt.y;
if (outz) pBox.z = sgn(pDiff.z) * pExt.z;
pBox += GetPosition();

//------------------------------------------------------
// see if the point on the box surface is in the sphere,
// by checking the distance of the point from the sphere
// centre against the sphere radius.
//------------------------------------------------------
Vector pDist = pBox - xSphere.GetPosition(); // relative position of point in box to the sphere centre
float dist2 = pDist * pDist; // distance of the point on the box to sphere centre, squared
float r2 = xSphere.GetRadius() * xSphere.GetRadius(); // radius of sphere, squared
if (dist2 > r2) returnfalse; // point outside sphere, no intersection
//------------------------------------------------------
// calcualte point on sphere surface closest to point on box.
//------------------------------------------------------
pDist /= sqrt(dist2); // normalise
pDist *= xSphere.GetRadius();

pSphere = pDist;
pSphere += xSphere.GetPosition();

returntrue;
}
}

//-----------------------------------------------------------------------------
// Game Interface
//-----------------------------------------------------------------------------
enum { iNumSpheres = 10, iNumBoxes = 20, iNumWalls = 6 };
CAABBox xBoxes [iNumBoxes]; // all boxes in the world
CSphere xSpheres[iNumSpheres]; // all spheres in the world
CObjectList xObjectList; // all objects in the world wrapped up in a list