Pygame 跳转问题

Pygame jump issue

我正在通过开发平台游戏来学习 pygame 模块。

我从这个 Youtube 视频和频道中汲取灵感

跳跃行为和问题

我可以处理玩家如果不在平台上就无法跳跃的事实。

但是我发现当我同时按下左右键和跳转键跳转值是应有值的两倍

我有一个 class Game 来处理主游戏循环和另外两个精灵 classes PlayerPlatform.

class Game

在 class Game 中,我有一个方法 update,我在其中检查 平台 玩家.

class Game:
    # game main loop 
    def __init__(self):
        # ...
        self.hits = None
        # ...

    def update(self):

        # update all sprites in the sprites group
        self.all_sprites.update(self.all_events, self.hits)

        # check collision between player and platforms
        self.hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
        if self.hits:
            self.player.rect.bottom = self.hits[0].rect.top

class Player

在 class Player 中,我然后使用碰撞列表,仅当玩家与平台发生碰撞时才跳跃:

class Player(pygame.sprite.Sprite):
    # player class
    def __init__(self):
        #...

    def update(self, events, hits):
        keystate = pygame.key.get_pressed()            
        self.move_player(keystate)
        self.apply_gravity()
        self.jump(keystate, events, hits)

    def jump(keystate, events, hits):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if keystate[KEYS[self.player_data["jump"]]] and hits:
                    self.rect.y -= self.player_data["jumpPower"]

您可以找到 whole project code on github.

我在 animated gif 上捕获了这个问题:

你知道如何解决这个奇怪的行为吗?

问题在于,在您的 jump 方法中,您没有检查玩家是否按下了 跳跃按钮 event.key == KEYS[self.player_data["jump"]]

但是如果任何按钮被按下并且跳转按钮被按住怎么办?!这意味着,如果您设法在同一帧上按下两个按钮,则会从您的位置减去两次。

要修复,检查事件是否是跳转按钮:

def jump(keystate, events, hits):
    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == KEYS[self.player_data["jump"]] and hits:
                self.rect.y -= self.player_data["jumpPower"]