# Closest Point on a Line

Actionscript:
1. // from
2. // http://www.gamedev.net/topic/444154-closest-point-on-a-line/
3.
4. function getClosestPoint(A:*, B:*, P:*, segmentClamp:Boolean=true):Point {
5.     var AP:Point = new Point(P.x - A.x, P.y - A.y),
6.         AB:Point = new Point(B.x - A.x, B.y - A.y);
7.     var ab2:Number=AB.x*AB.x+AB.y*AB.y;
8.     var ap_ab:Number=AP.x*AB.x+AP.y*AB.y;
9.     var t:Number=ap_ab/ab2;
10.     if (segmentClamp) {
11.         if (t<0.0) {
12.             t=0.0;
13.         } else if (t> 1.0) {
14.             t=1.0;
15.         }
16.
17.     }
18.     return new Point(A.x + AB.x * t, A.y + AB.y * t);
19. }
20.
21.
22. var point:Sprite = Sprite(addChild(new Sprite()));
23. point.x = 50;
24. point.y = 50;
25. with(point.graphics) beginFill(0), drawCircle(0,0, 3);
26.
27. var line:MovieClip = MovieClip(addChild(new MovieClip()));
28. line.a = new Point(20, 100);
29. line.b = new Point(300, 60);
30. with(line.graphics) lineStyle(0), moveTo(line.a.x, line.a.y), lineTo(line.b.x, line.b.y);
31.
32. var closestPoint:Point = getClosestPoint(line.a, line.b, point);
33.
34. var closest:Sprite = Sprite(addChild(new Sprite()));
35. closest.x = closestPoint.x;
36. closest.y = closestPoint.y;
37. with(closest.graphics) beginFill(0xFF0000), drawCircle(0,0, 3);

This entry was posted in Math. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

• ActionSnippet is on Twitter