(Moved from physics)Buggy vehicle code+ any improvements?

(Moved from the physics sections, but still my post)So I’m trying to delve into the world of physics in unity, since I’ve messed around enough in other parts(trying to improve my knowledge)and wanted to make a kinda decently featured car controller, and it led me to following a couple of tutorials, ultimately ending up with this code. Uses standard unity wheel colliders.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VehicleController : MonoBehaviour
{
    [Header("Vehicle Components")]
    public WheelCollider[] wheels = new WheelCollider[4];
    public Transform[] wheelMeshes = new Transform[4];
    public Transform CenterOfMass;
    public AnimationCurve enginePower;
    [Header("Vehicle Settings")]
    public float vehicleTorque;
    public float brakePower;
    public float steeringAngle;
    public float radius;
    public float downforce;
    public float maxRPM;
    public float minRPM;
    public float engineRPM;
    public float smoothTime = 0.01f;
    public float[] gears;
    public int gearNum = 0;
    private InputManager inputManager;
    private Rigidbody rb;
    private bool reverse;
    [Header("Vehicle Debug")]
    public float vehicleSpeed;
    public float wheelsRPM;
    private void Start()
    {
        inputManager = GetComponent<InputManager>();
        rb = GetComponent<Rigidbody>();
    }
    private void FixedUpdate()
    {
        SetSteering();
        SetWheels();
        SetDownforce();
        SetBrake();
        SetMisc();
        SetShift();
        CalculateEnginePower();
    }
    private void SetForces()
    {
        for (int i = 0; i < wheels.Length; i++)
        {
            wheels[i].motorTorque = vehicleTorque;
        }
    }
    private void SetSteering()
    {
        if (inputManager.horizontalInput > 0)
        {
            wheels[0].steerAngle = Mathf.Rad2Deg * Mathf.Atan(2.55f / (radius + (1.5f / 2))) * inputManager.horizontalInput;
            wheels[1].steerAngle = Mathf.Rad2Deg * Mathf.Atan(2.55f / (radius - (1.5f / 2))) * inputManager.horizontalInput;
        }
        else if (inputManager.horizontalInput < 0)
        {
            wheels[0].steerAngle = Mathf.Rad2Deg * Mathf.Atan(2.55f / (radius - (1.5f / 2))) * inputManager.horizontalInput;
            wheels[1].steerAngle = Mathf.Rad2Deg * Mathf.Atan(2.55f / (radius + (1.5f / 2))) * inputManager.horizontalInput;
        }
        else
        {
            wheels[0].steerAngle = 0;
            wheels[1].steerAngle = 0;
        }
    }
    private void SetWheels()
    {
        Vector3 wheelPos = Vector3.zero;
        Quaternion wheelRot = Quaternion.identity;
        for (int i = 0; i < 4; i++)
        {
            wheels[i].GetWorldPose(out wheelPos, out wheelRot);
            wheelMeshes[i].transform.position = wheelPos;
            wheelMeshes[i].transform.rotation = wheelRot;
        }
    }
    private void SetDownforce()
    {
        rb.AddForce(-Vector3.up * downforce * rb.velocity.magnitude);
    }
    private void SetBrake()
    {
        if (inputManager.handbrake)
        {
            wheels[0].brakeTorque = wheels[1].brakeTorque = wheels[2].brakeTorque = wheels[3].brakeTorque = brakePower;
        }
        else
        {
            wheels[0].brakeTorque = wheels[1].brakeTorque = wheels[2].brakeTorque = wheels[3].brakeTorque = 0;
        }
    }
    private void CalculateEnginePower()
    {
        GetRPM();
        vehicleTorque = enginePower.Evaluate(engineRPM) * (gears[gearNum]) * inputManager.verticalInput;
        float velocity = 0f;
        engineRPM = Mathf.SmoothDamp(engineRPM, 1000 + (Mathf.Abs(wheelsRPM) * 3.6f * (gears[gearNum])), ref velocity, smoothTime);
        engineRPM = engineRPM / 2;
        SetForces();
    }
    private void GetRPM()
    {
        float sum = 0;
        int R = 0;
        for (int i = 0; i < 4; i++)
        {
            sum += wheels[i].rpm;
            R++;
        }
        wheelsRPM = (R != 0) ? sum / R : 0;
        if (wheelsRPM < 0 && !reverse)
        {
            reverse = true;
        }
        else if (wheelsRPM > 0 && reverse)
        {
            reverse = false;
        }
    }
    private void SetMisc()
    {
        vehicleSpeed = rb.velocity.magnitude * 3.6f;
        rb.centerOfMass = CenterOfMass.localPosition;
    }
    private void SetShift()
    {
        if (engineRPM > maxRPM && gearNum < gears.Length-1 && !reverse)
        {
            gearNum++;
        }
        if (engineRPM < minRPM && gearNum > 0)
        {
            gearNum--;
        }
    }
}

Input Manager is extremely simple

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
    public float horizontalInput;
    public float verticalInput;
    public bool handbrake;
    private void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        handbrake = Input.GetButton("Jump");
    }
}

However, this code does often bug, especially with the engine RPM, which can sometimes fluctuate in multiple places causing undesired effects, and gears sometimes get stuck and don’t move, among other issues. Another very critical issue is it would cycle through the gears very quickly. I would also like to know if there’s any fixes and immediate problems that anybody sees with the code, as well as any improvements you could suggest? I understand this may not be the best way to do it, but I’ll at least give it a shot.

Staring at dynamic code and surmising errors isn’t really much of a thing, especially in Unity where scene setup is just as important as the code.

However there are plenty of other approaches that involve running the code and instrumenting it yourself.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

Mr. Kurt, you always come up with good answers, thanks for the help! I’ll look into it, and get back here with the results.

1 Like