2016-12-18 25 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查看此图片以了解我的意思 –