Sphere to Plane

Sphere to Plane

This function will allow us to check if a sphere is colliding with a plane. Our half space test helped us see if a point was in front of a plane, on a plane or behind a plane, so, we can base ourselves on that one and, after editing it a little, transform it into a sphere to plane check.

First, we make a vector from a point on the plane to the center of the sphere.
Then, we get the dot product of this vector with the normal of the plane. If the result is less than or equal to the radius of the sphere, it means the sphere is colliding with the plane (either by just touching it or by getting already on the negative side of the plane). It’s that simple!

struct TSphere
{
    D3DXVECTOR3 m_vecCenter;
    float m_fRadius;
};

bool SphereToPlane(const TSphere& tSph, const D3DXVECTOR3& vecPoint, const D3DXVECTOR3& vecNormal)
{
    //Calculate a vector from the point on the plane to the center of the sphere
    D3DXVECTOR3 vecTemp(tSph.m_vecCenter - vecPoint);

    //Calculate the distance: dot product of the new vector with the plane's normal
    float fDist(D3DXVec3Dot(&vecTemp, &vecNormal));

    if(fDist > tSph.m_fRadius)
    {
        //The sphere is not touching the plane
        return false;
    }

    //Else, the sphere is colliding with the plane
    return true;
}