How to freeze Z axis rotation in code?

Hi. I have problem with my camera script.
It is aimed by mouse movement and is set to look at player.
It works in vertical or horizontal way but when I move my mouse to corners my camera rotates at Z axis. How to freeze it in code?
Also it is attached to look at player’s right side but should stay behind him.

public class MouseAimCamera : MonoBehaviour {
    public GameObject target;
    public float rotateSpeed = 5;

    void Start() {
        transform.parent = target.transform;
        transform.LookAt(target.transform);
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
        float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
        target.transform.RotateAround(target.transform.position, Vector3.up, horizontal);
        target.transform.RotateAround(target.transform.position, Vector3.left, vertical);
    }
}

This is pretty easy to do. If your component has a rigidbody attached, use this code, and replace rb with the variable for your rigidbody:

rb.constraints = RigidbodyConstraints.FreezeRotationZ;

First, don’t use the deprecated RotateAround use Rotate instead. Next … realize that I answered this exact same question twice yesterday… It’s clear you came from the same tut because you’re code looks the same as theirs. But please try harder to search the site.

Rotation is not simple like translation because it is not commutative. Try to work it out in your head, rotating in two axes one at a time… you won’t end up without rotation on the third axis. So you are probably getting unintentional role. You’re case isn’t too hard though. Try this. It eliminates what is called cross-contamination by defining the two separate rotations in different coordinates… Don’t ask me how… wish I knew.

target.transform.Rotate(Vector3.up, horizontal, Space.Self);
target.transform.Rotate(Vector3.right, vertical, Space.World);

Hope this helps! good luck. And hey, if you did come here with this code from a tutorial would you kindly bring this info over to it… seems we are seeing a lot of this.

this worked for me

void FixedUpdate()
{
target.transform.Rotate(new Vector3(vertical, -horizontal, 0) * Time.deltaTime);
target.transform.eulerAngles = new Vector3(target.transform.eulerAngles.x,
target.transform.eulerAngles.y, 0);
}

Put LookAt inside Update, after the movement, this way the camera will adjust its orientation every frame (LookAt aligns to world up direction by default), :

         target.transform.RotateAround(target.transform.position, Vector3.up, horizontal);
         target.transform.RotateAround(target.transform.position, Vector3.left, vertical);
         transform.LookAt(target.transform); // aim at the player
}