/**
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 pointToLineDistance(p1:Sprite, p2:Sprite, p3:Sprite):Number {
var xDelta:Number = p2.x - p1.x;
var yDelta:Number = p2.y - p1.y;
if ((xDelta == 0) && (yDelta == 0)) {
// p1 and p2 cannot be the same point
p2.x += 1;
p2.y += 1;
xDelta = 1;
yDelta = 1;
}
var u:Number = ((p3.x - p1.x) * xDelta + (p3.y - p1.y) * yDelta) / (xDelta * xDelta + yDelta * yDelta);
var closestPoint:Point;
if (u < 0) {
closestPoint = new Point(p1.x, p1.y);
} else if (u > 1) {
closestPoint = new Point(p2.x, p2.y);
} else {
closestPoint = new Point(p1.x + u * xDelta, p1.y + u * yDelta);
}
return Point.distance(closestPoint, new Point(p3.x, p3.y));
}
/**
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 = pointToLineDistance(dotA, dotB, dotC).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() }
Last night I was working late and found myself in need of a way to calculate the distance between a point and a line. After a quick google search I found myself once again on Paul Bourke’s extremely useful website. I was in a rush, so I just quickly ported the java code (by Pieter Iserbyt) and wrote this test snippet to make sure it works.
This code could be optimized a bit, but it works nicely.
I needed this for a commercial project, but as I was porting the code I thought of an interesting way to use this code to draw a gradient – may write and post that tomorrow.
this is not helpful at all
hey elisa, I assume your not an actionscript programmer – and were just looking for the math… and if thats the case this link should be helful:
http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
Thanks for the code, it was really helpful, along with your line intersection code.
This was truly useful to me! It worked great!
Thanks! ^^
Thanks, its great.