2012-08-31 12 views
15

enter image description here2つの円の交点x、yを返すJavaScript関数ですか?

I(x、y)は中心二つの円の位置とその半径を得たが、私はJavaScriptを使用して(赤でマークされた)それらの交点を見つける必要があります。

数学に関する限り最良の説明はhere(2つの円の交点)ですが、私は実際に数学を理解していないので実装できません。

たとえば、d = || P1-P0 || 、何をしますか?立つ?結果の数字が常に正であることを意味しますか?

また、P2 = P0 + a(P1-P0)/ d、Pはここ(10,50)のようなものではありませんか?しかし、JavaScriptで(10,50)+13を実行すると63になるので、最初の数字は無視されますので、どうなるのでしょうか?結果はここ(23,63)か?また、P1-P0部分または(40,30) - (10,60)では、JavaScriptでどのように表現していますか?

+2

これらはベクトル関数です。あなたは結局、二次元で動作しています。あなたが望む結果を得るためには、JSで同等のベクトル代数関数を構築する必要があります。 – Xophmeister

+2

...下部にリンクされているC実装をJavaScriptに変換するか、翻訳します。 – duskwuff

+2

'd = || P1-P0 ||'はポイントP0とP1との間の距離を意味するので、d = sqrt((x1-x2)2 +(y1-y2)2) –

答えて

31

はJavaScriptにサイト上でC関数を翻訳:

function intersection(x0, y0, r0, x1, y1, r1) { 
     var a, dx, dy, d, h, rx, ry; 
     var x2, y2; 

     /* dx and dy are the vertical and horizontal distances between 
     * the circle centers. 
     */ 
     dx = x1 - x0; 
     dy = y1 - y0; 

     /* Determine the straight-line distance between the centers. */ 
     d = Math.sqrt((dy*dy) + (dx*dx)); 

     /* Check for solvability. */ 
     if (d > (r0 + r1)) { 
      /* no solution. circles do not intersect. */ 
      return false; 
     } 
     if (d < Math.abs(r0 - r1)) { 
      /* no solution. one circle is contained in the other */ 
      return false; 
     } 

     /* 'point 2' is the point where the line through the circle 
     * intersection points crosses the line between the circle 
     * centers. 
     */ 

     /* Determine the distance from point 0 to point 2. */ 
     a = ((r0*r0) - (r1*r1) + (d*d))/(2.0 * d) ; 

     /* Determine the coordinates of point 2. */ 
     x2 = x0 + (dx * a/d); 
     y2 = y0 + (dy * a/d); 

     /* Determine the distance from point 2 to either of the 
     * intersection points. 
     */ 
     h = Math.sqrt((r0*r0) - (a*a)); 

     /* Now determine the offsets of the intersection points from 
     * point 2. 
     */ 
     rx = -dy * (h/d); 
     ry = dx * (h/d); 

     /* Determine the absolute intersection points. */ 
     var xi = x2 + rx; 
     var xi_prime = x2 - rx; 
     var yi = y2 + ry; 
     var yi_prime = y2 - ry; 

     return [xi, xi_prime, yi, yi_prime]; 
    } 
+0

ES6から、 'Math.sqrt((dy * dy)+(dx * dx))'の代わりに 'Math.hypot(dx、dy)'を使うことができます。 – Arnauld

関連する問題