# Creating Rolling Eyes using ActionScript Trigonometric functions

Creating rolling eyes towards mouse is quite easy, but you need to know little math. I mean few trigonometry concepts and functions in ActionScript.

But how we can implement trigonometry using ActionScript. Let’s see how it is.

First find the radian of the angle, you can find out the radian using math class

[as3]

var radian:Number = Math.atan2(this.mouseY,this.mouseX);

[/as3]

Now you have radian and radius, that means radian and hypotenuse. Now find the x coordinate [adjacent] value for child movieclip that is eyeball.

See forumulas: Mnemonics

[as3]

var xCoord:Number = Math.cos(radian)*8;

[/as3]

And then find the y-coordinate [opposite] value for the eyeball.

[as3]

var yCoord:Number = Math.sin(radian)*8;

[/as3]

Now you have both coordinates.

Let me more simplify the logic. see the image below.

Our aim is moving movieclip towards mouse cursor, So, what we need?

Suppose the dotted line of circle is moving path of the eyeball, that is child movieclip, and you want to move it exactly on the doted path towards the mouse curser. And we need the x and y co-ordinates to place exactly on path.

Complete code : iBall.as

[as3]

// MovieClip Class

// Eye balls rolling towards mouse pointer

package {

import flash.display.MovieClip;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.events.TimerEvent;

import flash.utils.Timer;

public class iBall extends MovieClip {

// Define new timer & set interval to 1/10 second

private var timer:Timer = new Timer(100);

public function iBall():void {

// Assigning event to timer

timer.addEventListener(TimerEvent.TIMER, moveEyes);

// Starting timer, So it will call the function every 1/10 seconds

timer.start();

}

// Moving eyes function

private function moveEyes(e:TimerEvent):void {

// Finding radian

var radian:Number = Math.atan2(this.mouseY,this.mouseX);

// Rolling smaller eyeball

// And Finding the radius

var xCoord_small:Number = Math.cos(radian)*8;

var yCoord_small:Number = Math.sin(radian)*8;

small.x = xCoord_small;

small.y = yCoord_small;

// Rolling bigger eyeball

// And Finding the radius

var xCoord_big:Number =Math.cos(radian)*4;

var yCoord_big:Number =Math.sin(radian)*4;

big.x = xCoord_big;

big.y = yCoord_big;

}

}

}

[/as3]

If you want know more about Trigonometry, you can find on Wikipedia.com.

## Leave a Reply

Want to join the discussion?Feel free to contribute!