'構造体
Private Type POINTAPI
x As Long
y As Long
End Type
'座標 p1,p2 を結ぶ線分と座標 p3,p4 を結ぶ線分が交差しているかを調べる
'ただし、線分が重なっている場合(4点が一直線上にある)、「交差していない」、と判定します。
Private Function IntersectionStandard(p1 As POINTAPI, p2 As POINTAPI, _
p3 As POINTAPI, p4 As POINTAPI) As Boolean
'それぞれの点と点の差
Dim dx1 As Long, dx2 As Long, dy1 As Long, dy2 As Long
'交点
Dim xx As Long, yy As Long
dx1 = p1.x - p2.x: dy1 = p1.y - p2.y
dx2 = p3.x - p4.x: dy2 = p3.y - p4.y
'どちらもy軸に平行な線分ではない
If (dx1 <> 0& And dx2 <> 0&) Then
'平行な2線分ではない
If ((dy1 / dx1 - dy2 / dx2) <> 0&) Then
'交点を求める
xx = (p3.y - p1.y - p3.x * dy2 / dx2 + p1.x * dy1 / dx1) / _
(dy1 / dx1 - dy2 / dx2)
'その交点が線分の範囲にあるか
If (((xx <= p1.x And xx >= p2.x) Or (xx >= p1.x And xx <= p2.x)) And _
((xx <= p3.x And xx >= p4.x) Or (xx >= p3.x And xx <= p4.x))) Then
IntersectionStandard = True: Exit Function
End If
End If
'p1,p2 を結ぶ線分がy軸に平行である
ElseIf (dx1 = 0& And dx2 <> 0&) Then
'交点を求める
yy = p1.x * dy2 / dx2 + p3.y - p3.x * dy2 / dx2
'その交点が線分の範囲にあるか
If (((yy <= p1.y And yy >= p2.y) Or (yy >= p1.y And yy <= p2.y)) And _
((p1.x <= p3.x And p1.x >= p4.x) Or (p1.x >= p3.x And p1.x <= p4.x))) Then
IntersectionStandard = True: Exit Function
End If
'p3,p4 を結ぶ線分がy軸に平行である
ElseIf (dx1 <> 0& And dx2 = 0&) Then
yy = p3.x * dy1 / dx1 + p1.y - p1.x * dy1 / dx1
If (((yy <= p3.y And yy >= p4.y) Or (yy >= p3.y And yy <= p4.y)) And _
((p3.x <= p1.x And p3.x >= p2.x) Or (p3.x >= p1.x And p3.x <= p2.x))) Then
IntersectionStandard = True: Exit Function
End If
End If
'それ以外は交差しない
IntersectionStandard = False: Exit Function
End Function
|