Spawning units from a building

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Luckydude

Hey guys,

I would like to know what you would recommend as a spawning mechanism for units when they get “produced” in a building. Imagine a classic unit creation like in Command & Conquer or Age of Empires.

I see the problem that you need to calculate the position of the created unit. However, sometimes it can collide with other bodies. And sometimes, if the building is blocked from all sides, there is no chance to place the unit. The problem is actually bigger than it seems.

So I came up with this solution. I calculate the tiles around the building which represent the possible spawning areas. My idea is to create these tiles (12 in the screenshot) as Area2D nodes. Then, every time a unit is to be produced, I calculate a free tile using get_overlapping_bodies() from the Area2D class. This way I know if other buildings (StaticBody2D) or units (KinematicBody2D) are blocking the exit. And if all exits are blocked, I can tell the player to free the exits before he can produce more units

What do you think about that? Is this a good solution or do you know something simpler?

:bust_in_silhouette: Reply From: Lopy

This should work.
You cloud make it simpler if the spawned nodes cannot move directly (if some function gets called on the spawner for that to happen). In that case, the spawner could just remember what lies around it.