[unity learning] RPG Leaning(三)
写这个文章的目的就是为了初学unity,然后更好的掌握unity中的内容【主要是代码】
学习unity的途径是 Sebastian Lague 的教程;
接上篇: unity learning RPG Leaning(二).
最终目标
这次的目标就是把人物导入场景,并且把动作导入到场景中。[啊啊啊啊给的文档里面没有人物的动作,就只能自己想办法去网上找动作和模型。。]
人物绑定动作、骨架
由于教程给的那个文件里面没有人物的动作,所以不能实现下面的过程,所以我就去网上自己下了。
动作网站: mixamo.
在这个网站中选择一个模型,选择下载三个动作[ idle\ walk\ run ] 其中一个下载带skin,其余两个都可以不带skin。
然后直接拖入unity文件中,
然后分别进行设置:
主模型:
rig的设置:
选择type为人形,Avatar 设置为从此模型中来创建,点击Apply之后,点击Configure;
这里出现Avatar的设置,把pose选择一个合适的即可,Apply -> Done
在Animation中勾选Loop Time 以及设置下面的Motion 中的Root Motion Root 为 < Root transform >
动作的设置:
和主模型 在rig中的设置有差异,在Animation中的设置一样。
Avatar Definition 中设置为从其他的Avatar中拷贝过来,然后Source就设置为主模型的Avatar即可
Animation Controller
新建一个Animation Controller,在Animator界面新建一个From New Blend Tree。
进入这个节点
加入刚刚设置完的三个动画
在Parameters中把旁边的参数名字改了,上图的Parameter中的名字会对应改;但是你改上面的Parameter,下图的Parameters中的参数不会变化。所以要改这里。
这里的目的就是随着speedPercent的变化,动作也会相应变化
导入到scene中
需要设置的就是Controller ,把我们刚刚写的Animation Controller给他
设置Script,把speedPercent这个参数给Animation Controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PlayerAnimation : MonoBehaviour {
Animator animator;
NavMeshAgent agent;
// Start is called before the first frame update
const float localAnimationSmoothTime = 0.1f;
void Start () {
animator = GetComponentInChildren<Animator> ();
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update () {
float speedPercent = agent.velocity.magnitude / agent.speed;
animator.SetFloat ("speedPercent", speedPercent, localAnimationSmoothTime, Time.deltaTime);
}
}
总结
搞了一个下午的动作绑定,因为记得原来在实习的公司看到过这个网站,所以找了很久。网上关于动作 乱七八糟的网站太多了。。。
关于代码的理解的话,还是理解下面两句话就够了。
一个是计算参数,一个是传递参数。。
float speedPercent = agent.velocity.magnitude / agent.speed;
animator.SetFloat ("speedPercent", speedPercent, localAnimationSmoothTime, Time.deltaTime);