Fast rectangle to rectangle intersection(快速矩形到矩形交集)
问题描述
测试两个矩形是否相交的快速方法是什么?
What's a fast way to test if 2 rectangles are intersecting?
网上一搜就找到了这个单行代码(WOOT!),但我不明白如何用Javascript编写它,它似乎是用一种古老的C++形式编写的.
A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of 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
使函数起作用.
This is how that code can be translated to JavaScript. Note that there is a typo in your code, and in that of the article, as the comments have suggested. Specifically r2->right left
should be r2->right < r1->left
and r2->bottom top
should be r2->bottom < r1->top
for the function to work.
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
这篇关于快速矩形到矩形交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:快速矩形到矩形交集
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01