明月笑刀無情
2019-12-25 14:35:31
測試2個矩形是否相交的快速方法是什么?在Internet上進行了搜索,找到了這種單行代碼(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 );}
3 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
.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;
}
添加回答
舉報
0/150
提交
取消