How to get the closest object in the navMesh and making the agent move towards it
At the moment I have a semi-dynamic layout where my agent follows the randomized waypoints and after he reaches one, he deletes said waypoint. However, I want him to scan the closest waypoint to the object. Taking into account vector3.distance goes over obstacles, what are the other solutions.
public NavMeshAgent agent;
public GameObject[] waypoints // Waypoints
public Transform[] locations // Waypoint location
for (int x = 0; x < waypoints.Length; x++) // Sets random position
{
if (x < 5)
{
waypoints[x].transform.position = new Vector3(Random.Range(-33.0f, 30.0f), 3.575465f, Random.Range(30.0f, -35.0f));
}
for (int z = 0; z < waypoints.Length; z++)
{
if (z < 5 && waypoints[z] != null)
{
agent.SetDestination(locations[z].position);
}
}
}
Answer by tormentoarmagedoom · May 08, 2018 at 11:17 AM
Good day.
How many waypoint there are in the map?
You can create a script for each waypoint, that is calculating the distance between itself and the player with
float DistanceToPlayer = Vector3.Distance(transform.position , player.transform.position);
And then in the player have 2 stored variables, a float for distance called "DistanceToWaypoint" and gameobject for waypoint called "Waypoint", so the waypoints can do this
if (DistanceToPlayer < Player.DistanceToWaypoint)
{
Player.DistanceToWaypoint= DistanceToPlayer
Player.Waypoint = gameObject;
}
So Player will ahve always stored the nearest waypoint in the "Waypoint" variable!
If helped, accept the answer!
Bye!!
I have obstacles in my scene, anyway to measure distance through the navmesh? To answer your question, i have 5 waypoints.
Your answer
Follow this Question
Related Questions
Creating prefab through Zenject Factory makes navMeshAgent act strange 0 Answers
how can I implement navmesh in this script? 0 Answers
NavMeshAgent dont find the right way on runtime build NavMesh 0 Answers
Navmesh Agent - The Y Next Position & Y Velocity does not update if there is no X velocity. 0 Answers
Question about NavMesh and Rigidbody 0 Answers