矩形碰撞 (C++)
Rectangle collision (C++)
我目前正在使用这个冲突代码:
( // 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)
)
)
但是,它只检测左上像素、右上像素、左下像素或右下像素是否在要测试的矩形内。我不知道该怎么做,我已经用了很长时间才达到我正在使用的当前碰撞测试方法,我可以更改什么来解决这个问题?
我理解正确吗,一个矩形从 xpos 水平延伸到 xpos + w并且从ypos垂直延伸到ypos + h,另一个从水平延伸tx 到 tex 和从 ty 垂直到 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之一,两个版本是等价的。)
我目前正在使用这个冲突代码:
( // 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)
)
)
但是,它只检测左上像素、右上像素、左下像素或右下像素是否在要测试的矩形内。我不知道该怎么做,我已经用了很长时间才达到我正在使用的当前碰撞测试方法,我可以更改什么来解决这个问题?
我理解正确吗,一个矩形从 xpos 水平延伸到 xpos + w并且从ypos垂直延伸到ypos + h,另一个从水平延伸tx 到 tex 和从 ty 垂直到 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之一,两个版本是等价的。)