Eyes following mouse cursor AS3
- September 22, 2009
- ActionScript 3.0, Tutorials
- 22
A simple and easy tutorial for you to know how to use the mouse interactivity in Actionscript 3. We’ll create the eyes for an alien character that will follow the mouse. Also we’ll hide the mouse and change it with something else. All this is done in a general Movie Clip so you can drag it in your project.
Here’s the final result:
1. To create an alien eye draw a white circle that will represent the cornea. Convert it to a Movie Clip that has the registration point centered. Inside this clip draw 2 circles that will represent the iris and convert them to a Movie Clip. Position it right over the cornea. Give an instance name of eye1 for the parent Movie Clip. Drag other two eyes (instance name of eye2 and eye3) and position them on the alien’s body.
2. Now that we have obtained the eye let’s create the interactivity. The basic idea is that we’ll have to rotate the eye according to the mouse position. To do so we’ll calculate the angle from the eye position to the mouse position and rotate it. To obtain the angle we’ll use the atan2 function from Flash, that will have as parameters the Y and X position of the mouse.
radians1 = Math.atan2(a1, b1);
3. The angle obtained from the atan2 function is in radians. To convert it in degrees paste this line.
degrees1 = radians1 / (Math.PI / 180);
4. Now rotate the eye by the angle obtained in degrees.
eye1.rotation = degrees1;
5. In order to change the mouse with something else use this code:
Mouse.hide();
cookie.x = mouseX;
cookie.y = mouseY;
6. All code:
stage.addEventListener("mouseMove", eyesFollow);
cookie.visible = false;
function eyesFollow(e:MouseEvent):void {
var a1 = mouseY - eye1.y;
var b1 = mouseX - eye1.x;
var radians1 = Math.atan2(a1,b1);
var degrees1 = radians1 / (Math.PI / 180);
eye1.rotation = degrees1;
var a2 = mouseY - eye2.y;
var b2 = mouseX - eye2.x;
var radians2 = Math.atan2(a2,b2);
var degrees2 = radians2 / (Math.PI / 180);
eye2.rotation = degrees2;
var a3 = mouseY - eye3.y;
var b3 = mouseX - eye3.x;
var radians3 = Math.atan2(a3,b3);
var degrees3 = radians3 / (Math.PI / 180);
eye3.rotation = degrees3;
Mouse.hide();
cookie.visible = true;
cookie.x = mouseX;
cookie.y = mouseY;
}


Pingback: Eyes following mouse cursor AS3
Pingback: tripwire magazine | tripwire magazine
Pingback: Eyes following mouse cursor AS3 | favSHARE.net
Pingback: 80+ Stunning Articles for Designers and Developers | tripwire magazine
Pingback: The week in links 25/09/09 - Craig Baldwin's Blog
Pingback: 80+ Stunning Articles for Designers and Developers | huibit05.com
Pingback: Technical Progress | MMPP - what's cookin'