Question by
Shrimpy101 · Oct 11, 2021 at 12:35 PM ·
navmeshnavmeshagent
need help with navmesh ai ,Need help with navmesh ai
so im new with making stuff with navmesh and im trying to get my bunny to find the closest apple then find the next after eating it but im a bit stumped might need a new perspective.
public class FindFood : MonoBehaviour { public Transform Apples; public UnityEngine.AI.NavMeshAgent agent;
public void Update()
{
Apples = transform.Find("Apple");
ChooseTarget();
}
public void ChooseTarget()
{
float closestTargetDistance = float.MaxValue;
UnityEngine.AI.NavMeshPath path = null;
UnityEngine.AI.NavMeshPath Shortestpath = null;
for (int i = 0; i < Apples.Length; i++)
{
if (Apples[i] == null)
{
continue;
}
path = new UnityEngine.AI.NavMeshPath();
if (UnityEngine.AI.NavMesh.CalculatePath(transform.position, Apples[i].position, agent.areaMask, path))
{
float distance = Vector3.Distance(transform.position, path.corners[0]);
for (int j = 1; j < path.corners.Length; j++)
{
distance += Vector3.Distance(path.corners[j - 1], path.corners[j]);
}
if (distance < closestTargetDistance)
{
closestTargetDistance = distance;
Shortestpath = path;
}
}
}
if (Shortestpath != null)
{
agent.SetPath(Shortestpath);
}
}
}
Comment