本期讲自动寻路,unity有一个强大的引擎和组件NavMeshAgent这个主键,着可以让你用几行代码解决人物的制动寻路功能
想要完成自动寻路,首先你得添加这个主键,选中地形设置成静态的
然后给地形烘焙一下
然后选择Bake,在里面选择bake使用
接下来是代码段,注意这里需要引入AI的命名空间 using UnityEngine.AI;
public class Animators : MonoBehaviour {
private Animator an;
private NavMeshAgent agent; //动态加载这个组件
// Use this for initialization
void Start () {
an=GetComponent<Animator>();//使用这个组件
agent=GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
Move();
}
void Move()
{
if(Input.GetMouseButton(0))//点击鼠标左键生成一条射线
{
an.SetBool("Walk", true);//播放动画
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit))
{
agent.SetDestination(hit.point);//判断鼠标点击的位置,人物制动寻路到这个地方
}
}
if(agent.remainingDistance < 0.5f)
{
an.SetBool("Walk", false);//播放动画
}
}
}
这个自动寻路还可以绕开障碍物,需要给障碍物添加这个组件