2016-12-15 69 views
0

好吧,我一直在這一整天工作,我還沒有找到邏輯。Pygame - 旋轉並移動太空船(多邊形)

我想做一個經典風格的小行星遊戲,我開始與飛船。

我所做的就是畫一些線路用飛船的形狀:

import pygame 
import colors 
from helpers import * 

class Ship : 
    def __init__(self, display, x, y) : 
     self.x = x 
     self.y = y 
     self.width = 24 
     self.height = 32 
     self.color = colors.green 
     self.rotation = 0 
     self.points = [ 
      #A TOP POINT 
      (self.x, self.y - (self.height/2)), 
      #B BOTTOM LEFT POINT 
      (self.x - (self.width/2), self.y + (self.height /2)), 
      #C CENTER POINT 
      (self.x, self.y + (self.height/4)), 
      #D BOTTOM RIGHT POINT 
      (self.x + (self.width/2), self.y + (self.height/2)), 
      #A TOP AGAIN 
      (self.x, self.y - (self.height/2)), 
      #C A NICE LINE IN THE MIDDLE 
      (self.x, self.y + (self.height/4)), 
     ] 

    def move(self, strdir) : 
     dir = 0 
     if strdir == 'left' : 
      dir = -3 
     elif strdir == 'right' : 
      dir = 3 

     self.points = rotate_polygon((self.x, self.y), self.points, dir) 

    def draw(self, display) : 
     stroke = 2 
     pygame.draw.lines(display, self.color, False, self.points, stroke) 

船看起來是這樣的:

enter image description here

現在重要的事情要知道:

元組(self.x,self.y)是飛船的中間部分。

使用此功能,我設法旋轉(旋轉),它在命令中使用的密鑰A和d

def rotate_polygon(origin, points, angle) : 
    angle = math.radians(angle) 
    rotated_polygon = [] 

    for point in points : 
     temp_point = point[0] - origin[0] , point[1] - origin[1] 
     temp_point = (temp_point[0] * math.cos(angle) - temp_point[1] * math.sin(angle), 
         temp_point[0] * math.sin(angle) + temp_point[1] * math.cos(angle)) 
     temp_point = temp_point[0] + origin[0], temp_point[1] + origin[1] 
     rotated_polygon.append(temp_point) 

    return rotated_polygon 

enter image description here

的問題是:我怎樣才能使它向前或向後在太空船指向的方向?

OR

我怎麼可以更新self.x和self.y值,並更新他們的self.points名單內,並保留旋轉?

+0

最簡單且效率最低的選項是在更新到self.x或self.y後重新計算所有這些頂點。 – AndrewGrant

回答

0

在我看來,你應該能夠簡單地做到以下幾點。

def updatePosition(self, dx, dy): 
    self.x += dx 
    self.y += dy 

    newPoints = [] 
    for (x,y) in self.points: 
     newPoints.append((x+dx, y+dy)) 

    self.points = newPoints 
2

的最簡單,最常用的方法來處理移動和旋轉會使用一些矢量數學(可應用到3D圖形以及)。你可以保留一個2D矢量來代表你的船的前進方向。例如,如果你的船開始朝上,你的(0,0)座標是左上角。你可以做。

self.forward = Vector2D(0, -1) # Vector2D(x, y) 

當你旋轉你必須旋轉這個向量。您可以使用以下方式進行旋轉。

self.forward.x = self.forward.x * cos(angle) - self.forward.y * sin(angle) 
self.forward.y = self.forward.x * sin(angle) + self.forward.y * cos(angle) 

然後,當您想要移動船舶時,您可以將船舶點相對於此向量進行轉換。例如。

self.x += forward.x * velocity.x 
self.y += forward.y * velocity.y 

我會強烈建議你寫一個小的Vector2D類可以做一些基本操作,例如dot,cross,mult,add,sub,normalize等

如果您熟悉矩陣,那麼如果使用矩陣而不是線性方程組來實現它們,這些操作會變得更加容易。