How do I make a CharacterBody2D randomly spawn in one of 3 specified X axis positions?

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

How would I make an enemy randomly spawn in one of 3 specified X axes?

I have a timer to spawn them but how would I make it spawn randomly in one of 3 random X axes? I’ve tried looking at other questions but all of them seem to want a range instead of a certain specific position.

Sorry I’m quite new to game development right now :3

:bust_in_silhouette: Reply From: Zylann

If you have your 3 positions known in code, you can put them in an array and generate a random index to pick an item at random:

var positions_x = [100.0, 200.0, 300.0]
var random_x = positions_x[randi() % len(positions_x)]
character.position.x = random_x

You can do this technique with any item, not just numbers. It could be nodes too (spawn points you place in the level for example).

Thanks so much for the answer! It worked!

sushiboss2 | 2023-07-07 18:13