unity---寻路导航
寻路导航
1. 简单的寻路
- 
先搭建出类似下面的结构
 - 
将你想作为障碍的物体放入一个空物体中
 - 
进入空物体点击Static,仅勾选 Navigation Static 即可
 - 
依次点击 Window->AI->Navigation,出现如下面板
 - 
默认设置,点击烘培bake
 - 
蓝色区域为可以通行的区域
 - 
红色物体挂载以下组件
 - 
再挂载如下脚本
 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Nev0906 : MonoBehaviour
{//鼠标点击某处,物体自动前往鼠标指定地点
    // Start is called before the first frame update
    public NavMeshAgent nma;
    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButton(0)){
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit[] hits =Physics.RaycastAll(ray);
            foreach(var hit in hits){
                string name  = hit.collider.gameObject.name;
                    nma.SetDestination(hit.point);
            }
        }
    }
}
或者是这个简单脚本,自动前往目标物体
大致步骤
坡度烘培
关键在于角度的设置
选路
木头物体走木质桥,另一个物体走另一个桥
- 先搭建相应场景,并且进行简单路径的一些操作
 - 给两个桥取一下名字
 - 在这个区域写下相应名字
 - 在物体组件这选择他能够行走的区域
 - 选择桥的Navigation Area(不选的话默认为Walkable)
 
即可分路径行走
小小补充
选择两个物体然后,勾选Generate OffMeshLinks 自动链接
添加障碍物组件,设置一定的高度后,物体就无法走过
脚本控制一下障碍物
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ObstateTest : MonoBehaviour
{
    // Start is called before the first frame update
    NavMeshObstacle _obstacle;
    void Start()
    {
        _obstacle=this.GetComponent();
    }
    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0)){
            _obstacle.enabled=false;
            this.gameObject.GetComponent().material.color=Color.green;
        }
        if(Input.GetMouseButtonUp(0)){
            _obstacle.enabled=true;
            this.gameObject.GetComponent().material.color=Color.blue;
        }
    }
}