我目前正在使用pygame进行游戏,但是当我改变方向时,我停下来并且必须再次按箭头键。它看起来不是一个大问题,但它很容易让人讨厌。
这是代码(它在游戏循环中编写,所以这不是问题):
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
coordsX = coordsX - 0.1
elif event.key == K_RIGHT:
coordsX = coordsX + 0.1
elif event.key == K_UP:
coordsY = coordsY - 0.1
elif event.key == K_DOWN:
coordsY = coordsY + 0.1
elif event.key == K_LEFT and event.key == K_UP:
coordsX = coordsX - 0.1
coordsY = coordsY - 0.1
elif event.key == K_LEFT and event.key == K_DOWN:
coordsX = coordsX - 0.1
coordsY = coordsY + 0.1
elif event.key == K_RIGHT and event.key == K_UP:
coordsX = coordsX + 0.1
coordsY = coordsY - 0.1
elif event.key == K_RIGHT and event.key == K_DOWN:
coordsX = coordsX + 0.1
coordsY = coordsY + 0.1
答案 0 :(得分:1)
我在上述评论中的含义示例:
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
moving_left = True
elif event.key == K_RIGHT:
moving_right = True
elif ....
elif event.type == pygame.KEYUP:
if event.key == K_LEFT:
moving_left = False
elif event.key == K_RIGHT:
moving_right = False
elif ....
if moving_left:
coordsX = coordsX - 0.1
if moving_right:
coordsX = coordsX + 0.1
if ...
答案 1 :(得分:0)
对于这种情况,您可能在按下按键或按顺序时不在乎,但您确实想知道按下了哪些按键。相反,您可能希望查看pygame.key.get_pressed。
主循环看起来更像是
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
coordsX -= 0.1
if keys[K_RIGHT]:
coordsX += 0.1
...
另外,在这里跳过使用elif,条件会照顾好自己。