# how do i clamp my rotation which is controlled by touch controls?

I have tried multiple different solutions to clamping my rotation but none have worked. How would i clamp my rotation so that it doesn’t exceed 90 degrees in either direction. i have placed the code for rotation below.

``````public float mouseSensitivity = 100f;
public Transform playerBody;
private Vector2 touchPosition;
private Touch touch;

private float mouseY;

// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{

touch = Input.GetTouch(0);
touchPosition = Input.GetTouch(0).deltaPosition;
mouseY = touchPosition.x * mouseSensitivity * Time.deltaTime;
playerBody.Rotate(Vector3.up * mouseY);
``````

You can get there with a bit of refactoring and quaternion maths. One thing to note is that mouseY now stores the total rotation rather than just the delta;

``````public float mouseSensitivity = 100f;
public Transform playerBody;
private Vector2 touchPosition;
private Touch touch;

private float mouseY = 0f;

// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
touchPosition = Input.GetTouch(0).deltaPosition;
//Accumulate the rotation and clamp to 90 degrees
float totalRotation = Mathf.Clamp (mouseY + touchPosition.x * mouseSensitivity * Time.deltaTime, -90f, 90f);
//Find how much the rotation has changed
float rotation = totalRotation - mouseY;

//This rotates around an axis by an angle (similar to how you were handling rotation)
playerBody.rotation = Quaternion.AngleAxis (rotation, Vector3.up) * playerBody.rotation;

//Update the total rotation
mouseY = totalRotation;

...
``````