Question

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);
}
Was it helpful?

Solution

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top