快速矩形到矩形交叉

Rob*_*cks 78 javascript c++ language-agnostic graphics

什么是测试2个矩形相交的快速方法?


在互联网上搜索想出了这个一行代码(WOOT!),但我不知道如何把它写在Javascript中,似乎在一个古老的形式C++来编写.

struct
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} RECT; 

bool IntersectRect(const RECT * r1, const RECT * r2)
{
    return ! ( r2->left > r1->right
        || r2->right < r1->left
        || r2->top > r1->bottom
        || r2->bottom < r1->top
        );
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*llo 136

这就是将代码转换为JavaScript的方式.请注意,您的代码中存在拼写错误,并且正如文章的那些拼写错误一样.具体r2->right left应该是r2->right < r1->left,r2->bottom top应该是r2->bottom < r1->top功能工作.

function intersectRect(r1, r2) {
  return !(r2.left > r1.right || 
           r2.right < r1.left || 
           r2.top > r1.bottom ||
           r2.bottom < r1.top);
}
Run Code Online (Sandbox Code Playgroud)

测试用例:

var rectA = {
  left:   10,
  top:    10,
  right:  30,
  bottom: 30
};

var rectB = {
  left:   20,
  top:    20,
  right:  50,
  bottom: 50
};

var rectC = {
  left:   70,
  top:    70,
  right:  90,
  bottom: 90
};

intersectRect(rectA, rectB);  // returns true
intersectRect(rectA, rectC);  // returns false
Run Code Online (Sandbox Code Playgroud)

  • 如果r1和r2相同,则intersectRect函数将返回false (6认同)

DS.*_*DS. 65

function intersect(a, b) {
  return (a.left <= b.right &&
          b.left <= a.right &&
          a.top <= b.bottom &&
          b.top <= a.bottom)
}
Run Code Online (Sandbox Code Playgroud)

这假设top通常小于bottom(即y坐标向下增加).

  • 只要其中一个条件评估为假,也会执行此操作.即在与另一个完全相同的情况下. (18认同)
  • +1,比接受的答案更整洁.如果使用半开范围(即矩形包括顶部和左边但不包括底部和右边,这在许多图形系统中很常见),将`<=`更改为`<`应该有效. (4认同)
  • 这更好,因为它删除了否定操作. (3认同)

小智 19

这就是.NET Framework实现Rectangle.Intersect的方式

public bool IntersectsWith(Rectangle rect)
{
  if (rect.X < this.X + this.Width && this.X < rect.X + rect.Width && rect.Y < this.Y + this.Height)
    return this.Y < rect.Y + rect.Height;
  else
    return false;
}
Run Code Online (Sandbox Code Playgroud)

或静态版本:

public static Rectangle Intersect(Rectangle a, Rectangle b)
{
  int x = Math.Max(a.X, b.X);
  int num1 = Math.Min(a.X + a.Width, b.X + b.Width);
  int y = Math.Max(a.Y, b.Y);
  int num2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
  if (num1 >= x && num2 >= y)
    return new Rectangle(x, y, num1 - x, num2 - y);
  else
    return Rectangle.Empty;
}
Run Code Online (Sandbox Code Playgroud)


Duk*_*uke 5

另一个更简单的方法。(假设y轴向下增加)。

function intersect(a, b) {
  return Math.max(a.left, b.left) < Math.min(a.right, b.right) &&
          Math.max(a.top, b.top) < Math.min(a.bottom, b.bottom);
}
Run Code Online (Sandbox Code Playgroud)

上面条件中的4个数字(最大值和最小值)也给出了交点。