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

How can I make a sprite move when key is held down(按住键时如何进行精灵移动)

本文介绍了按住键时如何进行精灵移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,每次按下一个键,精灵只会移动 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

这篇关于按住键时如何进行精灵移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:按住键时如何进行精灵移动

基础教程推荐