# How do I clamp my rotation?

The player is in first-person, as humanoid model. To other players, when they look up, their torso rotates slightly vertically. It works the same way when I look down. This can also be observed in the game “Rust”, by Garry Newman. Here is my script, that is attatched to the spine.

``````var speed : float = 5;
var torsoRotation : float = 0;

function Update() {
torsoRotation = Input.GetAxis("Mouse Y") * speed;
Mathf.Clamp(torsoRotation, -90, 90);
transform.Rotate(0, 0, -torsoRotation, Space.Self);
}
``````

It works, except for the clamp. I can infinitely roll my upper body. I am suspicious at the fact that in the inspector, my `torsoRotation` is equal to 0. When I move the mouse up or down fairly quickly, it changes to about 0.5 or 1. When I stop using the mouse, it drifts back to 0. What is happening, and how can I fix it?

Old thread, but problem was never solved. Best solution for me was:

``````    float ClampAngle(float angle, float from, float to)
{
// accepts e.g. -80, 80
if (angle < 0f) angle = 360 + angle;
if (angle > 180f) return Mathf.Max(angle, 360+from);
return Mathf.Min(angle, to);
}

void RotateInFrame()
{
if (!Input.GetMouseButton(1)) return; // RMB down

float mx = Input.GetAxis("Mouse X") * Time.deltaTime * rotSpeed;
float my = Input.GetAxis("Mouse Y") * Time.deltaTime * rotSpeed;

Vector3 rot = transform.rotation.eulerAngles + new Vector3(-my, mx, 0f); //use local if your char is not always oriented Vector3.up
rot.x = ClampAngle(rot.x, -60f, 60f);

transform.eulerAngles = rot;
}
``````

Good luck!

Try this:

`````` function Update() {

torsoRotation = Input.GetAxis("Mouse Y") * speed;
transform.Rotate(0, 0, -torsoRotation, Space.Self);
transform.eulerAngles.y = Mathf.Clamp(transform.eulerAngles.y, -90, 90);

}
``````

Clamping just returns a value that you have to set into the rotation yourself. You need this after you’ve applied your rotation. However, this may still cause strange flicking, if so you might need to use a cleverer clamping function that understands angles.

Here it’s explained well

This worked fine for me.
But since I am moving in delta steps, I had to add this in order to clamp it right:

``````float deltaAngle = context.ReadValue<float>();
float clampAngle = ClampAngle(target.eulerAngles.x + deltaAngle);
deltaAngle = clampAngle - target.eulerAngles.x;

target.Rotate(target.right, deltaAngle, Space.World);
``````

Notice I am using a new input system event call to look up and down using the mouse Y axis. Also, I made the ClampAngle function a private member of my class, and removed the min and max parameters, since those are user defined parameters, and I made them members of the same class. Then I rotate the target Transform along its right axis.

Work as a charm!