反向动力学

子物体的运动带动父物体的运动

手指向的ik动画

IKanim1.gif

using UnityEngine;
public class IKDemo:MonoBehaviour
{
    private Animator animator;
    public Transform target;

    // 是否开启IK动画
    bool isIK;

    private void Start()
    {
        animator = this.transform.GetComponent<Animator>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            animator.SetBool("cute", true);
            isIK = true;
        }
        else if(Input.GetKeyUp(KeyCode.C))
        {
            animator.SetBool("cute", false);
        }

        AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0);
        // 如果当前的动画片段是Cutepose
        if (info.IsName("Cutepose"))
        {
            isIK = true;
        }else
        {
            isIK = false;
        }

    }
    // 使用这个前,必须将 IK pass勾选上
    // 参数:动画层的下标
    private void OnAnimatorIK(int layerIndex)
    {
        if (isIK)
        {
            // 1. 需要反向动力学部位的权重
            // 值为1,表示IK指向目标位置
            // 值为0,表示IK指向原始位置所指向的位置
            animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);

            // 2. 设置要做方向动力学的位置
            animator.SetIKPosition(AvatarIKGoal.RightHand, target.position);

        }
        else
        {
            animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 0);
        }
    }
}

使用动画曲线优化上面代码

  1. 添加动画参数danceCurve
  2. 添加动画曲线名字danceCurve,必须与动画参数保存一致
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Dance : MonoBehaviour
{
    private Animator anim;
    public Transform target;


    private void Start()
    {
        anim = this.GetComponent<Animator>();
    }

    private void OnAnimatorIK(int layerIndex)
    {
        var isIK = anim.GetFloat("danceCurve");
        if (isIK != 0)
        {
            anim.SetIKPositionWeight(AvatarIKGoal.RightHand, isIK);
            anim.SetIKPosition(AvatarIKGoal.RightHand, target.position);
        }
    }

    private void Update()
    {
        Debug.Log(anim.GetFloat("danceCurve"));
        if (Input.GetKeyDown(KeyCode.D))
        {
            anim.SetBool("dance", true);
        }
        if (Input.GetKeyUp(KeyCode.D))
        {
            anim.SetBool("dance", false);
        }
    }
}