Point in Sphere

Point in Sphere
Calculating to see if a point is inside a sphere is a very simple task.
We just need to check the distance between the center of the sphere to the point and compare it with the sphere’s radius.
If this distance is less than the radius, then the point is inside the sphere.
If the distance is the same, then the point is on the sphere’s edge. In this example, we will consider that a “false” case.

To get the distance between the sphere’s center and the point we need to create a vector between both points and get its magnitude. A more efficient way, however, is to get this vector and then make a dot product with itself. The dot product of a vector with itself is equals to the square of its magnitude.
So, instead of comparing the distance between the sphere’s center to the point with the radius, we will calculate the square of this distance with the radius of the sphere squared.

Here’s some sample code to check if a point is inside a sphere using the DirectX Vector functions.

struct TSphere
{
D3DXVECTOR3    m_vecCenter;
float          m_fRadius;
};

bool PointInSphere(const TSphere& tSph, const D3DXVECTOR3& vecPoint)
{
//Calculate the squared distance from the point to the center of the sphere
D3DXVECTOR3 vecDist(tSph.m_vecCenter - vecPoint);
float fDistSq( D3DXVec3Dot( &vecDist, &vecDist) );

//Calculate if the squared distance between the sphere's center and the point
//is less than the squared radius of the sphere
if( fDistSq < (tSph.m_fRadius * tSph.m_fRadius))
{
    return true;
}

//If not, return false
return false;
}