1.导航网格(即 Navigation Mesh,缩写为 NavMesh)是一种地形数据。该数据结构是从关卡几何体自动构建或烘焙的。
2.导航网格代理 (NavMesh Agent)组件,可帮助您创建在朝目标移动时能够彼此避开的角色。
3.网格外链接 (Off-Mesh Link)组件,无法使用可行走表面来表示的导航捷径。例如,跳过沟渠或围栏,传送点等。
4.导航网格障碍物(NavMesh Obstacle)组件,可用于描述导航时应避开的移动障碍物。
NavMesh Agent
设定物体的自动寻路区域:
如图:设定Cube为物体Not Walkable(不可通过)区域
设定Floor为物体Walkable(可通过)区域
通过代码---->控制鼠标点击---->物体移动
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using UnityEngine;
using UnityEngine.AI;
/// <summary>
///
/// </summary>
public class PlayerController : MonoBehaviour
{
public NavMeshAgent agent;
public GameObject go;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
if(Input.GetMouseButtonDown(1))
{
Ray movePosition = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(movePosition,out var hitInfo))
{
agent.SetDestination(hitInfo.point);
}
}
if(Input.GetKeyUp(KeyCode.Space))
{
agent.isStopped = true;
}
if(Input.GetKeyUp(KeyCode.X))
{
go.SetActive(false);
}
if(Input.GetKeyUp(KeyCode.Z))
{
go.SetActive(true);
}
}
}
烘焙
1.Agent Radius代理半径
决定了烘焙边缘精确度
控制平台可行走区域和边缘可行走区域
2.Agent Height代理高度
决定了烘焙高度精确度
控制拱桥是否可以穿越
3.Max Slope
最大坡度
斜坡度数
决定了斜坡是否可以行走
4.Step Height
最小楼梯高度
决定了台阶是否可以行走
5.Generated off mesh Links
生成非网格连接
两个分开的网格之间连接相关设置
6.Drop Height
掉落高度
可以从这个高度掉下来
7.Jump Distance跳跃距离
决定不同平面上的跳跃距离
组件
Off Mesh Link(传送门----->起点和终点)
Cost Override 如果值为正,则在计算处理路径请求的路径成本时使用该值。否则,使用默认成本(此游戏对象所属区域的成本)。如果Cost Override设置为值3.0,则在网格外链接上移动的成本将是在默认导航网格 。如果希望让代理通常优先选择步行,但当步行距离明显更长时使用网格外链接,则Cost Override设置将变得有用。
控制移动遮挡
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using static TMPro.SpriteAssetUtilities.TexturePacker_JsonArray;
using static UnityEditor.PlayerSettings;
/// <summary>
///
/// </summary>
public class Move : MonoBehaviour
{
public float speed = 1f;
public bool isAdd = false;
public float leftX = -3;
public float rightX = 3;
void Start()
{
}
//Update is called once per frame
void Update()
{
var offset = Time.deltaTime * speed;
var pos = this.transform.position;
var newX = pos.x + offset * (isAdd ? 1 : -1);
if (newX > rightX)
{
isAdd = false;
newX = rightX;
}else if (newX<leftX)
{
isAdd = true;
newX = leftX;
}
this.transform.position = new Vector3(newX,pos.y, pos.z);
}
}
敌人追踪
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
/// <summary>
///
/// </summary>
public class NewBehaviourScript : MonoBehaviour
{
private NavMeshAgent agent;
public GameObject target;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
agent.SetDestination(target.transform.position);
}
}