I have a 3D model of a house, and I want an autonomous robot to move from 1 object in this house to the next one. I have it moving to the first, but it won't move to the second one. This is my code:
using UnityEngine;
using System.Collections;
public class MoveTo : MonoBehaviour {
public Transform[] goals;
void Start () {
NavMeshAgent agent = GetComponent ();
agent.destination = goals[0].position;
if (agent.transform.position == goals[0].position) {
agent.destination = goals[1].position;
}
}
}
I'm a complete beginner in code, please keep that in mind :)
Answer
The Start
method is only executed once at start and the NavmeshAgent won't start moving the object before the Start
method finished. The moving happens between calls to Update
.
So check if you reached the destination in your Update
method, not your Start
method.
I would also recommend you to use agent.remainingDistance
to check if the destination is reached. Comparing positions for equality is quite error-prone because even though the == operator for Vector3 is overloaded for returning true even when the positions are just almost identical, Unity's definition of close enough might be different than yours. If you want to compare positions, at least do it by checking if their distance is smaller than what you would consider close enough for "being there".
No comments:
Post a Comment