26th May 2008

Hey Look, a Mouse.

In one of the books I am reading, Foundation Actionscript 3.0 Animation : Making Things Move! by Keith Peters, he has an example of using trig to make an arrow point at the location of the mouse. I decided to play with this a bit and make an animation where the eyes follow the mouse. I actully ended up adding this to my animation class, so this (after attaching the class via the library linkage):

can be accomplished with:

leftEye.startWatchingMouse();
rightEye.startWatchingMouse();

Functions in class:

public function startWatchingMouse():void{
stage.addEventListener(MouseEvent.MOUSE_MOVE,watchMouse);
}
public function stopWatchingMouse():void{
stage.removeEventListener(MouseEvent.MOUSE_MOVE,watchMouse);
}
private function watchMouse(event:MouseEvent):void{
var dx:Number = stage.mouseX - this.x;
var dy:Number = stage.mouseY - this.y;
var rad:Number = Math.atan2(dy,dx);
//for some reason the example as written was 90 degrees off, so I added 90 and that fixed it.
this.rotation = rad*180/Math.PI + 90;
}

Leave a Reply