[Math] Finding the clear spacing distance between two rectangles

geometry

Image for illustration

I want to find the clear spacing distance between two rectangles. The clear spacing distances are marked by a red segment connecting two rectangles in the image. (The rectangles are always orthogonal to the x-y axis)

Given

  1. Centers of both the rectangles (Center point 1 and center point from the figure)
  2. The width and breadth (B1, W1, and B2, W2)

Best Answer

With center point 1 at $(x_1, y_1)$ and center point 2 at $(x_2, y_2)$, and presuming you want the greater of the horizontal and the vertical clear spacing, you would use:

$$\max\big(|x_1-x_2|-(w_1+w_2)/2, |y_1-y_2|-(b_1+b_2)/2\big)$$

This takes the axial distance between the centers and subtract half of the appropriate dimension of the rectangles to acquire the clear spacing.

If the result is less than or equal to zero, the rectangles are touching.

Related Question