1

I have an image of my player (top-down 2D). The player rotates to face the camera, and holds a gun. When bullets are created, they are created at the player's x and y. This works when the player is facing the right way, but when the player rotates and shoots, the bullets go the right direction, but don't come from the gun. How can I fix this?

public void fire() {
    angle = sprite.getRotation();
    System.out.println(angle);
    x = sprite.getX();
    y = sprite.getY();

    Bullet b = new Bullet(x, y, angle);
    Utils.world.addBullet(b);
}
mad_manny
  • 1,081
  • 16
  • 28
Shane
  • 25
  • 5

1 Answers1

3

You will have to determine the offset for the gun (open the image in paint, or trial & error), and then rotate that offset to get the initial position for the bullet.

Something like the following should work: Note - I did not test this and it may have typos

public void fire() {
    angle = sprite.getRotation();
    System.out.println(angle);
    x = sprite.getX();
    y = sprite.getY();

    double bulletX = x + (gunOffsetX * Math.cos(angle) - gunOffsetY * Math.sin(angle));
    double bulletY = y + (gunOffsetX * Math.sin(angle) + gunOffsetY * Math.cos(angle));

    Bullet b = new Bullet(bulletX , bulletY , angle);
    Utils.world.addBullet(b);
}

Source: http://en.wikipedia.org/wiki/Rotation_(mathematics)

Hasen
  • 11,710
  • 23
  • 77
  • 135
Nick Eaket
  • 146
  • 3
  • This doesn't seem to work. It's almost the same as before, except now the bullets come from different positions. Take note that I don't have a gun image attached to a player, but rather an image of a player holding a gun. – Shane Jul 28 '12 at 01:52
  • Nevermind! I got it to work. All I had to do was convert the angle to radians before using Math.cos(...) and Math.sin(...). – Shane Jul 28 '12 at 16:13