- Home /
Anti-roll bar doesn't work
I'm making a racing game that has trucks as vehicles. For the truck movement, I'm using WheelColliders. After some testing, I found out that after a certain speed (~60km/h), turning made the truck flip to the side and hit the ground.
I found an Anti-Roll script and applied it to the truck, but the truck still flips but after a higher speed (~90km/h) and its physics seem a bit unstable.
Hhow can I prevent the truck from flipping like that? Here are the scripts I'm using:
Truck movement script:
using UnityEngine; using UnityEngine.UI; using System.Collections;
public class WheelTest : MonoBehaviour {
public WheelCollider WheelFL;
public WheelCollider WheelFR;
public WheelCollider WheelRL;
public WheelCollider WheelRR;
public Text txt;
public float speed;
public AudioSource EngineSound;
public GameObject COM;
public float steerMax = 8f;
public float motorMax = 30f;
public float brakeMax = 60f;
public float steer = 0f;
public float motor = 0f;
public float brake = 0f;
// Use this for initialization
void Start ()
{
COM.transform.position = rigidbody.centerOfMass;
}
void Update () {
int speedDisp = Mathf.RoundToInt(speed);
txt.text = speedDisp + "km/h";
EngineSound.volume = 0.5f + speed/50;
EngineSound.pitch = 0.75f + speed/75;
}
// Update is called once per frame
void FixedUpdate ()
{
steer = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1);
motor = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1);
brake = Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0) * -1;
speed = transform.InverseTransformDirection(rigidbody.velocity).z * 3.6f;
WheelRL.motorTorque = motorMax * motor;
WheelRR.motorTorque = motorMax * motor;
WheelRL.brakeTorque = brakeMax * brake;
WheelRR.brakeTorque = brakeMax * brake;
WheelFL.steerAngle = steerMax * steer;
WheelFR.steerAngle = steerMax * steer;
}
}
Anti-Roll Bar:
#pragma strict
var WheelL : WheelCollider; var WheelR : WheelCollider; var AntiRoll = 5000.0;
function FixedUpdate () { var hit : WheelHit; var travelL = 1.0; var travelR = 1.0;
var groundedL = WheelL.GetGroundHit(hit);
if (groundedL)
travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;
var groundedR = WheelR.GetGroundHit(hit);
if (groundedR)
travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;
var antiRollForce = (travelL - travelR) * AntiRoll;
if (groundedL)
rigidbody.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
WheelL.transform.position);
if (groundedR)
rigidbody.AddForceAtPosition(WheelR.transform.up * antiRollForce,
WheelR.transform.position);
}