2017-04-07 51 views
1

下面的代碼被設置,所以當頭像位移到屏幕並且敲擊空格鍵或向上鍵時,它會移動一次,但當它被按下時,它不會不斷地向上移動(在空中)。我需要改變我的代碼,所以當按住鍵的時候,移動是不變的。如何在按下pygame中的某個鍵時切換到不斷的移動?

import pygame, sys, time, random 
from pygame.locals import * 

class Player(Duck): 
    """The player controlled Duck""" 


    def __init__(self, x, y, width, height): 
     super(Player, self).__init__(x, y, width, height) 

     # How many pixels the Player duck should move on a given frame. 
     self.y_change = 0 
     # How many pixels the spaceship should move each frame a key is pressed. 
     self.y_dist = 50 


    def MoveKeyDown(self, key): 
     """Responds to a key-down event and moves accordingly""" 

     if (key == pygame.K_UP or key == K_SPACE): 
      self.rect.y -= self.y_dist 
    def MoveKeyUp(self, key): 
     """Responds to a key-up event and stops movement accordingly""" 

     if (key == pygame.K_UP or key == K_SPACE): 
      self.rect.y -= self.y_dist 


    def update(self): 
     """ 
     Moves the Spaceship while ensuring it stays in bounds 
     """ 
     # Moves it relative to its current location. 
     self.rect.move_ip(self.y_change, 0) 

     # If the Spaceship moves off the screen, put it back on. 
     if self.rect.y <= 0: 
      self.rect.y = 0 
     elif self.rect.y > window_width: 
      self.rect.y = window_width 

while True: # the main game loop 
    for event in pygame.event.get(): #Closes game 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     elif event.type == pygame.KEYUP: 
      player.MoveKeyUp(event.key) 
     elif event.type == pygame.KEYDOWN: 
      player.MoveKeyDown(event.key) 
+0

即使它被關閉作爲題外話,答案應該是幫助:http://stackoverflow.com/questions/43154793/in-pygame-why-can-i-not-move-my- sprite-while-button-is-held-down/43161906#43161906 – The4thIceman

+0

請提供[完整但很簡單的示例](http://stackoverflow.com/help/mcve)。我們需要可以不經調整就運行的示例。 – skrx

回答

0

MoveKeyDown方法您必須將self.y_change值設定爲所希望的速度,而不是調整self.rect.y值。 update方法中的self.rect.move_ip調用將移動精靈。您必須在主循環中的每一幀調用update方法。

def __init__(self, x, y, width, height): 
    super(Player, self).__init__(x, y, width, height) 
    # How many pixels the Player duck should move on a given frame. 
    self.x_change = 0 
    self.y_change = 0 
    # How many pixels the spaceship should move each frame a key is pressed. 
    self.speed = 50 

def MoveKeyDown(self, key): 
    """Responds to a key-down event and moves accordingly.""" 
    if key in (pygame.K_UP, pygame.K_SPACE): 
     self.y_change = -self.speed 

def MoveKeyUp(self, key): 
    if key in (pygame.K_UP, pygame.K_SPACE) and self.y_change < 0: 
     self.y_change = 0 

def update(self): 
    self.rect.move_ip(self.x_change, self.y_change) 
相關問題