我正在尝试创建一个“播放器”——黑色方块——当你按住 WASD 时它会移动。我试着在这里,在谷歌和 youtube 上查看如何使这项工作,但我尝试过的每个解决方案都有同样的问题:我不必在按住键的同时移动它,而是必须不断地点击键才能使它以小块移动。我不知道我做错了什么。这是代码(使用 python 3.3 - pygame 1.9):
import pygame
from pygame.locals import *
from pygame.time import *
import sys
pygame.init()
velX = 0
velY = 0
running = True
clock = pygame.time.Clock()
def draw():
global velX
global velY
playerx = 20
playery = 20
screen = pygame.display.set_mode((700,300))
pygame.display.set_caption('something')
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))
screen.blit(background, (0,0))
playerx = playerx + velX
playery = playery + velY
player_filename = 'player.png'
player = pygame.image.load(player_filename)
screen.blit(player, (playerx,playery))
pygame.display.flip()
def main():
global velX
global velY
global running
while running:
keys_down = pygame.key.get_pressed()
pygame.key.set_repeat(1, 50)
time = 50/1000
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running=False
if keys_down[K_d]:
velX += 50*time
if keys_down[K_w]:
velY -= 50*time
if keys_down[K_s]:
velY += 50*time
if keys_down[K_a]:
velX -= 50*time
clock.tick(50)
draw()
if __name__ == '__main__':
main()
我已经尝试了 set repeat 命令,但它似乎并没有做任何事情。我还尝试直接从我在 stackoverflow 上找到的一些解决方案中复制,但它们都不起作用。我想代码中还有其他问题。