NavAgent目的地切换

时间:2014-12-16 16:45:52

标签: c# unity3d

我有一个NavAgent应该从一个目标位置随机运行到下一个目标位置。这是我目前的代码。

public Transform target1;
public Transform target2;
NavMeshAgent agent;
Vector3 destinationLoc;

// Use this for initialization
void Start () {
    destinationLoc = target1.position;
    agent = GetComponent<NavMeshAgent> ();
}

// Update is called once per frame
void Update () {
    agent.SetDestination (destinationLoc);
    Debug.Log (agent.remainingDistance);
    if (agent.remainingDistance <= 1.0) {
        Debug.Log ("It gets here.");
        if (Random.Range(1,3) == 1) {
            destinationLoc = target1.position;
            Debug.Log ("Changed to 1.");
        } else {
            destinationLoc = target2.position;
            Debug.Log("Changed to 2");
        }
    }
}

现在它只在两个位置之间切换,但最终会更多。关于为什么这段代码不起作用的任何想法?

1 个答案:

答案 0 :(得分:1)

我认为你可能在设定目的地方面做得太过分了。我会在Start()中设置一次,并且只在它到达目的地后再次设置它。至于Random.Range(1,3),可能是完全巧合。您将获得3种可能性的整数,并返回1.尝试输入var,显示日志并从那里进行调整。尝试将范围扩展到30(用于测试)

void Start () {
    destinationLoc = target1.position;
    agent = GetComponent<NavMeshAgent> ();
    agent.SetDestination (destinationLoc);
}

// Update is called once per frame
void Update () {
    Debug.Log (agent.remainingDistance);
    if (agent.remainingDistance <= 1.0) {
        Debug.Log ("It gets here.");
        int rr = Random.Range(1,30);
        Debug.Log( "Random value: " + rr );

        if (rr == 1) {
            destinationLoc = target1.position;
            Debug.Log ("Changed to 1.");
        } else {
            destinationLoc = target2.position;
            Debug.Log("Changed to 2");
        }

        // Set destination AFTER it has been changed
        agent.SetDestination (destinationLoc);

    }
}

此外,您可以通过访问

的姐妹网站获得更好,更快的响应

https://gamedev.stackexchange.com/