Simple Intersection Tests For Games
A key component to virtually any graphical game, 2D or 3D, is a collision detection system for game objects. In this article, Looking Glass's Miguel Gomez explains some simple intersection tests for the most useful shapes: spheres and boxes.
![](https://eu-images.contentstack.com/v3/assets/blt740a130ae3c5d529/bltba62518415cda0e2/652fe6ddbc479f8697ef691f/default-cubic.png?width=1280&auto=webp&quality=95&format=jpg&disable=upscale)
Whether it's your car crossing the finish line at 180 miles per hour, or a bullet tearing through the chest of your best friend, all games make use of collision detection for object interaction. This article describes some simple intersection tests for the most useful shapes: spheres and boxes.
Sweep Tests for Moving Objects
A common approach to collision detection is to simply test for whether two objects are overlapping at the end of each frame. The problem with this method is that quickly moving objects can pass through each other without detection. To avoid this problem, their trajectories can be subdivided and the objects checked for overlap at each point; however, this gets expensive if either object experienced a large displacement. On the other hand, a sweep test can efficiently determine a lower and upper bound for the time of overlap, which can then be used as more optimal starting points for the subdivision algorithm.
A Sphere-Plane Sweep Test
Figure 1 shows an example of a quickly moving sphere passing through a plane. It can be seen that C0 is on the positive side of the plane and C1 is on its negative side.
In general, if a sphere penetrated a plane at some point during the frame, then d0>r and d1<r, where r is the radius of the sphere and d0 and d1 are the signed distances from the plane to C0 and C1, respectively. The signed distance from a point C to a plane can be calculated with the formula
More efficiently, we can store the plane in the form {n, D}, where
The distance d is then calculated
The trajectory from C0 to C1 can be parameterized with a variable u, which may be thought of as normalized time, since its value is 0 at C0 and 1 at C1. The normalized time at which the sphere first intersects the plane is given by
The center of the sphere at this time can then be interpolated with an affine combination of C0 and C1
This formula interpolates Ci correctly as long as d0 is not equal to d1 (which is the case if displacement has occurred), even when r = 0 (the case of a line segment). If desired, the parameter u can also be used to linearly interpolate the orientation of an object at this point.
In this example, it was assumed that the sphere approached the plane from the positive side and that the sphere was not already penetrating the plane at C0.. In the case that there could have been penetration on the previous frame, the condition |d0|<=r should also be checked. Listing 1 gives an implementation of this sphere-plane sweep test.
Listing 1. A sphere-plane sweep test.
#include "vector.h"
class PLANE
{
public:
VECTOR N;
//unit normal
SCALAR D;
//distance from the plane to the origin from a
//normal and a point
PLANE( const VECTOR& p0, const VECTOR& n ): N(n), D(-N.dot(p0))
{}
//from 3 pointsPLANE( const VECTOR& p0, const VECTOR& p1,
const VECTOR& p2 ): N((p1-p0).cross(p2-p0).unit()),
D(-N.dot(p0))
{}
//signed distance from the plane topoint 'p' along
//the unit normalconst SCALAR distanceToPoint( const VECTOR& p ) const
{
return N.dot(p) + D;
}
};
const bool SpherePlaneSweep
(
const SCALAR r, //sphere radius
const VECTOR& C0, //previous position of sphere
const VECTOR& C1, //current position of sphere
const PLANE& plane, //the plane
VECTOR& Ci, //position of sphere when it first touched the plane
SCALAR& u //normalized time of collision
)
{
const SCALAR d0 = plane.distanceToPoint( C0 );
const SCALAR d1 = plane.distanceToPoint( C1 );
//check if it was touching on previous frame
if( fabs(d0) <= r )
{
Ci = C0;
u = 0;
return true;
}
//check if the sphere penetrated during this frame
if( d0>r && d1<r )
{
u = (d0-r)/(d0-d1); //normalized time
Ci = (1-u)*C0 + u*C1; //point of first contact
return true;
}
return false;
}
For the definition of the VECTOR class, please see [3].
A Sphere-Sphere Sweep Test
Figure 2 shows two spheres that collided between frames. If these spheres experienced acceleration during the frame, their trajectories will be second or higher order curves; however, usually their paths can be accurately approximated as linear segments according to the equations
Since both spheres traveled for the same amount of time, u is the same for both trajectories. The square of the distance between the lines is
and to calculate when they first make contact, we must solve for u such that
This leads to the quadratic equation
The vector vba can be thought of as the displacement of B observed by A. This equation is quadratic in u, so there may be no solution (the spheres never collided), one solution (they just glanced each other), or two solutions (in which case the lesser solution is when they began to overlap and the greater is when they became disjoint again). Again, it is a good idea to check for overlap at the beginning of the frame, since this will handle the case of two stationary spheres. Listing 2 shows an implementation of the sphere-sphere sweep test.
Listing 2. The sphere-sphere sweep test.
#include "vector.h"
template< class T >
inline void SWAP( T& a, T& b )
//swap the values of a and b
{
const T temp = a;
a = b;
b = temp;
}
// Return true if r1 and r2 are real
inline bool QuadraticFormula
(
const SCALAR a,
const SCALAR b,
const SCALAR c,
SCALAR& r1, //first
SCALAR& r2 //and second roots
)
{
const SCALAR q = b*b - 4*a*c;
if( q >= 0 ){
const SCALAR sq = sqrt(q);
const SCALAR d = 1 / (2*a);
r1 = ( -b + sq ) * d;
r2 = ( -b - sq ) * d;
return true;//real roots}
else
{
return false;//complex roots
}
}
const bool SphereSphereSweep
(
const SCALAR ra, //radius of sphere A
const VECTOR& A0, //previous position of sphere A
const VECTOR& A1, //current position of sphere A
const SCALAR rb, //radius of sphere B
const VECTOR& B0, //previous position of sphere B
const VECTOR& B1, //current position of sphere B
SCALAR& u0, //normalized time of first collision
SCALAR& u1 //normalized time of second collision
)
{
const VECTOR va = A1 - A0;
//vector from A0 to A1
const VECTOR vb = B1 - B0;
//vector from B0 to B1
const VECTOR AB = B0 - A0;
//vector from A0 to B0
const VECTOR vab = vb - va;
//relative velocity (in normalized time)
const SCALAR rab = ra + rb;
const SCALAR a = vab.dot(vab);
//u*u coefficient
const SCALAR b = 2*vab.dot(AB);
//u coefficient
const SCALAR c = AB.dot(AB) - rab*rab;
//constant term
//check if they're currently overlapping
if( AB.dot(AB) <= rab*rab ){
u0 = 0;
u1 = 0;
return true;}
//check if they hit each other
// during the frame
if( QuadraticFormula( a, b, c, u0, u1 ) )
{
if( u0 > u1 )
SWAP( u0, u1 );
return true;}
return false;
}
An Axis-Aligned Bounding Box (AABB) Sweep Test
Just like the name says, the faces of an axis-aligned bounding box are aligned with the coordinate axes of its parent frame (see Figure 3). In most cases AABBs can fit an object more tightly than a sphere, and their overlap test is extremely fast.
To see if A and B overlap, a separating axis test is used along the x, y, and z-axes. If the two boxes are disjoint, then at least one of these will form a separating axis. Figure 4 illustrates an overlap test in one dimension.
In this example the x-axis forms a separating axis because
Note that the separating axis test will return true even if one box fully contains the other. A more general separating axis test is given in the section below on oriented bounding boxes (OBB’s). Listing 3 defines an AABB class that implements this overlap test.
Listing 3. An AABB class.
#include "vector.h"
// An axis-aligned bounding box
class AABB
{
public:
VECTOR P; //position
VECTOR E; //x,y,z extentsAABB( const VECTOR& p,
const VECTOR& e ): P(p), E(e){}
//returns true if this is overlapping b
const bool overlaps( const AABB& b ) const
{
const VECTOR T = b.P - P;//vector from A to B
return fabs(T.x) <= (E.x + b.E.x)
&&
fabs(T.y) <= (E.y + b.E.y)
&&
fabs(T.z) <= (E.z + b.E.z);
}
//NOTE: since the vector indexing operator is not const,
//we must cast away the const of the this pointer in the
//following min() and max() functions
//min x, y, or z
const SCALAR min( long i ) const
{
return ((AABB*)this)->P[i] - ((AABB*)this)->E[i];
}
//max x, y, or z
const SCALAR max( long i ) const
{
return ((AABB*)this)->P[i] + ((AABB*)this)->E[i];
}
};
For more information on AABBs and their applications, please see [8].
Just like spheres, AABBs can be swept to find the first and last occurrence of overlap. In Figure 5(a), A and B experienced displacements va and vb, respectively, while Figure 5(b) shows B's displacement as observed by A.
Figure 6 shows B's displacement as observed by A.
In this example, the normalized times it took for the x-extents and y-extents to overlap are given by
and it can be seen that the x-extents will cross before the y-extents. The two boxes cannot overlap until all the extents are overlapping, and the boxes will cease to overlap when any one of these extents becomes disjoint. If u0,x, u0,y, and u0,z were the times at which the x, y, and z-extents began to overlap, then the earliest time at which the boxes could have begun to overlap was
Likewise, if u1,x, u1,y, and u1,z are the times at which the x, y, and z-extents become disjoint, then the earliest time at which the boxes could have become disjoint was
In order for the two boxes to have overlapped during their displacement, the condition
must have been met. Just like in the sphere sweep test, the positions of first and last overlap can be linearly interpolated with u. Listing 4 gives an implementation of this AABB sweep algorithm.
Listing 4. An AABB sweep algorithm.
#include "aabb.h"
//Sweep two AABB's to see if and when they first
//and last were overlapping
const bool AABBSweep
(
const VECTOR& Ea, //extents of AABB A
const VECTOR& A0, //its previous position
const VECTOR& A1, //its current position
const VECTOR& Eb, //extents of AABB B
const VECTOR& B0, //its previous position
const VECTOR& B1, //its current position
SCALAR& u0, //normalized time of first collision
SCALAR& u1 //normalized time of second collision
)
{
const AABB A( A0, Ea );//previous state of AABB A
const AABB B( B0, Eb );//previous state of AABB B
const VECTOR va = A1 - A0;//displacement of A
const VECTOR vb = B1 - B0;//displacement of B
//the problem is solved in A's frame of reference
VECTOR v = vb - va;
//relative velocity (in normalized time)VECTOR u_0(0,0,0);
//first times of overlap along each axisVECTOR u_1(1,1,1);
//last times of overlap along each axis//check if they were overlapping
// on the previous frame
if( A.overlaps(B) )
{