ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Math & Physics > 2D/3D 물리 오브젝트의 흔들림 없는 타깃 추적을 위한 PID 제어기 구현Implementing a PID Controller for Oscillation-Free Physics Target Tracking
Math & Physics Intermediate Unity 2021.3+ / Unity 6

2D/3D 물리 오브젝트의 흔들림 없는 타깃 추적을 위한 PID 제어기 구현Implementing a PID Controller for Oscillation-Free Physics Target Tracking

비례(P), 적분(I), 미분(D) 항을 결합하여 차량 조향, 호버링 드론 수평 유지, 물리 기반 카메라 추적 시 오버슈트(Overshoot)와 진동을 억제하는 제어기 구현입니다.Combining Proportional (P), Integral (I), and Derivative (D) terms in C# to suppress overshoot and oscillation in vehicle steering, drone hovering, and physics-driven camera tracking.

#Math #Physics #PID #ControlTheory #Robotics
핵심 개념물리 엔진(Rigidbody.AddForce) 환경에서 단순히 목표까지의 거리 오차에 비례해 힘을 가하는 P 제어만 사용하면 관성 때문에 목표 지점을 지나쳐 왕복 진동(Overshoot)이 발생합니다. 변화율에 저항하는 미분(D) 항으로 제동력을 가하고, 중력이나 외력에 의한 정상 상태 오차(Steady-State Error)를 적분(I) 항으로 보상하면 물리 객체를 목표 위치에 안정적으로 수렴시킬 수 있습니다.
Key ConceptApplying force strictly proportional to position error (P-only control) via Rigidbody.AddForce causes momentum to carry the object past the target, resulting in oscillation (overshoot). Adding a Derivative (D) term provides braking force against rapid approach speeds, while an Integral (I) term eliminates steady-state offset caused by gravity or external loads.

1. 적분 와인드업(Windup) 방지 기능이 포함된 PID 제어기 C# 클래스1. PID Controller C# Class with Anti-Windup Clamping

PIDController.cs
using UnityEngine;

[System.Serializable]
public class PIDController
{
    public float Kp = 5.0f;          // 비례 게인 (목표 방향 탄성 강도)
    public float Ki = 0.1f;          // 적분 게인 (정상 상태 잔류 오차 제거)
    public float Kd = 1.2f;          // 미분 게인 (오버슈트 억제 댐핑)
    public float integralMax = 20f;  // 적분 와인드업 방지 상한

    private float _integral;
    private float _lastError;
    private bool _hasLastError;

    public float Update(float current, float target, float dt)
    {
        if (dt <= 0.0001f) return 0f;

        float error = target - current;

        // 1. 적분 항 누적 및 Anti-Windup 클램핑
        _integral = Mathf.Clamp(_integral + error * dt, -integralMax, integralMax);

        // 2. 미분 항 계산 (첫 프레임 스파이크 방지)
        float derivative = _hasLastError ? (error - _lastError) / dt : 0f;
        _lastError = error;
        _hasLastError = true;

        return (Kp * error) + (Ki * _integral) + (Kd * derivative);
    }

    public void Reset()
    {
        _integral = 0f;
        _lastError = 0f;
        _hasLastError = false;
    }
}
PIDController.cs
using UnityEngine;

[System.Serializable]
public class PIDController
{
    public float Kp = 5.0f;          // Proportional gain (stiffness toward target)
    public float Ki = 0.1f;          // Integral gain (eliminates steady-state error)
    public float Kd = 1.2f;          // Derivative gain (damping to suppress overshoot)
    public float integralMax = 20f;  // Anti-windup cap for integral accumulator

    private float _integral;
    private float _lastError;
    private bool _hasLastError;

    public float Update(float current, float target, float dt)
    {
        if (dt <= 0.0001f) return 0f;

        float error = target - current;

        // 1. Accumulate integral term with Anti-Windup clamping
        _integral = Mathf.Clamp(_integral + error * dt, -integralMax, integralMax);

        // 2. Compute derivative term (suppress spike on first frame)
        float derivative = _hasLastError ? (error - _lastError) / dt : 0f;
        _lastError = error;
        _hasLastError = true;

        return (Kp * error) + (Ki * _integral) + (Kd * derivative);
    }

    public void Reset()
    {
        _integral = 0f;
        _lastError = 0f;
        _hasLastError = false;
    }
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 적분 와인드업(Integral Windup) 클램핑 필수: 물리 객체가 벽에 막혀 한동안 목표에 도달하지 못하면 _integral 값이 끝없이 누적되어 장애물이 사라진 직후 과도하게 튕겨 나갑니다. 반드시 Mathf.Clamp로 적분 누적 범위를 제한해야 합니다.
  • 목표치 급변 시 미분 킥(Derivative Kick) 완화: 목표 좌표(target)가 순간 이동하듯 갑자기 바뀌면 error - _lastError가 크게 튀어 순간적인 충격력이 발생합니다. 이를 방지하려면 오차의 변화율 대신 현재 측정값의 변화율(-(current - _lastCurrent) / dt 또는 -rb.linearVelocity)을 미분 항으로 사용하는 것이 안전합니다.
  • FixedUpdate 주기에서 실행: PID 수식은 시간 간격 dt로 나누는 미분 연산을 포함하므로, 프레임 간격이 들쭉날쭉한 Update 대신 고정 시간 간격인 FixedUpdate(Time.fixedDeltaTime)에서 호출해야 제어 출력이 흔들리지 않습니다.
  • Clamp the Integral Accumulator (Anti-Windup): If an obstacle temporarily blocks the object from reaching its target, _integral grows unchecked and causes a severe overshoot once freed. Always bound _integral with Mathf.Clamp.
  • Prevent Derivative Kick on Target Teleports: When target jumps discontinuously, (error - _lastError) / dt produces a massive spike. Computing the derivative on measurement (-(current - _lastCurrent) / dt or -rb.linearVelocity) rather than error avoids this impulse.
  • Evaluate Inside FixedUpdate: Because the derivative term divides by dt, run the PID update inside FixedUpdate (Time.fixedDeltaTime) rather than variable-rate Update to avoid noisy force outputs.

비례(Kp)·미분(Kd) 게인 조합으로 먼저 진동 없는 감쇠 응답을 맞춘 뒤, 중력 처짐 같은 미세 잔류 오차가 있을 때만 작은 적분(Ki) 게인을 추가하는 순서로 튜닝하면 물리 기반 이동체를 손쉽게 안정화할 수 있습니다.

Tuning Kp and Kd first to achieve critically damped motion—and introducing a small Ki only when persistent gravity sag remains—yields stable, responsive physics controllers.

참고자료 & 관련 링크