Spawning Obstacles One After Another

Godot Version

4.3

Question

I am making an endless runner, and I am trying to spawn in random obstacles in front of the player in a loop. Currently I have the spawning down (it uses a timer), but the position of each new obstacle is too far. How can I make it so obstacles can spawn one after another but there is no gap in between them?

I’m visioning something like this:

Each of the staticbodies are meant to be the random obstacles.

Here is my code for their spawn logic so far:

public partial class Game : Node2D
{
	private Array obstacles;
	CharacterBody2D player;
	Timer timer;
	[Export] private PackedScene one, two, three;
	public override void _Ready()
	{
		timer = GetNode<Timer>("/root/Game/ObstacleSpawnTimer");
		player = GetNode<CharacterBody2D>("/root/Game/Player");
		obstacles = new Array { one, two, three };
	}

	private void OnTimerTimeout()
	{
		SpawnObstacles();
		timer.WaitTime = 3;
		timer.Start();
	}

	private void SpawnObstacles()
	{
		var toSpawn = GD.RandRange(0, obstacles.Count - 1);
		PackedScene packedScene = (PackedScene)obstacles[toSpawn];
		var spawn = (Node2D)packedScene.Instantiate();
		spawn.GlobalPosition = new Vector2(player.Position.X + 500, 0);
		AddChild(spawn);
	}
}

I’m guessing you’ll need to tune this 500 value to be smaller. To make it easier to calculate or have mathematically no gaps, you should spawn relative to the last structure rather than the player’s position.

1 Like

I suggest moving the obstacles instead of player. Over long distances, floating point inaccuracies can occur, but if the player remains near position (0, 0), this won’t be an issue. This way, you can create a true endless runner. Once obstacles move off the screen, you can reuse them by placing them back in front of the player with some randomization.

2 Likes

Thanks for the suggestion! I’ll try this one out.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.