• Create Account

# Handy piece of code

Posted by johnhattan, 04 August 2010 · 87 views

Here's a quick-n-simple piece of AS3 (or Javascript) that calculates the point on a line closest to a given point. It took me a couple of tries to get it right, so I figured I would share it.

var nearestPtToLine = function(segA:Point, segB:Point, p:Point, infinite:Boolean = true):Point

{

var dx:Number = segB.x - segA.x

var dy:Number = segB.y - segA.y

var u:Number = ((p.x - segA.x) * dx + (p.y - segA.y) * dy) / (dx * dx + dy * dy)

if (!infinite)

{

if (u > 1)

u = 1

else if (u < 0)

u = 0

}

return new Point(segA.x + u * dx , segA.y + u * dy)

}

seg1 and seg2 define a line segment. p is the point to test. infinite assumes that the line extends beyond seg1 and seg2. If you need the distance from a point to a line, just use the distance function in the flash.geom.Point object.https://blogger.googleusercontent.com/tracker/5927544581291786949-416910369498440079?l=thecodezone.blogspot.com

Source