The last thing you want is for your PIDs to get out of control and so I’ve implemented a PID controller class.
No, a PID controller is actually like a simple autopilot device that keeps a system in a stable state. It works by measuring a numeric value and then comparing that against a desired value known as the setpoint. The difference between the two is called the error value, and the output of the controller is a correction value that should be used somehow to get the system back to the setpoint.
A good example of this is a cruise control system. Say the desired speed (setpoint) is 50mph. If the car starts going up a hill then its speed will reduce, in which case more power should be applied. The amount of extra power (correction value) should depend on how much slower than the cruising speed the car is going (error value).
The real issue, of course, is how much correction to apply for how much error. The PID concept (present, integral, derivative) essentially takes an estimate of the present, past and future of the system into account when deciding how to get it to track the setpoint.
The class is very simple to use, just a matter of setting up the parameters and then determining the correction value with the Update function:-
var pid: PID; // Set values in the inspector.
…
var correction = pid.Update(setSpeed, actualSpeed, Time.deltaTime);
The three parameters are the setpoint value, the measured value and the time since the last update. The correction can be used to vary physical forces, angles, distances… almost anything. The main value of the PID controller for games is that it is easy to add a bit of realistic delay and tolerance of noise.
The theory of PID controllers is explained on Wikipedia and elsewhere on the internet. I’ve attached a very simple scene that shows how a PID-controlled value can be used to track a target.
Bon appétit!
436966–15184–$PID.cs (556 Bytes)
436966–15185–$PIDExample.zip (40.3 KB)
