• entries
1212
1738
• views
1144383

# Handy piece of code

265 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.

EDIT: I don't know why gamedev's source formatter is putting brackets around the 1's and 0's in the if (!infinite) block. Don't do that. Just regular ones and zeros.

There are no comments to display.

## Create an account

Register a new account