Get a random reachable point inside a circunference

Hi,

I was implementing a function that gets a random point on a circumference around the player to spawn coins when the player takes damage from an enemy. This function checks whether the random position is reachable for the player. It’s important to note that there may be multiple coins, so the function will be called multiple times within a single frame.

Vector3 randomPos = GetRandomPoint();

Vector3 closestNavMeshPos = AstarPath.active.GetNearest(randomPos, NNConstraint.Walkable).position;

randomPos.Set(closestNavMeshPos.x, randomPos.y, closestNavMeshPos.z);

Here, GetRandomPoint retrieves a random point on the circumference.

I’ve been reading some documentation and forum posts, and I’ve concluded that using only one call to GetNearest should be the most efficient option.

I believe NNInfo.position returns the closest point on the node rather than the closest position to the original point. Therefore, if there are few nodes, the positions may overlap and not be evenly distributed, if I’m correct.

Is there a better or more efficient way to do this? Perhaps retrieving some graph points to make the coin positions more accurate relative to the original random position or checking if the random point is reachable?

I’m using a NavMesh graph.

Thanks in advance!

  • A* version: 5.1.6
  • Unity version: 2023.2.13f1

My solution to this in my game was to have a separate graph specifically for spawning item powerups and other game objects I didn’t want too close to walls. Whether or not this is the “clean” method is debatable, but it worked very well for me. I just chose a random node from that graph and checked a few other things (for you, it would be checking if it’s a certain distance to the player, checking if it’s reachable from the player’s position) and if it was good I’d spawn my item.

If you need help getting any of that going let me know :+1:
Orrr if this doesn’t help in the slightest… also let me know :slight_smile:

Hi! Thank you for the quick response.

While I think your solution is valid, it may be a bit too performance-demanding for my particular case unfortunately. There will be multiple calculations in a single frame for a moderate number of coins.

I was initially looking for a way to get some random points on the graph close to a position that were reachable, but I’ve realized my approach had other problems. I’ve now decided to use another implementation that doesn’t involve AStar and allows multiple quick calculations per frame using a tile system.

On the bright side, your response opened up possibilities I hadn’t considered for the future, so thank you very much!

1 Like

Well glad to help, even if indirectly! :slight_smile: