Home > OS >  Need to know if a sphere intersects with cube using python code...?
Need to know if a sphere intersects with cube using python code...?

Time:05-12

I am developing a code in python to check whether a sphere having a center at (x, y, z) coordinates and with radius R, intersects the cube of dimension one, i.e., l = 1, b = 1, h = 1. As mentioned above, I want to know if the sphere intersects the cube at any point or direction, or proportion.

I have a list of sphere coordinates (x,y,z) that must be checked for the intersection. I had done some research on it but couldn't clear my doubts regarding how to approach this example.

I would love to know both the math and coding part of it. Can someone please help me solve it..?? Edit: Cube is axis aligned.

CodePudding user response:

To reveal a fact of intersection, you can calculate distance from cube to sphere center and compare it with sphere radius. 2D case is described here, it could be easily extended to 3D case.

Get cube center as (rcx, rcy, rcz) and find coordinate differences from cube center to sphere center

dx, dy, dz = x - rcx, y - rcy, z - rcz

Let SquaredDist = 0, and for every coordinate make:

t = dx   0.5                # 0.5 is half-size of your cube
if t < 0:
  SquaredDist  = t * t
else:
   t = dx - 0.5
   if t > 0:
  SquaredDist  = t * t

finally compare SquaredDist with R*R

Some explanation to comment:

Look at the picture in linked answer. For rectangle ABCD we have center G and coordinate differences GK and GJ, they include half of width and half of height. Squared distance (EC here) is sum of squared distances to proper side lines (planes in 3D case). When the closest (to sphere center) point is cube corner, we take into account three planes, when closest point lies at the edge - we take into account two planes, when closest point lies at facet - we take into account only one plane, and when sphere center is inside - SquaredDist remains zero.

  • Related