Line-to-Square Collision

Blitz3D Forums/Blitz3D Programming/Line-to-Square Collision

Buggy(Posted 2008) [#1]
Does anyone know of how I could conceivably detect whether or not a line intersects a square? Some sort of polygon-polygon collision would also work.

I only need the theory... I can write my own code.

Oh, and 2D only, so no useful picking or triangle stuff. I've tried searching the archives, old posts, and Google too, and I can't seem to get anything useful, so any help would be much appreciated.


Nate the Great(Posted 2008) [#2]
You can use the line intersects function Here it is. You would have to call it for every side of the square though and it isn't the most efficient way.




Jasu(Posted 2008) [#3]
I think this could be possible using orientation.

Function Orientation% ( x1#,y1#, x2#,y2#, Px#,Py# )
	; Linear determinant of the 3 points.
	; This function returns the orientation of px,py on line x1,y1,x2,y2.
	; Look from x2,y2 to the direction of x1,y1.
	; If px,py is on the right, function returns +1
	; If px,py is on the left, function returns -1
	; If px,py is directly ahead or behind, function returns 0
	Return Sgn((x2 - x1) * (Py - y1) - (Px - x1) * (y2 - y1))
End Function

I think that instead of checking when it does intersect, you need to deductively check when it doesn't intersect. For example put your line in parameters x1,y1,x2,y2 and run it with each of the corners of the square (calling the function 4 times). If the results are the same (-1,-1,-1,-1 or +1,+1,+1,+1), then you definitely have no intersection. If results are different, you need to continue with tests. The second set of tests would be running the function with sides of the square against end points of the line. If both ends of the line are on the "wrong" side of the square side, the line does not intersect. Then do the same for all 4 sides.

I think this would be enough to deduct all the possibilities when it doesn't intersect. I'm not sure though, so you need to test it properly. At maximum, you would be running Orientation function 12 times, but since the math of that function is so simple, it should be quite fast. Also it does less math if there is no intersection.

There should be seperate handling for the case where the length of the line is 0, but that should be easy.