AI 在跟随航路点 UNITY 时面临奇怪的方向

AI faces Weird Direction when following a waypoint UNITY

我的问题是,每当它试图向当前航路点移动时,它都会面对奇怪的方向并且没有完全遵循路径。

IEnumerator FollowPath() {
    Vector3 currentWaypoint = path[0];

    while (true) {
        //transform.LookAt (currentWaypoint);
        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.LookAt (currentWaypoint);
        transform.position = Vector3.MoveTowards(transform.position,currentWaypoint,speed * Time.deltaTime);

        yield return null;
    }
}  

目前正在使用*寻路。完整的源代码可在此处找到:https://github.com/SebLague/Pathfinding

到达当前航点后,随机改变方向或随机朝向,不经过下一个航点。 (Screenshot)

在代码的这一部分,targetIndex 将始终计算为 1

targetIndex=0;
targetIndex ++;

所以基本上,它永远不会超过第一个航路点。

此外,我会推荐,而不是

if (transform.position == currentWaypoint)

你会这样做:

float threshold = 0.1f;                // Adjust to your preference
if ((currentWaypoint - transform.position).sqrMagnitude < threshold)

这是因为我认为 MoveTowards 可能会过冲或无法准确到达目标矢量,并且在将鼠标悬停在目标矢量上时会转向并大幅改变方向。