【问题标题】:Object collision works for the right movement, but not left对象碰撞适用于右运动,但不适用于左运动
【发布时间】:2021-11-03 15:57:17
【问题描述】:

所以我已经在这个项目上工作了一周左右,我还没有能够完善矩形对象的碰撞。它适用于块上方和下方的碰撞,甚至当你在块的右侧时,但我无法弄清楚当玩家在左侧时如何修复碰撞。

当你靠墙移动时效果很好,但是当你在两个共享相同 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 坐标位于左上角。

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

【问题讨论】:

    标签: python pygame collision


    【解决方案1】:

    您可能需要添加其他条件:

    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
    

    另见How do I detect collision in pygame?

    【讨论】:

    • 非常感谢这有很大帮助(即使我必须对其进行一些调整以适应我的代码;))。我会赞成,但我在这里的代表太低了 lmao
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多