Top-Down RPG Shooter — Part 3 — Player Rotation

Hey everyone! Here’s a super brief tutorial. Just to hold you over for another week while I write the next big one ;)

The Code

We’ll be modifying the class so that the player rotates in the direction of the mouse. It only takes a few lines of code. (You can actually do it in one line of code, I’m just spelling everything out to make it nice and simple.)

Put all of these lines inside the bottom of the loop function in the class.

//calculate these values, which we will use to determine the angle we need to rotate to
var yDifference:Number = stageRef.mouseY - y;
var xDifference:Number = stageRef.mouseX - x;
//this constant will convert our angle from radians to degrees
var radiansToDegrees:Number = 180/Math.PI;
//this final line uses trigonometry to calculate the rotation
rotation = Math.atan2(yDifference, xDifference) * radiansToDegrees;

Continue reading