2011-03-18 12 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度の動きが必要なので、動的に計算する必要があります。 –

+0

@JT Johnson:同じテクニックを使っている限り、あなたは*何軸でも動かすことができます - 数学は同じです –

3

三角法:あなたの座標を取得するための式は次のとおりです。

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

あなたはオフセットため速度を使用します。 (これは、負の速度が後退することを意味します)。

はそう:

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

math.cos、math.sin:ラジアンとして回転を保存するので、用途ラジアン、

簡単です

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

loop_updateのようなものがあります。スピード/等を度として定義したいのであれば、それでも可能です。

# store radians, but define as degrees 
car.rotation_accel = radians(45) 
car.rotation_max_accel = radians(90) 
関連する問題