#Assume two surfaces
objectA
objectB
if objectA.right > objectB.left and objectA.left < objectB.right and objectA.top < objectB.bottom and objectA.bottom > objectB.top
#Collision happens
如果你想检测侧面碰撞(好像objectA在侧面碰到了objectB),你可以执行以下操作:
#Here is the code where objectA moves
objectA.X += 10
#Here check Collision, if collision happens objectA hitted objectB from the side
objectA.Y += 10
#Here check Collision again, if collision is true then objectA hitted object B from top/bottom
3 回答
在PyGame中没有任何功能可以让双方碰撞 .
但您可以尝试使用pygame.Rect.collidepoint来测试
A.rect.midleft
,A.rect.midright
,A.rect.midtop
,A.rect.midbottom
,A.rect.topleft
,A.rect.bottomleft
,A.rect.topright
,A.rect.bottomright
是否在B.rect
(pygame.Rect)内 .EDIT:
示例代码 . 使用箭头移动玩家并触摸敌人 .
(可能它不是最佳解决方案)
EDIT (08.2016): 版本与colllisions
rect
,rect_ratio
,circle
GitHub:furas/python-examples/pygame/collisions
就像Furas说的那样,没有,没有办法在Pygame中通过他 Build 的点系统获得侧面碰撞 . 即使那个人也不会给你你想要的东西,因为在处理矩形的行,列或角时,你永远无法确定碰撞的方向 .
这就是为什么大多数教程都建议保存精灵的初始方向 . 然后在发生碰撞时向相反方向移动 .
碰撞背后的逻辑是这样的:
如果你想检测侧面碰撞(好像objectA在侧面碰到了objectB),你可以执行以下操作: