Limiting rotation with Input.GetAxis

I’m trying to rotate the wheels of a car whenever you hold left/right. I have it working, but I want to be able to limit how far the rotation goes, something like 30 degrees or so.

using UnityEngine;
using System.Collections;

public class CarController : MonoBehaviour 
{
	public GameObject[] wheels;
	public float turnSpeed;
	private float wheelRotation;
	
	void Update () 
	{
		wheelRotation = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;

		if (Input.GetKey("d"))
		{
			wheels[0].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[1].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[2].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[3].transform.Rotate(0,wheelRotation,0, Space.World);
		}
		if (Input.GetKey("a"))
		{
			wheels[0].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[1].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[2].transform.Rotate(0,wheelRotation,0, Space.World);
			wheels[3].transform.Rotate(0,wheelRotation,0, Space.World);
		}
	}
}

I’ve tried Mathf.Clamp on wheelRotation, but all that does is slow down how fast it rotates.

Also, I’d like for when you let go of the button, the wheel goes back to a neutral position. I’m thinking I’ll have to do some sort of Lerp or Slerp in GetKeyUp, because otherwise it’d snap back instantly, which I don’t want. So how would I go about doing this?

Anytime you have something like this:

wheels[0].transform.Rotate(0,wheelRotation,0, Space.World);
wheels[1].transform.Rotate(0,wheelRotation,0, Space.World);
wheels[2].transform.Rotate(0,wheelRotation,0, Space.World);
wheels[3].transform.Rotate(0,wheelRotation,0, Space.World);

You’ll probably want to use a loop instead. (However, I’m wondering, given that with most cars only the front wheels rotate, do you actually want all four wheels to be rotated?)

Regarding the clamping issue, rather than using Rotate(), I’d track the ‘yaw’ angle of the wheels manually and then assign the orientation like this:

wheels[0].transform.localEulerAngles = new Vector3(0f, wheelYaw, 0f);

(This is assuming the wheels are child objects of another game object.)

You can then manipulate the yaw angle in whatever way you want, including clamping, applying damping, etc. (Also note that one way to apply damping is to modify the parameters - e.g. the ‘gravity’ setting - of the axis in question in the input manager.)

Yeah, I never even considered the fact that only two wheels would need to turn. Anyway, the localEulerAngles works just fine. It was jerky when I got to the limits of the eulerAngles, but adding it a clamp fixed it. Now all I gotta do is reverse that when you let up, I guess. Thanks for the help.