寻路在游戏开发中的重要性,不用多说了。从大型ARPG游戏到小规模体验游戏,都会不同程度的用到寻路功能。
塔防类游戏,战棋类游戏经常用到waypoint(路径)寻路。
下面我们来介绍一下waypoint寻路。
1.Path(路径)的设计。
图中每一个蓝色的Cube表示一个路径点(WayPoint),由7个waypoint构成path;
Path.cs代码如下:
using UnityEngine; using System.Collections; public class Path : MonoBehaviour { public WayPoint[] wayPoints; public ArrayList points; //存储wayPoints的transform.position属性 // Use this for initialization void Awake() { //print("path"); points = new ArrayList(); for (int i = 0; i < wayPoints.Length; i++) { points.Add(wayPoints[i].transform.position); } } //判断是否有下一个路径点 public bool HasNextPoint() { //points实例化过,并且存在N个路径点 if (points!=null && points.Count>0) { return true; } return false; } public Vector3 GetNextPoint() { if (points!=null && points.Count>0) { Vector3 p=(Vector3)points[0]; points.RemoveAt(0); return p; } return Vector3.zero; } }
为需要移动的物体或者人物创建WayPointAI
WayPointAI代码如下
using UnityEngine; using System.Collections; public class WayPointAI : MonoBehaviour { public Path path; private Vector3 pos; private float rotateSpeed = 10f; private float moveSpeed = 5f; // Use this for initialization void Start() { if (path!=null && path.HasNextPoint()) { pos = path.GetNextPoint(); } } // Update is called once per frame void Update() { bool reached = MoveToTarget(pos); if (reached==true && path!=null && path.HasNextPoint()) { pos = path.GetNextPoint(); } } bool MoveToTarget(Vector3 point) { //只在XZ平面上移动,消除鼠标点击对Y轴的偏移,保持transform.y Vector3 pointR = new Vector3(point.x, transform.position.y, point.z); //Quaternion插值 物体朝向目标点平缓转向 Quaternion wantedRot = Quaternion.LookRotation(pointR - transform.position); transform.rotation = Quaternion.Lerp(transform.rotation, wantedRot, rotateSpeed * Time.deltaTime); //使用插值当物体到达目标点以后,会有抖动现象,在point处消除抖动 float distance = Vector3.Distance(pointR, transform.position); if (distance < 0.05f) { return true; //到达point } //向目标点移动 Vector3 direction = (pointR - transform.position).normalized; transform.Translate(direction * moveSpeed * Time.deltaTime, Space.World); return false; } }