EasySuspension.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. using System.Collections;
  3. [ExecuteInEditMode()]
  4. public class EasySuspension : MonoBehaviour {
  5. [Range(0, 20)]
  6. public float naturalFrequency = 10;
  7. [Range(0, 3)]
  8. public float dampingRatio = 0.8f;
  9. [Range(-1, 1)]
  10. public float forceShift = 0.03f;
  11. public bool setSuspensionDistance = true;
  12. void Update () {
  13. // work out the stiffness and damper parameters based on the better spring model
  14. foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>()) {
  15. JointSpring spring = wc.suspensionSpring;
  16. spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
  17. spring.damper = 2 * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);
  18. wc.suspensionSpring = spring;
  19. Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
  20. float distance = GetComponent<Rigidbody>().centerOfMass.y - wheelRelativeBody.y + wc.radius;
  21. wc.forceAppPointDistance = distance - forceShift;
  22. // the following line makes sure the spring force at maximum droop is exactly zero
  23. if (spring.targetPosition > 0 && setSuspensionDistance)
  24. wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
  25. }
  26. }
  27. // uncomment OnGUI to observe how parameters change
  28. /*
  29. public void OnGUI()
  30. {
  31. foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>()) {
  32. GUILayout.Label (string.Format("{0} sprung: {1}, k: {2}, d: {3}", wc.name, wc.sprungMass, wc.suspensionSpring.spring, wc.suspensionSpring.damper));
  33. }
  34. var rb = GetComponent<Rigidbody> ();
  35. GUILayout.Label ("Inertia: " + rb.inertiaTensor);
  36. GUILayout.Label ("Mass: " + rb.mass);
  37. GUILayout.Label ("Center: " + rb.centerOfMass);
  38. }
  39. */
  40. }