2012-08-31 15 views
15

enter image description hereFunkcja JavaScript, która zwraca x, y punktów przecięcia między dwoma okręgami?

mam (x, y) w samym centrum dwóch okręgów i ich promień ale muszę znaleźć swoje punkty przecięcia (zaznaczone na czerwono) przy użyciu JavaScript.

Myślę, że najlepszym wyjaśnieniem w odniesieniu do matematyki jest here (przecięcie dwóch okręgów), ale tak naprawdę nie rozumiem matematyki, więc nie jestem w stanie jej wdrożyć.

Na przykład d = || P1 - P0 || , co robi || oznaczać? Czy to oznacza, że ​​wynikowa liczba jest zawsze dodatnia?

A także P2 = P0 + a (P1 - P0)/d, czy P nie ma tutaj czegoś takiego jak (10, 50)? Ale wykonanie (10,50) +13 w JavaScript daje 63, więc po prostu ignoruje pierwszą liczbę, więc co się stanie? Czy wynik powinien być tutaj (23,63) czy? A także część P1-P0 lub (40,30) - (10,60), jak wyrazić to w JavaScript?

+2

Są to funkcje wektorowe; w końcu działasz w dwóch wymiarach. Musisz skonstruować równoważne funkcje algebry wektorowej w JS, aby uzyskać pożądany rezultat. – Xophmeister

+2

... lub przetłumacz implementację C połączoną na dole z JavaScript. – duskwuff

+2

'd = || P1 - P0 ||' oznacza odległość między punktami P0 i P1, więc d = sqrt ((x1-x2) ² + (y1-y2) ²) –

Odpowiedz

31

Tłumaczone funkcję C na miejscu do JavaScript:

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

Począwszy od ES6, zamiast 'Math.sqrt ((dy * dy) + (dx * dx)) można użyć' Math.hypot (dx, dy) '. – Arnauld

Powiązane problemy