I have two rectangles characterized by 4 values each :
Left position X
, top position Y
, width W
and height H
:
Best example..
/**
* Check if two rectangles collide
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
*/
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
and also one other way see this link ... and code it your self..
Using a coordinate system where (0, 0) is the left, top corner.
I thought of it in terms of a vertical and horizontal sliding windows and come up with this:
(B.Bottom > A.Top && B.Top < A.Bottom) && (B.Right > A.Left && B.Left < A.Right)
Which is what you get if you apply DeMorgan’s Law to the following:
Not (B.Bottom < A.Top || B.Top > A.Bottom || B.Right < A.Left || B.Left > A.Right)
If the rectangles' coordinates of the lower left corner and upper right corner are :
(r1x1, r1y1), (r1x2, r1y2) for rect1 and
(r2x1, r2y1), (r2x2, r2y2) for rect2
(Python like code below)
intersect = False
for x in [r1x1, r1x2]:
if (r2x1<=x<=r2x2):
for y in [r1y1, r1y2]:
if (r2y1<=y<=r2y2):
intersect = True
return intersect
else:
for Y in [r2y1, r2y2]:
if (r1y1<=Y<=r1y2):
intersect = True
return intersect
else:
for X in [r2x1, r2x2]:
if (r1x1<=X<=r1x2):
for y in [r2y1, r2y2]:
if (r1y1<=y<=r1y2):
intersect = True
return intersect
else:
for Y in [r1y1, r1y2]:
if (r2y1<=Y<=r2y2):
intersect = True
return intersect
return intersect
Should the two rectangles have the same dimensions you can do:
if (abs (x1 - x2) < w && abs (y1 - y2) < h) {
// overlaps
}
I just tried with a c program and wrote below.
#include<stdio.h>
int check(int i,int j,int i1,int j1, int a, int b,int a1,int b1){
return (\
(((i>a) && (i<a1)) && ((j>b)&&(j<b1))) ||\
(((a>i) && (a<i1)) && ((b>j)&&(b<j1))) ||\
(((i1>a) && (i1<a1)) && ((j1>b)&&(j1<b1))) ||\
(((a1>i) && (a1<i1)) && ((b1>j)&&(b1<j1)))\
);
}
int main(){
printf("intersection test:(0,0,100,100),(10,0,1000,1000) :is %s\n",check(0,0,100,100,10,0,1000,1000)?"intersecting":"Not intersecting");
printf("intersection test:(0,0,100,100),(101,101,1000,1000) :is %s\n",check(0,0,100,100,101,101,1000,1000)?"intersecting":"Not intersecting");
return 0;
}
if( X1<=X2+W2 && X2<=X1+W1 && Y1>=Y2-H2 && Y2>=Y1+H1 ) Intersect
In the question Y is the top position..
Note: This solution works only if rectangle is aligned with X / Y Axes.