How to make a functional steering wheel for a car game?

I want my steering wheel to be like a real one and so I’ve made it so that you can rotate it left or right but I want to be able to reset the rotation of the wheel once the user has stopped turning the wheel, and I assume I’d need some kind of variable to store the amount of rotation of the wheel, but I don’t know how.

Anyways, here’s my code so far:

using UnityEngine;
using System.Collections;

public class Wheel : MonoBehaviour {

	public int turnSpeed;
	public GameObject wheel;
	

	void Update ()
	{

		if(Input.GetKey (KeyCode.A))
		{

			wheel.transform.Rotate(-Vector3.up * Time.deltaTime * turnSpeed);

		}

		if(Input.GetKey (KeyCode.D))
		{
			
			wheel.transform.Rotate(Vector3.up * Time.deltaTime * turnSpeed);
			
		}

	}

}

Just store the default rotation of the wheel at start to something like:

    float rotations = 0;
    Quaternion defaultRotation;

    void Start()
    {
        defaultRotation = wheel.transform.localRotation;
    }

then you can rotate it back like this:

void Update()
{
     if(Input.GetKey (KeyCode.A))
     {
         
        wheel.transform.Rotate(-Vector3.up * Time.deltaTime * turnSpeed);
        rotations -= turnSpeed;
     }
 
     else if(Input.GetKey (KeyCode.D))
     {
         
        wheel.transform.Rotate(Vector3.up * Time.deltaTime * turnSpeed);
        rotations += turnSpeed;
     }
    ...
    else    //rotate to default
    {
        if (rotations < -1)
        {
            wheel.transform.Rotate(Vector3.up * Time.deltaTime * turnSpeed);
            rotations += turnSpeed;
        }
        else if (rotations > 1)
        {
             wheel.transform.Rotate(-Vector3.up * Time.deltaTime * turnSpeed);
             rotations -= turnSpeed;
        }
        else if (rotations != 0)
        {
             wheel.transform.localRotation = defaultRotation;
             rotations = 0;
        }
    }
}

I think this should do it. There may be some inaccuracy with the floats so you can compare the rotations to 1 and -1 and you can just set the wheel to a default rotation. If you care about that 1 degree you need to do different checks though .

Note: if you don’t really need to use the wheel’s gameobject anywhere, store it’s Transform instead. (Or if you need it in just a few cases you can still access it as wheel.gameobject). This would be easier on the processor as it doesn’t need to access the transform every frame.

How to make a functional car steering wheel for a parking game.
#Unity 3D #car control for parking game with #steering wheel with free script.
Realistic car control with steering wheel UI to control car in unity game.