Skip to content

Instantly share code, notes, and snippets.

@twobob
Created January 5, 2025 00:17
Show Gist options
  • Save twobob/473a2ec5681bd1d404710345211e6be7 to your computer and use it in GitHub Desktop.
Save twobob/473a2ec5681bd1d404710345211e6be7 to your computer and use it in GitHub Desktop.
overlap circle code?
using UnityEngine;
public class CircleOverlapExample : MonoBehaviour
{
[System.Serializable]
public struct Circle
{
public Vector2 center;
public float radius;
}
// Returns half the combined overlap perimeter of two circles
float HalfOverlapPerimeter(Circle c1, Circle c2)
{
float dx = c2.center.x - c1.center.x;
float dy = c2.center.y - c1.center.y;
float d = Mathf.Sqrt(dx * dx + dy * dy);
float r1 = c1.radius, r2 = c2.radius;
// No intersection
if(d >= r1 + r2) return 0f;
// One circle completely inside another
if(d <= Mathf.Abs(r1 - r2))
{
float rMin = (r1 < r2) ? r1 : r2;
return Mathf.PI * 2f * rMin * 0.5f;
}
// Partial overlap
float alpha = 2f * Mathf.Acos((d * d + r1 * r1 - r2 * r2) / (2f * d * r1));
float beta = 2f * Mathf.Acos((d * d + r2 * r2 - r1 * r1) / (2f * d * r2));
float arc1 = r1 * alpha;
float arc2 = r2 * beta;
return 0.5f * (arc1 + arc2);
}
public Circle c1, c2, c3;
void Start()
{
float halfAB = HalfOverlapPerimeter(c1, c2);
float halfBC = HalfOverlapPerimeter(c2, c3);
float halfCA = HalfOverlapPerimeter(c3, c1);
Debug.Log("AB half-overlap: " + halfAB);
Debug.Log("BC half-overlap: " + halfBC);
Debug.Log("CA half-overlap: " + halfCA);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment