Code archives/3D Graphics - Maths/BMAX - Distance from Point to Line

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

Download source code

BMAX - Distance from Point to Line by Leon Drake
(Posted 19 years ago)
This is some old C code i found and ported it to Bmax. basically the command to run is DistancePointLine it returns True or False if the Point is within the line's segment. but you can access its X Y & Z coordinates on the line by grabbing ix,iy,iz and Distance# is the area distance from the point to the line.
Function Magnitude#( px#,py#,pz#,dx#,dy#,dz# )

 Local vx#,vy#,vz#
 vx# = dx# - px#
 vy# = dy# - py#
 vz# = dz# - pz#
 Return Float(Sqr( vx# * vx# + vy# * vy# + vz# * vz# ))
End Function

Function DistancePointLine( ax#,ay#,az#,bx#,by#,bz#,px#,py#,pz# )
 Local LineMag#,U#
 Local ix#,iy#,iz#
 Local Distance#
 LineMag# = Magnitude( bx#, by#, bz#, ax#, ay#, az# )
 U# = ( ( ( px# - ax# ) * ( bx# - ax# ) ) +( ( py# - ay# ) * ( by# - ay# ) ) +( ( pz# - az# ) * ( bz# - az# ) ) ) /( LineMag# * LineMag# )

 If  U# < 0.0 Or U# > 1.0 Then Return False 
 ' closest point does Not fall within the line segment
 
 ix# = ax# + U# * ( bx# - ax# )
 iy# = ay# + U# * ( by# - ay# )
 iz# = az# + U# * ( bz# - az# )
 Distance# = Magnitude( px#,py#,pz#,ix#,iy#,iz# )
 Return True
End Function