1

I am trying to implement a functionality where my character on the screen is movable by holding down the WASD keys, while pressing spacebar should cause my character to attack. The user shouldn't be able to hold the spacebar in order to attack, while simultaneously being able to hold down the WASD keys to move. This implementation causes the expected behaviour for attacks, but it causes the movement to also be activated by pressing down a key, thus making it impossible to hold down WASD to move:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        sys.exit()
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_w]:
        pos_y += speed                   //change y-position by the value of speed
    if pressed[pygame.K_a]:
        pos_x -= speed
    if pressed[pygame.K_s]:
        pos_y -= speed
    if pressed[pygame.K_d]:
        pos_x += speed

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            attack()                    //execute attack logic - irrelevant for this example

Is there a way to differentiate whether the key is held down or just pressed down?

1 Answers1

1

pygame.key.get_pressed() returns a sequence 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. You have to call pygame.key.get_pressed() in the application loop instead of the event loop:

# application loop
while True:

    #event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                attack() 

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_w]:
        pos_y += speed      
    if pressed[pygame.K_a]:
        pos_x -= speed
    if pressed[pygame.K_s]:
        pos_y -= speed
    if pressed[pygame.K_d]:
        pos_x += speed

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174