I am working on random enemy generation in my game. I wanted to spawn a cluster of them inside a circle.
How can I ensure that enemies do not get inside walls since the placement of these “spawners” will be random.
Some ideas:
-
put specially-identifiable (either with layers or a custom MonoBehavior) colliders on walls and raycast down to make sure you don’t hit one
-
store the coordinates of points within the walls and check against your proposed spawn point, don’t spawn if too close
That would make a trial and error solution since then a spawner might just not spawn anything.
Trial and error solutions can affect performance.
Everything is random, you don’t know the layout, so of course there is going to be a trial/error solution.
If you don’t want trial and error, you’re going to have to build in to your scene acceptable locations to spawn then. If your level is randomly generated… this will be difficult as part of the level generation you’ll have to have some algorithm scan the resulting layout and figure out where all the walls are and build a map of acceptable locations.
But if your levels are static (you create them before hand), you can just manually determine all the good spots and create a data container to hold that information. How you encode that information is up to you… a point graph, a mesh, a whatever. A really really simple out of the box solution could be to create an AI path graph using Unity’s pathing system, or Aron Granberg’s A*, or whatever. Create a graph for an object the size of your spawner and select a random point from within it.
This could actually work for the random generated rooms if your graph calculator can scan at runtime. I know Aron Granberg’s A* can perform a runtime scan (not sure if that’s a pro-only feature or not). Not so sure about Unity’s, haven’t used it in years. It didn’t do runtime scans back then.
I think I found it. shoot rays around a circle, if it collides with anything I will ignore it, if all the rays are ignored reduce the size of the circle, else get a random point from the line between the center and the edge of the circle.