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
$\endgroup$ 22 Answers
$\begingroup$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}$$
$\endgroup$ 2 $\begingroup$1- You can calculate x distance and y distance by writing $x_1 - x_2$ or $x_2 - x_1$ (it's depend on the bigger number), and it's the same in y distance.
2- You can use this formal ( xDistance $\leq (w_1 - w_2)/2$ and same her with y). from this point you can conclude that the rectangle is inside.
3- Overlap: the same as 2-step, but instead of $-$ write $+$
$\endgroup$