How spawn in a random point


#1

Hi, how can I instantiate an object in a random position that is walkable and can reach the player?
Now I instantiate it but sometimes it spawn in places where it can not reach the player.

	public Vector3 RandomPosition(){
		Vector3 destination;
		do{
			randomNode = nodes[UnityEngine.Random.Range(0, nodes.Count)];
		}while(!randomNode.Walkable);
		destination = randomNode.RandomPointOnSurface();
		return destination;
	}

#2

Hi

You can use PahtUtilities.IsPathPossible to check if it is reachable from some other point.

Also check out this tutorial: https://arongranberg.com/astar/docs/wander.html


#3

Thanks! How I get player’s node by position?
So?
AP.graphs[0].GetNearest(AleksiVariable.Aleksi.transform.position).node;


#4

Yes, that will work, but I would recommend:

AstarPath.active.GetNearest(somePosition).node;

as it checks all graphs and does a few more checks.


#5

Thanks! Work.

public Vector3 RandomPosition(){
	Vector3 destination;
        GraphNode NodePlayer = AP.graphs[0].GetNearest(AleksiVariable.Aleksi.transform.position).node;
        do
        {
		randomNode = nodes[UnityEngine.Random.Range(0, nodes.Count)];
	}while(!(randomNode.Walkable && PathUtilities.IsPathPossible(randomNode, NodePlayer)));
	destination = randomNode.RandomPointOnSurface();
	return destination;
}