标签:unity3d 动画 root motion
最近仔细比较了Unity3D目前版本中的两套动画系统:Legacy和Mecanim。Mecanim系统功能较之Legacy要强大很多,但是使用AnimatorController着实不方便(尽管使用AnimatorOverrideController可以避免重复编辑状态机),是因为游戏逻辑层面往往要用一个状态机或者类似的机制来控制角色的状态,而角色层面的状态逻辑和动画层面是无法一一对应的,两套复杂的状态机要配合起来。。。想想就觉得蛋疼啊!难怪很多朋友现在还在使用Legacy动画系统。Legacy动画系统其实功能也很全面了,包括Layer、过渡混合、上下身混合之类的功能完全能够胜任,而且控制起来就直接的多了。唯独Root Motion这个我很需要特性没有支持,本文就探讨一下如何在Legacy动画系统之上附加Root Motion功能,其实很简单。
//-- 计算当前帧的Root Motion Vector3 rootPos = m_rootBone.localPosition; m_rootMotion = rootPos - m_lastRootPos; m_lastRootPos = rootPos; rootPos.x = 0; rootPos.z = 0; m_rootMotion.y = 0; m_rootBone.localPosition = rootPos;请注意,我们在后续的代码中要把m_rootMotion附加的角色对象上,所以m_rootBone的postion被reset了。
//-- Apply Root Motion Vector3 nextPos = this.transform.position + m_rootMotion; this.transform.position = nextPos;另外,一个细节需要处理一下,在动画循环的那一帧,需要特殊处理一下。好的,看一下完整的源代码吧:
using UnityEngine; using System.Collections; public class ApplyRootMotion : MonoBehaviour { public Transform m_flagObject; // 用来测试位置的一个对象 //-- Root Motion 控制变量 Transform m_rootBone; Vector3 m_lastRootPos; Vector3 m_rootMotion; int m_lastAnimTime; void Start () { //-- 从SkinnedMeshRenderer中读取Root Bone SkinnedMeshRenderer skinMesh = this.gameObject.GetComponentInChildren<SkinnedMeshRenderer>(); m_rootBone = skinMesh.rootBone; //-- 变量初始化 m_rootMotion = Vector3.zero; m_lastRootPos = m_rootBone.localPosition; m_lastAnimTime = 0; } void Update () { //-- Apply Root Motion Vector3 nextPos = this.transform.position + m_rootMotion; this.transform.position = nextPos; //-- 测试代码:更新测试物体的位置 Vector3 flagPos = m_flagObject.position; flagPos.x = nextPos.x; flagPos.z = nextPos.z; m_flagObject.position = flagPos; //-- 测试代码:更新摄像机 Camera.main.transform.LookAt(this.transform); } void LateUpdate() { AnimationState animState = this.animation["walking"]; if ((int)animState.normalizedTime > m_lastAnimTime) { //-- 动画循环处理 m_lastRootPos = m_rootBone.localPosition; m_rootMotion = Vector3.zero; } else { //-- 计算当前帧的Root Motion Vector3 rootPos = m_rootBone.localPosition; m_rootMotion = rootPos - m_lastRootPos; m_lastRootPos = rootPos; rootPos.x = 0; rootPos.z = 0; m_rootMotion.y = 0; m_rootBone.localPosition = rootPos; } m_lastAnimTime = (int)animState.normalizedTime; } }
在Unity3D的Legacy动画系统中应用Root Motion
标签:unity3d 动画 root motion
原文地址:http://blog.csdn.net/neil3d/article/details/41724705