Ik反向动力学

一般我们都是通过父节点来调动子节点运动,而在实际开发过程中,有时候我们需要子节点带动父节点进行相应的动作。这种情况就是反向动力学。其实在国内的游戏中很少看见IK动画,一般而言国外的游戏较多。例如刺客信条,手部带动身体的爬行。
通俗讲:使用场景中的各种物体来控制和影响角色身体部位的运动

案例

首先我们先打开IK并设置权重为1


Ik反向动力学_第1张图片
Paste_Image.png

然后我们创建一个 Avatar Mask设置其固定骨骼


Ik反向动力学_第2张图片
Paste_Image.png
随后我们创建脚本Iktext 并写入一下代码,
public class Iktext : MonoBehaviour
{
    public Animator ani;
    public Transform sphere;
    private GameObject shoulei;//游戏对象
    public Transform shou;//手的位置
    private Rigidbody body;
    private float speed;//速度

    public Transform cube;
    
    void Start ()
    {
        speed = 500;
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.W))
        {
            sphere.transform.Translate(new Vector3(0, 0,0.1f));
        }
        if (Input.GetKey(KeyCode.S))
        {
            sphere.transform.Translate(new Vector3(0, 0, -0.1f));
        }
        if (Input.GetKey(KeyCode.A))
        {
            sphere.transform.Translate(new Vector3(-0.1f, 0, 0));
        }
        if (Input.GetKey(KeyCode.D))
        {
            sphere.transform.Translate(new Vector3(0.1f, 0, 0));
        }
        if (Input.GetKey(KeyCode.J))
        {
            sphere.transform.Translate(new Vector3(0, 0.1f, 0));
        }
        if (Input.GetKey(KeyCode.N))
        {
            sphere.transform.Translate(new Vector3(0, -0.1f, 0));
        }
        if (Input.GetKeyDown( KeyCode.Space))
        {
            ani.Play("Throw 0");
        }
    }
    void OnAnimatorIK(int layerIndex)//IK反向动力学
    {
        ani.SetLookAtWeight(1,1,1,1);//设置头部,身体,手,脚都跟着游戏对象动
        if (sphere)
        {
            ani.SetLookAtPosition(sphere.position);//看向Ik视觉的位置
        }
        if (cube)
        {
            ani.SetIKPositionWeight(AvatarIKGoal.LeftFoot, 1);//设置IK(反向)位置的权重(设置左脚,设置权重为1)
            ani.SetIKRotationWeight(AvatarIKGoal.RightHand, 1);//设置IK(反向)旋转的权重(设置左手,设置权重为1)

            ani.SetIKPosition(AvatarIKGoal.LeftFoot, cube.transform.position);//设置IK (反向)位置(设置左脚位置,按照Cube的位置来设置动画人物的左脚的位置)
            ani.SetIKRotation(AvatarIKGoal.RightHand, cube.transform.rotation);//设置IK (反向)旋转(旋转左手,按照Cube的旋转来设置动画人物的左手旋转)
        }
    }
    void NewEvent()//动画事件系统
    {
       shoulei= GameObject.CreatePrimitive(PrimitiveType.Sphere);
        shoulei.AddComponent();
        shoulei.transform.localScale=new Vector3(0.1f,0.1f,0.1f);
        shoulei.AddComponent();
        shoulei.transform.position = shou.position;
        body=shoulei.GetComponent();
        body.AddForce((sphere.transform.position-shou.transform.position)*Time.deltaTime*speed,ForceMode.Impulse);  
}
  
}

随后我们给其赋值

Ik反向动力学_第3张图片
Paste_Image.png
我们在将投球的状态机做好让我们给其赋动画的值和骨骼。这样我们大概就完成了 运行看看效果吧
IK反向动力效果
IK.gif

事件系统效果
SJ.gif

你可能感兴趣的:(Ik反向动力学)