I am working on a game that rotates an object on the z axis. I need to limit the total rotation to 80 degrees. I tried the following code, but it doesn't work. minAngle = -40.0f and maxAngle = 40.0f
Vector3 pos = transform.position;
pos.z = Mathf.Clamp(pos.z, minAngle, maxAngle);
transform.position = pos;
The code you posted clamps the z position. What you want is to use transform.rotation
Here's a static version of the nice solution by Imapler that, instead of changing the angle itself, it returns the campled angle, so it can be used with any axis.
Or if you don't expect to use the WrapAngle method, here's an all-in-one version:
So now you can do: