2014-04-11 58 views
5

我有一個線段(x1,y1,x2,y2)與半徑爲r的圓相交。我怎樣才能確定哪個交點最接近(x1,y1)?線段和圓交點

circle-line

+1

你能解釋一下「最接近的交點」是什麼意思?這是圓上的一個點嗎?細分市場上的一個點?兩件事都沒有? – andand

+4

這是一個基本的數學問題,將解決方案轉換爲C#非常簡單,並且不會使問題更具相關性。 –

+0

@andand相交點屬於兩條線。 – Dmitry

回答

7

要做到這一點首先找到與圓的交點,然後取最接近的一個線起點

所以檢查這個代碼

// CX,CY爲中心圓的點

 public PointF ClosestIntersection(float cx, float cy, float radius, 
      PointF lineStart, PointF lineEnd) 
     { 
      PointF intersection1; 
      PointF intersection2; 
     int intersections = FindLineCircleIntersections(cx, cy, radius, lineStart, lineEnd, out intersection1, out intersection2); 

     if (intersections == 1) 
      return intersection1;//one intersection 

     if (intersections == 2) 
     { 
      double dist1 = Distance(intersection1, lineStart); 
      double dist2 = Distance(intersection2, lineStart); 

      if (dist1 < dist2) 
       return intersection1; 
      else 
       return intersection2; 
     } 

     return PointF.Empty;// no intersections at all 
    } 

    private double Distance(PointF p1, PointF p2) 
    { 
     return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)); 
    } 

    // Find the points of intersection. 
    private int FindLineCircleIntersections(float cx, float cy, float radius, 
     PointF point1, PointF point2, out PointF intersection1, out PointF intersection2) 
    { 
     float dx, dy, A, B, C, det, t; 

     dx = point2.X - point1.X; 
     dy = point2.Y - point1.Y; 

     A = dx * dx + dy * dy; 
     B = 2 * (dx * (point1.X - cx) + dy * (point1.Y - cy)); 
     C = (point1.X - cx) * (point1.X - cx) + (point1.Y - cy) * (point1.Y - cy) - radius * radius; 

     det = B * B - 4 * A * C; 
     if ((A <= 0.0000001) || (det < 0)) 
     { 
      // No real solutions. 
      intersection1 = new PointF(float.NaN, float.NaN); 
      intersection2 = new PointF(float.NaN, float.NaN); 
      return 0; 
     } 
     else if (det == 0) 
     { 
      // One solution. 
      t = -B/(2 * A); 
      intersection1 = new PointF(point1.X + t * dx, point1.Y + t * dy); 
      intersection2 = new PointF(float.NaN, float.NaN); 
      return 1; 
     } 
     else 
     { 
      // Two solutions. 
      t = (float)((-B + Math.Sqrt(det))/(2 * A)); 
      intersection1 = new PointF(point1.X + t * dx, point1.Y + t * dy); 
      t = (float)((-B - Math.Sqrt(det))/(2 * A)); 
      intersection2 = new PointF(point1.X + t * dx, point1.Y + t * dy); 
      return 2; 
     } 
    } 

路口代碼的形式在這裏LINK

+1

距離的順序不會被sqrt改變,因此最好讓它們平方以獲得更好的速度。 – Preza8