两个矩形交叉点

Maj*_*ssi 53 algorithm math pseudocode shapes

我有两个矩形,每个矩形有4个值:

左侧位置X,顶部位置Y,宽度W和高度H:

X1, Y1, H1, W1
X2, Y2, H2, W2
Run Code Online (Sandbox Code Playgroud)

矩形不会旋转,如下所示:

+--------------------> X axis
|
|    (X,Y)      (X+W, Y)
|    +--------------+
|    |              |
|    |              |
|    |              |
|    +--------------+
v    (X, Y+H)     (X+W,Y+H)

Y axis
Run Code Online (Sandbox Code Playgroud)

确定两个矩形的交点是否为空的最佳解决方案是什么?

Tao*_*eng 91

if (X1+W1<X2 or X2+W2<X1 or Y1+H1<Y2 or Y2+H2<Y1):
    Intersection = Empty
else:
    Intersection = Not Empty
Run Code Online (Sandbox Code Playgroud)

如果你有四个坐标- ((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
Run Code Online (Sandbox Code Playgroud)

  • @AnkeshAnand交叉意味着布尔交叉 - 即矩形1的某个区域是否与矩形2的某个区域重叠 - 而不是矩形的"轮廓"是否相互交叉. (11认同)
  • 如果一个矩形完全位于另一个矩形内,则不起作用. (2认同)
  • 啊明白了。感谢您的澄清。我没有注意到这一点,因为就我而言,我关心的是*重叠*,而这个算法可以完美地处理它。 (2认同)

Xar*_*mer 5

最好的例子..

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

还有另一种方式看到这个链接......并自己编码..