关于这个问题有很多。但是他们都没有具体解决我的问题的答案,我已经尝试谷歌一整天了。
我的问题很简单。
我有一艘可以移动和旋转的 spaceship ,我已经在跟踪它的航向,它所面对的方向。例如,在下图中,船的航向大约为 45 度,它从 0°(从顶部开始顺时针方向)到 359°
我只需要让一颗子弹沿着我的飞船朝向的方向(航向)直线前进,从我的飞船当前所在的 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)
现在我船类的拍摄方法:
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?
请您参考如下方法:
给定船只角度,尝试:
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)
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
