I have two rectangles characterized by 4 values each :
Left position X
, top position Y
, width W
and height H
:
X1, Y1, H1, W1 X2, Y2, H2, W2
Rectangles are not rotated, like so:
+--------------------> X axis | | (X,Y) (X+W, Y) | +--------------+ | | | | | | | | | | +--------------+ v (X, Y+H) (X+W,Y+H) Y axis
What is the best solution to determine whether the intersection of the two rectangles is empty or not?
In order to check that two rectangles intersect all that's needed is x1 < x4 && x3 < x2 && y1 < y4 && y3 < y2 . That's it. (I used strict inequalities to exclude touching rectangles.)
Suppose there is a rectangle that is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Now two rectangles overlap if the area of their intersection is positive.
Rectangle rect1 = new Rectangle(100, 100, 200, 240); Rectangle rect2 = new Rectangle(120, 80, 80, 120); Rectangle intersection = rect1. intersection(rect2); say (x1, y1), (x2, y2) are bottom-left and bottom-right corners of Rect1 respectively, (x3, y3), (x4, y4) are those of Rect2.
Two rectangles do not overlap if one of the following conditions is true. 1) One rectangle is above top edge of other rectangle. 2) One rectangle is on left side of left edge of other rectangle.
if (X1+W1<X2 or X2+W2<X1 or Y1+H1<Y2 or Y2+H2<Y1): Intersection = Empty else: Intersection = Not Empty
If you have four coordinates – ((X,Y),(A,B))
and ((X1,Y1),(A1,B1))
– rather than two plus width and height, it would look like this:
if (A<X1 or A1<X or B<Y1 or B1<Y): Intersection = Empty else: Intersection = Not Empty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With