Skip to content

Instantly share code, notes, and snippets.

@brainwipe
Created February 12, 2022 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brainwipe/07f2332c9c4f73492d27115e4387187a to your computer and use it in GitHub Desktop.
Save brainwipe/07f2332c9c4f73492d27115e4387187a to your computer and use it in GitHub Desktop.
Unity C# PID Controller Example
using System;
using UnityEngine;
namespace Lang.Clomp.Infrastructure
{
[Serializable]
internal class PIDController
{
private readonly float cumulativeErrorLimit;
private float cumulativeError;
private float lastError;
public float Proportional = 1;
public float Integral = 0.01f;
public float Derivative = 0.1f;
public PIDController(float cumulativeErrorLimit)
{
this.cumulativeErrorLimit = cumulativeErrorLimit;
}
public float Calculate(float deltaTime, float target, float current)
{
var error = target - current;
var errorGradient = (error - lastError) * deltaTime;
cumulativeError += error * deltaTime;
cumulativeError = Mathf.Clamp(cumulativeError, -cumulativeErrorLimit, cumulativeErrorLimit);
lastError = error;
return Mathf.Clamp((Proportional * error) + (Integral * cumulativeError) + (Derivative * errorGradient), -1, 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment