ActionScript Eyes – Watching the cursor

View Example  |  Download Source Files

In this example, every 3 seconds about 15 eyes will randomly animate around your current cursor position. This is done using the tween class with a random variance. But what I want to talk about is how to get the eyeball to point to the cursor. Here’s the code that does that:  |

    var dx:Number = mouseX – eye.x;
    var dy:Number = mouseY – eye.y;
    var radians:Number = Math.atan2(dy, dx);
    eye.rotation = radians * 180 / Math.PI;
    eye.rotation = radians * 180 / Math.PI;

You can get the location of the eye with the x and y properties. Subtracting these, you get the length of the two triangle legs (dx and dy). Now, you simply need to use Math.atan2(dy,dx) to find the angle.
atan2 computes and returns the angle of the point y/x in radians, when measured counterclockwise from a circle’s x axis (where 0,0 represents the center of the circle). The return value is between positive pi and negative pi (pi = 180 degrees). Then convert it to degrees and set the eye’s rotation property to the result.

error

Enjoy this blog? Please spread the word :)