Unity3D NavMashAgent不移动 - #代码

问题描述:

我不知道这是一个正确的地方问这个问题。因为这是一个游戏开发相关的问题。我在这里发布这个问题(gamedev.stackexchange.com - https://gamedev.stackexchange.com/questions/109190/navmashagent-not-moving),但仍然没有回应。并在Unity论坛中发帖(http://answers.unity3d.com/questions/1075904/navmashagent-not-moving-in-unity3d-5.html)。任何一个在这里帮助我。Unity3D NavMashAgent不移动 - #代码

生病后在这里我的问题再次

我试着去一个立方体移动到检查点。 FindClosestTarget()方法提供最接近的检查点。当Cube碰到CheckPoint时,ChackPoint将被设置为非活动状态。碰撞发生时FindClosestTarget()再次调用并获取最近的新CheckPoint。事情是立方体不动。它看最近的检查点,但不移动。

using UnityEngine; 
using System.Collections; 

public class EnimyAI03N : MonoBehaviour { 

    NavMeshAgent agent; 
    Transform Target; 
    private float rotationSpeed=15.0f; 

    void Start() { 
     agent = GetComponent<NavMeshAgent>(); 
     Target = FindClosestTarget().transform; 
    } 

    void Update() 
    { 
     LookAt (Target); 
     MoveTo (Target); 

    } 

    // Turn to face the player. 
    void LookAt (Transform T){ 
     // Rotate to look at player. 
     Quaternion rotation= Quaternion.LookRotation(T.position - transform.position); 

     transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime*rotationSpeed); 
     //transform.LookAt(Target); alternate way to track player replaces both lines above. 

    } 

    void MoveTo (Transform T){ 
     agent.SetDestination(T.position); 
    } 

    void OnCollisionEnter (Collision col) 
    { 

     if(col.gameObject.name.Contains("CheckPoint")) 
     { 
      Target = FindClosestTarget().transform; 
     } 
    } 

    GameObject FindClosestTarget() { 
     GameObject[] gos; 
     gos = GameObject.FindGameObjectsWithTag("CheckPoint"); 

     GameObject closest=null; 
     float distance = Mathf.Infinity; 
     Vector3 position = transform.position; 
     foreach (GameObject go in gos) { 
      Vector3 diff = go.transform.position - position; 
      float curDistance = diff.sqrMagnitude; 

      if (curDistance < distance) { 
       closest = go; 
       distance = curDistance; 
      } 
     } 
     return closest; 
    } 

} 
+0

您需要检查并循环通过仅有的检查点! –

+0

通过FindClosestTarget()收集活动检查点自动收集。我使用unity3d 5 –

确保您寻找新的目标之前,通过只是把两条线路在同一地区的SetActive(false);正在发生的事情。

void OnCollisionEnter (Collision col) 
{ 
    if(col.gameObject.name.Contains("CheckPoint")) 
    { 
     col.gameObject.SetActive(false); 
     Target = FindClosestTarget().transform; 
    } 
}