矩形碰撞(C ++)

时间:2015-08-03 01:22:02

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

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

( // 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)
)
)

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

1 个答案:

答案 0 :(得分:0)

我是否正确理解一个矩形从 xpos 水平延伸到 xpos + w 并从 ypos 垂直延伸到 ypos + h ,另一个从 tx 水平延伸到 tex ,从 ty <垂直延伸/ em>到 tey ?使用 w h tex - tx tey - 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之一,这两个版本是等效的。)