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);
}
}