From 1f569181f9a9a533015c32136ecef77eaa6e75c4 Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 19 Oct 2026 18:23:13 +0200 Subject: mob spwaning, corridors, node -v 22 --- DungeonSystem/scripts/Door.cs | 34 ++- DungeonSystem/scripts/DungeonGenerator.cs | 457 +++++++++++++++++++++++++++++- 2 files changed, 471 insertions(+), 20 deletions(-) (limited to 'DungeonSystem/scripts') diff --git a/DungeonSystem/scripts/Door.cs b/DungeonSystem/scripts/Door.cs index 0a970b3..c30c462 100644 --- a/DungeonSystem/scripts/Door.cs +++ b/DungeonSystem/scripts/Door.cs @@ -11,17 +11,27 @@ public partial class Door : Node2D public enum DoorState { Open, Locked } public DoorState CurrentState { get; private set; } = DoorState.Open; - private CollisionShape2D _barrierCollision = null!; - private Area2D _triggerArea = null!; - private AnimationPlayer _animPlayer = null!; + private CollisionShape2D? _barrierCollision; + private Area2D? _triggerArea; + private AnimationPlayer? _animPlayer; public override void _Ready() { - _barrierCollision = GetNode("Barrier/CollisionShape2D"); - _triggerArea = GetNode("TriggerArea"); - _animPlayer = GetNode("AnimationPlayer"); + _barrierCollision = GetNodeOrNull("Barrier/CollisionShape2D") + ?? GetNodeOrNull("StaticBody2D/CollisionShape2D"); + _triggerArea = GetNodeOrNull("TriggerArea") + ?? GetNodeOrNull("Area2D"); + _animPlayer = GetNodeOrNull("AnimationPlayer"); + + if (_triggerArea != null) + { + _triggerArea.CollisionMask |= 1u << 1; + _triggerArea.Monitoring = true; + } + + if (_triggerArea != null) + _triggerArea.BodyEntered += OnBodyEntered; - _triggerArea.BodyEntered += OnBodyEntered; UnlockDoor(); } @@ -30,18 +40,18 @@ public partial class Door : Node2D if (CurrentState == DoorState.Locked) return; CurrentState = DoorState.Locked; - _barrierCollision.SetDeferred(CollisionShape2D.PropertyName.Disabled, false); + _barrierCollision?.SetDeferred(CollisionShape2D.PropertyName.Disabled, false); - if (_animPlayer.HasAnimation("lock")) + if (_animPlayer != null && _animPlayer.HasAnimation("lock")) _animPlayer.Play("lock"); } public void UnlockDoor() { CurrentState = DoorState.Open; - _barrierCollision.SetDeferred(CollisionShape2D.PropertyName.Disabled, true); + _barrierCollision?.SetDeferred(CollisionShape2D.PropertyName.Disabled, true); - if (_animPlayer.HasAnimation("unlock")) + if (_animPlayer != null && _animPlayer.HasAnimation("unlock")) _animPlayer.Play("unlock"); } @@ -52,4 +62,4 @@ public partial class Door : Node2D EmitSignal(SignalName.PlayerEnteredDoorway, this); } } -} \ No newline at end of file +} diff --git a/DungeonSystem/scripts/DungeonGenerator.cs b/DungeonSystem/scripts/DungeonGenerator.cs index dd59698..d830bdd 100644 --- a/DungeonSystem/scripts/DungeonGenerator.cs +++ b/DungeonSystem/scripts/DungeonGenerator.cs @@ -1,5 +1,6 @@ using Godot; using Godot.Collections; +using System.Collections.Generic; namespace DungeonSystem; @@ -11,27 +12,79 @@ public partial class DungeonGenerator : Node2D [Export] public PackedScene TreasureRoomScene { get; set; } = null!; [Export] public PackedScene BossRoomScene { get; set; } = null!; [Export] public PackedScene DoorScene { get; set; } = null!; + [Export] public PackedScene? EnemyScene { get; set; } = GD.Load("res://enemy.tscn"); [Export] public int TargetRoomCount { get; set; } = 10; [Export] public int MaxAttempts { get; set; } = 100; + [Export] public int CorridorLengthTiles { get; set; } = 6; + [Export] public int CorridorWidthTiles { get; set; } = 3; + [Export] public int CorridorTileSourceId { get; set; } = 0; + [Export] public Vector2I CorridorFloorAtlasCoords { get; set; } = new Vector2I(1, 6); + [Export] public Vector2I CorridorWallAtlasCoords { get; set; } = new Vector2I(1, 0); + [Export] public int MinEnemiesPerCombatRoom { get; set; } = 2; + [Export] public int MaxEnemiesPerCombatRoom { get; set; } = 4; + [Export] public float EnemySpawnPadding { get; set; } = 24.0f; + [Export] public float EnemySpawnMinDistance { get; set; } = 24.0f; + [Export] public float RoomEntryInnerMargin { get; set; } = 10.0f; - // --- ADD THESE TWO LINES --- private readonly Array _placedRooms = new(); private readonly Array _openDoors = new(); - // --------------------------- + private readonly List _corridorConnections = new(); + private readonly System.Collections.Generic.Dictionary> _roomDoors = new(); + private readonly System.Collections.Generic.Dictionary _encounterStates = new(); + + private TileMapLayer? _corridorTileMap; + private float _corridorTileSize = 16.0f; + private Node2D? _player; + private Room? _currentPlayerRoom; + + private readonly struct CorridorConnection + { + public readonly Vector2 From; + public readonly Vector2 To; + public readonly Vector2 Direction; + + public CorridorConnection(Vector2 from, Vector2 to, Vector2 direction) + { + From = from; + To = to; + Direction = direction; + } + } + + private sealed class EncounterState + { + public bool EncounterStarted; + public bool EncounterCleared; + public int AliveEnemies; + } public override void _Ready() { GenerateDungeon(); } + public override void _Process(double delta) + { + _UpdateRoomEntryEncounter(); + } + public void GenerateDungeon() { + _placedRooms.Clear(); + _openDoors.Clear(); + _corridorConnections.Clear(); + _roomDoors.Clear(); + _encounterStates.Clear(); + _currentPlayerRoom = null; + // 1. Instantiate Start Room if (StartRoomScene.Instantiate() is not Room startRoom) return; AddChild(startRoom); startRoom.GlobalPosition = Vector2.Zero; + _SetupCorridorTileMap(startRoom); + _placedRooms.Add(startRoom); _openDoors.AddRange(startRoom.GetOpenDoors()); @@ -44,6 +97,8 @@ public partial class DungeonGenerator : Node2D _TryAttachRoom(targetDoor); } + _BuildCorridors(); + // 3. Post-Process Doors SpawnDoorsAndSealUnconnected(); } @@ -57,21 +112,47 @@ public partial class DungeonGenerator : Node2D AddChild(candidate); + Vector2 targetDirection = _GetDoorDirection(targetDoor); + if (targetDirection == Vector2.Zero) + { + RemoveChild(candidate); + candidate.QueueFree(); + return false; + } + Array candidateDoors = candidate.GetOpenDoors(); - if (candidateDoors.Count == 0) + List compatibleEntryDoors = new(); + foreach (Marker2D candidateDoor in candidateDoors) + { + Vector2 candidateDirection = _GetDoorDirection(candidateDoor); + if (_AreOppositeDirections(targetDirection, candidateDirection)) + { + compatibleEntryDoors.Add(candidateDoor); + } + } + + if (compatibleEntryDoors.Count == 0) { RemoveChild(candidate); candidate.QueueFree(); return false; } - Marker2D entryDoor = candidateDoors[(int)(GD.Randi() % (uint)candidateDoors.Count)]; + Marker2D entryDoor = compatibleEntryDoors[(int)(GD.Randi() % (uint)compatibleEntryDoors.Count)]; - // Align candidate entry door directly to target door position - Vector2 offset = targetDoor.GlobalPosition - entryDoor.GlobalPosition; + float corridorGap = Mathf.Max(1, CorridorLengthTiles) * _corridorTileSize; + Vector2 desiredEntryPosition = targetDoor.GlobalPosition + targetDirection * corridorGap; + + Room? sourceRoom = targetDoor.GetParent()?.GetParent() as Room; + + // Align candidate entry door with a corridor gap from the target door. + Vector2 offset = desiredEntryPosition - entryDoor.GlobalPosition; candidate.GlobalPosition += offset; - if (CheckOverlap(candidate)) + bool roomOverlap = CheckOverlap(candidate); + bool corridorOverlap = CheckCorridorOverlap(targetDoor.GlobalPosition, entryDoor.GlobalPosition, targetDirection, sourceRoom); + + if (roomOverlap || corridorOverlap) { RemoveChild(candidate); candidate.QueueFree(); @@ -85,9 +166,11 @@ public partial class DungeonGenerator : Node2D _openDoors.Remove(targetDoor); _openDoors.AddRange(candidate.GetOpenDoors()); + _corridorConnections.Add(new CorridorConnection(targetDoor.GlobalPosition, entryDoor.GlobalPosition, targetDirection)); return true; } + private bool CheckOverlap(Room candidate) { Rect2 candidateRect = candidate.GetRoomRect().Grow(-2.0f); @@ -103,6 +186,158 @@ public partial class DungeonGenerator : Node2D return false; } + private bool CheckCorridorOverlap(Vector2 fromDoor, Vector2 toDoor, Vector2 axisDirection, Room? sourceRoom) + { + int walkWidthTiles = Mathf.Max(1, CorridorWidthTiles); + int halfWalkTiles = walkWidthTiles / 2; + int halfTotalTiles = halfWalkTiles + 1; + + Vector2 start = fromDoor + axisDirection * (_corridorTileSize * 0.5f); + Vector2 end = toDoor - axisDirection * (_corridorTileSize * 0.5f); + float corridorDistance = start.DistanceTo(end); + + if (corridorDistance <= Mathf.Epsilon) + { + return false; + } + + Vector2 perpendicular = new Vector2(-axisDirection.Y, axisDirection.X); + int steps = Mathf.Max(1, Mathf.CeilToInt(corridorDistance / (_corridorTileSize * 0.5f))); + + for (int i = 0; i <= steps; i++) + { + float t = (float)i / steps; + Vector2 center = start.Lerp(end, t); + + for (int lane = -halfTotalTiles; lane <= halfTotalTiles; lane++) + { + Vector2 samplePoint = center + perpendicular * (lane * _corridorTileSize); + + foreach (Room room in _placedRooms) + { + if (room == sourceRoom) + { + continue; + } + + if (room.GetRoomRect().Grow(-2.0f).HasPoint(samplePoint)) + { + return true; + } + } + } + } + + return false; + } + + private void _SetupCorridorTileMap(Room referenceRoom) + { + _corridorTileMap = GetNodeOrNull("CorridorTileMap"); + if (_corridorTileMap == null) + { + _corridorTileMap = new TileMapLayer(); + _corridorTileMap.Name = "CorridorTileMap"; + AddChild(_corridorTileMap); + } + + TileMapLayer? referenceTileMap = referenceRoom.GetNodeOrNull("TileMapLayer"); + if (referenceTileMap?.TileSet == null) + { + return; + } + + _corridorTileMap.TileSet = referenceTileMap.TileSet; + _corridorTileMap.Position = referenceTileMap.GlobalPosition - GlobalPosition; + _corridorTileMap.ZIndex = referenceTileMap.ZIndex; + _corridorTileMap.Clear(); + + _corridorTileSize = referenceTileMap.TileSet.TileSize.X; + if (_corridorTileSize <= Mathf.Epsilon) + { + _corridorTileSize = 16.0f; + } + } + + private void _BuildCorridors() + { + if (_corridorTileMap == null) + { + return; + } + + foreach (CorridorConnection connection in _corridorConnections) + { + _PaintStraightCorridor(connection); + } + } + + private void _PaintStraightCorridor(CorridorConnection connection) + { + if (_corridorTileMap == null) + { + return; + } + + int walkWidthTiles = Mathf.Max(1, CorridorWidthTiles); + int halfWalkTiles = walkWidthTiles / 2; + int halfTotalTiles = halfWalkTiles + 1; + + Vector2 start = connection.From + connection.Direction * (_corridorTileSize * 0.5f); + Vector2 end = connection.To - connection.Direction * (_corridorTileSize * 0.5f); + float corridorDistance = start.DistanceTo(end); + + if (corridorDistance <= Mathf.Epsilon) + { + return; + } + + Vector2 perpendicular = new Vector2(-connection.Direction.Y, connection.Direction.X); + int steps = Mathf.Max(1, Mathf.CeilToInt(corridorDistance / _corridorTileSize)); + + for (int i = 0; i <= steps; i++) + { + float t = (float)i / steps; + Vector2 center = start.Lerp(end, t); + + for (int lane = -halfTotalTiles; lane <= halfTotalTiles; lane++) + { + Vector2 worldPosition = center + perpendicular * (lane * _corridorTileSize); + Vector2I cell = _corridorTileMap.LocalToMap(_corridorTileMap.ToLocal(worldPosition)); + bool isWalkableLane = Mathf.Abs(lane) <= halfWalkTiles; + Vector2I atlasCoords = isWalkableLane ? CorridorFloorAtlasCoords : CorridorWallAtlasCoords; + + _corridorTileMap.SetCell(cell, CorridorTileSourceId, atlasCoords); + } + } + } + + private static Vector2 _GetDoorDirection(Marker2D door) + { + if (!door.HasMeta("direction")) + { + return Vector2.Zero; + } + + Vector2 direction = door.GetMeta("direction").AsVector2(); + if (direction == Vector2.Zero) + { + return Vector2.Zero; + } + + return direction.Normalized(); + } + + private static bool _AreOppositeDirections(Vector2 directionA, Vector2 directionB) + { + if (directionA == Vector2.Zero || directionB == Vector2.Zero) + { + return false; + } + + return directionA.Dot(directionB) <= -0.99f; + } + private void SpawnDoorsAndSealUnconnected() { foreach (Room room in _placedRooms) @@ -139,6 +374,7 @@ public partial class DungeonGenerator : Node2D AddChild(doorInstance); doorInstance.GlobalPosition = marker.GlobalPosition; doorInstance.ZIndex = 1; // Ensure it renders above tilemaps + _RegisterDoorForRoom(room, doorInstance); if (marker.HasMeta("direction")) { @@ -152,6 +388,211 @@ public partial class DungeonGenerator : Node2D marker.SetMeta("door_spawned", true); } + private void _RegisterDoorForRoom(Room room, Door door) + { + if (!_roomDoors.TryGetValue(room, out List? doors)) + { + doors = new List(); + _roomDoors[room] = doors; + } + + doors.Add(door); + } + + private void _UpdateRoomEntryEncounter() + { + if (!GodotObject.IsInstanceValid(_player)) + { + _player = GetTree().GetFirstNodeInGroup("player") as Node2D; + } + + if (_player == null) + { + return; + } + + Room? nextRoom = null; + Vector2 playerPosition = _player.GlobalPosition; + + foreach (Room room in _placedRooms) + { + if (room.Type != Room.RoomType.Combat) + { + continue; + } + + Rect2 roomRect = room.GetRoomRect(); + Rect2 innerRoomRect = roomRect.Grow(-Mathf.Max(0.0f, RoomEntryInnerMargin)); + if (innerRoomRect.Size.X <= 0.0f || innerRoomRect.Size.Y <= 0.0f) + { + innerRoomRect = roomRect; + } + + if (!innerRoomRect.HasPoint(playerPosition)) + { + continue; + } + + nextRoom = room; + break; + } + + if (nextRoom == _currentPlayerRoom) + { + return; + } + + _currentPlayerRoom = nextRoom; + if (_currentPlayerRoom != null) + { + _TryStartRoomEncounter(_currentPlayerRoom); + } + } + + private void _TryStartRoomEncounter(Room room) + { + if (room.Type != Room.RoomType.Combat) + { + return; + } + + EncounterState state = _GetEncounterState(room); + if (state.EncounterStarted || state.EncounterCleared) + { + return; + } + + state.EncounterStarted = true; + _SetRoomDoorsLocked(room, true); + + int requestedEnemyCount = _GetRandomEnemyCount(); + state.AliveEnemies = _SpawnEncounterEnemies(room, requestedEnemyCount); + + if (state.AliveEnemies == 0) + { + state.EncounterCleared = true; + _SetRoomDoorsLocked(room, false); + } + } + + private EncounterState _GetEncounterState(Room room) + { + if (_encounterStates.TryGetValue(room, out EncounterState? state)) + { + return state; + } + + state = new EncounterState(); + _encounterStates[room] = state; + return state; + } + + private void _SetRoomDoorsLocked(Room room, bool isLocked) + { + if (!_roomDoors.TryGetValue(room, out List? doors)) + { + return; + } + + foreach (Door door in doors) + { + if (!GodotObject.IsInstanceValid(door)) + { + continue; + } + + if (isLocked) + { + door.LockDoor(); + } + else + { + door.UnlockDoor(); + } + } + } + + private int _GetRandomEnemyCount() + { + int minCount = Mathf.Max(0, MinEnemiesPerCombatRoom); + int maxCount = Mathf.Max(minCount, MaxEnemiesPerCombatRoom); + return (int)GD.Randi() % (maxCount - minCount + 1) + minCount; + } + + private int _SpawnEncounterEnemies(Room room, int requestedCount) + { + if (EnemyScene == null || requestedCount <= 0) + { + return 0; + } + + Rect2 spawnRect = room.GetRoomRect().Grow(-EnemySpawnPadding); + if (spawnRect.Size.X <= 0 || spawnRect.Size.Y <= 0) + { + spawnRect = room.GetRoomRect().Grow(-8.0f); + } + + List usedPositions = new(); + int spawned = 0; + int maxAttempts = Mathf.Max(requestedCount * 10, 20); + + for (int attempt = 0; attempt < maxAttempts && spawned < requestedCount; attempt++) + { + float x = (float)GD.RandRange(spawnRect.Position.X, spawnRect.End.X); + float y = (float)GD.RandRange(spawnRect.Position.Y, spawnRect.End.Y); + Vector2 candidatePosition = new Vector2(x, y); + + bool overlapsExistingSpawn = false; + foreach (Vector2 usedPosition in usedPositions) + { + if (usedPosition.DistanceTo(candidatePosition) < EnemySpawnMinDistance) + { + overlapsExistingSpawn = true; + break; + } + } + + if (overlapsExistingSpawn) + { + continue; + } + + if (EnemyScene.Instantiate() is not Node2D enemyInstance) + { + continue; + } + + AddChild(enemyInstance); + enemyInstance.GlobalPosition = candidatePosition; + usedPositions.Add(candidatePosition); + spawned++; + + enemyInstance.TreeExited += () => _OnEncounterEnemyExited(room); + } + + return spawned; + } + + private void _OnEncounterEnemyExited(Room room) + { + if (!_encounterStates.TryGetValue(room, out EncounterState? state)) + { + return; + } + + if (!state.EncounterStarted || state.EncounterCleared) + { + return; + } + + state.AliveEnemies = Mathf.Max(0, state.AliveEnemies - 1); + if (state.AliveEnemies == 0) + { + state.EncounterCleared = true; + _SetRoomDoorsLocked(room, false); + } + } + private void _SealDoorwayWithWall(Room room, Marker2D marker) { var tileMapLayer = room.GetNodeOrNull("TileMapLayer"); @@ -165,4 +606,4 @@ public partial class DungeonGenerator : Node2D tileMapLayer.SetCell(cellPos, sourceId, wallAtlasCoords); } -} \ No newline at end of file +} -- cgit v1.2.3