How to spawn Coins one at a time in a random fixed points in my 2d game?

Godot Version



Hi, can anyone help in my current project. I’m working on my 2d game and I can’t figure out how to spawn coins one at a time. Basically there is only one coin appears at the beginning, also in a random fixed point. When the player collided with a coin, another coin spawns but in the other fixed point of the game.

You can create a timer, when timeout you can spawn it, when player die, it will call spawn coin function. So add a node2d for your coin spawning points collection, you can name it CoinPoints, then add a position 2d as the point, and pos it, do this multiple times as you want. So in codes, do this:

func spawn_coin()
   var random_point = coin_points.get_children().pick_random()
   var coin = preload("path/to/your/coin.tscn").instance()

This code needs a slight correction; randomize() should only be called once. Calling it before every random number ruins the algorithm, and makes it seem less random.

I was actually unaware of this but as of Godot 4. Randomize() is automatically being called when the game starts now.

I did some testing with picking random integers and array indexes without using randomize() anywhere and couldn’t tell the difference

1 Like