Last active
October 27, 2022 05:01
-
-
Save brihernandez/053968a0fddb01fd890beadc8bf207c7 to your computer and use it in GitHub Desktop.
I've been using this PID controller code for years.
This file contains 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 UnityEngine; | |
// From http://forum.unity3d.com/threads/68390-PID-controller | |
// Thank you andeeeee | |
public class PID | |
{ | |
public float pFactor, iFactor, dFactor; | |
float integral; | |
float lastError; | |
public PID() | |
{ | |
pFactor = 0.0f; | |
iFactor = 0.0f; | |
dFactor = 0.0f; | |
} | |
public PID(Vector3 values) | |
{ | |
pFactor = values.x; | |
iFactor = values.y; | |
dFactor = values.z; | |
} | |
public PID(float pFactor, float iFactor, float dFactor) | |
{ | |
this.pFactor = pFactor; | |
this.iFactor = iFactor; | |
this.dFactor = dFactor; | |
} | |
public float Update(float setpoint, float actual, float timeFrame) | |
{ | |
// Handle when time is paused. | |
if (timeFrame == 0f) | |
return actual; | |
float present = setpoint - actual; | |
integral += present * timeFrame; | |
float deriv = (present - lastError) / timeFrame; | |
lastError = present; | |
return present * pFactor + integral * iFactor + deriv * dFactor; | |
} | |
public void SetPidValues(float p, float i, float d) | |
{ | |
pFactor = p; | |
iFactor = i; | |
dFactor = d; | |
} | |
public void SetPidValues(Vector3 pidValues) | |
{ | |
pFactor = pidValues.x; | |
iFactor = pidValues.y; | |
dFactor = pidValues.z; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment