Unity3d Animator 动画倒放

mac2025-10-30  14

首先:百度到的Animator倒放方法可以用(https://jingyan.baidu.com/article/d713063593f99f13fdf475e1.html)。

 

但是 该方法需要在controller中添加参数,如果项目中有很多动画需要倒播,这么做出错率很高,重复劳动也很令人焦虑。

 

在网上一番搜索找到这位仁兄的方法:https://blog.csdn.net/qq_41752435/article/details/90113402#commentBox

 

一番测试之后确实可以使用,但是有几点需要补充说明一下:

 

Animator的播放速度由 Animator.speed 控制,断点后发现,如果不先执行 Animator.StartPlayback()方法,speed的值是不可以被赋负值的,会被置0。所以很多人问为什么speed置-1动画暂停了,因为其实是置0了。Animator.StartPlayback()方法应该是配合StartRecording()等方法用于动画的录制和回放的,不知道为什么会影响到speed的赋值。注意,如果需要倒放动画,需要从最后一帧往前放,和正常播放是相反的,所以需要执行:                                                         ani.Play(clipInfo.clip.name, 0, 1) , 正常的播放是ani.Play(clipInfo.clip.name, 0, 0)

 

 

贴上测试代码:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimatorTest : MonoBehaviour { Animator ani; // Use this for initialization void Start () { ani = GetComponent<Animator>(); } // Update is called once per frame void Update () { if(Input.GetKey(KeyCode.A)) { Play(1); } else if(Input.GetKey(KeyCode.B)) { Play(-1); } else if (Input.GetKey(KeyCode.C)) { Play(0.5f); } else if (Input.GetKey(KeyCode.D)) { Play(-0.5f); } else if (Input.GetKey(KeyCode.E)) { Stop(); } } void Play(float speed) { if (ani != null) { //ani.enabled = false; ani.enabled = true; AnimatorClipInfo[] temps = ani.GetCurrentAnimatorClipInfo(0); AnimatorClipInfo clipInfo = new AnimatorClipInfo(); if (temps.Length > 0) { clipInfo = temps[0];//获取动画clip } ani.StartPlayback(); ani.speed = speed; ani.Play(clipInfo.clip.name, 0, speed < 0 ? 1 : 0); } } void Stop() { AnimatorClipInfo[] temps = ani.GetCurrentAnimatorClipInfo(0); AnimatorClipInfo clipInfo = new AnimatorClipInfo(); if (temps.Length > 0) { clipInfo = temps[0]; } ani.Play(clipInfo.clip.name,0,0); ani.speed = 0; } }

 

  

 

   

   

 

 

  

 

 

 

 

最新回复(0)