Python – 按住键移动一个精灵的作品,但只在一个方向

我一直在testing用Python创建的格斗游戏的动作。

问题是,当我尝试移动精灵时,它会正确地向左移动,但只能在该方向上运行。 我认为问题出在我的事件处理循环上,但是我没有太多的经验,所以我不知道如何解决这个问题。 谷歌search,花一段时间做试验和错误是没有帮助的。

我的主循环如下所示:

pressedLeft = None pressedRight = None pressedUp = None pressedDown = None while True: #event handling for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: pressedLeft = True elif event.key == pygame.K_d: PressedRight = True elif event.key == pygame.K_w: PressedUp = True elif event.key == pygame.K_s: PressedDown = True elif event.type == pygame.KEYUP: if event.key == pygame.K_a: pressedLeft = False elif event.key == pygame.K_d: PressedRight = False elif event.key == pygame.K_w: PressedUp = False elif event.key == pygame.K_s: PressedDown = False # movement if pressedLeft: profx -= 5 elif pressedRight: profx += 5 elif pressedUp: profy -= 5 elif pressedDown: profy += 5 DisplaySurf.fill(white) DisplaySurf.blit(profImg, (profx, profy)) pygame.display.update() fpsClock.tick(FPS) 

你的variables名的大小写有问题。

对于pressedLeft使用小写的第一个字母,但对其他名称( PressedRight vs pressedRight ,上下相同)不小心。

这会导致在您的if创建从未使用的值。

语法着色帮助我马上find它。

这应该做的伎俩:

 pressedLeft = None pressedRight = None pressedUp = None pressedDown = None while True: #event handling for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: pressedLeft = True elif event.key == pygame.K_d: pressedRight = True elif event.key == pygame.K_w: pressedUp = True elif event.key == pygame.K_s: pressedDown = True elif event.type == pygame.KEYUP: if event.key == pygame.K_a: pressedLeft = False elif event.key == pygame.K_d: pressedRight = False elif event.key == pygame.K_w: pressedUp = False elif event.key == pygame.K_s: pressedDown = False # movement if pressedLeft: profx -= 5 elif pressedRight: profx += 5 elif pressedUp: profy -= 5 elif pressedDown: profy += 5 DisplaySurf.fill(white) DisplaySurf.blit(profImg, (profx, profy)) pygame.display.update() fpsClock.tick(FPS)