Python - Shoot a bullet in the direction (angle in degrees) my spaceship is facing

为君一笑 提交于 2019-12-24 00:52:21

问题


There are a lot of questions about this. But none of them have answers that solve my problem in specific, I've tried to google this all day.

My problem is simple.

I have this space ship that I can move and rotate around and I'm already tracking it's heading, the direction it's facing. For example in the image below the ship is heading approximately 45 degrees It goes from 0° (starting top and going clockwise) to 359°

I just need to make a bullet go straight forward the direction (heading) my spaceship is facing, starting from the X,Y coordinate my spaceship currently is

The Projectile class:

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)

Now the shoot method of my ship class:

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?

回答1:


Given the ships angle, try:

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)

The relevant part of 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


来源:https://stackoverflow.com/questions/41205388/python-shoot-a-bullet-in-the-direction-angle-in-degrees-my-spaceship-is-faci

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!