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

using UnityEngine;
using System.Collections;
public class Suspension : MonoBehaviour {
public GameObject dispWheel;
public float supLength;
public float supStrength;
public float supDampner;
public Rigidbody carRigid;
public RaycastHit supHit;
public float supcompressionRatio;
//public GameObject carBody;
// Use this for initialization
void Start () {
carRigid = transform.parent.GetComponent<Rigidbody>();
if (carRigid == null)
carRigid = transform.root.GetComponentInChildren<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate () {
float compRatio = calcCompRatio ();
if (compRatio !=0)
calcForce (compRatio);
}
void Update(){
wheelDisplay (supcompressionRatio);
}
private float calcCompRatio(){
float compressionRatio = 0;
RaycastHit hit;
Ray ray = new Ray (transform.position, -transform.up);
Debug.DrawRay (ray.origin, ray.direction*supLength, Color.green);
if (Physics.Raycast (ray, out hit, supLength)) {
Debug.DrawRay (ray.origin, ray.direction*hit.distance, Color.red);
compressionRatio = 1-hit.distance/supLength;
}
supHit = hit;
supcompressionRatio = compressionRatio;
return compressionRatio;
}
private void calcForce(float compRatio){
Vector3 curVel = carRigid.GetPointVelocity (transform.position);
Vector3 curForce = Vector3.Project (curVel, transform.up);
Vector3 newForce = Vector3.up * supStrength * compRatio;
Vector3 deltaForce = newForce - curForce*supDampner ;
//Debug.Log (deltaForce);
carRigid.AddForceAtPosition (deltaForce, transform.position);
}
private void wheelDisplay(float compRatio){
if (dispWheel == null)
return;
Vector3 newPos = transform.position;
newPos.y = transform.position.y - ((1 - compRatio) * supLength)+ (0.25f * dispWheel.transform.lossyScale.y);
dispWheel.transform.position = newPos;
}
}