2011-03-18 60 views
3

我正在製作一款自頂向下的賽車遊戲,它會順利進行,直到我遇到我的舊剋星...我想讓汽車旋轉,當你按左和右鍵(已經完成該部分),精靈的旋轉以度爲單位存儲在變量中。我希望能夠按照它面臨的方向加速移動。我可以自己弄清楚加速度部分,它只是確定在那個方向上的哪個像素。任何人都可以給我一些簡單的代碼來幫助這個嗎?PYGAME讓精靈在朝着它的方向移動

這裏有類是relavent內容:

def __init__(self, groups): 
    super(Car, self).__init__(groups) 
    self.originalImage = pygame.image.load(os.path.join("Data", "Images", "Car.png")) #TODO Make dynamic 
    self.originalImage.set_colorkey((0,255,0)) 
    self.image = self.originalImage.copy() # The variable that is changed whenever the car is rotated. 

    self.originalRect = self.originalImage.get_rect() # This rect is ONLY for width and height, the x and y NEVER change from 0! 
    self.rect = self.originalRect.copy() # This is the rect used to represent the actual rect of the image, it is used for the x and y of the image that is blitted. 

    self.velocity = 0 # Current velocity in pixels per second 
    self.acceleration = 1 # Pixels per second (Also applies as so called deceleration AKA friction) 
    self.topSpeed = 30 # Max speed in pixels per second 
    self.rotation = 0 # In degrees 
    self.turnRate = 5 # In degrees per second 

    self.moving = 0 # If 1: moving forward, if 0: stopping, if -1: moving backward 


    self.centerRect = None 

def update(self, lastFrame): 
    if self.rotation >= 360: self.rotation = 0 
    elif self.rotation < 0: self.rotation += 360 

    if self.rotation > 0: 
     self.image = pygame.transform.rotate(self.originalImage.copy(), self.rotation) 
     self.rect.size = self.image.get_rect().size 
     self.center() # Attempt to center on the last used rect 

    if self.moving == 1: 
     self.velocity += self.acceleration #TODO make time based 

    if self.velocity > self.topSpeed: self.velocity = self.topSpeed # Cap the velocity 

回答

1

我真的不能做不是指向你this tutorial(*)更好。特別是,first part解釋瞭如何進行旋轉並使精靈在某些方向上移動。


(*)無恥的插件:-),但與問題非常相關。

+0

是的,這並沒有太大的幫助,我想要超過8軸運動。我想要360軸移動,這意味着它需要動態計算。 – 2011-03-18 22:53:28

+0

@JT約翰遜:只要你使用相同的技術,你可以有*任意軸*運動 - 數學是相同的 – 2011-03-19 06:29:47

3

三角:公式讓你的座標爲:

# cos and sin require radians 
x = cos(radians) * offset 
y = sin(radians) * offset 

您使用偏移速度。 (這意味着負速度將向後驅動)。

這樣:

def rad_to_offset(radians, offset): # insert better func name. 
    x = cos(radians) * offset 
    y = sin(radians) * offset 
    return [x, y] 

loop_update是一樣的東西:

# vel += accel 
# pos += rad_to_offset(self.rotation, vel) 

math.cos,math.sin:使用弧度,所以

存儲旋轉的弧度更簡單。如果你想將速度/等等定義爲度數,你仍然可以。

# store radians, but define as degrees 
car.rotation_accel = radians(45) 
car.rotation_max_accel = radians(90)