对此有很多疑问。但是他们都没有解决我的具体问题的答案,我试着整天都在谷歌。
我的问题很简单。
我有这艘太空船,我可以移动和旋转,我已经跟踪它的方向,它面向的方向。例如,在下面的图像中,船的航向大约 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?
答案 0 :(得分: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)
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