Handy piece of code

Published August 04, 2010
Advertisement
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.5927544581291786949-416910369498440079?l=thecodezone.blogspot.com

Source


















Previous Entry This is a test
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement