来自于:吴雨葵
    Unity OnAnimatorIK提供了简单IK的实现方式。
    准备:
    Model的Animation Type设置为Humanoid。
    检测Avatar是否有异常。
    Animator勾选IK Pass。
    准备好之后,挂载的MonoBehaviour的OnAnimatorIK才会被回调。
    代码:

    1. public class IKTest : MonoBehaviour
    2. {
    3. [Range(0, 1)]
    4. // IK权重
    5. public float weight = 1;
    6. // IK跟随的物体
    7. public Transform rightHandFollowObj;
    8. public Transform leftHandFollowObj;
    9. protected Animator animator;
    10. private void Start()
    11. {
    12. animator = GetComponent<Animator>();
    13. }
    14. private void OnAnimatorIK(int layerIndex)
    15. {
    16. if (animator)
    17. {
    18. // 设置Position和Rotation权重
    19. animator.SetIKPositionWeight(AvatarIKGoal.RightHand, weight);
    20. animator.SetIKRotationWeight(AvatarIKGoal.RightHand, weight);
    21. animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, weight);
    22. animator.SetIKRotationWeight(AvatarIKGoal.LeftHand, weight);
    23. // 改变Position和Rotation
    24. if (rightHandFollowObj != null)
    25. {
    26. animator.SetIKPosition(AvatarIKGoal.RightHand, rightHandFollowObj.position);
    27. animator.SetIKRotation(AvatarIKGoal.RightHand, rightHandFollowObj.rotation);
    28. }
    29. if (leftHandFollowObj != null)
    30. {
    31. animator.SetIKPosition(AvatarIKGoal.LeftHand, leftHandFollowObj.position);
    32. animator.SetIKRotation(AvatarIKGoal.LeftHand, leftHandFollowObj.rotation);
    33. }
    34. }
    35. }
    36. }

    Unity - 简单的IK实现-OnAnimatorIK - 图1