[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] One key press many events




> On Sep 17, 2020, at 5:16 AM, Daniel Foerster <pydsigner@xxxxxxxxx> wrote:
> 
> Jan:
> 
> Your player moves just once because you are listening for KEYDOWN events to move. KEYDOWN is only triggered when you first press a key. You can get the behavior you want in two ways.
> 
> Option 1: use pygame.key.get_pressed() to see the current state of the keys you want to check instead of examining events from the event queue. 
> 
> Option 2: have the UserInterface remember what KEYDOWNs have occurred and clear them when a KEYUP occurs.
> 
> — Daniel

To follow up on Option 1, you will need some code like this:

    keyPressedTuple = pygame.key.get_pressed()
           
    if keyPressedTuple[pygame.K_a]:  # moving left
        #  whatever you want to do here

    if keyPressedTuple[pygame.K_d]:  # moving right
        #  whatever you want to do here

    if keyPressedTuple[pygame.K_w]:  # moving up
        #  whatever you want to do here

    if keyPressedTuple[pygame.K_s]:  # moving down
        #  whatever you want to do here 

But this code should NOT be inside the for loop that handles events, because this is not based on events.  Instead, this code checks the state of the keyboard every time through your main loop.

Irv