作用:Apply RootMotion让角色动画驱动角色运动,提高了动画的使用效率
这就有两种情况,比如跑步动画
1.当我们的动画是原地跑的时候,这时候使用Apply RootMotion的时候,人物还是在原地跑,就不需要用了,需要代码手动控制人物的移动
以下代码不可运行:
private Vector3 move;
private void CaculateMove()
{
move.Set(playerInput.Move.x, 0, playerInput.Move.y);
move *= Time.deltaTime * moveSpeed;
//相机跟随人物移动的方向
move = renderCamera.TransformDirection(move);
if (move.x != 0 || move.z != 0)
{
move.y = 0;
//旋转速度,根据插值让移动速度影响旋转速度
float turnSpeed = Mathf.Lerp(maxAngleSpeed, minAngleSpeed, moveSpeed / maxMoveSpeed) * Time.deltaTime;
//RotateTowards从人物方向旋转到人物移动方向,最后一个参数为过度时间
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(move), turnSpeed);
}
//跳跃速度
move += Vector3.up * verticalspeed * Time.deltaTime;
Character.Move(move);
isGrouned = Character.isGrounded;
}
//人物在移动时速度的过度在0-5之间,播放动画的切换
private void CaculateForwardSpeed()
{
moveSpeed = Mathf.MoveTowards(moveSpeed, maxMoveSpeed
* playerInput.Move.normalized.magnitude, acceleratedSpeedd * Time.deltaTime);
if(playerInput.Move.x == 0 && playerInput.Move.y == 0)
animator.SetFloat("forwardSpeed", 0.05f);
else
{
animator.SetFloat("forwardSpeed", moveSpeed);
}
}
2.如果是可以一直往前跑的动画时,就可以使用Apply RootMotion使用动画驱动人物移动,
//系统将自动调用OnAnimatorMove
private void OnAnimatorMove()
{
CaculateMove();
}
private void CaculateMove()
{
//动画对于上一帧的偏移
move = animator.deltaPosition;
move += Vector3.up * verticalspeed * Time.deltaTime;
Character.Move(move);
isGrouned = Character.isGrounded;
}
private void CaculateRotation()
{
if (playerInput.Move.x != 0 || playerInput.Move.y != 0)
{
Vector3 targetDirection = renderCamera.TransformDirection
(new Vector3(playerInput.Move.x, 0, playerInput.Move.y));
targetDirection.y = 0;
float turnSpeed = Mathf.Lerp(maxAngleSpeed, minAngleSpeed, moveSpeed / maxMoveSpeed) * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(targetDirection), turnSpeed);
}
}
其实人为控制用 move *= Time.deltaTime * moveSpeed;
动画控制用move = animator.deltaPosition;其它地方都一样
这边文章也可以比较容易理解:
点这里
总结:不开启rootmotion,如果动画本身是一个带位移的动作的话,人物会脱离胶囊体,进而没有碰撞,会产生穿墙的效果,并且动画播完之后,人物会回到胶囊体的位置,不带位移(原地)就不用勾选rootmotion。