Closest point on a line

BlitzMax Forums/BlitzMax Programming/Closest point on a line

Raz(Posted 2012) [#1]
I looked in the code archives but couldn't see anything

Looking for the closest point on a line to another point. So something like.

Global LinePointX:Float
Global LinePointY:Float

Function ClosestPointOfLine( PointX:Float, PointY:Float, LineX1:Float, LineY1:Float, LineX2:Float, LineY2:Float )
    ' Magic fun here that sets LinePointX and LinePointY to whatever
EndFunction


Anyone know of such a thing?

Ta!


Raz(Posted 2012) [#2]
Woop! :)

Global PointOnLineX:Float
Global PointOnLineY:Float
Function ClosestPointOnLine( PX:Float, PY:Float, LX1:Float, LY1:Float, LX2:Float, LY2:Float)

	' PA Vector
	Local PL1DX:Float = PX - LX1
	Local PL1DY:Float = PY - LY1
	
	' AB Vector
	Local L2L1DX:Float = LX2 - LX1
	Local L2L1DY:Float = LY2 - LY1
	
	Local AB2:Float = ( L2L1DX * L2L1DX ) + ( L2L1DY * L2L1DY )
	Local APAB:Float = ( PL1DX * L2L1DX ) + ( PL1DY * L2L1DY )
	
	Local T:Float = APAB / AB2
	
	If T < 0.0
		T = 0.0
	ElseIf T > 1.0
		T = 1.0
	EndIf
	
	PointOnLineX = LX1 + (L2L1DX * T)
	PointOnLineY = LY1 + (L2L1DY * T)

EndFunction



Jesse(Posted 2012) [#3]
yes very useful. It can also help figure out distance to line:
Function PointDIstanceToLine:float( PX:Float, PY:Float, LX1:Float, LY1:Float, LX2:Float, LY2:Float)

	' PA Vector
	Local PL1DX:Float = PX - LX1
	Local PL1DY:Float = PY - LY1
	
	' AB Vector
	Local L2L1DX:Float = LX2 - LX1
	Local L2L1DY:Float = LY2 - LY1
	
	Local AB2:Float = ( L2L1DX * L2L1DX ) + ( L2L1DY * L2L1DY )
	Local APBA:Float = ( PL1DX * L2L1DY ) - ( PL1DY * L2L1DX )
	
	Local D:Float = APBA / AB2
	
	Return Sqr((L2L1DY *D)^2+(L2L1DX * D)^2)

End Function


this is how I first learned to check collision for circle and line.
both very useful