7

How can I calculate the minimum distance between two rectangles?
It is easy for rectangles which have no angles (i.e. 0 degrees one), but for rotated rectangles with any different angles I do not know how to do it.

Can you recommend any way?

WhiteFlare

eraxillan
  • 1,552
  • 1
  • 19
  • 40
WhiteFlare
  • 73
  • 1
  • 3

2 Answers2

3
  1. Calculate coordinates of all 8 points of 2 rectangles.
  2. Take the two lowest distances among all 4 * 4 = 16 pairs of points (points from different rectangles). And get the 3 points P1, P2 and P3 {Two of them belong to one rectangle and the third to the other}
  3. The 2 Points belong to one rectangle should considered as segment, Now find the Short distance between a segment and the third point.
Waleed A.K.
  • 1,596
  • 13
  • 13
  • Because of (3), your method won't work for two parallel segments where one is longer than the other (and who share the same x-coord somewhere in the middle if they're parallel to the latter axis) – Hakim Mar 24 '23 at 17:06
1
  1. Check either they intersect first (try to take point from one rectangle and check either it is inside other rectangle).
    There are several ways to do it. One method (not the best one, but easy to explain) is the following.
    Let A1, A2, A3, A4 - rectangle points, T - some other point.
    Then count squares for triangles:
    S1 = (A1,A2,T), S2 = S(A2,A3,T), S3 = S(A3, A4, T), S4 = S(A4, A1, A2).
    Let S_rectangle be reactangle square.
    Then T lies inside rectangle <=> S1 + S2 + S3 + S4 = S_rectangle.

    If reactangles don't intersect each other, then do these steps.

  2. Calculate coordinates of all 8 points of 2 rectangles.

  3. Take minimum among all 4 * 4 = 16 pairs of points (points from different rectangles).
    Let's denote it min_1.

  4. Then, take some point from the first rectangle (4 ways to do it),
    take 4 segments of another rectangle (4 ways),
    check either perpendicular from that point to that segment gets inside segment.
    Take the mininmum of such perpendiculars. Let's denote it min_2.

  5. The same as in 3, but take point from the second rectangle, lines from the first:
    you get min_3.

  6. result = min(min_1, min_2, min_3)

eraxillan
  • 1,552
  • 1
  • 19
  • 40
Max
  • 4,792
  • 4
  • 29
  • 32
  • @BlueRaja - Danny Pflughoeft, then, the distance equals zero, I edited my answer. – Max Jun 14 '10 at 20:56