- Home /
Question by
putlucky · May 09, 2017 at 06:11 AM ·
c#updatenavmeshagentgroup
Ensuring a group of navmesh agents stay put.
Hi, so I want a group of navmesh agents to move toward a target location and within a few units to STOP. The group is controlled in formation by a leader, which has the below script attached to it. If the target moves away, I want them to follow.
Right now I have them moving to the target location, getting there and swarming all around to try and reach the target location, despite my efforts to prevent this.
Here is my code:
void Update()
{
//Need to see if units are being destroyed.
groupStrength = group.Count;
//If distance between you and the nearest enemy is less than detection radius.
var thisRoutine = StartCoroutine(Track());
if (CheckDistance() <= combatRadius)
{
StopCoroutine(thisRoutine);
leaderAgent.Stop();
Engage();
} else if (CheckDistance() <= combatRadius) { StartCoroutine(Track()); }
}
public IEnumerator Track()
{
//We want delay, so that the enemy formation is circumventable.
trackerTimer -= Time.deltaTime;
if (trackerTimer <= 0.0f)
{
if (CheckDistance() <= detectionRadius)
{
target.transform.position = nearestPlayerUnit.transform.position;
Debug.Log("Position acquired");
yield return new WaitForSeconds(0.0f);
}
trackerTimer = 2.0f;
}
}
private float CheckDistance()
{
float minDist = Mathf.Infinity;
foreach (GameObject playerUnit in playerUnits)
{
distance = Vector3.Distance(transform.position, playerUnit.transform.position);
if (distance < minDist)
{
nearestPlayerUnit = playerUnit;
minDist = distance;
//We don't need to get the leader because that will be done in the inspector.
}
}
return distance;
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612121558im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Flip over an object (smooth transition) 3 Answers
My ai is getting stuck when there is a lot of them 0 Answers
Using multiple yields in a Coroutine 1 Answer