Game Development Reference

In-Depth Information

spheres. The distance between any two points in 3D space is found by

calculating a vector from one point to the next, starting at either end, then

finding the square root of the sum of the squares of components of this

vector.

double CalcDistance(VECTOR a, VECTOR b){

VECTOR ab;

ab.x = a.x - b.x;

ab.y = a.y - b.y;

ab.z = a.z - b.z;

return sqrt(ab.x*ab.x + ab.y*ab.y + ab.z*ab.z);

}

Unfortunately, square root operations are computationally expensive.

But, wait a minute, we don't actually need a distance, we are only

interested in a condition, namely is sphere A intersecting with sphere B.

For this we can use the squared distance and the combined radii squared,

avoiding any use of square roots.

//a and b give the sphere centres, R and r give the sphere radii

typedef struct stSPHERE{

double x,y, z; //Centre

double r; //radius

}SPHERE;

BOOL DoSpheresIntersect(SPHERE a, SPHERE b){

VECTOR ab;

double sqdist, sqrad;

//Vector from b to a

ab.x = a.x - b.x;

ab.y = a.y - b.y;

ab.z = a.z - b.z;

sqdist = ab.x*ab.x + ab.y*ab.y + ab.z*ab.z;

//Combined radii squared

sqrad = a.r*a.r + b.r*b.r;

return (sqdist<sqrad);

}

Search Nedrilad ::

Custom Search