Actionscript:
-
// from
-
// http://www.gamedev.net/topic/444154-closest-point-on-a-line/
-
-
function getClosestPoint(A:*, B:*, P:*, segmentClamp:Boolean=true):Point {
-
var AP:Point = new Point(P.x - A.x, P.y - A.y),
-
AB:Point = new Point(B.x - A.x, B.y - A.y);
-
var ab2:Number=AB.x*AB.x+AB.y*AB.y;
-
var ap_ab:Number=AP.x*AB.x+AP.y*AB.y;
-
var t:Number=ap_ab/ab2;
-
if (segmentClamp) {
-
if (t<0.0) {
-
t=0.0;
-
} else if (t> 1.0) {
-
t=1.0;
-
}
-
-
}
-
return new Point(A.x + AB.x * t, A.y + AB.y * t);
-
}
-
-
-
var point:Sprite = Sprite(addChild(new Sprite()));
-
point.x = 50;
-
point.y = 50;
-
with(point.graphics) beginFill(0), drawCircle(0,0, 3);
-
-
var line:MovieClip = MovieClip(addChild(new MovieClip()));
-
line.a = new Point(20, 100);
-
line.b = new Point(300, 60);
-
with(line.graphics) lineStyle(0), moveTo(line.a.x, line.a.y), lineTo(line.b.x, line.b.y);
-
-
var closestPoint:Point = getClosestPoint(line.a, line.b, point);
-
-
var closest:Sprite = Sprite(addChild(new Sprite()));
-
closest.x = closestPoint.x;
-
closest.y = closestPoint.y;
-
with(closest.graphics) beginFill(0xFF0000), drawCircle(0,0, 3);