# How to clamp the rotation between two values in unity 3d

How can i clamp the rotation of cube between two values and then rotate between them gradually

Details Of what i Want When I press A or D keys cube should Rotate On Y Axis from 0 to 13 deg gradually and when key is released cube back to straight position

• Would any of the answers here suit your case? If not, can you edit your question to describe how your case differs from what those solve? Nov 16, 2017 at 20:41
• @DMGregory Ok Done Nov 16, 2017 at 20:47

You could use Mathf.Clamp to constrain your values, to rotate smoothly, transform.Rotate would do the trick, but the problem comes with orientation, as I see it. You may parent that cube to an object that keeps a fixed orientation, so you rotate the cube as a child. I am asuming you want to rotate on the Y-Axis, so here is an example:

public Transform cubeChild;
public float minAngle;
public float maxAngle;
public float rotationSpeed;

void Update()
{
cubeChild.Rotate(transform.up, (rotationSpeed * Time.deltaTime));
cubeChild.rotation.eulerAngles = new Vector3
(
transform.eulerAngles.x,
Mathf.Clamp(transform.eulerAngles, minAngle, maxAngle),
transform.eulerAngles.z
);
}


The code is untested, but I'll try it in a couple of minutes to confirm you.