Juan Bonnett
Juan Bonnett

Reputation: 1853

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

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°

enter image description here

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?

Upvotes: 2

Views: 1642

Answers (1)

jmunsch
jmunsch

Reputation: 24089

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)

enter image description here

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

Upvotes: 1

Related Questions