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

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


1 Answer 1


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
                                        Mathf.Clamp(transform.eulerAngles, minAngle, maxAngle),

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


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .