首页 > 技术文章 > 导航系统(二)

LiuChangwei 2017-04-16 16:15 原文

一、导航系统部分Bake属性的效果

1)Agent Radius: 新建一个平面Plane,应用Static属性(可以在Inspector检视图勾选也可以在Navigation导航窗口中勾选“Navigation Static”选项)。设置Bake属性中“Agent Radius”为0.3,烘焙如图:

2)Drop Height:新建一个Cube,应用Static属性。在Navigation中勾选“Generate OffMeshLinks”,在Bake属性中设置“Drop Height”为2.5。烘焙代理跳下平面的导航链接;如下图

3)Step Height:新建阶梯,阶梯的高度为0.2。在Bake属性中设置“Step Height”为0.2。效果如下:

4)Jump Distance: 桥距离

5)Agent Height: 代理高度

6)Height Mesh:勾选Advanced之下的Height Mesh,然后烘焙。使代理贴着平面走。如下

二、代码控制导航代理

1、点击鼠标控制代理运动

using UnityEngine;
using UnityEngine.AI;//引用AI系统

public class AI : MonoBehaviour
{
    public Camera cam;
    NavMeshAgent agent;
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))//如果按下鼠标左键
        {
            Vector3 ms = Input.mousePosition;//获取鼠标的位置
            Ray ray = cam.ScreenPointToRay(ms);//将屏幕位置转换为射线
            RaycastHit hit;//声明变量记录射线碰撞信息。这个为射线命中的点
            if (Physics.Raycast(ray, out hit, 100f))//物理静态类中的光线投射方法。(射线投射到命中点,射线长度为100f)
            {
                agent.SetDestination(hit.point); //把目的地,终点赋给agent,即导航代理                     
            }
        }
    }
}

2、同时应用NavMeshObstacle(障碍物)和NavMeshAgent(导航代理),让代理围着某一点停下

using UnityEngine;
using UnityEngine.AI;//引用AI系统

public class AI : MonoBehaviour
{
    public Camera cam;
    NavMeshAgent agent;
    NavMeshObstacle obstacle;
    void Start()
    {
        //获取组件
        agent = GetComponent<NavMeshAgent>();
        obstacle = GetComponent<NavMeshObstacle>();
        obstacle.enabled = false;
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))//如果按下鼠标左键
        {
            Vector3 ms = Input.mousePosition;//获取鼠标的位置
            Ray ray = cam.ScreenPointToRay(ms);//将屏幕位置转换为射线
            RaycastHit hit;//声明变量记录射线碰撞信息。这个为射线命中的点
            if (Physics.Raycast(ray, out hit))//物理静态类中的光线投射方法
            {
                agent.enabled = true;//enabled激活的
                obstacle.enabled = false;
                agent.SetDestination(hit.point); //把目的地,终点赋给agent,即导航代理                     
            }
        }
        if (agent.enabled && agent.remainingDistance < 2.5 && agent.remainingDistance > 0.5)//enabled(激活的);remainingDistance(剩余距离)
        {
            //agent.Stop();
            agent.enabled = false;
            obstacle.enabled = true;
        }
    }
}

 

推荐阅读