• Advertisement
  • entries
    1212
  • comments
    1738
  • views
    1141997

Handy piece of code

Sign in to follow this  

255 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.
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement