2D Line Intersection

Blitz3D Forums/Blitz3D Programming/2D Line Intersection

Otus(Posted 2006) [#1]
I'm attempting to write a collision system, which uses vector projection of the velocity vector on a line (ground). However, I have a problem with finding the point of intersection between perpendicular lines. Some variables will always get a value of either "Infinity" or "NaN" due to division by zero or division of zero by zero.

If someone could offer help I'd greatly appreciate. The code should be quite self explanatory. Remove the semicolons to see a situation, where my method does not work.

SeedRnd MilliSecs()
Graphics 800,600

.start

Cls

x1#=Rnd(100,700)
x2#=Rnd(100,700)

y1#=Rnd(100,500)
y2#=Rnd(100,500)

a1#=Rnd(100,700)
a2#=Rnd(100,700)

b1#=Rnd(100,500)
b2#=Rnd(100,500)

;a1#=100
;a2#=700

;b1#=300
;b2#=300

;x1#=400
;x2#=400

;y1#=200
;y2#=400


Color 192,192,192
Line x1,y1,x2,y2

Color 128,128,128
Line a1,b1,a2,b2

t#=((b1#-y1#)*(x2#-x1#) - (y2#-y1#)*(a1#-x1#)) / ((y2#-y1#)*(a2#-a1#) - (b2#-b1#)*(x2#-x1#))
t2#=(b1+t*(a2-a1)-x1) / (x2-x1)

Print t#


If t>=0 And t<=1 And t2>=0 And t2<=1
	c#=a1+t*(a2-a1)
	d#=b1+t*(b2-b1)
	
	Color 0,192,0
	Line a1,b1,c,d
	
	x#=c+((a2-c)*(x2-x1) + (b2-d)*(y2-y1)) / ((x2-x1)^2 + (y2-y1)^2) * (x2-x1)
	y#=d+((a2-c)*(x2-x1) + (b2-d)*(y2-y1)) / ((x2-x1)^2 + (y2-y1)^2) * (y2-y1)
	
	Color 192,0,0
	Line c,d,x,y
End If

WaitKey

If KeyDown(2) Then Goto start



BlackJumper(Posted 2006) [#2]
For the case where x1=x2, the difference will be zero. You need to code this as a special case. Since you know the x-ordinate of both, there is no need to project... just work out the equivalent y-ordinate on the other line (checking first that its range will actually lead to an intersection... i.e. a1 < x1 and x1 < a2 for the case a1 < a2 )

You might also have to check for ((y2#-y1#)*(a2#-a1#) - (b2#-b1#)*(x2#-x1#)) = 0