This example treats the segments as parameterized vectors:
X = X1 + t * (X2 - X1), Y = Y1 + t * (Y2 - Y1)
X = A1 + s * (A2 - A1), Y = B1 + s * (B2 - B1)
where the parameters s and t vary from 0 to 1. It solves these equations for s and t to see where the lines intersect. If the segments intersect, then s and t are both between 0.0 and 1.0.
|
' Return True if the segments intersect.
Private Function SegmentsIntersect(ByVal X1 As Single, _
ByVal Y1 As Single, ByVal X2 As Single, ByVal Y2 As _
Single, ByVal A1 As Single, ByVal B1 As Single, ByVal _
A2 As Single, ByVal B2 As Single) As Boolean
Dim dx As Single
Dim dy As Single
Dim da As Single
Dim db As Single
Dim t As Single
Dim s As Single
dx = X2 - X1
dy = Y2 - Y1
da = A2 - A1
db = B2 - B1
If (da * dy - db * dx) = 0 Then
' The segments are parallel.
SegmentsIntersect = False
Exit Function
End If
s = (dx * (B1 - Y1) + dy * (X1 - A1)) / (da * dy - db * _
dx)
t = (da * (Y1 - B1) + db * (A1 - X1)) / (db * dx - da * _
dy)
SegmentsIntersect = (s >= 0# And s <= 1# And _
t >= 0# And t <= 1#)
' If it exists, the point of intersection is:
' (x1 + t * dx, y1 + t * dy)
End Function
|