【问题标题】:Collision Detection rectangle/rectangle algorithm碰撞检测矩形/矩形算法
【发布时间】:2019-09-24 04:47:38
【问题描述】:

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

我正在尝试用矩形的图片和代码找出矩形/矩形的碰撞检测算法。根据 Jeff Thompson 的碰撞检测文章,有价值的 r1RightEdge 是 r1x + r1w。

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

图中蓝色矩形的r1RightEdge垂直点线是有价值的吗?如果是这样,为什么有价值的 r1RightEdge 是 r1x +r1w 而不是 r1x+r1h?

【问题讨论】:

  • 你被“垂直线”这个词弄糊涂了。您需要了解有关坐标的更多信息。这样想:当您在平面上沿水平(左/右)方向移动时,您正在更改“x”坐标。当您垂直移动(上/下)时,“y”正在发生变化。要从盒子的垂直右边缘通过,您必须水平移动(x 方向)。如果你垂直移动,你到右边缘线的距离将是固定的,你永远不会到达它。
  • 感谢您的解释!我现在明白了。

标签: html algorithm canvas collision-detection rectangles


【解决方案1】:

基于示例代码

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;

我理解 x(在您的情况下为:r1x)表示 r1 左上点的水平位置 - 或 R1LeftEdge,只有在我们添加 r1w(即宽度)时才有意义,因为它们都是水平的,结果是 r1 的水平右上点 - 或 R1RightEdge。 "r1x+r1h" 没有意义,因为一个是水平的,另一个是垂直的。

【讨论】:

  • 您的解决方案过于具体。我相信,它只适用于问题中提到的那种例子。
  • 似乎混淆OP的是变量命名,所以我试图解释它们的意思。
【解决方案2】:

一个通用且更简单的解决方案可以是:

// 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;

这也将处理矩形相交但任何矩形的角都不在其他角内的特殊情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多