简体   繁体   中英

Pygame single push event

in Pygame i am trying to translate an image by 10% in each direction using each arrow key. right now the code i am using moves the image as long as the key is pushed down, what I want is for it to move only once regardless if the key is still pushed down or not.

if event.type == KEYDOWN:
    if (event.key == K_RIGHT):
        DISPLAYSURF.fill((255,255,255)) #Clears the screen
        translation_x(100)
        draw(1)
    if (event.key == K_LEFT):
        DISPLAYSURF.fill((255,255,255)) #Clears the screen
        translation_x(-100)
        draw(2)
    if (event.key == K_UP):
        DISPLAYSURF.fill((255,255,255)) #Clears the screen
        translation_y(100)
        draw(3)
    if (event.key == K_DOWN):
        DISPLAYSURF.fill((255,255,255)) #Clears the screen
        translation_y(-100)
        draw(4)

is there a simpler way of implementing this besides using time.sleep

You can use pygame.key.set_repeat() to disable repeated events from keys that are still down.

However, it should be disabled by default:

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.

When pygame is initialized the key repeat is disabled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM