# How limit the rotation of an object Or if there is other way to rotate

Hello Every One.

How can i limit the rotation of an object by the Axis of Horizontal (ont Y axis), i know there is method called Mathf.clamp but i don’t know how to use it for below code.

If there is another why to Rotate an object instead of the code that i am using below that will be helpful too.

`````` transform.Rotate(0, Input.GetAxis("Horizontal")*Time.deltaTime*turnSpeed, 0);
``````

thanks to those who help!!!

Note: i Included Time.deltaTime*turnSpeed on the code to so that nobody get confuse

The simplest option would be:

``````public float rotationSpeed = 5.0f;
public float minimumValue = -30f;
public float maximumValue = 30f;

void Update(){
transform.Rotate(0, Input.GetAxis("Horizontal")*rotationSpeed*Time.deltaTime, 0);
//The function is Mathf.Clamp(value, min, max)
transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Clamp (transform.eulerAngles.y, minimumValue, maximumValue), transform.eulerAngles.z);
}
``````

However, it has a problem. Unity automatically converts negative angles to their positive counterpart. For example, -10 becomes 350 (360-10). The problem is, that as soon as that happens our code realizes 350 is bigger than 30, so it clamps it. The solution to this is the following:

``````public float rotationSpeed = 5.0f;
public float minimumValue = -30f;
public float maximumValue = 30f;

void Update(){
transform.Rotate(0, Input.GetAxis("Horizontal")*rotationSpeed*Time.deltaTime, 0);
//The function is Mathf.Clamp(value, min, max)
if(transform.eulerAngles.y < 180){
transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Clamp (transform.eulerAngles.y, 0, maximumValue), transform.eulerAngles.z);
}
else{
transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Clamp (transform.eulerAngles.y-360, minimumValue, 0), transform.eulerAngles.z);
}
}
``````

Here we are checking the angle to see from which ‘side’ of our imaginary circle to tackle the limitation. For all angles over 180 degrees, we assume the original angle was negative and try to recover it. (-10 is converted to 350, and we recover it by doing 350-360)