我已经“解决”了这个问题,现在有了一个足够好的解决方案。
首先,我通过在每个航路点请求一条新路径,使寻路变得动态。其次,即使在到达目标后,路径查找仍在继续,通过一些逻辑,检查每一帧单元是否足够远,以重复协同程序。如果是,则停止旧的协同程序并启动新的协同程序。
下面是代码:
using UnityEngine;
using System.Collections;
public class Unit : MonoBehaviour {
public Transform target;
float speed = 20;
Vector3[] path;
int targetIndex;
bool newRequestReady;
void Start() {
PathRequestManager.RequestPath(transform.position,target.position, OnPathFound);
newRequestReady = false;
}
void Update(){
float distance = Vector3.Distance (transform.position, target.position);
Debug.Log(distance);
if(distance < 5){
StopCoroutine("FollowPath");
newRequestReady = true;
}
else if(distance >=10 && newRequestReady){
PathRequestManager.RequestPath(transform.position,target.position, OnPathFound);
StopCoroutine("FollowPath");
newRequestReady = false;
}
}
public void OnPathFound(Vector3[] newPath, bool pathSuccessful) {
if (pathSuccessful) {
path = newPath;
StopCoroutine("FollowPath");
StartCoroutine("FollowPath");
}
}
IEnumerator FollowPath() {
Vector3 currentWaypoint = path[0];
while (true) {
if (transform.position == currentWaypoint) {
PathRequestManager.RequestPath(transform.position,target.position,OnPathFound);
targetIndex=0;
targetIndex ++;
//Debug.Log(currentWaypoint);
if (targetIndex >= path.Length) {
targetIndex =0;
path = new Vector3[0];
//yield break;
}
currentWaypoint = path[targetIndex];
}
transform.position = Vector3.MoveTowards(transform.position,currentWaypoint,speed * Time.deltaTime);
yield return null;
}
}
}