AddRelativeForce not going straight?

So in this script I move a car in forward and backwards directions and keeping the speed at a certain range.

void MoveCar(float direction)
    {

        Vector3 localVelo= transform.InverseTransformDirection(rb.velocity);

       
        if (localVelo.z < maxSpeed && localVelo.z > maxBackSpeed)
        rb.AddRelativeForce(Vector3.forward * speed * direction);

       

       

       
    }

I call it in FixedUpdate. If the direction parameter is 1 it goes forward, -1 it goes backwards. However the problem is that it does not go in a straight line and the Y axis ever so slightly increases as the car moves. The object itself is rotated 90 degrees on the Y axis for level design purposes. Is there a way to fix this? Thanks in advance guys :slight_smile:

There are several factors that may cause a car not driving in straight line in your situation:

  • Asymmetries in wheels (WheelCollider or Raycast): positions, parameters, etc.
  • Center of mass not being centered (Rigidbody.centerOfMass). If this is not configured explicitly from scripting, then Unity will calculate it out of the colliders associated to the Rigidbody, which may not be perfectly symmetrical.
  • Inertia tensor rotated. As with the center of mass, Unity calculates Rigidbody.inertiaTensor and Rigidbody.inertiaTensorRotation. To ensure perfect balance, you should set rigidbody.inertiaTensorRotation = Quaternion.identity.