PIDController.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. [System.Serializable]
  5. public class AxleInfo
  6. {
  7. public WheelCollider leftWheel;
  8. public WheelCollider rightWheel;
  9. public bool motor;
  10. }
  11. [System.Serializable]
  12. public class PIDController
  13. {
  14. float error_old = 0f;
  15. //The controller will be more robust if you are using a further back sample
  16. float error_old_2 = 0f;
  17. float error_sum = 0f;
  18. //If we want to average an error as input
  19. //float error_sum2 = 0f;
  20. //PID parameters
  21. public float gain_P;
  22. public float gain_I;
  23. public float gain_D;
  24. //Sometimes you have to limit the total sum of all errors used in the I-action
  25. private float error_sumMax = 20f;
  26. public float GetFactorFromPIDController(float error)
  27. {
  28. float output = CalculatePIDOutput(error);
  29. return output;
  30. }
  31. //Use this when experimenting with PID parameters
  32. public float GetFactorFromPIDController(float gain_P, float gain_I, float gain_D, float error)
  33. {
  34. this.gain_P = gain_P;
  35. this.gain_I = gain_I;
  36. this.gain_D = gain_D;
  37. float output = CalculatePIDOutput(error);
  38. return output;
  39. }
  40. //Use this when experimenting with PID parameters and the gains are stored in a Vector3
  41. public float GetFactorFromPIDController(Vector3 gains, float error)
  42. {
  43. this.gain_P = gains.x;
  44. this.gain_I = gains.y;
  45. this.gain_D = gains.z;
  46. float output = CalculatePIDOutput(error);
  47. return output;
  48. }
  49. private float CalculatePIDOutput(float error)
  50. {
  51. //The output from PID
  52. float output = 0f;
  53. //P
  54. output += gain_P * error;
  55. //I
  56. error_sum += Time.fixedDeltaTime * error;
  57. //Clamp the sum
  58. this.error_sum = Mathf.Clamp(error_sum, -error_sumMax, error_sumMax);
  59. //Sometimes better to just sum the last errors
  60. //float averageAmount = 20f;
  61. //CTE_sum = CTE_sum + ((CTE - CTE_sum) / averageAmount);
  62. output += gain_I * error_sum;
  63. //D
  64. float d_dt_error = (error - error_old) / Time.fixedDeltaTime;
  65. //Save the last errors
  66. this.error_old_2 = error_old;
  67. this.error_old = error;
  68. output += gain_D * d_dt_error;
  69. return output;
  70. }
  71. }