我有一个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");
}
}
}现在,它只在两个位置之间切换,但最终会更多。对于为什么这段代码不起作用有什么想法吗?
发布于 2014-12-16 18:22:50
我想你在设定目的地方面可能做得太过分了。我将在Start()中设置一次,并且只在它到达目的地后再设置一次。至于Random.Range(1,3),可能是完全巧合。您将得到一个包含3种可能性的整数,它将返回1。尝试放入一个变量,显示日志并从那里进行调整。尝试将测试范围扩大到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://stackoverflow.com/questions/27509676
复制相似问题