【问题标题】:Moving sprites with key events in pygame在pygame中使用关键事件移动精灵
【发布时间】:2011-10-10 00:09:07
【问题描述】:

我刚刚让一个精灵使用“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 世界的新手,在询问之前我已经检查了很多手册和文档,希望你能提供帮助,谢谢。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    当按下 K_SPACE 时,您将 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.
    

    【讨论】:

    • 天哪,谢谢,删除“ypos = player.rect.top”解决了问题,现在我看到了,非常明显xD
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多