Search code examples
ruby2d-gameslibgosu

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


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?


Solution

  • 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.