这是一个用c++快速检查两个矩形是否重叠的方法:
return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)
&& std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);
它的工作原理是计算相交矩形的左右边界,然后比较它们:如果右边界等于或小于左边界,这意味着交点是空的,因此矩形不重叠;否则,它将再次尝试顶部和底部边框。
What is the advantage of this method over the conventional alternative of 4 comparisons? It's about how modern processors are designed. They have something called branch prediction, which works well when the result of a comparison is always the same, but have a huge performance penalty otherwise. However, in the absence of branch instructions, the CPU performs quite well. By calculating the borders of the intersection instead of having two separate checks for each axis, we're saving two branches, one per pair.
如果第一个比较有很高的错误几率,那么四个比较方法可能比这个方法更好。但这是非常罕见的,因为这意味着第二个矩形通常在第一个矩形的左边,而不是在右边或重叠;大多数情况下,您需要检查第一个矩形的两侧,这通常会使分支预测的优势失效。
根据矩形的预期分布,这种方法还可以进一步改进:
If you expect the checked rectangles to be predominantly to the left or right of each other, then the method above works best. This is probably the case, for example, when you're using the rectangle intersection to check collisions for a game, where the game objects are predominantly distributed horizontally (e.g. a SuperMarioBros-like game).
If you expect the checked rectangles to be predominantly to the top or bottom of each other, e.g. in an Icy Tower type of game, then checking top/bottom first and left/right last will probably be faster:
return std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom)
&& std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right);
然而,如果相交的概率接近于不相交的概率,那么最好有一个完全无分支的替代方案:
return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)
& std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);
(注意&&变成了一个&)