【问题标题】:Rectangle collision (C++)矩形碰撞 (C++)
【发布时间】:2015-08-03 09:30:11
【问题描述】:

我目前正在使用这个碰撞代码:

( // tx = other x, tex = other end x etc.
( // horizontal collision
(xpos >= tx && xpos <= tex)
||
((xpos + w) <= tex && (xpos + w) >= tx)
)
&&
( // vertical collision
(ypos >= ty && ypos <= tey)
||
((ypos + h) <= tey && (ypos + h) >= ty)
)
)

但是,它只检测左上像素、右上像素、左下像素或右下像素是否在要测试的矩形内。我不知道该怎么办,我现在使用的碰撞测试方法已经花了很长时间,我可以改变什么来解决这个问题?

【问题讨论】:

    标签: c++ collision-detection game-engine collision rect


    【解决方案1】:

    我是否正确理解一个矩形从 xpos 水平延伸到 xpos + w 并从 ypos 垂直延伸到ypos + h,另一个从tx水平延伸到tex,从ty 到 tey?使用 whtex - txtey - ty都是正面的?

    如果是这样,那么你可以这样写:

    xpos <= tex && xpos + w >= tx       // horizontal collision
    && ypos <= tey && ypos + h >= ty    // vertical collision
    

    或者,如果您计算它们碰撞的条件,您可能会发现更容易推理,只需添加!

    !(
        xpos > tex             // first rectangle entirely to right of second
        || xpos + w < tx       // first rectangle entirely to left of second
        || ypos > tey          // first rectangle entirely above second
        || ypos + h < ty       // first rectangle entirely below second
    )
    

    (由于De Morgan's laws 之一,这两个版本是等效的。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多