NavmeshAgent doesnt update position with the Root animation
I was looking if you can help me with this... I have a nav agent that follows and attacks the player from a distance, and I set an animation on the animator controller, that when it takes a certain amount of damage, it plays a straf/dodge animation, as you can see in the gif, it does the animation correctly, but the position, and everything attached to the game object, doesn't follow the root position.
I use animations from mixamo
This is the code that i use to use the animations properly:
{
Animator anim;
NavMeshAgent agent;
AlienGunnerController alienGunnerController;
Vector2 smoothDeltaPosition = Vector2.zero;
Vector2 velocity = Vector2.zero;
bool alreadystrafe;
bool strafing;
Vector3 moveDirection;
void Start()
{
anim = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
alienGunnerController = GetComponent<AlienGunnerController>();
anim.applyRootMotion = true;
// Don’t update position automatically
agent.updatePosition = false;
alreadystrafe = false;
}
void Update()
{
Vector3 worldDeltaPosition = agent.nextPosition - transform.position;
// Map 'worldDeltaPosition' to local space
float dx = Vector3.Dot(transform.right, worldDeltaPosition);
float dy = Vector3.Dot(transform.forward, worldDeltaPosition);
Vector2 deltaPosition = new Vector2(dx, dy);
// Low-pass filter the deltaMove
float smooth = Mathf.Min(1.0f, Time.deltaTime / 0.15f);
smoothDeltaPosition = Vector2.Lerp(smoothDeltaPosition, deltaPosition, smooth);
// Update velocity if time advances
if (Time.deltaTime > 1e-5f)
velocity = smoothDeltaPosition / Time.deltaTime;
bool shouldMove = velocity.magnitude > 2f;
// Update animation parameters
anim.SetBool("AIwalking", shouldMove);
anim.SetFloat("Velocity XAl", velocity.x, 0.15f, Time.deltaTime * 2);
anim.SetFloat("Velocity ZAl", velocity.y, 0.15f, Time.deltaTime * 2);
AlienStrafing();
}
void OnAnimatorMove()
{
// Update position to agent position
transform.position = agent.nextPosition;
}
private void AlienStrafing()
{
if(alienGunnerController.Health <= 110 && alreadystrafe == false)
{
anim.SetTrigger("Strafing");
alreadystrafe = true;
}
}
Heres the configuration of the animation
Your answer
Follow this Question
Related Questions
It is possible to create AnimationClip ingame whose do not loop / reset position? 0 Answers
Root Motion 'due to floating-point precision limitations error.. ' and object teleported ? 0 Answers
Aim down sights not working with animations 0 Answers
Can't play an animation from the Animator 1 Answer
Problems with using the same Animator Controller on multiple objects. 0 Answers