我有两个矩形,每个矩形的特征是4个值:
左侧位置X
,顶部位置Y
,宽度W
和高度H
:
X1, Y1, H1, W1
X2, Y2, H2, W2
矩形不会旋转,如下所示:
+--------------------> X axis
|
| (X,Y) (X+W, Y)
| +--------------+
| | |
| | |
| | |
| +--------------+
v (X, Y+H) (X+W,Y+H)
Y axis
确定两个矩形的交点是否为空的最佳解决方案是什么?
答案 0 :(得分:88)
if (X1+W1<X2 or X2+W2<X1 or Y1+H1<Y2 or Y2+H2<Y1):
Intersection = Empty
else:
Intersection = Not Empty
如果您有四个坐标 - ((X,Y),(A,B))
和((X1,Y1),(A1,B1))
- 而不是两个加宽度和高度,它将如下所示:
if (A<X1 or A1<X or B<Y1 or B1<Y):
Intersection = Empty
else:
Intersection = Not Empty
答案 1 :(得分:4)
最好的例子..
/**
* 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);
}
以及另一种方式看到这个link ...并自己编码......
答案 2 :(得分:2)
如果两个矩形具有相同的尺寸,您可以这样做:
if (abs (x1 - x2) < w && abs (y1 - y2) < h) {
// overlaps
}
答案 3 :(得分:0)
我刚试过一个c程序,并写在下面。
#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;
}
答案 4 :(得分:0)
使用坐标系,其中(0,0)是左上角。
我从垂直和水平滑动窗口的角度来考虑它 并提出这个:
(B.Bottom&gt; A.Top&amp;&amp; B.Top&lt; A.Bottom)&amp;&amp; (B.Right&gt; A.Left&amp;&amp; B.Left&lt; A.Right)
如果您将DeMorgan定律应用于以下内容,您将获得以下内容:
不是(B.Bottom&lt; A.Top || B.Top&gt; A.Bottom || B.Right&lt; A.Left || B.Left&gt; A.Right)
答案 5 :(得分:0)
如果左下角和右上角的矩形坐标为:
rect1和
的(r1x1,r1y1),(r1x2,r1y2)
rect2的(r2x1,r2y1),(r2x2,r2y2)
(Python如下代码所示)
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
答案 6 :(得分:-1)
if(X1 <= X2 + W2&amp;&amp; X2&lt; = X1 + W1&amp; Y1&gt; = Y2-H2&amp; Y2&gt; = Y1 + H1) 相交
问题Y是最高位置..
注意:此解决方案仅在矩形与X / Y轴对齐时才有效。