Create extra bullets, offset according to angle of spaceship, in libGosu/Chingu?

256 views Asked by At

I am trying to create a weapons upgrade for my basic, tutorial-style Spaceship, using libGosu and Chingu.

In the player class I have tried several variations of the following:

def fire
  Bullet.create(:x => @x, :y => @y, :angle => @angle)
  Bullet.create(:x => @x + Gosu::offset_x(90, 25), :y => @y + Gosu::offset_y(@angle, 0), :angle => @angle)
end

It sort of works, but not exactly how it ideally should. For reference, this is what the Bullet class looks like:

class Bullet < Chingu::GameObject
  def initialize(options)
    super(options.merge(:image => Gosu::Image["assets/laser.png"]))
    @speed = 7
    self.velocity_x = Gosu::offset_x(@angle, @speed)
    self.velocity_y = Gosu::offset_y(@angle, @speed)
  end

  def update
    @y += self.velocity_y
    @x += self.velocity_x
  end
end

How should I construct "def fire" in order to get the extra bullets to align properly when the spaceship rotates?

2

There are 2 answers

0
Matt Lemmon On BEST ANSWER

The following simple solution did the trick:

Bullet.create(:x => @x + Gosu::offset_x(@angle+90, 25), :y => @y + Gosu::offset_y(@angle+90, 25), :angle => @angle)

There is an in-depth description of the forces at work in this answer from GameDev.StackExchange.

I also came across the following "long way around the barn," using Sin and Cos, and converting the angle to radians with PI:

Bullet.create(:x => @x + 20 * Math.cos(@angle*Math::PI/180) , :y => @y + 20 * Math.sin(@angle*Math::PI/180), :angle => @angle)

A more detailed description of the Sin/Cos approach can be found here.

The formula to convert degrees to radians is degrees*Π/180.

1
chase4926 On

The x needs to be offset in the same manner that the y is offset.

Also, why are you creating the bullet twice in different ways if @weapon == 2?