I’m creating a sheep-dog game where there’s a flock of sheep wandering randomly. I’m able to make the sheep wander, but I also want the sheep to wander away from each other.

Currently, this is the update method I’m using, to update the sheep’s destination.
Vector3 destination;

void updatePosition()
	{
		float x,z;
		x = Random.Range (-maxWanderDistance,maxWanderDistance);
		z = Random.Range (-maxWanderDistance,maxWanderDistance);
	 	destination.x = transform.position.x+x;
		destination.z = transform.position.z+z;
		
	}

While the sheep does wander randomly as it should, it’s not taking into account the location of other sheep in the vicinity. So what’s the best way to detect other sheep? Never mind the moving away part for now…I’ll take care of it.

I assume you have some way to track sheep in the scene, so loop through each sheep to get their position, then subtract that from the current sheep’s position. Now take that value, get its magnitude squared with sqMagnitude, and compare that to some minimum distance squared.

I.e. Let’s say you store all the sheep in a static list in the sheep class:

`
class Sheep : MonoBehaviour
{
static List _sheepList = new List;

void Awake()
{
_sheepList.Add(this);
}

void UpdatePosition()
{
foreach (Sheep littleLamb in _sheepList)
{
Vector3 distSq = (littleLamb.transform.position - transform.position).sqMagnitude();

  if (distSq > MAX_DIST_SQ)
    MoveAway();
}

}

}
`

You’ll note there’s a flaw with this you’ll need to consider. What if this sheep is too close to five other sheep? Which way does he go? In this case, you might loop through all sheep to find the closest one, and move away from it. A better approach might be to move sheep on the outside outward and then process each sheep as you get closer to the sheep in the center of the herd.