[Math] Shortest distance between two rectangles in 2D

euclidean-geometrygeometryrectangles

Given the center points and dimensions of two rectangles and the angles $\theta_1$ and $\theta_2$, how to calculate the shortest distance between two rectangles ($d$)? $\theta$ is the angle that the length of rectangle makes with $X$ axis on a $2D$ plane.

enter image description here

Best Answer

This is not a trivial problem and requires a lot of effort. In other words, you need a computer. I will also assume that you are familiar with elementary calculations from analytical geometry. In particular you should be able to:

  1. Calculate coordinates of all corner points of both rectangles.
  2. Determine if two segments AB and CD intersect or not. Basically, you have equation of line AB and equation of line CD; if the intersection point M is between A and B and also between C and D, the segments do intersect.
  3. Find a line $p$ through point A perpendicular to line BC and find the intersection point D of line $p$ and line BC. You should also be able to determine if the point D lies between points B and C.

All of this is fairly trivial and I won't go into details.

Step 1: You have four segements of the first rectange and four segments of the second rectangle. By using (2) find out if any segment from the first rectangle intersects with any segment from the second rectangle. If any pair of segments has an intersection point, the rectangles overlap (or touch) and their distance is zero. If not, go to step 2.

Step 2: For every corner point from the first rectangle find distances to all segments from the second rectangle by applying (3). You have two particular cases:

Case 1: Line through corner point A of the first rectangle perpendicular to segment BC from the second rectangle intersects line BC at point D between points B and C. In this case:

$$d=AD$$

enter image description here

Case 2: Line through corner point A of the first rectangle perpendicular to segment BC from the second rectangle intersects line BC at point D which is not between points B and C. In this case:

$$d=\min(AB,AC)$$

enter image description here

This gives you four distances for every corner point of the first rectangle. For the whole first rectangle you will get a set of 4x4=16 different distances $(d_1,d_2,...,d_{16})$.

Step 3: Repeat step 2, but this time consider distances from corner points of the second rectangle to segments of the first rectangle. This gives another set of 16 distances: $(d_{17},d_{18},...,d_{32})$.

The distance between rectangles is:

$$D=\min(d_1,d_2,...,d_{32})$$

Related Question