快速矩形到矩形相交
什么是测试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
);
}
这是如何将该代码转换为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);
}
测试用例:
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
只是要添加/确认 - 这是测试三个20px x 20px的盒子,除了rectB,它是30px x 30px – verenion 2013-03-20 12:29:20
如果r1和r2相同,intersectRect函数将返回false – zumalifeguard 2013-09-23 15:28:31
Fantastic雄辩实现。爱它! +1,完美地为我的游戏工作。 – Unome 2014-09-04 22:37:21
function intersect(a, b) {
return (a.left <= b.right &&
b.left <= a.right &&
a.top <= b.bottom &&
b.top <= a.bottom)
}
这假定top
通常小于bottom
(即该y
坐标向下增加)。
这是.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;
}
或者静态版本:
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;
}
另一个更简单办法。 (这假定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);
}
上述条件中的4个数字(最大值和最小值)也给出了交点。
这有一个可以使用的矩形类型。 它已经是JavaScript了。
https://dxr.mozilla.org/mozilla-beta/source/toolkit/modules/Geometry.jsm
此代码将针对Rects A(0,0,100,100)&B(100,100,100,100)返回false。我认为theres应该是 2016-11-02 11:50:32
englebart 2016-11-16 21:05:57
我想你已经在你的副本有一个错字/粘贴 – fmark 2010-05-02 03:35:26
好了,这是从哪儿它,它看起来同我 - http://tekpool.wordpress.com/2006/ 10/11/rectangle-intersection-determining-if-two-given-rectangles-intersect-each-other-or-not/ – 2010-05-02 03:36:50
原文有一个错字。 'r2->左'没有意义。由于HTML转义问题,它可能会被破坏。 – 2010-05-02 03:41:53