Unity 2D: my LookRotation keeps rotating on the wrong axis

I’m trying to rotate a 2D sprite towards another 2D sprite on the same plane / Z location. For some reason with the following code, the sprite seems to rotate on the X and Y instead of the Z and I can’t figure out why. It should ONLY rotate on the Z. Sometimes when I tweak with it, the sprite dissappears or doesn’t rotate at all.

            //Rotate
            Vector3 relativePos = targetLocation - transform.position;
            Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
            transform.rotation = rotation;

targetLocation is a vector3 transform.position sent from another object.

Even though it seems like it should work in 2D, Unity still uses 3D coordinates and rotations when operating in 2D. This means that when you use Quaternion.LookRotation() it will act as if the sprite is just a 3D transform and point it towards the other sprite in a 3D-orientation.

Try this instead:

Vector3 relativePos = target.position - transform.position;
float angle = Mathf.Atan2(relativePos.y, relativePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

This will grab the 2D angle you want and apply it on the forward axis (facing into the screen), which will rotate the direction you want it to. I’m not sure how your sprites are oriented “forward”, so you might need to rotate it by 90 degrees more. You should be able to figure that part out though.