# Advanced Sphere-Sphere Continuous Collision Detection (CCD)

In simple collision detection algorithm we have calculated whether the two spheres were colliding. More advanced calculations include finding the time of the collision as well as the direction of the spheres during the test.

Let us assume we have a vector between sphere centers (s), relative speed (v) and sum of radii (radiusSum):

We can calculate squared distance between centers. If the distance (dist) is negative, they already overlap:

Spheres intersect if squared distance between centers is less than squared sum of radii:

If b is 0.0 or positive, they are not moving towards each other:

If d is negative, no real roots, and therefore no collisions:

If we’ve come so far, we can calculate time of the collision:

**Read also:** Sphere vs AABB collision detection test

### Code

bool testMovingSphereSphere(Scenenode *A, Scenenode *B, double &t)
{
Planet *pa = (Planet *) A;
Planet *pb = (Planet *) B;
Vector3D<double> s = pa->pos - pb->pos; // vector between the centers of each sphere
Vector3D<double> v = pa->vel - pb->vel; // relative velocity between spheres
double r = pa->radius + pb->radius;
double c = s.dot(s) - r*r; // if negative, they overlap
if (c < 0.0) // if true, they already overlap
{
t = .0;
return true;
}
float a = v.dot(v);
float b = v.dot(s);
if (b >= 0.0)
return false; // does not move towards each other
float d = b*b - a*c;
if (d < 0.0)
return false; // no real roots ... no collision
t = (-b - sqrt(d)) / a;
return true;
}

## Comments

You may use these HTML tags and attributes: `<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> `

Be the first to comment.