1
$\begingroup$

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$
  • $\begingroup$ 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 ? $\endgroup$ – Sinπ Jan 25 at 1:23
  • $\begingroup$ Yes, the sides will be parallel to the axis. Rotation won't be necessary. $\endgroup$ – donfontaine12 Jan 25 at 1:33
1
$\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$
  • $\begingroup$ What conditions will occur when the rectangle is completely inside? $\endgroup$ – donfontaine12 Jan 25 at 10:53
  • $\begingroup$ It works for each condition now. Thank you. $\endgroup$ – donfontaine12 Jan 25 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.