How to efficiently hold a key in Pygame?

前端 未结 7 1696
谎友^
谎友^ 2020-12-11 07:10

I\'ve found two related questions:

  • Pygame hold key down causes an infinite loop
  • pygame - on hold button down

But I want to be specific. H

7条回答
  •  独厮守ぢ
    2020-12-11 07:30

    Dominik's solution is the perfect one (separating event.get() from the keyboard ones). It works perfectly! Finally, no more problems with pygame's input.

    Flags:

    flag = False # The flag is essential.
    while not done:
        for e in event.get(): # At each frame it loops through all possible events.
            keys = key.get_pressed() # It gets the states of all keyboard keys.
            if e.type == QUIT:
                done = True
            if e.type == KEYDOWN: # If the type is KEYDOWN (DIFFERENT FROM "HELD").
                if keys[K_DOWN]: # And if the key is K_DOWN:
                    flag = True # The flag is set to true.
            elif e.type == KEYUP: # The very opposite.
                if keys[K_DOWN]:
                    flag = False
        if flag == True: # DON'T USE "while flag == true", it'll crash everything. At every frame, it'll check if the flag is true up there. It's important to remember that the KEYDOWN worked ONLY ONCE, and it was enough to set that flag. So, at every frame, THE FLAG is checked, NOT THE KEYDOWN STATE. Every "player movement" while a key is being held MUST be done through flags.
            print "DOWN"
    

提交回复
热议问题