- Home /
Getting framerate independent movement in OnStateMove or OnAnimatorMove
TL;DR Is there a best practice for calculating deltaTime in StateMachineBehavior.OnStateMove?
My specific issue:
I am trying to implement a knockback mechanic where an object will be knocked back in a different direction depending on where it is hit from, but implementing it as part of the knockback animation. Here's my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Knockback : StateMachineBehaviour
{
[SerializeField] float m_knockbackDistance = 1f;
Vector2 m_velocity;
float m_lastTime;
Rigidbody2D m_rb;
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
base.OnStateEnter(animator, stateInfo, layerIndex);
Vector2 direction = new Vector2(
animator.GetFloat("HitDirectionX"),
animator.GetFloat("HitDirectionY"));
m_velocity = (m_knockbackDistance / stateInfo.length) * direction;
m_rb = animator.GetComponent<Rigidbody2D>();
m_lastTime = stateInfo.normalizedTime;
}
public override void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
base.OnStateMove(animator, stateInfo, layerIndex);
// need to manually track time here because this gets called after both Update and FixedUpdate
float deltaTime = stateInfo.normalizedTime - m_lastTime; // I'm assuming the animation doesn't loop here.
m_lastTime = stateInfo.normalizedTime;
m_rb.MovePosition((Vector2)animator.transform.position + m_velocity * deltaTime);
}
}
As you can see, there is some funkiness around using deltaTime in the script. My impression from reading the documentation on execution order is that OnStateMove is called both during FixedUpdate and Update, which means using Time.deltaTime or Time.fixedDeltaTime is incorrect and might end up doubling the movement depending on how the cycles line up. https://docs.unity3d.com/Manual/ExecutionOrder.html
However, I'm running into some bugs where objects seem to jump/teleport on some machines and not others. The bug is happening on a mac running the game at ~120 FPS (according to the stats tab in the editor), but not a PC running at ~600 FPS. I think this script is causing the problem. The most obvious answer is that my method for calculating deltaTime in the script is flawed somehow and the FPS difference is causing the different behaviors.
Suggestions? Thanks for your help!