Rotate object in direction of movement

Hi all, I know similar questions have been asked but I am still struggling.
I have an NPC that randomly moves in the X and Z direction, and I want it to turn to the direction it is moving so as so be more realistic, but when I tried coding it, it just randomly rotates forever.

public class Walking : MonoBehaviour {
    private float latestDirectionChangeTime;
    private readonly float directionChangeTime = 3f;
    private float characterVelocity = 2f; //Random.Range(.5f, 3f);
    private Vector3 movementDirection;
    private Vector3 movementPerSecond;
    public GameObject alien;
 
    
    void Start(){
        latestDirectionChangeTime = 0f;
        calcuateNewMovementVector();
    }
 
    void calcuateNewMovementVector(){
        //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
        movementDirection = new Vector3(Random.Range(-1.0f, 1.0f), 0,Random.Range(-1.0f, 1.0f)).normalized;
        movementPerSecond = movementDirection * characterVelocity;
    }
 
    void Update(){
        //if the changeTime was reached, calculate a new movement vector
        if (Time.time - latestDirectionChangeTime > directionChangeTime){
            latestDirectionChangeTime = Time.time;
            calcuateNewMovementVector();
        }
     
        //move enemy: 
        transform.position = new Vector3(transform.position.x + (movementPerSecond.x * Time.deltaTime), 22.45f,
            transform.position.z + (movementPerSecond.z * Time.deltaTime));
        
        //wait a set amount of timeeeeeee
        //if his movement is to the west, then he turns 90 in the y axis
        
        if (transform.position.x > 0)
            {
                alien.transform.Rotate(0,90,0);
            }
        
        
 
    }

  
    
}




thank you in advance!
1 Like

You’ve already calculated and stored the movement direction, so all you need to do is transform that into a quaternion and assign it in your Update function and you’re done;

alien.transform.rotation = Quaternion.LookRotation (movementDirection);

If you want the transition to be smoother, you can interpolate the rotation as well;

alien.transform.rotation = Quaternion.Slerp (alien.transform.rotation, Quaternion.LookRotation (movementDirection), Time.deltaTime * 40f);