The question is answered, right answer was accepted
C# - Animation Based on Speed and Direction
So I want to play my movement animations for my AI based on that AI's speed and direction. This works when they are going at slower speeds but when I increase to a faster movement speed the animations seem jittery or just don't play(they are stuck in one position of the animation).
The idea is to have a mechanim speed and direction variable that will be used in a blend tree to play the movement animation. So I calculate the speed (this one seems to be fine) and direction (this one does not).
I have two ways of calculating direction: one based on rotation and the other on actual direction (I found this one on the help room):
void Update () {
//is moving left or right?
Vector3 dir = this.transform.position;
dir.Normalize ();
// Debug.Log (dir.x);
animator.SetFloat ("direction", dir.x);
// animator.SetFloat ("direction", transform.rotation.eulerAngles.y - lastRotation);
// lastRotation = transform.rotation.eulerAngles.y;
Then the following is the one I am pretty sure is working fine. Its the speed calculation:
//for speed calculation
speed = Vector3.Distance(lastPos, this.transform.position) / Time.deltaTime;
lastPos = this.transform.position;
switch(lastState) {
case "calm":
animSpeed = speed / calmSpeed;
break;
case "suspicious":
animSpeed = speed / suspiciousSpeed;
break;
case "hostile":
animSpeed = speed / hostileSpeed;
break;
}
if (animSpeed > 1000 || animSpeed < -1000 || animSpeed == 0 ||
animSpeed == Mathf.Infinity || animSpeed == Mathf.NegativeInfinity) {
animSpeed = 0;
animator.SetFloat ("speed", animSpeed);
}
else {
animator.SetFloat ("speed", animSpeed);
}
Then the mechanim is setup like the following:
![alt text][1]
Any ideas as to why the animations might be pausing or not running? It's like they are stuck halfway between starting to run and its idle state (when speed and direction are zero).
Any help and direction on this would be fantastic. [1]: /storage/temp/69670-capture.png
Still nothing? Did I just not explain my issue well enough? Any help on this would be amazing.
Can you please re-post your image of the mechanim setup? I am having the same issue. But the png you posted gets cut off.
Answer by wesleywh · May 17, 2016 at 11:29 PM
Wow I can't believe I did this... feel free to use the above script. It works like a charm! The issue was with the animations themselves. I needed to mark them as loops. So it would play through it once and freeze was my issue. I can't believe it took me this long to figure it out. Hopefully this will help someone in the future.