Created
February 12, 2022 21:02
-
-
Save brainwipe/07f2332c9c4f73492d27115e4387187a to your computer and use it in GitHub Desktop.
Unity C# PID Controller Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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