Can constant key input move a sprite constantly?

我只是一个虾纸丫 提交于 2019-12-01 11:40:05

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'

As an overview,

  • Listen for the KEYDOWN event in the pygame message queue.
  • Check if the key you're interested in is pushed down.
  • Move in that direction
  • Check message queue for KEYUP event that matches your key.
  • Stop moving.

Read the documentation as to how to implement this.

You normally use have a moving function in your update method that looks like this:

this.pos_x = direction * speed * delta

Now on your KEYDOWN events you set your direction to 1 or -1 and on KEYUP you set it back to 0. That way you have a nice constant movement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!