Problem with halt with rotating on y axis

I’ve basically made a small script that will make a object rotate towards the player if they are in range but they are unable to look up and down so they can only rotate side to side. I did it with this script:

if (Vector3.Distance(transform.position, player.transform.position) <= maxDistance)
        {
            Vector3 rotationLock = transform.rotation.eulerAngles;
            rotationLock = new Vector3(0, rotationLock.y, 0);
            transform.rotation = Quaternion.Euler(rotationLock);

            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(player.transform.position - transform.position, Vector3.up), rotationSpeed * Time.deltaTime);
        }

It does what I want it to do by that it doesn’t rotate up and down if the player jumps for example. But the problem is that it seems to be trying to rotate along the y axis as it keeps shaking if the player is under or above the object. It still rotates side to side perfectly but it just shakes rapidly and I want it to stop.

Does anyone know how I could stop it?

You shouldn’t use eulerangles if you can avoid it. At the moment you reset the rotation and then you apply a relative rotation on top. You want to do something like this:

Vector3 dir = player.transform.position - transform.position;
dir.y = 0f;
Quaternion targetRotation = Quaternion.LookRotation(dir, Vector3.up);

transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

That way your target rotation will always be parallel to the x-z plane no matter where the objects are on the y axis.