Can constant key input move a sprite constantly?

后端 未结 3 528
深忆病人
深忆病人 2021-01-16 05:31

If I want to move a sprite based on key input in pygame, is there anyway to write code so if I hold down a key, the sprite will keep moving in that direction until I release

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-16 05:52

    The OP wants keystate polling, not KEYDOWN events.

    This example shows using both key events, and key polling. You use one for 'on key press' and the other for 'while held down'.

    import pygame
    from pygame.locals import *
    
    done = False    
    player.pos = Rect(0,0,10,10)
    
    while not done:
        for event in pygame.event.get():
            # any other key event input
            if event.type == QUIT:
                done = True        
            elif event.type == KEYDOWN:
                if event.key == K_ESC:
                    done = True
    
        # get key current state
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]:
            player.pos.left -= 10
        if keys[K_RIGHT]:
            player.pos.left += 10
        if keys[K_UP]:
            player.pos.top -= 10
        if keys[K_DOWN]:
            player.pos.left += 10
        if keys[K_SPACE]: 
            print 'firing gun'
    

提交回复
热议问题