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.
I have now come up myself with a solution that I am still not 100% sure that it is correct, but I have tested it for many examples and it seems to work. Also I am not sure if there isn't a more elegant/efficient solution. But in case anyone has the same problem I wanted to share my solution here:
For a given function
$$
\operatorname{\tau}(x):={\begin{cases}-1&{\text{if }}|x|>0.5,\\1&{\text{else}}\end{cases}}
$$
the angel should be defined by
$$
a(x_1, y_1, x_2, y_2) = atan2(\tau(y_2-y_1) \cdot (y_2-y_1), \tau(x_2-x_1) \cdot(x_2, x_1))
$$
or in a (for me) more intuitive python code way:
def angle_computation(x1, y1, x2, y2):
if abs(x2 - x1) < (1 - abs(x2 - x1)):
deltax = x2 - x1
else:
deltax = (x2 - x1) * - 1
if abs(y2 - y1) < (1 - abs(y2 - y1)):
deltay = y2 - y1
else:
deltay = (y2 - y1) * - 1
return math.atan2(deltay, deltax)
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:
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$$
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)$$
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})$$