Search code examples
c++geometrycollision-detection

C++ Plane Sphere Collision Detection


I'm attempting to implement Sphere-Plane collision detection in C++. I have a Vector3, Plane and Sphere class.

#include "Vector3.h"

#ifndef PLANE_H
#define PLANE_H

class Plane
{
public:
    Plane(Vector3, float);
    Vector3 getNormal() const;
protected:
    float d;
    Vector3 normal;
};

#endif

I know the equation for a plane is Ax + By = Cz + D = 0 which we can simplify to N.S + d < r where N is the normal vector of the plane, S is the center of the sphere, r is the radius of the sphere and d is the distance from the origin point. How do I calculate the value of d from my Plane and Sphere?

bool Sphere::intersects(const Plane& other) const
{
    // return other.getNormal() * this->currentPosition + other.getDistance() < this->radius;
}

Solution

  • There is rather simple formula for point-plane distance with plane equation

    Ax+By+Cz+D=0 (eq.10 here)

    Distance = (A*x0+B*y0+C*z0+D)/Sqrt(A*A+B*B+C*C)
    

    where (x0,y0,z0) are point coordinates. If your plane normal vector (A,B,C) is normalized (unit), then denominator may be omitted.

    (A sign of distance usually is not important for intersection purposes)