-
/**
-
Original function by Pieter Iserbyt:
-
http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/DistancePoint.java
-
from Paul Bourke's website:
-
http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
-
*/
-
function pointToLineDist(x1:Number, y1:Number, x2:Number, y2:Number,x3:Number, y3:Number):Number {
-
var dx:Number=x2-x1;
-
var dy:Number=y2-y1;
-
if (dx==0&&dy==0) {
-
x2+=1;
-
y2+=1;
-
dx=dy=1;
-
}
-
var u:Number = ((x3 - x1) * dx + (y3 - y1) * dy) / (dx * dx + dy * dy);
-
-
var closestX:Number;
-
var closestY:Number;
-
if (u<0) {
-
closestX=x1;
-
closestY=y1;
-
} else if (u> 1) {
-
closestX=x2;
-
closestY=y2;
-
} else {
-
closestX=x1+u*dx;
-
closestY=y1+u*dy;
-
}
-
dx=closestX-x3;
-
dy=closestY-y3;
-
return Math.sqrt(dx * dx + dy * dy);
-
}
-
-
/**
-
Test out the function
-
*/
-
-
var dotA:Sprite = dot(100, 100);
-
var dotB:Sprite = dot(200, 200);
-
var dotC:Sprite = dot(150, 100, 0x0000FF);
-
var txt:TextField = TextField(dotC.addChild(new TextField()));
-
with(txt) x = 5, y = 5, autoSize = "left", selectable = false, mouseEnabled = false;
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
graphics.clear();
-
graphics.lineStyle(0,0x000000);
-
graphics.moveTo(dotA.x, dotA.y);
-
graphics.lineTo(dotB.x, dotB.y);
-
txt.text = pointToLineDist(dotA.x, dotA.y, dotB.x, dotB.y, dotC.x, dotC.y).toFixed(2);
-
}
-
-
// draggable dot
-
function dot(xp:Number, yp:Number, col:uint = 0xFF0000, rad:Number=4):Sprite {
-
var s:Sprite = Sprite(addChild(new Sprite));
-
s.x = xp;
-
s.y = yp;
-
with(s.graphics) beginFill(col), drawCircle(0,0,rad);
-
s.buttonMode = true;
-
s.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
-
return s;
-
}
-
function onDrag(evt:MouseEvent):void { evt.currentTarget.startDrag() }
-
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
-
function onUp(evt:MouseEvent):void{stopDrag() }
This is the same as yesterdays post about the distance between a point and a line segment. I just took a few minutes to optimize the function - it runs close to 3X faster now. For more info see yesterdays post.