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).
here's the a code that i have found on unity forum, it works perfectly on 3D, but i can't make it work on 2D
void FaceTarget()
{
Vector3 direction = agent.steeringTarget;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5);
}
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 can't figure out any solution for it.
void FaceTarget()
{
Vector3 lookTarget = agent.velocity.normalized;
float angel = Vector3.Angle(lookTarget, Vector3.up);
transform.rotation = Quaternion.Euler(0,0,angel);
}
I've solved it with help of ChatGpt. Here's the code
Here's another code provided by @DMGregory