bigbat
June 15, 2013, 11:57am
1
Hi to all,
In my current project i use unity navmesh for ai navigation.i want my npc’s be able to get a random walkable destination(point) on navmesh and flee to that point when he/she see the player.
Any help or tips on how to do it, I’d be grateful.
This might not be the best way to do it but it worked for my purpose.
I generated a random point with in a unit sphere and multiplied it by the max distance I wanted my agents to walk:
Vector3 randomDirection = Random.insideUnitSphere * walkRadius;
I then added my agents current position to this vector and used the NavMesh.SamplePosition function to find the close position on the NavMesh:
randomDirection += transform.position;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, walkRadius, 1);
Vector3 finalPosition = hit.position;
I then used final postion as the destination for my agent.
Hope this helps!
Thanks for the answer Valkyr_x! Expanding on that here’s a C# function for getting a random Vector3 Navmesh Position:
public Vector3 RandomNavmeshLocation(float radius) {
Vector3 randomDirection = Random.insideUnitSphere * radius;
randomDirection += transform.position;
NavMeshHit hit;
Vector3 finalPosition = Vector3.zero;
if (NavMesh.SamplePosition(randomDirection, out hit, radius, 1)) {
finalPosition = hit.position;
}
return finalPosition;
}
And this can make the NavAgent move by calling this code, with whatever radius you want:
myNavAgent.SetDestination(RandomNavmeshLocation(4f));