Skip to content

Instantly share code, notes, and snippets.

@w8r
Created January 12, 2017 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w8r/f20462dac3c2b7853fd0da5df83faa63 to your computer and use it in GitHub Desktop.
Save w8r/f20462dac3c2b7853fd0da5df83faa63 to your computer and use it in GitHub Desktop.
Circle-circle intersection
/**
* Intersection point of 2 circles
*
* http://paulbourke.net/geometry/circlesphere/
*
* @param {number} x0
* @param {number} y0
* @param {number} r0
* @param {number} x1
* @param {number} y1
* @param {number} r1
* @return {null|Array.<Array.<number>>}
*/
function circleCircleIntersection (x0, y0, r0, x1, y1, r1) {
let a, dx, dy, d, h, rx, ry;
let 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(dx * dx + dy * dy);
// no solution. circles do not intersect.
if (d > (r0 + r1)) return null;
// no solution. one circle is contained in the other
if (d < Math.abs(r0 - r1)) return null;
// '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 * 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
return [
[x2 + rx, y2 + ry],
[x2 - rx, y2 - ry]
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment