# How do I make a 2D character aim their gun toward the mouse?

Heli Attack is a perfect example of the shooting mechanic I'd like. The character aims perpetually toward the mouse. What's going on here?

From what I've read so far, you could separate the arm and rotate that. I've also noticed some people use a different sprite for each weapon.

How can I achieve this?

# Projector sheets

You know those ancient projectors that come with transparent sheets? In primary school, I discovered you could draw a character's torso on one transparent sheet...

... and then take out another sheet, lay it on top, and draw arm with a gun on it ...

... and then rotate the top sheet with the arm on it (reeeally carefully, to keep the shoulder in the right place) ...

... and it would be amazing. I made multiple characters had them fight.

# Draw order

In secondary school, I taught myself Game Maker and I was making a platformer game. Playing around with sprites, I remembered my childish projector sheet battles and thought I wonder if I could do that with code.

So I drew sprites like I'd drawn them years ago and wrote code in the player's Draw event, something like

var rotation = direction_to_point(self.shoulder_position, mouse_position)
# Draw back arm
draw_sprite(player_back_arm, self.shoulder_position, rotation);
# Draw torso
draw_sprite(player_torso, self.position);
# Draw front arm
draw_sprite(player_front_arm, self.shoulder_position, rotation);


I remember I was really proud I had graduated to two arms. I printed the code out and taped it to the inside of my locker door, next to my circle-AABB collision resolution code. I figured this would get me girls. Hm.

When we did trigonometry in math class, I noticed that because the tangent of the angle between the adjacent and the hypotenuse equalled the length of the opposite over that of the adjacent, it was possible to find the angle given just the adjacent and opposite and that that's what the angle_to_point function in Game Maker must be doing.

Just imagine A is where the shoulder is and B is where you're aiming (the mouse position, say).

See my answer over here for a more complete explanation of the trigonometry involved, with sample code.

So that's how you might do that.

• +1 For much better than the average programmer's art. – concept3d Feb 10 '14 at 9:26