0
votes

I have two objects that I control with my keboard, one with WASD and the other with the arrows. (Imagine a 2D game)

I recently made the code to make them keep moving while the key is pressed but if I keep pressing W and up arrow at the same time only one works and the other one stops. I would like to know a fix.

This is the movement code:

if e.type == pygame.KEYDOWN:

    if e.key==K_d:
        PX += movimentenpx
        EnergiaD +=energiapermoviment

    if e.key==K_a:
        PX -= movimentenpx
        EnergiaD +=energiapermoviment

    if e.key==K_w:

        PY -= movimentenpx
        EnergiaD +=energiapermoviment

    if e.key==K_s:

        PY += movimentenpx
        EnergiaD +=energiapermoviment

    if e.key ==K_UP:

        PY2 -= movimentenpx
        EnergiaD2 +=energiapermoviment

    if e.key ==K_LEFT:
        PX2 -= movimentenpx

        EnergiaD2 +=energiapermoviment

    if e.key ==K_DOWN:

        PY2 += movimentenpx
        EnergiaD2 +=energiapermoviment

    if e.key ==K_RIGHT:
        PX2 +=movimentenpx
        EnergiaD2 +=energiapermoviment
1
You might need to get a better keyboard. - khelwood
I just tryed it and it has nothing to do with the type of keyboard. - Alberto Dos Santos Rodriguez
Can you post the code? - Joyal Mathew

1 Answers

2
votes

Grabbing the key presses from for event in pygame.event.get(): will only get you one key press at a time. you need to use pygame.key.get_pressed() to grab the array of that state of the entire keyboard.

pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_w]:
    # do stuff
if pressed_keys[pygame.K_s]:
    # do stuff

This all happens in the main game loop. This is also the way to grab the keys if you want to hold down keys.

For more documentation: https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed