Using the center's x- and y-coordinates, width and length of each rectangle, determine if the second rectangle is inside, overlaps or doesn't overlap the first rectangle.
I know that if I divide the width or height by 2, I will get the reach of both sides of rectangle, horizontally and vertically. I can't seem to come up with a formula to solve for each condition.
Here's the list of variables I'm using:
Rectangle 1: x1, y1, width1, height1
Rectangle 2: x2, y2, width2, height2
Here's the formulas I'm coming up with:
The absolute value of the horizontal distance = x1 – x2
The absolute value of the vertical distance = y1 – y2
Or is it better to subtract the smaller number from the larger one?
Any ideas? Thank you
Best Answer
If any of the following are true, the rectangles don't intersect, otherwise they do: $$x_1+\frac{w_1}{2} < x_2-\frac{w_2}{2}$$ $$x_1-\frac{w_1}{2} > x_2+\frac{w_2}{2}$$ $$y_1+\frac{h_1}{2} < y_2-\frac{h_2}{2}$$ $$y_1-\frac{h_1}{2} > y_2+\frac{h_2}{2}$$
Edit
For the second rectangle to be inside the first, all of the following must be true:
$$x_2+\frac{w_2}{2} \le x_1+\frac{w_1}{2}$$ $$x_2-\frac{w_2}{2} \ge x_1-\frac{w_1}{2}$$ $$y_2+\frac{h_2}{2} \le y_1+\frac{h_1}{2}$$ $$y_2-\frac{h_2}{2} \ge y_1-\frac{h_1}{2}$$