立方体球体相交测试?

时间:2011-01-02 15:12:55

标签: c++ intersection

最简单的方法是什么?我在数学上失败了,我在互联网上找到了非常复杂的公式...我希望如果有一些更简单的那个?

我只需要知道一个球体是否与一个立方体重叠,我不关心它的作用点等。

我也希望它能利用两个形状都是对称的事实。

编辑:立方体在x,y,z轴上直线对齐

3 个答案:

答案 0 :(得分:22)

考虑半空间是不够的,你还必须考虑最接近的方法:

借用Adam的符号:

假设一个轴对齐的立方体,让C1和C2成为对角,S是球体的中心,R是球体的半径,两个物体都是实心的:

inline float squared(float v) { return v * v; }
bool doesCubeIntersectSphere(vec3 C1, vec3 C2, vec3 S, float R)
{
    float dist_squared = R * R;
    /* assume C1 and C2 are element-wise sorted, if not, do that now */
    if (S.X < C1.X) dist_squared -= squared(S.X - C1.X);
    else if (S.X > C2.X) dist_squared -= squared(S.X - C2.X);
    if (S.Y < C1.Y) dist_squared -= squared(S.Y - C1.Y);
    else if (S.Y > C2.Y) dist_squared -= squared(S.Y - C2.Y);
    if (S.Z < C1.Z) dist_squared -= squared(S.Z - C1.Z);
    else if (S.Z > C2.Z) dist_squared -= squared(S.Z - C2.Z);
    return dist_squared > 0;
}

答案 1 :(得分:19)

Jim Arvo在Graphics Gems 2中有一个算法可以在N-Dimensions中运行。我相信您希望在此页面底部显示“案例3”:http://www.ics.uci.edu/~arvo/code/BoxSphereIntersect.c 根据你的情况清理的是:

bool BoxIntersectsSphere(Vec3 Bmin, Vec3 Bmax, Vec3 C, float r) {
  float r2 = r * r;
  dmin = 0;
  for( i = 0; i < 3; i++ ) {
    if( C[i] < Bmin[i] ) dmin += SQR( C[i] - Bmin[i] );
    else if( C[i] > Bmax[i] ) dmin += SQR( C[i] - Bmax[i] );     
  }
  return dmin <= r2;
}

答案 2 :(得分:-2)

// Assume clampTo is a new value. Obviously, don't move the sphere
closestPointBox = sphere.center.clampTo(box)

isIntersecting = sphere.center.distanceTo(closestPointBox) < sphere.radius

其他一切都只是优化。

哇,-2。艰难的人群。好的,这是three.js实现,基本上逐字逐句地说同样的事情。 https://github.com/mrdoob/three.js/blob/dev/src/math/Box3.js

intersectsSphere: ( function () {

    var closestPoint;

    return function intersectsSphere( sphere ) {

        if ( closestPoint === undefined ) closestPoint = new Vector3();

        // Find the point on the AABB closest to the sphere center.
        this.clampPoint( sphere.center, closestPoint );

        // If that point is inside the sphere, the AABB and sphere intersect.
        return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );

    };

} )(),
相关问题