简体   繁体   English

碰撞检测矩形/矩形算法

[英]Collision Detection rectangle/rectangle algorithm

http://jeffreythompson.org/collision-detection/rect-rect.phphttp://jeffreythompson.org/collision-detection/rect-rect.php

I am trying to figure out the algorithm of the collision detection of the rectangle/rectangle with the rectangles' picture and code.我试图用矩形的图片和代码找出矩形/矩形的碰撞检测算法。 According to Jeff Thompson's collision detection article, valuable r1RightEdge is r1x + r1w.根据 Jeff Thompson 的碰撞检测文章,有价值的 r1RightEdge 是 r1x + r1w。

float r1RightEdge = r1x + r1w;
if (r1RightEdge >= r2x) {
// right edge of r1 is past left edge of r2
}

Is valuable r1RightEdge vertical dot line of the blue rectangle in the picture?图中蓝色矩形的有价值的r1RightEdge垂直点线? If so, why is the valuable r1RightEdge is r1x +r1w instead of r1x+r1h?如果是这样,为什么有价值的 r1RightEdge 是 r1x +r1w 而不是 r1x+r1h?

Based on the example code基于示例代码

if (r1x + r1w >= r2x &&     // r1 right edge past r2 left
  r1x <= r2x + r2w &&       // r1 left edge past r2 right
  r1y + r1h >= r2y &&       // r1 top edge past r2 bottom
  r1y <= r2y + r2h) {       // r1 bottom edge past r2 top
    return true;
}
return false;

I under stand that x (in you case: r1x) mean horizontal position of the upper left dot of r1 - or R1LeftEdge, it only make sense if we add r1w (which is width) to it as they are both horizontal, the result is the horizontal upper right dot of r1 - or R1RightEdge.我理解 x(在你的情况下:r1x)表示 r1 左上点的水平 position - 或 R1LeftEdge,只有在我们添加 r1w(即宽度)时才有意义,因为它们都是水平的,结果是r1 - 或 R1RightEdge 的水平右上点。 "r1x+r1h" doesn't make sense because one is horizontal and the other is vertical. "r1x+r1h" 没有意义,因为一个是水平的,另一个是垂直的。

A generic and simpler solution can be:一个通用且更简单的解决方案可以是:

// If one rectangle is on left side of other 
if (r1x > r2x + r2w || r2x > r1x + r1w) 
    return false; 

// If one rectangle is above other 
if (r1y > r2y + r2h || r2y > r1y + r1h) 
    return false; 

// If none of the above meet then there will be a intersection
return true;

This will also handle the special case when rectangles intersect but none of the corner of any rectangle lies inside other.当矩形相交但任何矩形的角都不在其他角内时,这也将处理特殊情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM