Object rotation not clamped properly

Can someone explain why this code is not functioning right? What I want to do is have my object rotate in accordance to the arrow keys, but always stay between -10 and 10 when it rotates.

private var newZ : float;

function Update () {
	newZ = Mathf.Clamp(transform.rotation.z+Input.GetAxis("Horizontal"),-10,10);
	transform.rotation.z = newZ;

Thanks in advance!

Your problem is that you are accessing ‘transform.rotation’. Transform.rotation is a quaternion, a non-intuitive, 4D construct. The x,y,z & w components have values between 0.0 and 1.0. Unless you have a firm understanding of Quaternions, it recommended that you avoid using the individual components. There are a number of helper functions and other ways to deal with them.

The first stop for a solution may be ‘Transform.eulerAngles’. This may do what you want, but you don’t want to be assigning the axes independently. You want to assign all three at the same time. Even then there are issues. Since Unity stores rotations internally as Quaternions, the eulerAngles values are derived. There are multiple euler angle3 representations for any given physical rotation, and Unity may change them on you. So the angles you are using may not stay in a representation/range you expect.

This is because Mathf.Clamp actually “clamps” the first parameter to be between the values of the 2nd and 3rd parameters, which you’ve specified as being -10 and 10 :slight_smile:

See here: