Code archives/3D Graphics - Maths/Point distance to a Line

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

Download source code

Point distance to a Line by Danny2006
Given 2 3d points A and B (that make up for a line-segment) and a point P; this function will return the shortest distance between that point P and the line.
I use this for my vertex lighting system where I have a 'linear light' (a light defined by 2 3d coordinates) to check if a vertex (point P) is 'within range' of that light, and it's distance determines it's fall-off.

You could also use this to determin if the player is 'too close' to a laser beam for example (or some other linear-object) like: IF 'player-distance-to-line' <= 'heath-range-of-beam' THEN 'add damage to player' :)

Danny
Function PointDistanceToLine#( ax#,ay#,az#, bx#,by#,bz#, px#,py#,pz# )
;| Calculates the shortest distance between a point P(xyz) and a line segment defined by A(xyz) and B(xyz) - danny.

	;get the length of each side of the triangle ABP
	ab# = Sqr( (bx-ax)*(bx-ax) + (by-ay)*(by-ay) + (bz-az)*(bz-az) )
	bp# = Sqr( (px-bx)*(px-bx) + (py-by)*(py-by) + (pz-bz)*(pz-bz) )
	pa# = Sqr( (ax-px)*(ax-px) + (ay-py)*(ay-py) + (az-pz)*(az-pz) )

	;get the triangle's semiperimeter
	semi# = (ab+bp+pa) / 2.0
	
	;get the triangle's area
	area# = Sqr( semi * (semi-ab) * (semi-bp) * (semi-pa) )
	
	;return closest distance P to AB
	Return (2.0 * (area/ab))
	
End Function

Comments

Craig H. Nisbet2007
That works great! Thanks for posting!


puki2007
I use this for my vertex lighting system


Clear off "Nisbet" - this is clearly my code.


"Danny" - old buddy/pal.

You forgot to post the vertex lighting system - no need to worry - just email it to me - I'll check it over.


Code Archives Forum