0

I'm trying to write a 2D game in Python and I'm trying to call a function when I press and release Spacebar from my keyboard. If I'm using the function "is_pressed()" from keyboard it will be continuously called and glitch my program. Can you help, please?

Ralex4
  • 1

1 Answers1

0

You have to use the keyboard events instead. 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 (see pygame.event module) 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.

e.g.:

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run  = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # do something
                # [...]

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                # do something
                # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174