Sunday, July 18, 2010

Rotate object to mouse using AS3

In this tutorial we will create an eye that is always facing the cursor. Here's the result:

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;


Anonymous said...

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

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

Kirill Poletaev said...

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

Anonymous said...

Thanks a lot, I found it very usefull

Anonymous said...

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

Anonymous said...

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

mccarthyq said...

Doesn't work.

Unknown said...

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