# Mathf.Clamp Input rotation

Hello

Im trying to limit the rotation of the gun (gameobject) however im having trouble getting it to work so clearly im doing something wrong.

``````float gunRotFactor = 0f;

if (0f != Input.GetAxis("MouseVertical")) //Input.GetAxis will equal a negative or possitive value between 0.0 and 1.0 and is then compared to 0. Aka: Is the mouse rotating?
{
gunRotFactor = Mathf.Sign(Input.GetAxis("MouseVertical"));
}

float gunUpDown = gunRotFactor * gunTurnSpeed;

gun.transform.Rotate (0, 0, Mathf.Clamp(gunUpDown, -10f, 20f));
``````

This is because transform.Rotate is a function that Rotates your gun a set amount. Your clamping how much it can Rotate each frame. Not the absolute Rotational Position. SO each frame the gun can’t rotate more than 20degrees. but over 18 frames it could easily rotate a full 360… Because each frame your rotating it 20 degrees.

What you want is this:

``````gun.transform.Rotate (0, 0,gunUpDown));

// get the rotation in normal degrees
Vector3 eulerAngle = gun.transform.eulerAngles;

// eulerangles are always 0->360.. so if you rotated to -10 its now at 350.
// so we need to check which way we were rotating then clamp
if (gunUpDown < 0)
eulerangle.z = Mathf.Clamp(eulerAngle.z,350f, 360f);
else
eulerangle.z = Mathf.Clamp(eulerAngle.z, 0f, 20f);

tranform.eulerAngles = eulerAngle;
``````

Just realized that code will warp the gun back to -10 if your were at 20 and started going backwards. Needs to be this:

``````// 185 is the halfway point between 20 and 350.
//We assume our gun can't zoom around this fast in one frame
if (eulerAngle.z > 185)
Mathf.Clamp(eulerAngle.z,350f,360f);
else
Mathf.Clamp(eulerAngle.z,0f,20f);
``````