Where is the Intersect between 2 lines

Monkey Forums/Monkey Code/Where is the Intersect between 2 lines

slenkar(Posted 2013) [#1]
Strict
Import mojo

Class intersect Extends App
Method OnUpdate:Int()
Return 0
End Method
Method OnRender:Int()
Cls(0,0,0)

Local line1x1:Int=20
Local line1y1:Int=20
Local line1x2:Int=90
Local line1y2:Int=20


Local line2x1:Int=30
Local line2y1:Int=15
Local line2x2:Int=30
Local line2y2:Int=90

DrawLine(line1x1,line1y1,line1x2,line1y2)
DrawLine(line2x1,line2y1,line2x2,line2y2)



Local A1:Float = line1y2-line1y1
 Local B1:Float = line1x1-line1x2
 Local C1:Float = A1*line1x1+B1*line1y1

Local A2:Float = line2y2-line2y1
 Local B2:Float = line2x1-line2x2
 Local C2:Float = A2*line2x1+B2*line2y1
 
Local delta:Float = A1*B2 - A2*B1
If(delta = 0) 
   Print("Lines are parallel");
Endif
Local x:Float = (B2*C1 - B1*C2)/delta
Local y:Float = (A1*C2 - A2*C1)/delta
SetColor (255,0,0)
DrawOval(x-1,y-1,2,2)
SetColor(255,255,255)
Return 0
End Method

Method OnCreate:Int()
SetUpdateRate(30)

Return 0
End Method
End Class

Function Main:Int()
New intersect
Return 0
End Function



Sub_Zero(Posted 2013) [#2]
Here's another one i ported from blitzmax:

        Field Intersection_X:Float
	Field Intersection_Y:Float
	
	Method Lines_Intersect:Int(Ax:Float, Ay:Float, Bx:Float, By:Float, Cx:Float, Cy:Float, Dx:Float, Dy:Float)	'finds the line intersections...
		Local DymCy:Float = Dy - Cy
		Local DxmCx:Float = Dx - Cx
	
		Local Rn:Float = (Ay-Cy)*(DxmCx) - (Ax-Cx)*(DymCy)
		Local Rd:Float = (Bx-Ax)*(DymCy) - (By-Ay)*(DxmCx)
	
		Local Intersection_AB:Float
		Local Intersection_CD:Float
		If Rd = 0 
		
		' Lines are parralel.
		' If Rn# is also 0 Then lines are coincident.  All points intersect. 
		' Otherwise, there is no intersection point.
			Return False
		Else
			' The lines intersect at some point.  Calculate the intersection point.
			Local Sn:Float = (Ay-Cy)*(Bx-Ax) - (Ax-Cx)*(By-Ay)
			Intersection_AB = Rn / Rd
			Intersection_CD = Sn / Rd
			Intersection_X = Ax + Intersection_AB*(Bx-Ax)
			Intersection_Y = Ay + Intersection_AB*(By-Ay)			
		Endif
		
		If Intersection_AB>0 And Intersection_AB<1 And Intersection_CD>0 And Intersection_CD<1
				Return True	
			Else
				Return False
		Endif
	End Method