Reputation: 109
I have this function calculating the closest distance between two infinite lines.
public static double GetClosestDistanceBetweenLines(Vector3 line1Point, Vector3 line1Vector, Vector3 line2Point, Vector3 line2Vector)
{
var u = line1Vector;
var v = line2Vector;
var w = line1Point- line2Point;
var a = Vector3.Dot(u, u); // always >= 0
var b = Vector3.Dot(u, v);
var c = Vector3.Dot(v, v); // always >= 0
var d = Vector3.Dot(u, w);
var e = Vector3.Dot(v, w);
var D = a * c - b * b; // always >= 0
double sc, tc;
// compute the line parameters of the two closest points
if (D < Epsilon)
{ // the lines are almost parallel
sc = 0.0;
tc = (b > c ? d / b : e / c); // use the largest denominator
}
else
{
sc = (b * e - c * d) / D;
tc = (a * e - b * d) / D;
}
// get the difference of the two closest points
var dP = w + (sc * u) - (tc * v); // = L1(sc) - L2(tc)
return dP.Length; // return the closest distance
}
However, I want to calculate the distance between two finite lines.
public static double GetClosestDistanceBetweenLines(Vector3 line1Point1, Vector3 line1Point2, Vector3 line2Point1, Vector3 line2Point2)
How do I do this?
Upvotes: 3
Views: 930
Reputation: 80325
You have got two parameters sc and tc.
If both lie in range 0..1, then closest distance points lie inside segments and distance is valid.
If parameter for one segment is out of this range, calculate distance from another segment to appropriate end of this segment. For example, if sc<0, use sc=0.
If both parameters are out of range, find the smallest distance for segment end combinations
Upvotes: 3