Math & Physics
Intermediate
Unity 2021.3+ / Unity 6
각도와 거리 가중치를 합산하는 스마트 타깃 조준 보정 알고리즘Smart Target Aim-Assist Scoring Algorithm with Angle and Distance Weights
고속 액션 환경에서 조준 방향과 후보 대상 간의 각도 오차, 정규화 거리 비율, 장애물 가림 여부를 평가해 최적의 타깃을 선별하는 조준 보정(Aim Assist) 수학입니다.Evaluating angular error, normalized distance ratio, and line-of-sight occlusion in C# to select the optimal grapple anchor or enemy target during fast-paced gameplay.
#Math #Algorithm #Aim Assist #2D Physics #Gameplay
핵심 개념빠르게 이동하는 액션 게임이나 게임패드 스틱 조작에서는 작은 앵커 포인트나 적을 픽셀 단위로 정확히 조준하기 어렵습니다. 유효 반경과 시야각(FOV Cone) 내의 후보들을 수집한 뒤, 각도 오차($\theta$)와 정규화 거리 비율($d / D_{\max}$)을 가중치 합산하여 비용 점수(Cost Score)가 가장 낮은 대상으로 조준선을 보정합니다.
Key ConceptIn high-speed action games or when aiming with a gamepad thumbstick, hitting pixel-sized grapple anchors or fast enemies directly is difficult. By gathering candidates within a maximum range and FOV cone, verifying line of sight, and combining angular error ($\theta$) with normalized distance ($d / D_{\max}$) into a weighted cost score, the system snaps cleanly to the candidate that best matches player intent.
1. 타깃 보정 스코어링 알고리즘 C# 구현1. Target Aim-Assist Scoring Implementation in C#
using UnityEngine;
public static class AimAssistScoring
{
private static readonly Collider2D[] HitBuffer = new Collider2D[32];
public static Transform FindBestTarget(
Vector2 origin, Vector2 aimDirection, float maxDistance, float maxAngle,
LayerMask targetLayer, LayerMask obstacleLayer, float distanceBias = 20f)
{
int count = Physics2D.OverlapCircleNonAlloc(origin, maxDistance, HitBuffer, targetLayer);
Transform bestTarget = null;
float bestScore = float.MaxValue;
for (int i = 0; i < count; i++)
{
Collider2D col = HitBuffer[i];
Vector2 targetPos = col.bounds.center;
Vector2 toTarget = targetPos - origin;
float dist = toTarget.magnitude;
if (dist < 0.1f) continue;
Vector2 dir = toTarget / dist;
float angle = Vector2.Angle(aimDirection, dir);
if (angle <= maxAngle)
{
// 지형·벽 장애물 가림 검사 (Line of Sight Raycast)
RaycastHit2D hit = Physics2D.Raycast(origin, dir, dist - 0.1f, obstacleLayer);
if (hit.collider == null)
{
// 낮을수록 우수한 비용 점수 = 각도 오차(deg) + 정규화 거리(0~1) * 거리 가중치
float score = angle + (dist / maxDistance) * distanceBias;
if (score < bestScore)
{
bestScore = score;
bestTarget = col.transform;
}
}
}
}
return bestTarget;
}
}
using UnityEngine;
public static class AimAssistScoring
{
private static readonly Collider2D[] HitBuffer = new Collider2D[32];
public static Transform FindBestTarget(
Vector2 origin, Vector2 aimDirection, float maxDistance, float maxAngle,
LayerMask targetLayer, LayerMask obstacleLayer, float distanceBias = 20f)
{
int count = Physics2D.OverlapCircleNonAlloc(origin, maxDistance, HitBuffer, targetLayer);
Transform bestTarget = null;
float bestScore = float.MaxValue;
for (int i = 0; i < count; i++)
{
Collider2D col = HitBuffer[i];
Vector2 targetPos = col.bounds.center;
Vector2 toTarget = targetPos - origin;
float dist = toTarget.magnitude;
if (dist < 0.1f) continue;
Vector2 dir = toTarget / dist;
float angle = Vector2.Angle(aimDirection, dir);
if (angle <= maxAngle)
{
// Line-of-Sight raycast check against walls/obstacles
RaycastHit2D hit = Physics2D.Raycast(origin, dir, dist - 0.1f, obstacleLayer);
if (hit.collider == null)
{
// Lower cost score is better = angular error (deg) + normalized distance (0~1) * bias
float score = angle + (dist / maxDistance) * distanceBias;
if (score < bestScore)
{
bestScore = score;
bestTarget = col.transform;
}
}
}
}
return bestTarget;
}
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- 정적 버퍼를 통한 GC 할당 방지: 매 프레임 조준선 프리뷰 UI를 갱신할 때
Physics2D.OverlapCircleAll을 호출하면 배열 힙 할당이 누적되므로, 미리 선언한 고정 크기 배열(Collider2D[32])과 Non-Alloc 오버로드(또는 Unity 6의Physics2D.OverlapCircle(origin, maxDistance, contactFilter, results))를 사용해야 합니다. - 타깃 전환 깜빡임 방지를 위한 히스테리시스(Hysteresis) 부여: 두 타깃의 점수가 거의 비슷할 때 플레이어가 조금만 움직여도 조준 대상이 매 프레임 번갈아 바뀌는 채터링이 발생할 수 있습니다. 직전 프레임에 선택되었던 타깃(
currentLockedTarget)에는 점수 계산 시-3.0f정도의 보너스(가점)를 부여해 임계치를 넘을 때만 타깃이 교체되도록 구성합니다. - 단위 정규화와
distanceBias조율:angle은 도(Degree, 예:0~45) 단위이고dist / maxDistance는0~1범위이므로,distanceBias를20f로 설정하면 최대 사거리 끝에 있는 타깃은 정조준 시 약 20도의 각도 페널티와 동등한 비용을 갖게 됩니다.
- Use Pre-Allocated Buffers to Avoid GC Allocations: Calling
Physics2D.OverlapCircleAllevery frame to update a targeting reticle allocates managed arrays and triggers garbage collection. Reuse a static buffer (Collider2D[32]) with Non-Alloc queries (orPhysics2D.OverlapCircle(origin, maxDistance, contactFilter, results)in Unity 6). - Add Hysteresis (Sticky Bias) to Prevent Target Flickering: When two targets have nearly identical scores, slight player movement can cause the lock-on reticle to flicker rapidly between them. Subtract a small stickiness bonus (e.g.,
-3.0fdegrees) from the currently locked target's score so the reticle switches only when another candidate is decisively better. - Balancing
distanceBiasAgainst Degree Units: Becauseangleis measured in degrees (e.g.,0–45) whiledist / maxDistanceis normalized to0–1, settingdistanceBias = 20fmakes a target at maximum range equivalent in cost to a point-blank target that is20°off-axis.
시야각 제한, 시선 가림(Line-of-Sight) 레이캐스트, 그리고 각도·거리 가중치 비용 함수를 결합하면 플레이어의 조준 의도를 해치지 않으면서도 쾌적한 타깃 락온 보조 시스템을 구축할 수 있습니다.
Combining FOV cone filtering, line-of-sight occlusion raycasts, and a weighted angle-distance cost function produces an aim-assist system that respects player aim direction while keeping fast traversal responsive.