# Mathf.Clamp Rotation Problem

Hey guys
Ive been trying to make a block rotate to certain point when moving with the arrow keys
but for some reason the mathf.clamp doesn’t want to work with the rotate ? I have this same code in the same project where I clamp the position of my player and that works. Any help please! Thanks in advance
Bernard ``````function Update () {

transform.rotation.z = Mathf.Clamp(transform.rotation.z, -45, 45);
if (Input.GetAxis("Horizontal") > 0) {
transform.rotation.z -= 5 * Time.deltaTime;
}
else if (Input.GetAxis("Horizontal") < 0) {
transform.rotation.z += 5 * Time.deltaTime;
}
else {
transform.rotation.z = 0;
}

}
``````

You have a couple of issues. First, unless you have a good knowledge of Quaternions don’t directly modify the x,y,z,w properties of Quaternion (rotation). In this case, you were probably okay, but directly modifying these values does not necessarily produce the desired result. Instead use “transform.eulerAngles”

Next, on line 11, you are snapping the rotation back to 0 anytime “Horizontal” is 0. Comment out this line and see if the behavior is what you want.

Transform.rotation is a quaternion, which does not use degrees nor does it relate directly to euler angles. You should track the rotation yourself, which is demonstrated clearly in the default MouseLook script including with the character controller standard package.

Robertbu is right, you should avoid directly modifying the quaternion values unless you know what you’re doing. One of the reasons for this however is because the x ,y, z values of the quaternion are not the axis rotation angles as you would expect them to be. It looks like you are trying to modify the angles as Euler angles (0-360 on x,y,z axis’).

I would suggest either using the quaternion helper functions to apply the rotation, or pull out the euler values, modify them, and then push them back. as the below code demonstrates.

``````function Update()
{
var tmpEuler:Vector3 = transform.eulerAngles;
tmpEuler.z = Mathf.Clamp(tmpEuler, -45, 45);
if (Input.GetAxis("Horizontal") > 0)
{
tmpEuler.z -= 5 * Time.deltaTime;
}
else if (Input.GetAxis("Horizontal") < 0)
{
tmpEuler.z += 5 * Time.deltaTime;
}
transform.eulerAngles = tmpEuler;
}
``````