How to restrict rotation when its gets so far

I have a camera that the player can orbit around and up and down. I want it to stop when it gets to a certain height up or down. Here is what i have:

public Vector3 myEuler = Vector3.zero;
    public float rotVel;
 
    void Start () {
    myEuler.x = transform.eulerAngles.x;
 
    }
 
    void Update () {
 
       if (Input.GetKey(KeyCode.LeftArrow)) {
         transform.Rotate(0,Time.deltaTime * 50,0, Space.World);
       }
 
       else if (Input.GetKey(KeyCode.RightArrow)) {
         transform.Rotate(0,Time.deltaTime * -50,0, Space.World);
       } 
 
       else if (Input.GetKey(KeyCode.UpArrow)) {
         myEuler.x += rotVel * Time.deltaTime;
       }
 
       else if (Input.GetKey(KeyCode.DownArrow)) {
         myEuler.x -= rotVel * Time.deltaTime;
       } 
    }

although its not working. Any clues?

Personal advice 1: NEVER use eulerAngles unless you know 101% what you are doing.
Personal advice 2: ALWAYS use Quaternions, might seems work intensive, but prevents the Gimbal Lock

I can tell you why it’s not working:

Line 20 and 24 modify the myEuler variable but you never assign the variables to the transform like you did in lines 12 and 16. So either insert

transform.rotation.x = myEuler.x;

at the end or replace line 20 with

transform.Rotate(Time.deltaTime * rotVel, 0, 0, Space.World);

and line 24 with

transform.Rotate(Time.deltaTime * -rotVel, 0, 0, Space.World);

Limiting how far you can turn around is another topic.

I dont know about the code but the MouseController script that is attached to the default first person controller comes with all the basic functionality including limiting rotation. I have used it myself, just drag and drop the MouseController script to the player.

in the MouseController script you will see some variable that can be tweaked in the editor to change the sensitivity of the mouse, or limit the viewing angle :slight_smile:

Hope this helps :slight_smile: