# How to Align Gun with Bullets

I have a top-down 2D shooter. I have an image of a player holding a gun, that rotates to face the mouse. Please note that the gun isn't a separate image tethered to the player, but rather part of the player. Right now, bullets are created at the player's x and y. This works when the player is facing the right way, but not when they rotate. The bullets move in the right direction, but don't come from the gun. How can I fix this?

TL;DR: When the player rotates, bullets don't come from gun.

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

Bullet b = new Bullet(x, y, angle);
}
``````
-

Telling by what you describe, the gun of the character has an offset from the player center point. So you must calculate the initial position of the bullet, it should be the end of the gun barrel.

-
Well, I can offset the bullet so it's at the barrel, but how do I calculate the offset when the player rotates? Since the gun moves, the offset has to change. –  Shane Jul 28 '12 at 15:44
I can't really answer that since each asset is different. But the important part is that the origin where the bullet is "spawned" so to speak, should be the tip of the "barrel" or where the bullet touches last the gun. –  Leonel Samayoa Jul 28 '12 at 16:16

It's not easy to tell form the code you provided (what does addBullet do? where does it draw the bullet in relation to your sprite?) nor is there information about your sprite in general (how big it is, where the origin point of it is).

However, I would hazard a guess that your gun is not located at the X,Y coordinates that the Sprite returns. However, those are the coords you pass to your bullet-drawing routine, which I am guessing draws your bullets at the point you specify.

You need to determine the offset of the gun from your sprite's origin point, and then modify your x and y values before calling addBullet:

``````public void fire() {
angle = sprite.getRotation();
System.out.println(angle);
//One option, where the gun's offset from sprite origin
x = sprite.getX() - sprite.getGunOffsetX();
y = sprite.getY() - sprite.getGunOffsetY();

//Another option, where you store the gun's position on the sprite
x = sprite.getGunX();
y = sprite.getGunY();

Bullet b = new Bullet(x, y, angle);
``````

}

-
The origin is the center of the sprite. addBullet just creates the bullet. The gun is around the top left. I know how to offset the bullet so it comes from the gun, but when the player (and gun) rotates, the bullet is no longer coming from the gun, because it's position has changed. –  Shane Jul 28 '12 at 15:55

Let `x`, `y` be the offset of the end of the barrel from the (unrotated) sprite's center, and `theta` the angle of rotation (counter-clockwise)

Then the barrel's offsets `x2`, `y2` for the rotated sprite can be calculated like this:

``````x2 = x * cos(theta) - y * sin(theta)
y2 = x * sin(theta) + y * cos(theta)
``````
-