How to use pygame.KEYDOWN?

后端 未结 4 1424
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 12:59

So, my question was most likely already asked, but I didn\'t know what to search for, and didnt find much. So, my problem is, I made 2 functions, which would check for an e

相关标签:
4条回答
  • 2020-11-29 13:26

    Use pygame.key.set_repeat().

    set_repeat(delay, interval) -> None.

    When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay is the number of milliseconds before the first repeated pygame.KEYDOWN will be sent. After that another pygame.KEYDOWN will be sent every interval milliseconds. If no arguments are passed the key repeat is disabled.

    0 讨论(0)
  • 2020-11-29 13:27
    event.key == chr('a') 
    

    event.key returns the ascii of the key

    0 讨论(0)
  • 2020-11-29 13:32

    Use pygame.KEYDOWN and pygame.KEYUP to detect if a key is physically pressed down or released. You can activate keyboard repeat by using pygame.key.set_repeat to generate multiple pygame.KEYDOWN events when a key is held down, but that's rarely a good idea.

    Instead, you can use pygame.key.get_pressed() to check if a key is currently held down:

    while True:
        ...
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_w]:
           print("w is pressed")
        if pressed[pygame.K_s]:
           print("s is pressed")
    
    0 讨论(0)
  • 2020-11-29 13:35

    I would advice you to stick with the event-driven approach rather than using a polling mechanism.

    You should let the key events alter some internal state to reflect a pressed key imo.

    Example: You are controlling a spaceship with your keyboard. You want the propulsion rockets to fire when you press one of 'w', 's', 'a' or 'd' to make the ship accelerate in a certain direction:

    • On pygame.KEYDOWN event, set an appropriate acceleration vector for the object if event.key in [K_w, K_s, K_a, K_d].
    • On pygame.KEYUP event, set the acceleration vector to the zero vector if event.key in [K_w, K_s, K_a, K_d].

    This will effectively make the object accelerate while a movement key is pressed, and stop accelerating when the key is released.

    0 讨论(0)
提交回复
热议问题