Simple Limitation of a rotation?

Hello

First of all, i am not so familiar with scripting, becaus i come from the design perspektiv. What i try to do is a touch control to view an object. so far, it works by using the following script:

 void Update()
    {

        if (Input.touchCount == 1)
        {
            if (Input.touches.Length > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                transform.rotation *= Quaternion.AngleAxis((Input.GetTouch(0).deltaPosition.y * rotSpeed), Vector3.left);
                    
                   
                }
            }
        }

but now i want to limit the rotation to 90 degrees up and down. I tought about clamping the rotation, but i didn*t get, how to clamp that quoternian right.
Thanks for any help.

Greetings from Germany
Asta

Just use: transform.rotation.eulerAngles so you can use angle expression in degrees.

Don’t do this! Euler angles suck. It won’t reliably give you a useful value for this kind of functionality. (It sometimes will, but it may unexpectedly break at some point, for the reasons detailed in the linked article.)

I recommend having a Vector2 variable representing the amount you have dragged; you can safely use Mathf.Clamp on this value to limit your rotation. This value can then be applied to your transform’s rotation using Quaternion.AngleAxis (make sure this is a one-way street though!)

Vector2 trackedRotation = Vector2.zero;
void Update()
    {

        if (Input.touchCount == 1)
        {
            if (Input.touches.Length > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
            {
trackedRotation.y += (Input.GetTouch(0).deltaPosition.y * rotSpeed);
trackedRotation.y = Mathf.Clamp(trackedRotation.y, -90f, 90f);
                transform.rotation = Quaternion.AngleAxis(trackedRotation.y, Vector3.left);
 }
}
}

(Apologies for weird indentation, I typed it up in the input box and can’t tab.)

You really only need a float for your Y rotation, but I assume at some point you’ll probably want to add in X as well, so a Vector2 will let you add that easily.

1 Like

Thank you very much, StarManta! That works exactly as i want it!