Microgame代码解析——自动寻路
作者:互联网
1. NavMesh Surface
- 得先添加Navmesh的组件,应该是在包管理器导入。
- 创建一个空物体,添加脚本Nav Mesh Surface。
- Bake即可获得区域。
- 设置如下图:
2. 在目标上挂上NavMeshAgent
3. 设置路径
- 设置了三个点当做范围,目标会依次到达这三个点。
- 都是空物体。
4. PatrolPath.cs
- 可以把enemy的List改成gameObject。
using System.Collections.Generic;
using UnityEngine;
namespace Unity.FPS.AI
{
public class PatrolPath : MonoBehaviour
{
[Tooltip("Enemies that will be assigned to this path on Start")]
public List<EnemyController> EnemiesToAssign = new List<EnemyController>();
[Tooltip("The Nodes making up the path")]
public List<Transform> PathNodes = new List<Transform>();
void Start()
{
foreach (var enemy in EnemiesToAssign)
{
enemy.PatrolPath = this;
}
}
public float GetDistanceToNode(Vector3 origin, int destinationNodeIndex)
{
if (destinationNodeIndex < 0 || destinationNodeIndex >= PathNodes.Count ||
PathNodes[destinationNodeIndex] == null)
{
return -1f;
}
return (PathNodes[destinationNodeIndex].position - origin).magnitude;
}
public Vector3 GetPositionOfPathNode(int nodeIndex)
{
if (nodeIndex < 0 || nodeIndex >= PathNodes.Count || PathNodes[nodeIndex] == null)
{
return Vector3.zero;
}
return PathNodes[nodeIndex].position;
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.cyan;
for (int i = 0; i < PathNodes.Count; i++)
{
int nextIndex = i + 1;
if (nextIndex >= PathNodes.Count)
{
nextIndex -= PathNodes.Count;
}
Gizmos.DrawLine(PathNodes[i].position, PathNodes[nextIndex].position);
Gizmos.DrawSphere(PathNodes[i].position, 0.1f);
}
}
}
}
标签:Count,nodeIndex,解析,List,PathNodes,position,Microgame,寻路,public 来源: https://blog.csdn.net/weixin_39801219/article/details/116721114