1

I'm trying to get my character to move as long as the key is pressed but so far it moves once per single press and the key needs to be released for him to move again.

I've tried using the pygame.key.get_pressed() as shown and I can't figure out what's wrong with it.

def keyPressed(input_key):
    keysPressed = pygame.key.get_pressed()
    if keysPressed[input_key]:
        return True
    else:
        return False
...

run = True
while run:

    for event in pygame.event.get():
        if keyPressed(pygame.K_LEFT) and x > vel:
            x -= vel
...

1 Answer 1

1

You have to call pygame.key.get_pressed() in the application loop rather than the main loop. The event loop is only executed when an event occurs (like pygame.KEYDOWN). But the application loop is executed in every frame.
The typical use for pygame.key.get_pressed() may look as follows:

while run:

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

    #<---| Indentation

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and x > vel:
        x -= vel
    if keys[pygame.K_RIGHT] and x < width-vel:
        x += vel

    # [...]
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for answering, I have tried doing it exactly as you've written down but it still doesn't work. maybe it's something to do with Pycharm or a version of pygame..? I'm at a loss.
@Brandy Then you've another bug elsewhere. Did you respect the Indentation?
That was it! thank you! I thought I needed to put the keypress within the event.get() for some reason, that was dumb of me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.