Can't get object to look at another object in 2D

Hello

I have a field of view for a guard and I want it to rotate to mimic that the guard is looking around but I’m having trouble trying to figure it out. I’ve looked around and found LookAt, and LookRotation but both of these do that same thing they change the x, and y values but not the z value.

I have found a few 2D versions but those just did nothing.
https://www.youtube.com/watch?v=1Oda2M4BoNs

The object I want to look at is an object that moves up and down with Mathf.PingPong

My Code:

public GameObject FOV_RotationObject;

void FellowTheTarget()
    {
        Vector3 targetPos = FOV_RotationObject.transform.position - transform.position;
        transform.localRotation = Quaternion.LookRotation(targetPos);
    }

I hope I explained this well.
Thank You.

It is difficult to provide an answer as we don’t know in what orientation your objects/transforms are.

For example, if your transform is facing in the z-direction, that is the transform.forward.
In this case you can set transform.forward = targetPos.normalized

On line 5, targetPos is actually misnamed. That is the displacement between target and current. If your normalize the vector, the vector is then the direction of the target (from local)

Thank you for the reply.

I did the changes you suggested and it fixed the rotation x, and y values now they are both 0. Only rotation z changes but it’s still not rotating. It gets a value and stays at that value. I try to change it and the value reverts back to it.

Updated Code:

void FellowTheTarget()
    {
        Vector3 targetPos = FOV_RotationObject.transform.position - transform.position;
        transform.localRotation = Quaternion.LookRotation(Vector3.forward, targetPos.normalized);
    }

Thank You

Hi, what I suggested was:

    {
        Vector3 targetPos = FOV_RotationObject.transform.position - transform.position;
        transform.localRotation = Quaternion.LookRotation(Vector3.forward, targetPos.normalized);
    }```