2016-11-23 122 views
3

我有這個函數計算兩條無限行之間的最近距離。有限行之間的最近距離

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 
    } 

但是,我想計算兩條有限行之間的距離。

public static double GetClosestDistanceBetweenLines(Vector3 line1Point1, Vector3 line1Point2, Vector3 line2Point1, Vector3 line2Point2) 

我該怎麼做?

+0

這是否有幫助? http://stackoverflow.com/a/627578/106159 –

回答

3

您有兩個參數sc和tc。

如果兩者都位於範圍0..1內,則最近的距離點位於區段內且距離有效。

如果一個線段的參數超出此範圍,請計算從另一個線段到該線段適當端點的距離。例如,如果sc < 0,則使用sc = 0。

如果兩個參數都超出範圍,請找出段末端組合的最小距離