# Determine if a Rectangle is Inside, Overlaps, Doesn't Overlaps Another Rectangle

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

• You may possibly need more variables , as in your case , the rectangles can be rotated , which can consequently yield more than $1$ answer . Or are you assuming that the sides are parallel to the axes ? – Sinπ Jan 25 at 1:23
• Yes, the sides will be parallel to the axis. Rotation won't be necessary. – donfontaine12 Jan 25 at 1:33

## 1 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}$$

• What conditions will occur when the rectangle is completely inside? – donfontaine12 Jan 25 at 10:53
• It works for each condition now. Thank you. – donfontaine12 Jan 25 at 18:30