Clamp rotation of camera in Unity

Some notes and issues when trying to clamp the rotation of a camera in Unity. All the code was put on a script assigned to a controller that controlled the camera view. Used the Simple Touch Controller from the asset store.

Problem trying to clamp EulerAngles

It appears that the following code does not work as EulerAngles expects a value from 0-365.

transform.localEulerAngles = new Vector3(Mathf.Clamp(transform.localEulerAngles.x - rightController.GetTouchPosition.y * Time.deltaTime * speedContinuousLook, 0f , 20f ),transform.localEulerAngles.y + rightController.GetTouchPosition.x * Time.deltaTime * speedContinuousLook, 0f);

Extra debug info

Debug.Log("Rotation = " + transform.localEulerAngles.ToString());

Code to clamp rotation

You have to do some math to take the value from 0-365, then translate it to -90 – 90 so it can be clamped properly

// Put these with the rest of your public variables.  These should show up in the Unity Inspector and allow you to modify the values
public float speedProgressiveLook;
public float clampXRotationUp;
//  The following lines allow the script to Clamp the camera X rotation and should go in the Update function

float playerRotation = transform.localEulerAngles.x - rightController.GetTouchPosition.y * Time.deltaTime * speedContinuousLook; 

if (playerRotation > 180)        {             
    playerRotation = playerRotation - 360 ;  // Sets our working numbers between -180 - 180  
playerRotation = Mathf.Clamp(playerRotation, clampXRotationDown, clampXRotationUp);

Vector3 newRotation;
newRotation.x = playerRotation;
newRotation.y = transform.localEulerAngles.y + rightController.GetTouchPosition.x * Time.deltaTime * speedContinuousLook;
newRotation.z = 0;

transform.localEulerAngles = newRotation;

The following links were helpful.

Leave a Reply