Hi, I just came across this new thing called PID Controllers and I decided to try and implement one myself, inspired by this:
http://www.matthewpeterkelly.com/tutorials/pdControl/index.html
Following the wiki article (Proportional–integral–derivative controller - Wikipedia) I implemented only the proportional and derivative terms, but I believe that I’m doing the wrong calculations with the derivative one.
First, what I’m trying to do is something like in the first link, you consider the position of some object as your desired position, and any displacement or offset from that position is considered an error, and will try to correct it over time.
The proportional term was trivial to implement, taking the difference of the object’s position and later multiply
it by the proportional factor (kp from the wiki article).

current_error = target.position - body.position;
Now, for the derivative term, if I understood correctly, you need to use the finite differentiation method to calculate the derivative of the error (with respect to time)

and that implies doing something like:
(previous_error - current_error) / Time.deltaTime
(from this article Finite difference - Wikipedia)
My problem is that if I divide it by deltaTime, everything “blows up” with infinity or NaN errors, but if I multiply instead of divide, it “works”. But the derivative term doesn’t seem to be contributing anything to the result, no matter what derivative factor I use. Here is my full code for completeness
Vector3 last_error;
public float kp=3f;
public float kd=1f;
void Update ()
{
Vector3 error = target.position - body.position;
// f(x) - f(x-h) / h?
Vector3 de_dt = (error - last_error) * Time.deltaTime;
last_error = error;
body.position += (kp * error + kd * de_dt) * Time.deltaTime;
}
Also, I need to multiply once more the result by deltaTime…but I feel like it shouldn’t be the case.
Any help is appreciated, thanks!