Algorithm to check if two boxes overlap

Two axes aligned boxes (of any dimension) overlap if and only if the projections to all axes overlap. The projection to an axis is simply the coordinate range for that axis.

enter image description here

The blue and the green boxes in the image above overlap because their projections to both axes overlap. The blue and the orange box do not overlap, because their projections to the x-axis do not overlap (note that their projections to the y-axis do overlap). The green and the orange box do not overlap, because their projections to the y-axis don't overlap (while their projections to the x-axis do overlap).

So when it comes to code for 1D boxes (intervals) we have:

box1 = (xmin1, xmax1)
box2 = (xmin2, xmax2)
isOverlapping1D(box1,box2) = xmax1 >= xmin2 and xmax2 >= xmin1

For 2D boxes (rectangles) we have:

box1 = (x:(xmin1,xmax1),y:(ymin1,ymax1))
box2 = (x:(xmin2,xmax2),y:(ymin2,ymax2))
isOverlapping2D(box1,box2) = isOverlapping1D(box1.x, box2.x) and 
                             isOverlapping1D(box1.y, box2.y)

For 3D boxes we have:

box1 = (x:(xmin1,xmax1),y:(ymin1,ymax1),z:(zmin1,zmax1))
box2 = (x:(xmin2,xmax2),y:(ymin2,ymax2),z:(zmin2,zmax2))
isOverlapping3D(box1,box2) = isOverlapping1D(box1.x, box2.x) and 
                             isOverlapping1D(box1.y, box2.y) and
                             isOverlapping1D(box1.z, box2.z)

if(xMin1 <= xMax2 || xMax1 >= xMin2)
 
if(yMin1 <= yMax2 || yMax1 >= yMin2)

if(zMin1 <= zMax2 || zMax1 >= zMin2)

All of these conditions have to be true for the boxes to not be overlapped.

Also I assumed that the box edges could lay on the same x,y,z co-ordinates.

If not, just take the equal signs outs.

if(xMin1 < xMax2 || xMax1 > xMin2)
 
if(yMin1 < yMax2 || yMax1 > yMin2)

if(zMin1 < zMax2 || zMax1 > zMin2)

Tags:

Algorithm