Is there a good way to spawn object randomly withoud colliding with other objects?

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

I’m making a game that will randomly spawn several enemies (KinematicBody) and How do I know if the spawn point is not collide with other objects?

Is there a good way to spawn a number of enemies randomly in certain area?


:bust_in_silhouette: Reply From: eons

Get the “world” and use the direct_space_state from it, then cast points or shapes to test the “ground”.
, if colliding test another point or use collisions as reference to test again.

For details of the direct space state, see

or the 2D equivalent if 2D.

:bust_in_silhouette: Reply From: picnic

It depends on when you want to spawn the enemies - if it’s midway through a ‘level’ when the other entities have already moved then there’s little alternative to testing as eons suggests - unless you have a spawn point (or several) that is not reused until clear, that way you just check that area rather than testing against all other enemies etc.

A simple but effective way at the start of the level: if your sprites were, say, 64x64 pixels, imagine the viewport split into 64 pixel columns (or wider) and place your enemies somewhere in that column. You might not have or want to use all the columns, adding to the apparent randomness. For example, if your viewport was 640x480 you’s have 10 columns but might only want to spawn in six of them.

Just some ideas… :smiley: