Hey everyone! Here’s a super brief tutorial. Just to hold you over for another week while I write the next big one ;)
We’ll be modifying the Player.as 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 Player.as 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;
That’s it. Compile and run your code. I told you it was quick.
If you want to be super efficient with your code, you can even replace all that code with this one line:
rotation = Math.atan2(stageRef.mouseY - y, stageRef.mouseX - x) * 180/Math.PI;
Wait! So why does that code work? It isn’t magic… it’s math. Let’s go through the math, step-by-step.
We are setting the rotation to Math.atan2(stageRef.mouseY – y, stageRef.mouseX – x) * 180/Math.PI
- stageRef.mouseY – y
- This gives use the difference between the y position of the mouse, and the y position of the player
- stageRef.mouseX – x
- Similarly, this gives use the difference between the x positions of the mouse and the player.
- Math.atan2( [ y difference ] , [ x difference ] )
- Math.atan2 is actionscript’s version of taking the inverse tangent. It uses a comma to separate the numerator and the denominator.
- If you know basic trigonometry, you’ll know all about the inverse tangent. If you’re unfamiliar with it, trigonometry is really useful in programming, so you might want to learn the basics, but here’s the general idea: we can use the lengths and angles of a right triangle to calculate new, useful information. Specifically to this tutorial, we can use the lengths of two sides of a right triangle to determine its angles. Using the yDifference and xDifference as the two lengths, we can find what angle the player should rotate to. The only problem: Math.atan2 gives the angle in radians, not degrees. To convert back to degrees, which Flash uses, we need to multiply our value by a constant.
- * 180 / Math.PI
- This converts the angle from radians (between 0 and 2 PI) to degrees (between 0 and 360)
That’s it for today, folks! You can pickup your source files here.
Thanks for reading :-)