Need help with simple car script.

using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour
{

public WheelCollider FrontLeft;
public WheelCollider FrontRight;
public WheelCollider RearRight;
public WheelCollider RearLeft;

float speed = 10.0f;
float braking = 20.0f;
float turning = 20.0f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

//this code makes car go forward
RearRight.motorTorque = Input.GetAxis(“Vertical”) * speed;
RearLeft.motorTorque = Input.GetAxis(“Vertical”) * speed;

RearRight.brakeTorque = 0;
RearLeft.brakeTorque = 0;

//this code is for turning
FrontRight.steerAngle = Input.GetAxis(“Horizontal”) * turning;
FrontLeft.steerAngle = Input.GetAxis(“Horizontal”) * turning;

//Breaking
if (Input.GetKey (KeyCode.Space))
{
RearRight.brakeTorque = braking;
RearLeft.brakeTorque = braking;

}

}

How can i make this so that it doesnt flip over so easy?

How can i make this so that it doesnt flip over so easy?

I modified the car to have TWO rigidbodies connected by a
FixedHinge and separated by some vertical distance.

One rigidbody is at y == 0, the other is at y == 1.

This improves the stability in the roll axis somewhat.

See attached project. It’s not great, but it’s better.

I added some wheelbase and wheel width parameters you can tinker with too.

The SmoothFollow.js is straight out of the Unity3D Standard Assets scripts.

1915240–123583–forum290174.zip (20.9 KB)

I’d bet that the most common cause for the rolling over problems people new to vehicle simulation modeling have is the center of gravity being too high. Here’s a database of real vehicles and their center of gravity heights:

https://www.google.com/webhp?sourceid=chrome-instant&rlz=1C1GIWA_enUS615US615&ion=1&espv=2&ie=UTF-8#safe=off&q=yaw moment of inertia center of gravity height database

Grab the sae file “sae1999-01-1336.pdf” entitled “Measured Vehicle Inertial Parameters.” This also has yaw/pitch/roll inertia values for a large collection of real cars.

Generally you’re going to be about 0.6 meters in height above the ground. For race cars it can be lower than this.

I would not model a vehicle’s chassis as two separate rigid bodies unless you’re concerned with chassis flex. If you’re doing simple scripts for vehicles like most people are rather than a serious simulation, chassis flex isn’t probably a concern, and I wouldn’t trust PhysX to handle that with enough precision to bother. So I’d stick to one rigid body and make sure it’s center of mass is placed appropriately relative to the ground and car mesh.

One last thing: You’re more likely to get replies if you wrap your code up in code tags so it’s readable in the forums.

1 Like