Keep camera x rotation

Hi!
I’ve road a script for camera behaviour to follow player and rotate around, but when i run it, it chenges rotation x to 41.987 from any position. Help me please to fix it.

public class CameraScript : MonoBehaviour
{
    private GameObject player;
    private Vector3 offset;

    void Start()
    {
        player = GameObject.Find("Player");
        offset = new Vector3(player.transform.position.x, player.transform.position.y + 8, player.transform.position.z - 10);
    }

    void Update()
    {
        FollowPlayer();
    }

    void FollowPlayer()
    {
        transform.position = player.transform.position + offset;
        Cursor.visible = true;

        if (Input.GetKey(KeyCode.Mouse1))
        {
            Cursor.visible = false;
            offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X"), Vector3.up) * offset;
            transform.LookAt(player.transform.position);
        }
    }
}

Hi @Keyleas, it appears you are only rotating around the player on the World Up axis.

Of course x will not change because you are not rotating the camera on the x axis - which would have the affect of moving the camera up and down - by “pitching” the camera up or down.

You need to decide how you want the camera to rotate.

If you want to orbit in the vertical direction then you need to apply pitch. Add line of code after the current horizontal input the get the Vertical input and create a quaternion that based on the camera’s local Right vector (transform.right) . It will be the same as your horizontal line, but just rotating on the right axis.

Perhaps you don’t realize what you are doing. You have your camera set from the start to look at the player from a particular position. So as soon as you run the game and you press your key, LookAt forces the camera to rotate toward player. That is what sets your x angle. From there, because you are only rotating on world Y, x will not change.

If you were to move your camera to a different starting location in your start function, you would set a different x angle when you press your key, but again x will be stuck at that new angle when you rotate around.

It is the initial location of your camera that determines it’s starting x angle. I hope that makes sense.