Weird behaviors with transform.LookRotation when looking at position+Vector3

I'm working on a character controller for an isometric retro shooter. However, when making the character rotate towards where they are moving, I encountered some issues.

• The character doesn't fully rotate; instead of 90 degrees, it's about 85.
• The character's rotation sometimes lags and glitches when changing directions.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
public float MoveSpeed;
private CharacterController controller;
public Quaternion lookTo;

private Vector3 move;
public Vector3 velocity; //For Debugging

// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}

// Update is called once per frame
void Update()
{
float moveX = Input.GetAxis("Vertical")*MoveSpeed*-1f;
float moveY = Input.GetAxis("Horizontal")*MoveSpeed;
move = new Vector3(moveX, 0f, moveY);
velocity = controller.velocity;
lookTo = Quaternion.LookRotation(transform.position+controller.velocity);
lookTo.z = 0f;
lookTo.x = 0f;
transform.rotation = lookTo;

controller.Move(move);
}
}


Does anyone know what I did wrong? Thank you!

Three mistakes:

1. You're reading the controller's velocity before you've fed it the latest input, so this is stale data, adding a frame of latency to your rotation. That accounts for the lag you're seeing.

2. The input to LookRotation() needs to be the direction to look in, not a position to look at.

Do not add the object's position here:

lookTo = Quaternion.LookRotation(transform.position+controller.velocity);


That accounts for the less-than-90° rotation you observe, since the position offset was adding an unwanted bias.

3. The output is a quaternion, not a set of Euler angles. You should not manipulate the x y z w components of a quaternion individually unless you know what you're doing with imaginary numbers in 4-dimensional space.

Corrected code would look like this:

void Update()
{
float moveX = Input.GetAxis("Vertical")*MoveSpeed*-1f;
float moveY = Input.GetAxis("Horizontal")*MoveSpeed;
move = new Vector3(moveX, 0f, moveY);

// Since move.y is 0 by construction,
// this will be a pure yaw (y) rotation.
// No need to mess with its components.
lookTo = Quaternion.LookRotation(move);

transform.rotation = lookTo;

controller.Move(move);
}