# Rotating a model to a maximum of 45 degrees

Hi i have a model that is controlled by the player, and when i turn i want it to rotate on the z axis to a maximum of 45 degrees. however it doesn’t work. I have tried different things, and either it wont turn to the other side when i have turned to one, or like in this case, i can see the that it actually executes the rotate function but it doesn’t rotate. and another thing that puzzles me is that my debug.log call prints 2 different numbers, one for when i turn right and one for when i turn left, am i missing something?

``````		if(moveHorizontal != 0 && rigidbody.velocity.x < maxSpeed  )
{

if(moveHorizontal > 0 &&  Mathf.Approximately(transform.eulerAngles.z, 315))
{
float temp = transform.eulerAngles.z -360;
if(temp > -45f)
transform.Rotate(0,0,-1);
}

else if(moveHorizontal < 0 )
if(transform.eulerAngles.z < 45)
transform.Rotate (0,0,1);

}

if(moveVertical !=0 && rigidbody.velocity.z < maxSpeed)
``````

I assume from your description and code that you want to restrict global Z axis rotation to a +/- 45 degree range?

You are rotating the transform by an arbitrary amount (+/- 1 degree) rather than clamping it. You should just set the Z rotation directly if it’s outside your desired range. Something like this should work provided the maximum change in rotation is less than 135 degrees (otherwise you’ll need to store the previous rotation value to determine where to clamp).

``````Vector3 eulerAngles = transform.eulerAngles;
if (eulerAngles.z > 45 && eulerAngles.z <= 180) {
eulerAngles.z = 45;
transform.eulerAngles = eulerAngles;
} else if (eulerAngles.z < 315) {
eulerAngles.z = 315;
transform.eulerAngles = eulerAngles;
}
``````

You’re code has a number of issues that could cause it to do ‘nothing’:

• The Mathf.Approximately check means you will only make the -1 rotation adjustment if the current Z rotation is almost exactly 315 degrees (you could overshoot this depending on the movement rotation, plus wrong to check this in any case if you want to clamp a value).
• Both of your angle checks are wrong as they will trigger if the rotation is in your desired range.

Have you tried Mathf.Clamp?