C++ Plane Sphere Collision Detection

荒凉一梦 提交于 2021-01-29 10:15:42

问题


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;
}

回答1:


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)




回答2:


I needed the same computation in a game I made. This is the minimum distance from a point to a plane:

distance = (q - plane.p[0])*plane.normal;

Except distance, all variables are 3D vectors (I use a simple class I made with operator overload).

distance: minimum distance from a point to the plane (scalar).

q: the point (3D vector), in your case is the center of the sphere.

plane.p[0]: a point (3D vector) belonging to the plane. Note that any point belonging to the plane will work.

plane.normal: normal to the plane.

The * is a dot product between vectors. Can be implemented in 3D as a*b = a.x*b.x + a.y*b.y + a.z*b.z and yields a scalar.

Explanantion

The dot product is defined:

a*b = |a| * |b| * cos(angle)

or, in our case:

a = q - plane.p[0]
a*plane.normal = |a| * |plane.normal| * cos(angle)

As plane.normal is unitary (|plane.normal| == 1):

a*plane.normal = |a| * cos(angle)

enter image description here

a is the vector from the point q to a point in the plane. angle is the angle between a and the normal to the plane. Then, the cosinus is the projection over the normal, which is the vertical distance from the point to the plane.



来源:https://stackoverflow.com/questions/22093749/c-plane-sphere-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!