My script is supposed to determine the speed at which an AI is going and give that information to my animation state machine. But for some reason in the scene I’m testing in the speed will read just fine for about a second and then it’ll read zero. In other scenes it will read always read zero, and in others it works just fine.
using UnityEngine;
using System.Collections;
public class BurlapAni : MonoBehaviour
{
public static Vector3 currVel;
Vector3 prevPos;
public void Update()
{
SageLibrary_GameController controller = gameObject.GetComponent<SageLibrary_GameController>();
prevPos = transform.position;
StartCoroutine( CalcVelocity(prevPos) );
controller.SetFloat("Speed", currVel.magnitude * 8);
}
IEnumerator CalcVelocity( Vector3 pos )
{
yield return new WaitForEndOfFrame();
currVel = (pos - transform.position) / Time.deltaTime;
}
}
There seems to be some extra complexity in there that might be making calculations at the wrong time. If my memory isn’t completely shot, Update might be able to fire at times other than once per frame.
I’ve always just used:
private Vector3 lastPos;
public void Update() {
velocity = (transform.position - lastPos) / Time.deltaTime;
// do whatever movement stuff
lastPos = transform.position;
}
// then physics does whatever movement stuff
// and next time you hit update, velocity is updated