/
PID.cs
68 lines (59 loc) · 1.97 KB
/
PID.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using UnityEngine;
using ExtensionMethods;
[System.Serializable]
public class PID {
public float pFactor, iFactor, dFactor;
Vector3 integral;
Vector3 lastError;
public PID(float pFactor, float iFactor, float dFactor) {
this.pFactor = pFactor;
this.iFactor = iFactor;
this.dFactor = dFactor;
}
public Vector3 Update(Vector3 present, float timeFrame) {
integral += present * timeFrame;
Vector3 deriv = (present - lastError) / timeFrame;
lastError = present;
return present * pFactor + integral * iFactor + deriv * dFactor;
}
}
public class PIDRigidbodyHelper {
public PID velocityPID;
public PID slowingPID;
public PID headingPID;
public PID dampeningPID;
public Rigidbody rb;
public bool isActive;
public PIDRigidbodyHelper(Rigidbody rigidbody, float acceleration, float dampening) {
rb = rigidbody;
isActive = true;
velocityPID = new PID(acceleration, 0, 0.3f);
slowingPID = new PID(dampening, 0, 0.3f);
headingPID = new PID(acceleration, 0, 0.3f);
dampeningPID = new PID(dampening, 0, 0.3f);
}
public void Update(Vector3 targetPos, Quaternion targetRot) {
if (!isActive)
return;
UpdateVelocity(targetPos);
UpdateTorque(targetRot);
}
public void UpdateVelocity(Vector3 targetPos, float forceMult = 1f, float slowMult = 1f) {
if (!isActive)
return;
if (Time.deltaTime != 0 && Time.deltaTime != float.NaN) {
var force = velocityPID.Update(targetPos - rb.transform.position, Time.deltaTime).SafetyClamp() * forceMult
+ slowingPID.Update(-rb.velocity, Time.deltaTime).SafetyClamp() * slowMult;
rb.AddForce(force);
}
}
public void UpdateTorque(Quaternion targetRot) {
if (!isActive)
return;
if (Time.deltaTime != 0 && Time.deltaTime != float.NaN) {
var torque = -headingPID.Update(Vector3.Cross(rb.transform.rotation * Vector3.forward, targetRot * Vector3.forward), Time.deltaTime).SafetyClamp()
+ dampeningPID.Update(-rb.angularVelocity, Time.deltaTime).SafetyClamp();
rb.AddTorque(torque);
}
}
}