Players can place items/buildings in my top-down 2d game, this means that there are no pre-defined areas in a scene that are empty of colliders/obsticles.
The problem is I need to Instantiate NPCs at a random position in the scene when the player enters that scene, but sometimes they spawn on top of a building or some other collider, which prevents them from wandering around (and obviously looks weird).
Right now I’m using a simple PolygonCollider2D to determine a spawn-area, which is more or less the entire scene, then I pick the spawn-position like this:
public Vector3 FindPointInArea()
{
var bounds = _collider.bounds;
var center = bounds.center;
float x = 0;
float y = 0;
int attempt = 0;
do
{
x = Random.Range(bounds.min.x, bounds.max.x);
y = Random.Range(bounds.min.y, bounds.max.y);
attempt++;
}
while (!_collider.OverlapPoint(new Vector2(x, y)));
return new Vector3(x, y, 0);
}
Is there some smart solution that can make sure NPCs are never Instantiated on top of an obsticle?
I would have to create the vAvailable List every time the player makes a change to the scene (adding another building for example), but as long as that doesnt end up being too costly this seems like a very neat solution Will try it
You would certainly have to establish some method for working out whether the location is availalbe or not.
Raycasting may be one way of doing that. Another may be to create a simple GameObject with a trigger collider attached - place it at the location and see if the collider hits another collider or not.
This, trigger mesh collider is my best solution to odd shaped buildings, otherwise I use raycasts and overlap sphere(not sure what the 2D counterpart is, overlap circle perhaps?)
Update: This works like a charm and does not seem at all costly Although I did realize I’m basically just doing the same scan that A* pathfinding is doing, so I’m going to see if I can use that data and save on performance cost
The way I would do it would be pick a random location and then use Physics.OverlapBox or Physics.OverlapSphere to check for any colliders you don’t want. If none you’re good to go, if you find any then pick a new random location and try again.