2011-10-10 42 views
2

我刚刚在窗口中使用“w,a,s,d”移动了一个精灵,我想通过按空格键使这个精灵“射击”。在pygame中使用关键事件移动精灵

我得到的问题是,精灵出现,但不会移动,直到我释放空格键,我想要精灵射击前进,直到窗口结束,只需按空格键,不是通过发布它。

这是我的主循环:

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

我在这条巨蟒,pygame的世界的新的,我问,虽然之前查了很多手册和文件的,希望你能帮助,谢谢。

回答

0

当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. 
+0

OMG感谢你,删除“ypos = player.rect.top”解决了这个问题,现在我看到它,这是非常明显的xD – Castell