Math & Physics
Beginner
Unity 2021.3+ / Unity 6
원(Circle)과 축 정렬 경계 상자(AABB) 간의 최단 접점 클램핑 충돌 검사Circle vs. AABB Closest-Point Clamping Collision Detection
별도의 무거운 물리 엔진 없이 원형 캐릭터·투사체와 직사각형 타일 사이의 교차 여부, 충돌 법선(Normal), 침투 깊이(Penetration Depth)를 구하는 2D 충돌 판정 수학입니다.2D collision mathematics for testing intersection, contact normal, and penetration depth between a circle and an Axis-Aligned Bounding Box (AABB) without a heavy physics engine.
#Math #Physics #Collision #Geometry #2D
핵심 개념축 정렬 경계 상자(AABB) 영역 안에서 원의 중심 좌표에 가장 가까운 최단 접점 $C$를 구하려면, 원 중심의 $(x, y)$ 좌표를 각각 상자의
[min, max] 범위로 클램핑(Clamp)하면 됩니다. 원 중심과 접점 $C$ 사이의 거리 제곱이 반지름 제곱($R^2$)보다 작으면 두 도형은 교차한 상태입니다.Key ConceptTo find the closest point $C$ on or inside an Axis-Aligned Bounding Box (AABB) to a circle's center, clamp the circle center's $(x, y)$ coordinates to the box's
[min, max] bounds along each axis. If the squared distance between the circle center and $C$ is less than the squared radius ($R^2$), the two shapes intersect.1. Circle vs AABB 판정 C# 구현1. Circle vs. AABB Collision Check in C#
using UnityEngine;
public static class Collision2DUtil
{
public static bool CheckCircleAABB(
Vector2 circleCenter, float radius, Rect box, out Vector2 normal, out float depth)
{
normal = Vector2.zero;
depth = 0f;
// 1. 박스 내부 영역으로 가장 가까운 접점 클램핑
float closestX = Mathf.Clamp(circleCenter.x, box.xMin, box.xMax);
float closestY = Mathf.Clamp(circleCenter.y, box.yMin, box.yMax);
Vector2 closestPoint = new Vector2(closestX, closestY);
// 2. 제곱 거리 검사 (불필요한 Sqrt 연산 지연)
Vector2 diff = circleCenter - closestPoint;
float distSqr = diff.sqrMagnitude;
if (distSqr < radius * radius)
{
float dist = Mathf.Sqrt(distSqr);
normal = dist > 0.0001f ? diff / dist : Vector2.up;
depth = radius - dist;
return true;
}
return false;
}
}
using UnityEngine;
public static class Collision2DUtil
{
public static bool CheckCircleAABB(
Vector2 circleCenter, float radius, Rect box, out Vector2 normal, out float depth)
{
normal = Vector2.zero;
depth = 0f;
// 1. Clamp circle center to box bounds to find closest point
float closestX = Mathf.Clamp(circleCenter.x, box.xMin, box.xMax);
float closestY = Mathf.Clamp(circleCenter.y, box.yMin, box.yMax);
Vector2 closestPoint = new Vector2(closestX, closestY);
// 2. Squared distance check (defer Sqrt until collision is confirmed)
Vector2 diff = circleCenter - closestPoint;
float distSqr = diff.sqrMagnitude;
if (distSqr < radius * radius)
{
float dist = Mathf.Sqrt(distSqr);
normal = dist > 0.0001f ? diff / dist : Vector2.up;
depth = radius - dist;
return true;
}
return false;
}
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- 제곱 거리(
sqrMagnitude) 비교를 통한Sqrt연산 절약: 대다수의 비충돌 프레임에서는distSqr < radius * radius비교만으로 즉시false를 반환하고, 실제 충돌이 확정된 경우에만 비용이 큰Mathf.Sqrt()를 1회 호출하도록 구성해야 성능상 유리합니다. - 원 중심이 상자 내부에 완전히 들어간 경우의 예외 처리: 고속 이동으로 인해 원의 중심(
circleCenter)이 AABB 내부로 깊숙이 파고들면closestPoint == circleCenter가 되어dist == 0이 됩니다. 이때 단순히Vector2.up으로 밀어내면 벽 안쪽으로 잘못 튕길 수 있으므로, 상자의 4개 변(xMin,xMax,yMin,yMax) 중 가장 가까운 변의 바깥쪽 법선과 거리로 보정해 주어야 합니다. - 위치 보정(Depenetration) 적용 방법: 충돌이 감지되었을 때 원의 좌표를
circleCenter += normal * depth;만큼 즉시 밀어내면 타일 모서리에 끼이지 않고 부드럽게 미끄러지는 슬라이딩 이동을 구현할 수 있습니다.
- Defer
Mathf.Sqrtvia Squared Distance Comparison: ComparingdistSqr < radius * radiusrejects non-overlapping pairs using only multiplication and addition, invokingMathf.Sqrt()only when an actual overlap occurs. - Handling Circle Centers Deep Inside the AABB: If high speed pushes
circleCenterinside the box,closestPointequalscircleCenter(dist == 0). For full depenetration in fast-moving games, find the minimum distance to the four edges (xMin,xMax,yMin,yMax) and push the circle out along that nearest face normal. - Applying Depenetration for Smooth Wall Sliding: Resolving overlaps by adding
circleCenter += normal * depth;pushes the circle cleanly around box corners and along flat walls.
클램핑 기반 Circle-AABB 판정은 사각형 모서리에서의 대각선 밀어내기 벡터까지 하나의 수식으로 계산해 주므로, 커스텀 2D 캐릭터 컨트롤러나 탄막 슈팅 충돌 엔진의 기본 구성 요소로 활용됩니다.
Clamping-based Circle-AABB detection handles both flat edge contacts and rounded corner normals in a single branchless clamp step, making it a practical building block for custom 2D physics.