2016-12-18 23 views
2

有很多關於此的問題。但他們都沒有解決我的問題的具體解決方案,我試圖谷歌這一整天。Python - 在我的飛船正面臨的方向(角度度數)上拍攝子彈

我的問題很簡單。

我有這個太空船,我可以移動和旋轉,我已經跟蹤它的標題,它面對的方向。例如船在下面的圖片是標題大約45度它從0°(從頂部和去順時針)至359°

enter image description here

我只是需要讓子彈徑直向前方向(航向)我的飛船正面臨着從X開始,Y座標我的飛船是目前

彈丸類:

class Projectile(object) : 

    def __init__(self, x, y, vel, screen) : 
     self.screen = screen 
     self.speed = 1 #Slow at the moment while we test it 
     self.pos = Vector2D(x, y) 
     self.velocity = vel #vel constructor parameter is a Vector2D obj 
     self.color = colors.green 

    def update(self) : 
     self.pos.add(self.velocity) 

    def draw(self) : 
     pygame.draw.circle(self.screen, self.color, self.pos.int().tuple(), 2, 0) 

現在SH我的船級的OOT方法:

class Ship(Polygon) : 

    # ... A lot of ommited logic and constructor 

    def shoot(self) : 
     p_velocity = # .......... what we need to find 
     p = Projectile(self.pos.x, self.pos.y, p_velocity, self.screen) 
     # What next? 
+0

如果是邏輯更新'self.pos'?也許保留最後2個位置的列表並計算它們的速度? – jmunsch

+0

@jmunsch我不認爲我理解正確。兩個類都有一個屬性,它們只是它們在屏幕上的位置。它們通過在每幀中添加速度值進行更新 –

+0

您爲Vector2D導入了什麼庫? – eyllanesc

回答

1

考慮到船舶的角度,嘗試:

class Projectile(object) : 
    def __init__(self, x, y, ship_angle, screen) : 
     self.screen = screen 
     self.speed = 5 #Slow at the moment while we test it 
     self.pos = Vector2D(x,y) 
     self.velocity = Vector2D().create_from_angle(ship_angle, self.speed, return_instance=True) 
     self.color = colors.green 

    def update(self) : 
     self.pos.add(self.velocity) 

    def draw(self) : 
     pygame.draw.circle(self.screen, self.color, self.pos.int().tuple(), 2, 0) 

enter image description here

Vector2D相關部分:

def __init__(self, x = 0, y = 0) : # update to 0 
    self.x = x 
    self.y = y 

def create_from_angle(self, angle, magnitude, return_instance = False) : 
    angle = math.radians(angle) - math.pi/2 
    x = math.cos(angle) * magnitude 
    y = math.sin(angle) * magnitude 
    print(x, y, self.x, self.y, angle) 
    self.x += float(x) 
    self.y += float(y) 
    if return_instance : 
     return self 
+0

想要告訴你它是如何表現的 –

+0

這裏發生的事情是子彈正在0,0座標中創建,而不是在船的位置:s –

+0

http://imgur.com/a/8zl4F查看此圖片以瞭解我的意思 –