Constraining Rotation

Is there a way to constrain the rotation of one or more axis so that it can only rotate up to a certain amount? For example, allowing the Y axis to only rotate to 30 or -30 degrees?
I wasn’t able to find anything that looked like this in the scripting reference. Any ideas?

I don’t think that there’s anything super-elegant [edit: I was wrong.], but you can always just write

if (transform.rotation.y > 30)
{
transform.rotation.y = 30;
}
if (transform.rotation.y < -30)
{
transform.rotation.y = -30;
}

It isn’t beautiful, but it’ll do the job.

transform.rotation.y = Mathf.Clamp(transform.rotation.y, -30.0, 30.0);

This is almost true: you should use transform.eulerAngles though.

transform.rotation.y would modify the 2nd component in the rotation quaternion, which does not have any intuitive effect.

Thanks for your responses. The script with eulerAngles works but I am getting some choppy motion. I have other things affecting the physics of the objects though, so I will keep playing with it and see if I can smooth things out.
Thanks again for your help.

If the object has a rigidbody you are going to have to use rigidbody.AddForce(). For doing stuff like this ForceMode.VelocityChange is your freind. This constrains a rigidbody on it’s y axis:

relativeAngularVelocity = transform.InverseTransformPoint(rigidbody.angularVelocity);
relativeAngularVelocity.y = 0;
newAngularVelocity = transform.TransformPoint(relativeAngularVelocity);
difference = newAngularVelocity - rigidbody.angularVelocity;
rigidbody.AddTorque(difference, ForceMode.VelocityChange);
1 Like