Solved
VB Calculating the distance between a point and a line segment
Posted on 2003-11-14
Hey, I'm trying to calculate the distance between a point and a line segment with a function. The only possible line segments are in 45 degree rotations, eg: _ | / \
I almost have it done, but my last problem is that if the line is in this orientation / it seems to move the line or somehow thing that it is like \ This is what I have so far. THe code at the beginning prevents similar screw ups like this with the other line orientations bu just swaping the pairs of coordinates.
' Calculate the distance between the point and the segment
Public Function DistanceToLine(PX As Single, PY As Single, X1 As Single, Y1 As Single, X2 As Single, Y2 As Single) As Single
Dim TempX As Single, TempY As Single
Dim DX As Single, DY As Single
Dim T As Single
'Swap coords if needed to keep the first one smaller
If (X1 > X2) Or (Y1 > Y2) Then
TempX = X1
TempY = Y1
X1 = X2
Y1 = Y2
X2 = TempX
Y2 = TempY
End If
' Calculate the distance between the point and the segment
DX = Abs(X2 - X1)
DY = Abs(Y2 - Y1)
T = (PX + PY - X1 - Y1) / (DX + DY)
If T < 0 Then
DX = PX - X1
DY = PY - Y1
ElseIf T > 1 Then
DX = PX - X2
DY = PY - Y2
Else
X2 = X1 + T * DX
Y2 = Y1 + T * DY
DX = PX - X2
DY = PY - Y2
End If
DistanceToLine = Sqr(DX * DX + DY * DY)
End Function
Thanks, Jebus