如何在 Pygame 中用另一个对象(玩家)“推”一个对象(板条箱)?

问题描述 投票:0回答:0

我正在尝试使用 Pygame 制作一个可推动的板条箱。

我可以向各个方向(上、下、左、右)推动板条箱,效果很好。我还可以上下推动板条箱,同时左右移动。 问题是当我向左或向右推动箱子并同时向上或向下移动时,箱子会跳到我的玩家对象的顶部或底部。

我创建了一个 GIF 来向您展示我的意思:

我在我的 Player 类中使用方法/函数来处理推送:

def push(self, other):
    if self.this.colliderect(other):
        self.speed = 1
        if self.dx < 0:
            other.x = self.this.left - other.this.width
        elif self.dx > 0:
            other.x = self.this.right
        elif self.dy < 0:
            other.y = self.this.top - other.this.height
        elif self.dy > 0:
            other.y = self.this.bottom
    else:
        self.speed = 3

self.dx
self.dy
是update方法中赋值的变量,如下:

def update(self, x, y):
    self.dx = x
    self.dy = y
    self.rect.x += x
    self.rect.y += y

以下是我如何处理游戏循环中的移动:

    # Deal with movement related key presses
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_w:
            up = True
        if event.key == pygame.K_s:
            down = True
        if event.key == pygame.K_a:
            left = True
        if event.key == pygame.K_d:
            right = True

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_w:
            dy = 0
            up = False
        if event.key == pygame.K_s:
            dy = 0
            down = False
        if event.key == pygame.K_a:
            dx = 0
            left = False
        if event.key == pygame.K_d:
            dx = 0
            right = False

# Apply velocity to Player
if up:
    dy = -player.speed
if down: 
    dy = player.speed
if left:
    dx = -player.speed
if right:
    dx = player.speed

# Move the Player and check for wall/door collisions
if dx != 0:
    player.update(dx, 0)
    player.collision(level.wall_tiles)
    player.collision(level.door_tiles)
if dy != 0:
    player.update(0, dy)
    player.collision(level.wall_tiles)
    player.collision(level.door_tiles)

从逻辑上讲,看看我的

push()
方法,我可以明白为什么当我向左或向右推动板条箱时板条箱会弹出,因为我正在根据玩家的方向设置板条箱
y
位置。但是,我不明白为什么当我向上或向下推动板条箱并向左或向右移动板条箱时,板条箱没有发出提示音...

我最终只希望玩家能够推动板条箱而不会发出砰砰声。

我尝试了多种解决方案,比如检查

self.dx
self.dy
是否都处于活动状态,以及处理游戏循环中板条箱的行为,而不是附加到 Player 对象的方法。

我尝试的任何事情似乎都无法让推动动作按照我想要的方式行事。

如果它有助于检查我的整个游戏代码到目前为止,它是在这里

你对我如何正确处理这种互动有什么建议吗?

python pygame game-physics game-development collision
© www.soinside.com 2019 - 2024. All rights reserved.