NavMesh Agent rotates on X axis when moving and snaps back to 0.

I’ve been successful in creating a NavMesh at the run time and I am able to get my player unit to move around on the NavMesh. All is well there.

The weird part is that the player unity rotates every so slightly on the X axis but upon reaching the intended destination snaps back to 0 rotation again. My movement is a pretty basic click-to-move system that doesn’t involve any rotation other than using the transform.LookAt before moving.

I haven’t been able to figure out what is causing this weird rotation or how to stop it from happening yet. Any ideas on what might be causing it would be greatly appreciated.

Please, share your code to find the problem, and tell us if you are using animator.

I am not using animator. My player movement code looks like this:

public class PlayerMovement : MonoBehaviour {
    public float speed = 3;
    private Vector3 targetPosition;    
    private bool isMoving;
    const int LEFT_MOUSE_BUTTON = 0;
	private float yAxis; 
    private float distance;
    

    void Start() {
        targetPosition = transform.position;
        isMoving = false;
		yAxis = gameObject.transform.position.y;
    }
		
	void Update () {
        if(Input.GetMouseButtonDown(LEFT_MOUSE_BUTTON)) {			
            SetTargetPosition();
        }
		if(isMoving) {            
			MovePlayer();
		}		
	}

	void MovePlayer() {        
        gameObject.transform.LookAt(targetPosition);        
        distance = Vector3.Distance(targetPosition, gameObject.transform.position);
        if(distance >= .5){
            gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, targetPosition, speed * Time.deltaTime);
        }                       
        if(distance < .5) {
            isMoving = false;
        }

        Debug.DrawLine(transform.position, targetPosition, Color.red);
    }

    void SetTargetPosition() {
		RaycastHit hit;		
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);		

        if(Physics.Raycast(ray, out hit, 100)) {
			targetPosition = hit.point;
			targetPosition.y = yAxis;
            isMoving = true;                    
        }        
    }	
}

The player object does move properly to the clicked location within the navmesh too. Just the weird X rotation happening is the weird part.