getCircleIntersections method

List<Point> getCircleIntersections(
  1. Circle other
)

Get intersection points of this circle with other

Returns 0, 1, or 2 points.

Implementation

List<Point> getCircleIntersections(Circle other) {
  final dist = center.distanceTo(other.center);

  // No intersection
  if (dist > radius + other.radius) return [];
  if (dist < (radius - other.radius).abs()) return [];
  if (dist == 0 && radius == other.radius) return [];

  final a = (radius * radius - other.radius * other.radius + dist * dist) /
      (2 * dist);
  final hSq = radius * radius - a * a;
  if (hSq < 0) return [];
  final h = sqrt(max(0, hSq));

  final px = center.x + a * (other.center.x - center.x) / dist;
  final py = center.y + a * (other.center.y - center.y) / dist;

  if (h < 1e-10) {
    return [Point(px, py)];
  }

  final rx = -h * (other.center.y - center.y) / dist;
  final ry = h * (other.center.x - center.x) / dist;

  return [
    Point(px + rx, py + ry),
    Point(px - rx, py - ry),
  ];
}