按住键时如何进行精灵移动

2022-01-29 00:00:00 python pygame

问题描述

目前,每次按下一个键,精灵只会移动 1 个像素.按住左键或右键时,如何使水管工精灵不断移动?

Currently the sprite only moves 1 pixel every time a key is pressed. How could I cause the plumber sprite to move constantly when left or right key is being held down?

while running:
    setup_background()
    spriteimg = plumberright

    screen.blit(spriteimg,(x1, y1))

    for event in pygame.event.get():
         if event.type == pygame.QUIT:
             running = False
         elif event.type == pygame.KEYDOWN:
             if event.key == pygame.K_UP:
                 x1 = x1 + 0
                 y1 = y1 - 1
             elif event.key == pygame.K_DOWN:
                 x1 = x1 + 0
                 y1 = y1 + 1
             elif event.key == pygame.K_LEFT:
                 x1 = x1 -1
                 y1 = y1 + 0
             elif event.key == pygame.K_RIGHT:
                 x1 = x1 + 1
                 y1 = y1 + 0

    pygame.display.flip()
    clock.tick(120)


解决方案

你可以使用 pygame.key.get_pressed 这样做.

You can use pygame.key.get_pressed to do that.

示例:

while running:
    keys = pygame.key.get_pressed()  #checking pressed keys
    if keys[pygame.K_UP]:
        y1 -= 1
    if keys[pygame.K_DOWN]:
        y1 += 1

相关文章