- Home /
Reversing a sprite animation
I have a project I'm trying to get working correctly in Unity 5. I've managed everything except this one this. Frustrating that it was so easy in Unity 4 and now seems like a complete mess to achieve.
I have a sprite animation that plays when the user looks at the sprite, if the user looks away before the sprite animation completes, it reverses it (using speed = -1) and plays back to the first frame. If the user plays the entire animation, the scene changes via an animation event trigger.
Now it seems in Unity 5, you cannot use speed = -1 to reverse an animation. Below is my script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Collider))]
public class LookTrigger : MonoBehaviour {
private CardboardHead head;
private Animator animator;
public bool ticked = false;
public bool looked = false;
public GameObject open;
void Start() {
head = Camera.main.GetComponent<StereoController>().Head;
animator = gameObject.GetComponent<Animator>();
animator.speed = 0;
}
void Update() {
RaycastHit hit;
bool isLookedAt = GetComponent<Collider>().Raycast(head.Gaze, out hit, Mathf.Infinity);
if (isLookedAt && !looked)
{
looked = true;
animator.speed = 1;
}
else if (!isLookedAt && looked)
{
looked = false;
animator.speed = 0;
}
}
void EndTrigger(){
if(animator.speed == 1){
open.SetActive(true);
animator.speed = 0;
this.gameObject.SetActive(false);
}
}
}
This worked so well in Unity 4, I'm not sure what to do to get it working the same in Unity 5. Any help appreciated! I tried looking into the animation state system, and setup 2 sprites (one reverse, one forward) and can get them to change, however I can't find a way to sync the frame the user looked away from the sprite, to have it seamlessly play in reverse. Why has this become so complicated?
It should still be possible to use Speed -1. Nevertheless, you can also declare a new float variable parameter in the Animator inspector, and use this as the modifier of an AnimationState's speed. If you set teh variable to -1, the speed will be reversed as well.
Edit: Tested Speed -1 and it works as intended.