package

{

import flash.display.Sprite;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.geom.Point;

/**

* ...

* @author Lorenzo Nuvoletta

*/

public class Main extends Sprite

{

private var _points:Vector. = new Vector.();

private var _distance:Number = 100;

private var _lastPoint:int = 2;

private var _theta1:Number = 0;

private var _theta2:Number = 0;

public function Main():void

{

if (stage) init();

else addEventListener(Event.ADDED_TO_STAGE, init);

}

private function init(e:Event = null):void

{

removeEventListener(Event.ADDED_TO_STAGE, init);

// entry point

_points.push(new Point(100, 100));

_points.push(new Point(200, 100));

_points.push(new Point(300, 100));

draw();

stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);

}

private function onMouseMove(e:MouseEvent):void

{

solve();

draw();

}

private function solve():void {

// Compute difference between start and end points

var dx:Number = mouseX - _points[0].x;

var dy:Number = mouseY - _points[0].y;

// Compute distance between start and end points

var dist:Number = Math.sqrt(dx*dx + dy*dy);

// Compute angle between start and end points

var theta:Number = Math.atan2(dy,dx);

// Clamp the distance

var totalLength:Number = _distance * 2;

if( dist < totalLength ) {

// Calculate first angle: http://en.wikipedia.org/wiki/Dot_product#Geometric_interpretation

_theta1 = Math.acos( dist / totalLength ) + theta;

dx = dx - _distance * Math.cos( _theta1 );

dy = dy - _distance * Math.sin( _theta1 );

// Calculate second angle from first angle and segment

_theta2 = Math.atan2(dy, dx);

} else {

// If the distance is greater than arm length, arm is straight

_theta1 = _theta2 = theta;

}

// Compute positions from angles

_points[1].x = _points[0].x + Math.cos( _theta1 ) * _distance;

_points[1].y = _points[0].y + Math.sin( _theta1 ) * _distance;

_points[2].x = _points[1].x + Math.cos( _theta2 ) * _distance;

_points[2].y = _points[1].y + Math.sin( _theta2 ) * _distance;

}

private function draw():void {

this.graphics.clear();

this.graphics.lineStyle(4, 0);

this.graphics.moveTo(_points[0].x, _points[0].y);

for (var i:int = 1; i < _points.length; i++) {

this.graphics.lineTo(_points[i].x, _points[i].y);

}

}

}

}