How to lock LookAt() Y axis?

I was doing some basic enemy AI and it works, but the whole enemy model moves when player jumps. Is there any simple way to lock Y axis? I´m new with code.

This is my script:

    void Update()
    {
        animator.SetFloat("Speed", agent.velocity.magnitude / agent.speed);
        if(timePassed >= attackCD)
        {
            if (Vector3.Distance(player.transform.position, transform.position) <= attackRange)
            {
                animator.SetTrigger("Attack");
                timePassed = 0;
            }
        }
        timePassed += Time.deltaTime;

        if (newDestinationCD <= 0 && Vector3.Distance(player.transform.position, transform. position) <= aggroRange)
        {
            newDestinationCD = 0.5f;
            agent.SetDestination(player.transform.position);
        }
        newDestinationCD -= 0.5f;
        transform.LookAt(player.transform);
 
    }

hmmm, I would probably lock the y rotation of the object like this:

// If you want for example the Y rotation to be 120 degrees, you can simply replace the 0 with 120
Vector3 euler = transform.rotation.euler;
transform.rotation = Quaternion.Euler(euler.x, 0, euler.z);

but i dont know if this works because i dont want to open unity, and its 2:30 AM in germany right now

1 Like

Yes, there is a simple way. Instead of

transform.LookAt(player.transform);

you would do this

var pos = player.transform;
pos.y = transform.position.y;
transform.LookAt(pos);
4 Likes

Thanks! I used ChatGPT, and sent me this result hehe.