How do I limit the rotation of a camera orbiting an empty GameObject?

Hierarchy:
-Character (GameObject)-> has an idependent controller script so it rotates independently of the camera’s rotation. No problem.
-Camera Rotator (empty Gameobject)-> has a camera rotation script based on the input of the mouse.
-Main Camera

Sorry, I am a beginner in Unity :((joined in 2018 but started learning this month), and programming.

This is the code component of the Empty GameObject called Camera Rotator:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRotScript : MonoBehaviour
{
 
    float rotX;
  


    float rotspeedY = 100.0f;
    float rotspeedX = 100.0f;
    // Start is called before the first frame update
    void Start()
    {
      


    }

    // Update is called once per frame
    void Update()
    {
      
        rotX = transform.eulerAngles.x;

        //to avoid problems with negative rotation values, I add +360 to a negative value.
        if (rotX < 0)
        {
            rotX += 360;
        }
      


        //ROTATE CAMERA ROTATOR AROUND THE Y AXIS!
        if (Input.GetMouseButton(1))
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * rotspeedY * Time.deltaTime, 0);
        }



        //ROTATE CAMERA ROTATOR AROUND THE X AXIS!

        if (Input.GetMouseButton(1))
        {
            if (rotX > 310 || rotX < 40)
            {

                transform.Rotate(Input.GetAxis("Mouse Y") * rotspeedX * Time.deltaTime, 0, 0);
            }
        }


    }

  

}

(^ I do the same for the rotation around the Y axis but I don’t want to limit it, so it’s out of question.)

This code is to rotate the Camera Rotator so its child, the Main Camera(where I have already inserted a
script to LookAt the rotator), also gets rotated. The problem is, I want to limit its rotation to -60 and 60.
I have tried many different ways to do that. The answers of similar questions the internet are a bit confusing for me, it’s like they are answering people who have been programming for some time on the engine.

My most successful but still not desired result was obtained by adding +360 in case the float transform.eulerAngles.x<0, and using conditions of transform.eulerAngles.x>300 and transform.eulerAngles.x<60 for the camera to be able to be rotated. But the camera just freezes in the boundaries… and another problem: if I shake the mouse too much, its “deltas” will be so big that the X rotation will get to something like 100 or even more, which is undesirable.

Is the problem the hierarchy? Or the way I’m using the input, so the shaking throws a very high value of the Mouse Y input? What about the boundaries freezing forever instead of just limiting? I don’t know if this is common with beginners but at this rate I’m starting to think I’m just throwing random stuff at my code until it somehow works… if I need to rewrite THE WHOLE CODE, I WILL, but, please, help! :face_with_spiral_eyes:

Hey, I’ll see if I can help here.

If I have this right, you’re trying to make a simple script that orbits the camera around a focal point, but you’re having issues clamping the camera along the up and down axes relative to your object. You’re also running into an issue with the camera getting stuck. I also noticed this code causes the camera to lean left and right.

The primary issue would be using a game object as your focal point. If your camera were in a fixed position, and you were only rotating on one axis, this would be fine. However, once you introduce more than one axis, you start to run into weird euler issues. You’re actually rotating on all three axes. This is why your deltas and your rotX check fails, because you’re also rotating on the Z axis unknowingly.

I would recommend using math to calculate the position of the camera manually. You also mentioned that you looked up online how to do this, and the answers were a bit confusing. After approaching the problem several different ways, I tried to come up with the simplest method I could think of. Since it’s frustrating looking for answers to a problem and all you get is really complicated or difficult to understand solutions, I’ll just post the code instead and explain it after.

public class CameraRotScript : MonoBehaviour
{
    //The focal point of our camera.
    public Transform FocalPoint = null;
    //The distance from the object we want to position our camera.
    public float FocalDistance = 10.0f;
    //The angle left and right relative to the object.
    public float AngleX = 0.0f;
    //The angle up and down relative to the object.
    public float AngleY = 0.0f;
    //The clamping values for the lower and upper angles of our y angle.
    public Vector2 AngleYClamp = new Vector2(-60.0f, 60.0f);

