Rotating the character with NavMeshAgent navigation

pathfinding
My character was foot-sliding and walking sideways!

After the rush of trying to make the character rotate as it followed its path, visually it still looked like he was foot-sliding.

I trying increasing the angular speed but the character still was sliding a bit.

The solution was to write a component that would turn the character in the direction the NavMeshAgent was moving.

Basically there is a property called pathEndPosition in the NavMeshAgent that gives you the next position the agent is translating to.

I used this information to interpolate a rotation between the direction the player was facing and the direction it was supposed to go.

This is the script:

using UnityEngine;
using UnityEngine.AI;

public class FaceNavMeshMovement : MonoBehaviour {

    NavMeshAgent agent;

	// Use this for initialization
	void Start () {
        agent = GetComponent();
        agent.updateRotation = false;
	}
	
	// Update is called once per frame
	void Update () {
        if (!agent.isStopped)
        {
            var targetPosition = agent.pathEndPosition;
            var targetPoint = new Vector3(targetPosition.x, transform.position.y, targetPosition.z);
            var _direction = (targetPoint - transform.position).normalized;
            var _lookRotation = Quaternion.LookRotation(_direction);

            transform.rotation = Quaternion.RotateTowards(transform.rotation, _lookRotation, 360);
        }
	}
}

Fairly simple this script first deactivates the agent rotation update and gets its component in the Start method. Then we can update it ourselves in the Update method interpolating pathEndPosition and the transform position.

The target point uses a trick: I create a Vector3 here as I want the rotation destination to have the same information (not changing) as before.

If we don’t do this, the character will spin and face the ground.

It was useful in our project, hope it help you guys!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s