First of all, we need to draw our eye, arrow, whatever you want to follow or cursor. Make sure it faces right, this is very important.

Next, the coding. I'm going to find out the angle using Math.atan2 in radians and then convert the number to degrees. I tried to explain the whole code in the picture:

Here's the code:

stage.addEventListener(MouseEvent.MOUSE_MOVE, lookAtMouse); function lookAtMouse(event:MouseEvent):void { // find out mouse coordinates to find out the angle var cy:Number = mouseY - eye.y; var cx:Number = mouseX - eye.x; // find out the angle var Radians:Number = Math.atan2(cy,cx); // convert to degrees to rotate var Degrees:Number = Radians * 180 / Math.PI; // rotate eye.rotation = Degrees; }

## 7 comments:

but...isn't the angle always 90 ° ?

the program works, i just don't see how that angle is gonna change

My bad, I've put the wrong angle on the picture. It is fixed now.

Thanks a lot, I found it very usefull

Thank's a Lot,this is very useful to learn about atan2 keep updating,Thank's

Thanks. I thought it was so had.. yet its so simple.

Doesn't work.

It uh... seems to not work too well. Using it to move a 2d gunbarrel has the barrels at 12'o'clock when the mouse is at 3'o'clock, aiming at three when mouse is at six, aiming at six when its at nine, aiming at nine when its at twelve. I copied the code exactly and changed the modifiers

## Post a Comment