    public float rotspeedY = 100.0f;
    public float rotspeedX = 100.0f;

    // Update is called once per frame
    void Update()
    {
        //If the right mouse button is pressed.
        if (Input.GetMouseButton(1))
        {
            //Move our angleX by the mouse X's value.
            AngleX += Input.GetAxis("Mouse X") * rotspeedX * Time.deltaTime;
            //Move our angleY by the mouse Y's value.
            AngleY += Input.GetAxis("Mouse Y") * rotspeedY * Time.deltaTime;

            //Clamp AnglY using Mathf.Clamp and the AngleYClamps.
            AngleY = Mathf.Clamp(AngleY, AngleYClamp.x, AngleYClamp.y);

            //Prevent excessive rollover, it could cause messy results later.
            if (AngleX > 360.0f)
                AngleX -= 360.0f;
            if (AngleX < 0.0f)
                AngleX += 360.0f;

            //Prevent excessive rollover, it could cause messy results later.
            if (AngleY > 360.0f)
                AngleY -= 360.0f;
            if (AngleY < 0.0f)
                AngleY += 360.0f;
        }

        CalculateCameraPosition();
    }

    // Calculate a new camera position based on our inputs.
    void CalculateCameraPosition()
    {
        if (FocalPoint != null)
        {
            //Calculate a camera position that's a certain distance from zero.
            Vector3 tCameraPosition = -Vector3.forward * FocalDistance;

            //Rotate that position along the x/z axis by the AngleY the user has specified. This is a rotation relative to the origin.
            tCameraPosition = Quaternion.Euler(AngleY, 0.0f, 0.0f) * tCameraPosition;

            //Rotate the position along the y axis by the AngleX the user has specified. This is a rotation relative to the origin.
            tCameraPosition = Quaternion.Euler(0.0f, AngleX, 0.0f) * tCameraPosition;

            //With our new rotated position calculated, offset it by the focal point's position. That way, if something moves the focal point, we'll keep up with it.
            transform.position = FocalPoint.transform.position + tCameraPosition;

            //Tell the transform of the camera to look at the object. This is a handy function that does some work for us.
            transform.LookAt(FocalPoint);
        }
    }
}

The idea is pretty simple. You want to position your camera relative to a focal point, a Transform basically. You solve each rotation one step at a time.

  1. You take the position of that transform and push it away by a certain distance(forward * focal distance).
  2. Rotate this position using Quaternions. Quaternions are simply representations of rotations, but you only need to worry about the angle value you input in. Multiplying a position or vector by a quaternion rotates it relative to the origin. Quaternions always rotate before a vector(Quaternion * Vector).
  3. Once the camera is positioned, call transform.LookAt to face the camera towards your object. It’s a handy function that does a lot of math for us.

This should give you a much more stream-lined rotation, as it’s calculated every frame and is solved using quaternion math. You don’t have to keep up with much using this method. All you have to do is assign the focal point on the script in the inspector, and it should snap to it and start working immediately.

You should also try using “public” or “[SerializeField]” to expose data members to the Unity editor. Since all of these values are public/serialized, the inspector will let you tweak the numbers while the game is running. With this script, trying changing the focal distance or the angles while the game is running. You’ll also see the angle values change in the inspector as you move with the mouse.

Good luck, hope this helps!

1 Like

Thanks for the help! :slight_smile: But for some reason, the camera’s rotation returns to X=60 when I reach the value of 0

Edit: nvm, fixed it by removing the if(AngleY<0){AngleY += 360} thing. As you clamped it to on max 60, it was returning to this value, as 300 is much bigger than 60. Thank you very much! I see a big part of my mistakes were caused by a certain difficulty on understanding the reference and value stuff. :wink: