Pygame player can jump for as long as it wants

87 views Asked by At

I'm trying to make a jumping method for my player in pygame. It goes up but I can just hold the space bar key down and it will go up for as long as I want and I don't know how to prevent it. Here's the code for my player 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()
1

There are 1 answers

0
Shiv On BEST ANSWER

The jump event changes the way the player is moving. When a key is released, then that speed is not reverted. Use the pygame keydown event, and then the keyup event.

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()