P2L1——路点和寻路
塔防游戏的敌人需要沿着固定的路线行走,因此敌人需要沿着路点进行寻路
在场景上设置一些路点,敌人会主动向路点直线移动,走到路点后就转向另一个路点移动,直到遍历所有路点
例如下面的场景,Cube需要沿着这几个路点依次进行移动:
这里的实现思路是:
- 所有的路点被一个父对象管理,路点父对象挂载一个获取节点位置和节点数量的脚本
Path 
- Cube挂载寻路脚本
PathFind,寻路脚本和路点父对象的Path关联,
通过得到的路点位置移动,到达点就切换到下一个路点,直至遍历所有路点 
Path.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
   | using System.Collections.Generic; using UnityEngine;
 
  public class Path : MonoBehaviour {          List<Transform> nodeList = new List<Transform>();
      void Start()     {                  foreach (Transform node in transform)         {             nodeList.Add(node);         }     }
           public Vector3 GetNodePos(int i)     {         return nodeList[i].position;     }
           public int GetMaxNodeNum()     {         return nodeList.Count;     } }
   | 
 
PathFind.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   | using UnityEngine;
  public class PathFind : MonoBehaviour {     public Path path;                         public int curPathNodeIndex = 0;    
      void Update()     {                  if (curPathNodeIndex >= path.GetMaxNodeNum())         {             print("到达终点");             return;         }                  Vector3 curNodePos = path.GetNodePos(curPathNodeIndex);         float dis = Vector3.Distance(curNodePos, transform.position);                  if (dis < 0.1f)             curPathNodeIndex++;                  Vector3 dir = (curNodePos - transform.position).normalized;                  transform.position += dir * 6 * Time.deltaTime;     } }
   |