2

I am struggling how I can make it so that when a key is pressed in Pygame, you aren't able to keep on holding the key. I am working on player jumps, but it doesn't work unless the key is only pressed once. Here is my keypress code:

keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and not self.jumping:
    self.jumping = True

And here is my jumping method (which also includes gravity)

def gravity(self):
        # if the player isn't jumping
        if not self.jumping:
            # set acceleration constant and accelerate
            self.accel_y = PLAYER_ACCELERATION
            self.y_change += self.accel_y

            # terminal velocity
            if abs(self.y_change) >= PLAYER_MAX_SPEED_Y:
                # set the y change to the max speed
                self.y_change = PLAYER_MAX_SPEED_Y

            self.y += self.y_change

        else: # jumping
            self.accel_y = -PLAYER_ACCELERATION_JUMPING
            self.y_change += self.accel_y

            if abs(self.y_change) >= PLAYER_MAX_SPEED_JUMPING:
                self.jumping = False

            self.y += self.y_change

            print(self.y_change)

The player can just keep on holding the up arrow key, and the player will fly - which is not good. I would like it so that you can only press once, and then self.jumping is set to False when it has reached it's top speed (which I have already implemented)

Caleb Shaw
  • 35
  • 4

1 Answers1

2

Don't use pygame.key.get_pressed() in this case, but use the keyboard events (see pygame.event).

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:

The keyboard events occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

For instance:

while True:

     for event in pygame.event.get():

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and not self.jumping:
                self.jumping = True
Rabbid76
  • 202,892
  • 27
  • 131
  • 174