Quaternion.LookRotation around just one axis

I keep running across this and it’s time I find out if I’m doing anything wrong.
Frequently I want a character to turn smoothly around the Y axis to face something. If I create a target rotation with Quaternion.LookRotation and Quaternion.Lerp to it, the character rotates in X, Y and Z when I only want rotation in Y (so the character remains standing naturally). I’ve been simply adding a line

transform.eulerAngles.x = transform.eulerAngles.z = 0;

but this seems tacky and wrong.

I thought the second argument to LookRotation would keep the character’s head up but it doesn’t, and setting it to the local transform.up doesn’t help either. I heard that it’s best to avoid setting euler angles for rotations, so what’s the best way to do this?

You can avoid using angles altogether:

var toTarget = target.position - transform.position;
toTarget.y = 0;

// without smoothing:
transform.forward = toTarget;

// or with smoothing:
transform.forward = Vector3.Slerp(transform.forward, toTarget, Time.deltaTime);
2 Likes

Thanks, that makes sense. I was thinking anything involving rotations had to involve quaternions somehow.