Code archives/Algorithms/minimum distance from point to line

This code has been declared by its author to be Public Domain code.

Download source code

minimum distance from point to line by TomToad2004
You can find the distance from a point to a line by calling the function MinDistPointLine#(px#,py#,x1#,y1#,x2#,y2#) where (px,py) is the point and (x1,y1)(x2,y2) defines the endpoints of a line. Useful for collision detection with games using line graphics. Just use something like:
If MinDistPointLine(px,py,x1,y1,x2,y2) < BoundingRadius then CollisionHappened()
You can also find the distance between 2 points by calling PointToPointDist#(x1#,y1#,x2#,y2#)
Function PointToPointDist#(x1#,y1#,x2#,y2#)

dx# = x1-x2
dy# = y1-y2

Return Sqr(dx*dx + dy*dy)
End Function

Function MinDistPointLine#(px#,py#,x1#,y1#,x2#,y2#)

If x1 = x2 And y1 = y2 Then Return PointToPointDist(px,py,x1,y1)

sx# = x2-x1
sy# = y2-y1

q# = ((px-x1) * (x2-x1) + (py - y1) * (y2-y1)) / (sx*sx + sy*sy)

If q < 0.0 Then q = 0.0
If q > 1.0 Then q = 1.0

Return PointToPointDist(px,py,(1-q)*x1+q*x2,(1-q)*y1 + q*y2)
End Function

Comments

Santiworld2009
hey!. thanks!


Code Archives Forum