Cube Sphere Intersection Test?

What is the easiest way to do this? I fail in math and I found quite complex formulas on the internet ... im hoping if theres a little easier?

I just need to know if the sphere overlaps the cube, I don't care about at what point it does it, etc.

I also hope that he takes advantage of the fact that both forms are symmetrical.

Edit: the cube is aligned right along the x, y, z axes

+4
source share
3 answers

It is not enough to look at half-spaces; you should also consider the point of the closest approach:

Adat Notation Borrowing:

Assuming a cube aligned along the axis and giving C1 and C2 opposite angles, S is the center of the sphere, R is the radius of the sphere, and that both objects are strong:

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 (SX < C1.X) dist_squared -= squared(SX - C1.X); else if (SX > C2.X) dist_squared -= squared(SX - C2.X); if (SY < C1.Y) dist_squared -= squared(SY - C1.Y); else if (SY > C2.Y) dist_squared -= squared(SY - C2.Y); if (SZ < C1.Z) dist_squared -= squared(SZ - C1.Z); else if (SZ > C2.Z) dist_squared -= squared(SZ - C2.Z); return dist_squared > 0; } 
+19
source

Jim Arvo has an algorithm for this in Graphics Gems 2, which works in N-Dimensions. I believe that you need “case 3” at the bottom of this page: http://www.ics.uci.edu/~arvo/code/BoxSphereIntersect.c which is cleared for your case:

 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; } 
+14
source
 // Assume clampTo is a new value. Obviously, don't move the sphere closestPointBox = sphere.center.clampTo(box) isIntersecting = sphere.center.distanceTo(closestPointBox) < sphere.radius 

Everything else is just optimization.

Wow, -2. Tough crowd. Ok, here is an implementation of three.js that basically says the same word for word. 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 ); }; } )(), 
-1
source

Source: https://habr.com/ru/post/1333989/


All Articles