# How to rotate NavMeshAgent toward its movement direction?

I'm working on a 2D game in XY plane. I've created enemies using NavMeshAgent and I've gave my agents way pints to move between them. The problem is that I don't know how to rotate them in the direction they are moving or vector of the velocity (blue arrow). The front of the agent is in the direction of Y axis(green arrow). Note that updateRotation isn't an option, That will rotate agent and make it disappear(agent rotates 90 degree around X axis).

Blue arrow is vector of the velocity

Please provide a code along your ideas.

    void FaceTarget()
{
Vector3 lookTarget = agent.velocity.normalized;
float angel = Vector3.Angle(lookTarget, Vector3.up);
transform.rotation = Quaternion.Euler(0,0,angel);
}


I've tried this code, It calculates the angel between the vector of the velocity and local Y axis. Desired output is that agent rotates toward its movement direction. In the actual output, agent rotates, But in some points, It's not toward the movement direction. I know the problem is that angels range is [0,180], not [0,360], But I couldn't figure out any solution for it.

• In future, please edit your existing question rather than deleting and re-posting a second question about the same topic. Sep 14, 2023 at 15:50

You can avoid the trig and angles by using the LookRotation helper method in a slightly different way:

void FaceTarget() {
var vel = agent.velocity;
vel.z = 0;

if (vel != Vector3.zero) {
transform.rotation = Quaternion.LookRotation(
Vector3.forward,
vel
);
}
}


This uses the fact that LookRotation points the object's local z+ axis (blue arrow on the local translation gizmo) to point toward the first argument. Here we provide the global z+ direction, so the sprite stays correctly oriented in the XY plane.

Then LookRotation twists the object around that vector so that its local y+ axis (green arrow) points toward the second argument. By providing the velocity, we neatly rotate the front of the unit to face its velocity, without needing to compute the angle explicitly.

• This works too, thanks🙏 Sep 15, 2023 at 9:30

I've solved it with help of ChatGpt. Here's the code

void FaceTarget()
{
if (agent.velocity != Vector3.zero)
{
Vector3 moveDirection = new Vector3(agent.velocity.x, agent.velocity.y, 0f);
if (moveDirection != Vector3.zero)
{
float angel = Mathf.Atan2(moveDirection.x, moveDirection.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angel, Vector3.back);
}
}

}