我正在为学校项目制作 Pygame 程序。玩家角色将穿过敌方 Sprite 而不触发碰撞。我该如何解决这个问题?
如果两个 Sprite 之间有任何重叠,则应运行 CODE。
if CharY > thing_starty and CharY < thing_starty + Enemy2_height or CharY+PCHeight > thing_starty and CharY + PCHeight < thing_starty + Enemy2_height:
if CharX > thing_startx and CharX < thing_startx + Enemy2_width or CharX + PCWidth > thing_startx and CharX + PCWidth < thing_startx + Enemy2_width:
CODE
最佳答案
我建议使用pygame.Rect
对象和.colliderect()
检查两个矩形的碰撞:
# detects collisions
charRect = pg.Rect(CharX, CharX, PCWidth, PCHeight)
enemyRect = pg.Rect(thing_startx, thing_starty, Enemy2_width, Enemy2_height)
if charRect.colliderect(enemyRect):
# [...]
# CODE
<小时/>
如果您想自己进行碰撞检测,那么您必须检查矩形在两个维度上是否重叠。
范围 [x1
, x1+w1
] 与范围 [x2
, x2+w2
] 重叠如果满足以下条件:
intersect = x1 < x2+w2 and x2 < x1+w1
注意,w1
和 w2
必须大于 0。
对两个维度都执行此操作:
if CharX < thing_startx + Enemy2_width and thing_startx < CharX + PCWidht and \
CharY < thing_starty + Enemy2_height and thing_starty < CharY + PCHeight
# [...]
# CODE
关于python - pygame 中的碰撞不起作用(对象发生碰撞但代码未触发),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836336/