## Friday, July 1, 2011

### AS3: To determine the angle between two given coordinates

Here is a sample code to determine the angle between two given coordinates. In other words, to calculate the angle of an object with respect to the origin.

This could be used to determine current angle of mouse-pointer with some pre-defined origin. In which case the movieclip attached to the mouse-pointer can always point towards it's origin.

Many examples of this logic can be seen on web. One of the popular example is; a female face with moving eyes that follows the user's mouse-pointer movement, so that the eyes always look towards the mouse-pointer.

Sample Code:
`````` package
{
import flash.geom.Point;
/**
* @file Connecteur.as
* @author Abhishek Kumar
*/
public class Connecteur
{
private var originCoordinate:Point;
private var currentCoordinate:Point;
private function setOriginCoordinate():void
{
originCoordinate = new Point(Source.x, Source.y);
}
private function setCurrentCoordinate():void
{
currentCoordinate = new Point(Pointer.x, Pointer.y);
}
private function getCurrentAngle():Number
{
var perpendicular:Number = (currentCoordinate.y - originCoordinate.y);
var base:Number = (currentCoordinate.x - originCoordinate.x);
var theta:Number = Math.atan2(perpendicular, base); // in radians
return (theta * 180 / Math.PI); // in degrees
}
}
``````

#### 1 comment:

1. nice.understanding that the angle between horizon and point one and two were meant was much easier in this post, compared to the others.