AnimatorController反向运动学IK

时间:2023-03-09 18:40:36
AnimatorController反向运动学IK

通过使用反向运动学IK,我们可以根据需要控制角色身体某个特定部位进行旋转或移动,达到想要的一些效果,比如:在移动时,让一只脚带伤拖行;让手抬起去拿桌上的苹果;让脑袋一直面向我们的色像机,就像一直注视着我们 等等。

先来个模拟受伤的脚吧:
在此之前,请将角色的动画状态机中,应用IK的层勾选IKPass属性:
AnimatorController反向运动学IK
然后,在人物对象下,建立一个空的子物体IKTarget,放在右脚踝靠后的地方。
最后后在人物上添加脚本IKController:

 using UnityEngine;
using System.Collections; public class IKController : MonoBehaviour
{
public Transform target; //IK目标
public bool ikActive; //IK是否可用
private Animator anim; void Awake()
{
anim = GetComponent <Animator> ();
} //IK控制要在OnAnimatorIK方法中写!
void OnAnimatorIK()
{
if (ikActive)
{
//指定要控制的身体部位的IK权重,1为启用,0为不启用。
anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, );
anim.SetIKRotationWeight(AvatarIKGoal.RightFoot, ); //设置IK的目标值
anim.SetIKPosition(AvatarIKGoal.RightFoot, target.position);
anim.SetIKRotation(AvatarIKGoal.RightFoot, target.rotation);
}
}
}

将target设置为我们的刚才建立的空物体IKTarget,运行游戏,让角色移动动画播放起来,可以看到右脚的动画没有播放,而是拖着走的咯。我们可以在scene视图中改变IKTarget的位置和旋转,主角的右脚也会跟着移动,当然这也可以用代码进行控制。

再来个控制人物一直注视色像头的:
将色像机放在角色前面,并在上面脚本添加一点代码:

 anim.SetLookAtWeight();
//眼睛看这里
anim.SetLookAtPosition(GameObject.FindWithTag("MainCamera").transform.position);

OK,运行游戏,移动色像机,别这样一直看着人家啊,会害羞的^^!
AnimatorController反向运动学IK