2017-01-25 23 views
2

我的問題是,無論何時它試圖朝着當前的航點移動,它都會面臨奇怪的方向,並且完全不遵循路徑。AI在遇到航點時面臨奇怪的方向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)

回答

1

在這部分的代碼,targetIndex將始終評估爲1

targetIndex=0; 
targetIndex ++; 

所以基本上,它永遠不會走得更遠比第一航點。

此外,我會建議,而不是

if (transform.position == currentWaypoint) 

你可以這樣做,而不是:

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

這是因爲我覺得MoveTowards都不可能過沖或沒有完全達到目標向量和意志當鼠標懸停在目標矢量上時,可以大幅改變方向。

+0

我忘了告訴它,當沒有方向,或者位置是靜態時,它會轉到另一個路點。但是當我向他所看到的方向添加方向時,它會面臨奇怪的方向約10秒,然後轉到下一個航點或有時不會轉到下一個航點,因爲他正在查看該當前點。 –

+0

擺脫'targetIndex = 0;' – maksymiuk

+0

我嘗試了你的建議,但它在到達航點後仍然面臨奇怪的方向。雖然我不知何故得到了錯誤來自哪裏。它來自動畫和這行代碼「transform.LookAt(currentWaypoint);」。我曾嘗試刪除動畫,並以某種方式進入下一個航點。我怎樣才能解決這個問題?該動畫僅具有靜態運行。所以它沒有空閒或任何東西,只有運行動畫。 –