AnimatorController反向运动学IK

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

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

 1 using UnityEngine;
 2 using System.Collections;
 3  
 4 public class IKController : MonoBehaviour 
 5 {
 6     public Transform target;  //IK目标
 7     public bool ikActive;     //IK是否可用
 8     private Animator anim;
 9  
10     void Awake()
11     {
12         anim = GetComponent <Animator> ();
13     }
14  
15     //IK控制要在OnAnimatorIK方法中写!
16     void OnAnimatorIK()
17     {
18         if (ikActive)
19         {
20             //指定要控制的身体部位的IK权重,1为启用,0为不启用。
21             anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1);
22             anim.SetIKRotationWeight(AvatarIKGoal.RightFoot, 1);
23  
24             //设置IK的目标值
25             anim.SetIKPosition(AvatarIKGoal.RightFoot, target.position);
26             anim.SetIKRotation(AvatarIKGoal.RightFoot, target.rotation);
27         }
28     }
29 }

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

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

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

OK,运行游戏,移动色像机,别这样一直看着人家啊,会害羞的^^!
QQ截图20151007210633

原文地址:https://www.cnblogs.com/zhenlong/p/4870990.html