You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
1.8 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class Suspension : MonoBehaviour {
  4. public GameObject dispWheel;
  5. public float supLength;
  6. public float supStrength;
  7. public float supDampner;
  8. public Rigidbody carRigid;
  9. public RaycastHit supHit;
  10. public float supcompressionRatio;
  11. //public GameObject carBody;
  12. // Use this for initialization
  13. void Start () {
  14. carRigid = transform.parent.GetComponent<Rigidbody>();
  15. if (carRigid == null)
  16. carRigid = transform.root.GetComponentInChildren<Rigidbody>();
  17. }
  18. // Update is called once per frame
  19. void FixedUpdate () {
  20. float compRatio = calcCompRatio ();
  21. if (compRatio !=0)
  22. calcForce (compRatio);
  23. }
  24. void Update(){
  25. wheelDisplay (supcompressionRatio);
  26. }
  27. private float calcCompRatio(){
  28. float compressionRatio = 0;
  29. RaycastHit hit;
  30. Ray ray = new Ray (transform.position, -transform.up);
  31. Debug.DrawRay (ray.origin, ray.direction*supLength, Color.green);
  32. if (Physics.Raycast (ray, out hit, supLength)) {
  33. Debug.DrawRay (ray.origin, ray.direction*hit.distance, Color.red);
  34. compressionRatio = 1-hit.distance/supLength;
  35. }
  36. supHit = hit;
  37. supcompressionRatio = compressionRatio;
  38. return compressionRatio;
  39. }
  40. private void calcForce(float compRatio){
  41. Vector3 curVel = carRigid.GetPointVelocity (transform.position);
  42. Vector3 curForce = Vector3.Project (curVel, transform.up);
  43. Vector3 newForce = Vector3.up * supStrength * compRatio;
  44. Vector3 deltaForce = newForce - curForce*supDampner ;
  45. //Debug.Log (deltaForce);
  46. carRigid.AddForceAtPosition (deltaForce, transform.position);
  47. }
  48. private void wheelDisplay(float compRatio){
  49. if (dispWheel == null)
  50. return;
  51. Vector3 newPos = transform.position;
  52. newPos.y = transform.position.y - ((1 - compRatio) * supLength)+ (0.25f * dispWheel.transform.lossyScale.y);
  53. dispWheel.transform.position = newPos;
  54. }
  55. }