Skip to content

Instantly share code, notes, and snippets.

@gekidoslair
Last active May 10, 2022 10:07
Show Gist options
  • Save gekidoslair/a37267c1402ab6ee5ad1929c8be86ea1 to your computer and use it in GitHub Desktop.
Save gekidoslair/a37267c1402ab6ee5ad1929c8be86ea1 to your computer and use it in GitHub Desktop.
Root Motion based Navmesh characters in Unity
using UnityEngine;
using UnityEngine.AI;
namespace PixelWizards.GameSystem.Controllers
{
/// <summary>
/// All this does is implement the OnAnimatorMove() for our Units
/// </summary>
public class RootMotionNavMesh : MonoBehaviour
{
Vector3 worldDeltaPosition = Vector3.zero;
Vector3 position = Vector3.zero;
NavMeshAgent agent;
Animator animator;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
// don't update the agent's position, the animation will do that
agent.updatePosition = false;
}
private void Update()
{
worldDeltaPosition = agent.nextPosition - transform.position;
// Pull agent towards character
if (worldDeltaPosition.magnitude > agent.radius)
agent.nextPosition = transform.position + 0.9f * worldDeltaPosition;
}
private void OnAnimatorMove()
{
// Update position based on animation movement using navigation surface height
position = animator.rootPosition;
position.y = agent.nextPosition.y;
transform.position = position;
}
}
}
@gekidoslair
Copy link
Author

apparently I typed this out raw without actually testing, just posted a fixed version that actually compiles

@calypsoresende
Copy link

This way ignores Navmeshes obstacles!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment