Pygame 玩家想跳多久就跳多久

Pygame player can jump for as long as it wants

我正在尝试为 pygame 中的播放器制作一个跳跃方法。它会上升,但我可以按住 space 栏键,它会上升到我想要的时间,我不知道如何防止它。这是我的播放器 class:

的代码
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pygame.Surface((32, 64))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)
        self.direction = pygame.math.Vector2(0, 0)
        self.speed = 8
        self.jump_speed = -16
        self.gravity = 0.8

    def get_input(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.direction.x = 1

        elif keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.direction.x = -1
        else:
            self.direction.x = 0
        
        if keys[pygame.K_SPACE] or keys[pygame.K_w] or keys[pygame.K_UP]:
            self.jump()
    
    def apply_gravity(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y
    
    def jump(self):
        self.direction.y = self.jump_speed

    def update(self):
        self.get_input()

jump事件改变了玩家移动的方式。当释放一个键时,该速度不会恢复。使用 pygame keydown 事件,然后是 keyup 事件。

import pygame
from pygame.locals import *

#Your code

while True:
  #Your event loop code
  for event in pygame.event.get():
      if event.type == KEYDOWN:
         if event.key == K_SPACE:
           player.jump()
      if event.type == KEYUP:
         if event.key == K_SPACE:
           player.revert_jump()
      if event.type == QUIT:
        pygame.quit()
        exit()