目标:实现绿色、红色、蓝色小球分别走绿色道路、红色道路、蓝色道路到达End
1.搭建对应的场景,给三条路分别加上不同颜色的材质,创建三个小球,并给它们加上对应不同道路颜色的材质,将小球拖入Resources文件夹中(自己创建该文件夹,名字要与这里一样),其中Start、End是两个空物体,分别放在路得两端,是小球诞生的起点,以及小球需要到达的终点
2.选中需要烘焙的物体,勾选Navigation Static,然后打开Navigation面板(菜单栏Window——AI——Navigation)
3.在Navigation面板的Areas中新加green、red、blue区域
4.选中不同颜色道路的物体,在Navigation的Object下修改Navigation Area属性为对应的Area(如下图,选中蓝色道路将Navigation Area改为blue),对其它颜色的道路全部进行相同的操作(这里就不赘述了)
5.选中需要烘焙的物体,点击Bake按钮进行烘焙(下图是已经烘焙好的)
6.为三种颜色的小球都添加Nav Mesh Agent组件,并修改不同颜色小球Nav Mesh Agent组件的Area Mask属性,即对蓝色小球勾选Walkable、blue,对绿色小球勾选勾选Walkable、green,对红色小球勾选Walkable、red
7.将下面的脚本挂载到三种小球身上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyDestroy : MonoBehaviour
{
// Start is called before the first frameupdate
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Vector3.Distance(GameObject.Find("End").transform.position,transform.position)< 1f)
{
Destroy(this.gameObject);
}
}
}
8.选中三种颜色小球,点击Overrides下拉菜单中的Apply按钮,将对小球的操作应用到Resources中的小球上(因为我们是自动生成小球,然后自动寻路),下图是已经点击过Apply按钮
9.将下面的脚本挂载到场景中激活物体的身上(比如Main Camera),并将Start、End拖入脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AIRoad : MonoBehaviour
{
//起点
public Transform start;
//终点
public Transform end;
float t = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//时间的叠加
t+=Time.deltaTime;
if(t> 0.8)
{
//随机获取并生成Resources文件夹中的三种小球之一
GameObject obj= Instantiate(Resources.Load("Sphere" + Random.Range(1, 4))) as GameObject;
obj.transform.position = start.position;
//使生成的小球自动寻找end终点
obj.GetComponent<NavMeshAgent>().SetDestination(end.position);
t = 0;
}
}
}
最后运行unity,可以看到不同颜色的小球,沿着自己颜色的道路走向终点
结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。