Hello. I'm new to Godot, and I've created a simple dungeon generator. It generally works well, as it avoids repeating rooms; however, I've encountered issues where rooms aren't always connected or are placed diagonally. I've been trying to fix these problems for a while, but I can't figure out what is wrong. Can anyone point me in the right direction? Thank you in advance.
Example:
My code:
using Godot;
using System.Collections.Generic;
public partial class Rooms : Node2D
{
[Export] private const int numRooms = 10;
private PackedScene[] SPAWN_ROOMS;
private PackedScene[] INTERMEDIATE_ROOMS;
private PackedScene[] END_ROOMS;
private const int TILE_SIZE = 16;
private List<Vector2> rooms;
private Node2D room;
private TileMap roomTilemap;
public override void _Ready()
{
SPAWN_ROOMS = new PackedScene[] { GD.Load<PackedScene>("res://Rooms/SpawnRoom0.tscn")};
INTERMEDIATE_ROOMS = new PackedScene[] { GD.Load<PackedScene>("res://Rooms/Room0.tscn")};
END_ROOMS = new PackedScene[] { GD.Load<PackedScene>("res://Rooms/EndRoom0.tscn") };
Generate(numRooms);
}
private void AddRoom(Node2D room)
{
while (rooms.Contains(room.Position))
{
Vector2 dir = new Vector2[] { new (-1, 0), new (1, 0), new (0, -1), new (0, 1) }[GD.Randi() % 4];
roomTilemap = room.GetNode<TileMap>("TileMap");
room.Position += dir * roomTilemap.GetUsedRect().Size.Y * TILE_SIZE;
}
rooms.Add(room.Position);
AddChild(room);
}
private void Generate(int count)
{
rooms = new List<Vector2> { new(0, 0) };
Vector2 from = rooms[rooms.Count - 1];
for (int i = 0; i < count; i++)
{
Vector2 dir = new Vector2[] { new (-1, 0), new (1, 0), new (0, -1), new (0, 1) }[GD.Randi() % 4];
if (i == 0)
{
room = SPAWN_ROOMS[GD.Randi() % SPAWN_ROOMS.Length].Instantiate() as Node2D;
roomTilemap = room.GetNode<TileMap>("TileMap");
room.Position = from + dir * roomTilemap.GetUsedRect().Size.Y * TILE_SIZE;
AddRoom(room);
from = room.Position;
}
else
{
if (i == count - 1)
{
room = END_ROOMS[GD.Randi() % END_ROOMS.Length].Instantiate() as Node2D;
roomTilemap = room.GetNode<TileMap>("TileMap");
room.Position = from + dir * roomTilemap.GetUsedRect().Size.Y * TILE_SIZE;
room.Modulate = Color.Color8(255, 50, 255);
AddRoom(room);
from = room.Position;
}
else
{
room = INTERMEDIATE_ROOMS[GD.Randi() % INTERMEDIATE_ROOMS.Length].Instantiate() as Node2D;
roomTilemap = room.GetNode<TileMap>("TileMap");
room.Position = from + dir * roomTilemap.GetUsedRect().Size.Y * TILE_SIZE;
AddRoom(room);
from = room.Position;
}
}
}
}
}