2013-01-10 79 views
0

我可以讓我的對象停下來。一旦我按下w,a,s或d就會移動,但不會停止。當我按其中一個方向時,它會移動但不會停止。我釋放密鑰時需要停止。所有類型的幫助將不勝感激。繼承人我的代碼:如何讓我的對象停下來?

while (running == 1): 
    screen.fill(white) 
    for event in pygame.event.get(): 
     if (event.type == pygame.QUIT): 
      running = 0 
     elif (event.type == pygame.KEYDOWN): 
      if (event.key == pygame.K_d): 
       dir = "R" 
      elif (event.key == pygame.K_a): 
       dir = "L" 
      elif (event.key == pygame.K_s): 
       dir = "D" 
      elif (event.key == pygame.K_w): 
       dir = "U" 
      elif (event.key == pygame.K_ESCAPE): 
       sys.exit(0) 
      elif (event.key == pygame.K_SPACE): 
       shot=True 
       xbul=xgun 
       ybul=ygun 
      #if key[K_SPACE]: 
       #shot = True 


    #OBJECT'S MOVEMENTS 
    if (dir == "R" and xgun<595): 
     xgun = xgun + 3 
     pygame.event.wait 
    elif (dir == "L" and xgun>0): 
     xgun = xgun - 3 
     pygame.event.wait 
    elif (dir == "D" and ygun<460): 
     ygun = ygun + 3 
     pygame.event.wait 
    elif (dir == "U" and ygun>0): 
     ygun = ygun - 3 

    screen.blit(gun, (xgun,ygun)) 
    #PROJECTILE MOTION 
    #key = pygame.key.get_pressed() 

    if shot == True: 
     xbul = xbul + 3 
     screen.blit(bullet, (xbul, ybul)) 

    if xbul>600: 
     shot=False 

    pygame.display.flip() 
    time.sleep(0.01) 
+0

,你總是可以設置'目錄== S'在循環的開始,然後檢查特定鍵被按下。 – ninMonkey

回答

6

你應該趕上pygame.KEYUP並停止當前的運動。

+0

謝謝!它確實有用! – Whosyourdaddy

+0

@IraGabrielGarcia你應該爲你的問題選擇一個答案,以便它對其他人有用。 – ATOzTOA

0

使用pygame.key.get_pressed()

如果使用,有getstate代替也就是說

key = pygame.key.get_pressed() 
if key[pygame.K_d]: 
    dir = "R" 
elif key[pygame.K_a]: 
    dir = "L" 
elif key[pygame.K_s]: 
    dir = "D" 
elif key[pygame.K_w]: 
    dir = "U" 
elif key[pygame.K_ESCAPE]: 
    sys.exit(0) 
elif key[pygame.K_SPACE]: 
    shot = True 
    xbul = xgun 
    ybul = ygun 
else:   # If none of the keys is pressed, Stop. 
    dir = 'S' 
相關問題