开发者

Moving sprites with key events in pygame [duplicate]

This question already has answers here: How can I make a sprite move when key is held down (6 answers) Closed 3 months ago.

I just got a sprite moving around the window using "w,a,s,d", and i want to make this sprite "shoot" by pressing the space bar.

The problem i've got is that the sprite appears but doesn't move until i release the space bar, and i want the sprite shot to go forward until the end of the window, just by pressing the space bar, not by releasing it.

This is my main loop:

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()

I'm new at this python-pygame world, 开发者_如何学运维i've checked a lot of manuals and documentation before asking though, hope you can help, thanks.


You are setting xpos to the player most right position on every loop when the K_SPACE is pressed. You shouldn't do that. Try removing that line.

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

Also, I don't know if you are checking if the shot is on the screen somewhere else on the code, but the code you posted will not set it to 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