Python 在pygame中使用关键事件移动精灵

Python 在pygame中使用关键事件移动精灵,python,pygame,Python,Pygame,我刚刚用“w,a,s,d”让一个精灵在窗户周围移动,我想通过按空格键让这个精灵“射击” 我遇到的问题是,精灵出现了,但在我释放空格键之前不会移动,我想让精灵的快照一直向前,直到窗口结束,只需按下空格键,而不是释放它 这是我的主要循环: while pygame.event.poll().type != QUIT: screen.blit(background, (0, 0)) #"player" is the sprite moving around the window

我刚刚用“w,a,s,d”让一个精灵在窗户周围移动,我想通过按空格键让这个精灵“射击”

我遇到的问题是,精灵出现了,但在我释放空格键之前不会移动,我想让精灵的快照一直向前,直到窗口结束,只需按下空格键,而不是释放它

这是我的主要循环:

while pygame.event.poll().type != QUIT:


    screen.blit(background, (0, 0))

    #"player" is the sprite moving around the window
    player.move(width,height)
    screen.blit(player.image, player.rect)
    key = pygame.key.get_pressed()

    if key[K_SPACE]:
        xpos = player.rect.right
        ypos = player.rect.top
        shot_on_screen = True


    if shot_on_screen:
        xpos += 1
        #"kame" is the sprite i want to move forward
        screen.blit(shot.kame, (xpos, ypos))
    else:
        shot.x = player.rect.right
        shot.y = player.rect.top
        shot_on_screen = False


    pygame.display.update()

我是python pygame世界的新手,在询问之前我查阅了大量手册和文档,希望您能提供帮助,谢谢。

当按下K_空格时,您正在将xpos设置为每个循环中玩家最正确的位置。你不应该那样做。试着去掉那条线

if key[K_SPACE]:
    ypos = player.rect.top
    shot_on_screen = True
另外,我不知道您是否正在检查快照是否在代码的其他地方的屏幕上,但是您发布的代码不会将其设置为false

if shot_on_screen:
    xpos += 1
    #"kame" is the sprite i want to move forward
    screen.blit(shot.kame, (xpos, ypos))
else:
    shot.x = player.rect.right
    shot.y = player.rect.top
    shot_on_screen = False # won't work. It is already False.

当按下K_空格时,您将xpos设置为每个循环中玩家最正确的位置。你不应该那样做。试着去掉那条线

if key[K_SPACE]:
    ypos = player.rect.top
    shot_on_screen = True
另外,我不知道您是否正在检查快照是否在代码的其他地方的屏幕上,但是您发布的代码不会将其设置为false

if shot_on_screen:
    xpos += 1
    #"kame" is the sprite i want to move forward
    screen.blit(shot.kame, (xpos, ypos))
else:
    shot.x = player.rect.right
    shot.y = player.rect.top
    shot_on_screen = False # won't work. It is already False.
Omg谢谢,删除“ypos=player.rect.top”解决了问题,现在我看到了,这是非常明显的xDOmg谢谢,删除“ypos=player.rect.top”解决了问题,现在我看到了,这是非常明显的xD