This is from a small Flash project I made some years ago. I wanted to create some really nice eye motion for looking at the mouse pointer, where the pupil properly stops moving at the rim of the eye and a pair of eyes doesn't go crazy cross eyed when the mouse is between the eyes. Then I went a little crazy with the arrangement, and the result is satisfyingly psychedelic :)
Here is the source code for the eye motion:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Eye extends MovieClip {
public var eyeball:Eyeball;
public var eyeballMask:EyeballMask;
public var pupil:Pupil;
public var maxDistance;
public function Eye():void {
eyeball.mask = eyeballMask;
pupil.mask = eyeballMask;
eyeballMask.alpha = 0;
maxDistance = 156;
addEventListener(Event.ENTER_FRAME, followMouse);
}
function followMouse(e:Event):void {
// calculate mouse offset
var distx:Number = mouseX - eyeball.x;
var disty:Number = mouseY - eyeball.y;
var dist:Number = Math.sqrt(distx*distx + disty*disty);
//if the pupil is within the confines of the eyeball
//translate it towards the mouse at a set fraction
if (dist < maxDistance) {
pupil.x = distx / 7;
pupil.y = disty / 7;
}
//if the pupil is at the edge of the eyeball
//translate it along the radius of the eyeball
else {
var angleA:Number = Math.atan2(distx, disty);
var angleB:Number = (180*(Math.PI/180)) - ((90*(Math.PI/180)+angleA));
disty = maxDistance * Math.cos(angleA);
distx = maxDistance * Math.cos(angleB);
pupil.x = distx / 7;
pupil.y = disty / 7;
}
}
}
}