对象碰撞适用于向右移动,但不适用于向左移动



所以我已经在这个项目上工作了一个星期左右,我还没有能够完善矩形物体碰撞。它适用于方块上方和下方的碰撞,甚至当你靠近方块的右侧时,但我不知道如何修复当玩家在左侧时的碰撞。

当你靠墙移动时效果很好,但当你在两个共享相同y坐标的方块之间向左移动时,玩家就会停下来,好像有一堵墙挡在路上。

这是与玩家右侧的块碰撞的代码,它按预期工作:

# character to the left of the block
if p1.x + p1.width / 2 < block.x and p1.dx > 0:
p1.dx = 0
p1.x = block.x - p1.width

然而这是导致问题的代码:

# player is to the right of the block
elif p1.x + p1.width/2 > block.x + block.width and p1.dx < 0:
p1.dx = 0
p1.x = block.x + block.width

使用轴对齐边界块方法检查碰撞,块的x和y坐标位于左上角。

对于任何试图解决这个问题的人,谢谢:)

可能需要添加其他条件:

if p1.x + p1.width / 2 < block.x < p1.x + p1.width and p1.dx > 0:
p1.dx = 0
p1.x = block.x - p1.width
elif p1.x < block.x + block.width < p1.x + p1.width/2 and p1.dx < 0:
p1.dx = 0
p1.x = block.x + block.width

使用pygame.Rect对象可以大大简化代码:

p1_rect = pygme.Rect(p1.x, p1.y, p1.width, p1.height)
block_rect = pygme.Rect(block.x, block.y, block.width, block.height)
if p1_rect.center < block_rect.left < p1_rect.right and p1.dx > 0:
p1.dx = 0
p1_rect.right = block_rect.left
p1.x = p1_rect.x
elif p1_rect.left < block_rect.right < p1_rect.center and p1.dx < 0:
p1.dx = 0
p1_rect.left = block_rect.right
p1.x = p1_rect.left

参见如何在pygame中检测碰撞?

相关内容

最新更新