AIAgent.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. /// <summary>
  5. /// AI Agent that navigates the maze with limited knowledge
  6. /// Only knows about the room it's currently in and rooms visited by same character type
  7. /// </summary>
  8. public class AIAgent : MonoBehaviour
  9. {
  10. [Header("Agent Identity")]
  11. [SerializeField] private string agentCharacterType = "Default";
  12. [SerializeField] private int agentId;
  13. [Header("AI Settings")]
  14. [SerializeField] private float movementSpeed = 2f;
  15. [SerializeField] private float pathUpdateInterval = 0.5f;
  16. [SerializeField] private float stoppingDistance = 0.1f;
  17. private float actualMovementSpeed; // Per-agent speed variation to reduce synchronization
  18. [Header("Pathfinding")]
  19. [SerializeField] private bool showPath = true;
  20. [SerializeField] private LineRenderer pathRenderer;
  21. [SerializeField] private Color pathColor = Color.yellow;
  22. private MazeController mazeController;
  23. private MazeData maze;
  24. private MazePathfinder pathfinder;
  25. private AIRoomMemory roomMemory;
  26. private List<Vector2Int> currentPath = new();
  27. private int currentPathIndex = 0;
  28. private float lastPathUpdate = 0f;
  29. private Vector2Int currentRoom = Vector2Int.zero;
  30. private Vector2Int targetRoom = Vector2Int.zero;
  31. private Vector2Int targetExitTile = Vector2Int.zero; // Target hallway exit to move toward
  32. private Queue<int> recentRooms = new Queue<int>(); // Track last N rooms to avoid backtracking
  33. private const int RECENT_ROOMS_BUFFER_SIZE = 10; // Larger buffer = less backtracking
  34. private MazeRoom lastRoomExitedFrom = null; // Track which room we exited to prevent immediate backtracking
  35. private bool hasReachedGoal = false; // Track if agent has reached the goal room
  36. private bool commitedToExit = false; // Track if agent has committed to a specific hallway exit
  37. private float nextRandomWait = 0f; // Random wait time before exploring new areas
  38. private float agentRandomOffset = 0f; // Per-agent random offset to desync movement
  39. void Start()
  40. {
  41. mazeController = FindAnyObjectByType<MazeController>();
  42. if (mazeController == null)
  43. {
  44. Debug.LogError("AIAgent: MazeController not found in scene!");
  45. enabled = false;
  46. return;
  47. }
  48. maze = mazeController.GetCurrentMaze();
  49. if (maze == null)
  50. {
  51. Debug.LogError("AIAgent: Current maze is null!");
  52. enabled = false;
  53. return;
  54. }
  55. pathfinder = new MazePathfinder(maze);
  56. roomMemory = AIRoomMemoryManager.GetMemory(agentCharacterType);
  57. // Initialize with a random start point
  58. if (maze.StartPoints.Count > 0)
  59. {
  60. int startIndex = agentId % maze.StartPoints.Count; // Distribute agents across start points
  61. Vector2Int startPos = maze.StartPoints[startIndex];
  62. // Get the start room and spawn randomly within it
  63. MazeRoom startRoom = maze.GetRoomAtTile(startPos.x, startPos.y);
  64. if (startRoom != null)
  65. {
  66. // Spawn at random position within start room
  67. Vector2Int randomPosInRoom = new Vector2Int(
  68. Random.Range(startRoom.MinX + 1, startRoom.MaxX),
  69. Random.Range(startRoom.MinY + 1, startRoom.MaxY)
  70. );
  71. transform.position = new Vector3(randomPosInRoom.x + 0.5f, 1f, randomPosInRoom.y + 0.5f);
  72. }
  73. else
  74. {
  75. // Fallback to exact start point
  76. transform.position = new Vector3(startPos.x + 0.5f, 1f, startPos.y + 0.5f);
  77. }
  78. // Rotate to be visible from above - 90 degrees around X axis
  79. transform.rotation = Quaternion.Euler(90, 0, 0);
  80. UpdateCurrentRoom(); // This will add to recentRooms and visit room
  81. }
  82. else
  83. {
  84. Debug.LogError("AIAgent: No start points found in maze!");
  85. enabled = false;
  86. return;
  87. }
  88. // Setup per-agent random offset to desync decision timings (prevents all agents moving in sync)
  89. agentRandomOffset = Random.Range(0f, pathUpdateInterval * 0.5f);
  90. nextRandomWait = Time.time + Random.Range(2f, 4f); // Random initial wait before first decision
  91. // Randomize movement speed slightly per agent (±20% variation)
  92. actualMovementSpeed = movementSpeed * Random.Range(0.8f, 1.2f);
  93. // Setup path renderer
  94. if (showPath && pathRenderer == null)
  95. {
  96. pathRenderer = gameObject.AddComponent<LineRenderer>();
  97. pathRenderer.startWidth = 0.1f;
  98. pathRenderer.endWidth = 0.1f;
  99. pathRenderer.material = new Material(Shader.Find("Sprites/Default"));
  100. pathRenderer.startColor = pathColor;
  101. pathRenderer.endColor = pathColor;
  102. }
  103. }
  104. void Update()
  105. {
  106. if (maze == null) return;
  107. // Update current room
  108. UpdateCurrentRoom();
  109. // Update pathfinding periodically with agent-specific offset to desync behavior
  110. if (Time.time - lastPathUpdate > pathUpdateInterval + agentRandomOffset)
  111. {
  112. UpdatePathToGoal();
  113. lastPathUpdate = Time.time;
  114. }
  115. // Move along path
  116. FollowPath();
  117. // Debug visualization
  118. if (showPath && pathRenderer != null)
  119. {
  120. UpdatePathVisualization();
  121. }
  122. }
  123. /// <summary>
  124. /// Updates the current room based on position
  125. /// </summary>
  126. private void UpdateCurrentRoom()
  127. {
  128. Vector2Int tilePos = WorldToTile(transform.position);
  129. MazeRoom room = maze.GetRoomAtTile(tilePos.x, tilePos.y);
  130. if (room != null)
  131. {
  132. if (currentRoom.x != room.Id)
  133. {
  134. currentRoom = new Vector2Int(room.Id, 0);
  135. roomMemory.VisitRoom(room.Id);
  136. // Track recent rooms to avoid immediate backtracking
  137. recentRooms.Enqueue(room.Id);
  138. if (recentRooms.Count > RECENT_ROOMS_BUFFER_SIZE)
  139. recentRooms.Dequeue();
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Updates pathfinding to reach the goal
  145. /// Agent only knows about current room and visited rooms
  146. /// NEW LOGIC: Pick a hallway exit from current room and move straight to it
  147. /// </summary>
  148. private void UpdatePathToGoal()
  149. {
  150. if (maze.ExitPoints.Count == 0)
  151. {
  152. Debug.LogWarning($"AIAgent {agentId}: No exit points in maze!");
  153. return;
  154. }
  155. Vector2Int currentPos = WorldToTile(transform.position);
  156. MazeRoom currentRoomData = maze.GetRoomAtTile(currentPos.x, currentPos.y);
  157. // CHECK FOR GOAL ROOM FIRST - this should work even while following path
  158. var goalRooms = maze.GetRoomsByType(MazeRoom.RoomType.End);
  159. if (currentRoomData != null && goalRooms.Contains(currentRoomData))
  160. {
  161. if (!hasReachedGoal)
  162. {
  163. hasReachedGoal = true;
  164. currentPath.Clear();
  165. currentPathIndex = 0;
  166. }
  167. return; // Stay stopped
  168. }
  169. // If we already have a valid path and we're following it, don't recalculate (stay committed)
  170. if (currentPath.Count > 0 && currentPathIndex < currentPath.Count)
  171. {
  172. return; // Keep following existing path
  173. }
  174. // If we've committed to reaching an exit and haven't reached it yet, keep trying
  175. if (commitedToExit && targetExitTile != Vector2Int.zero)
  176. {
  177. // Try to find a path to the committed exit
  178. if (currentPath.Count == 0)
  179. {
  180. currentPath = FindPathInRoom(currentPos, targetExitTile, currentRoomData);
  181. currentPathIndex = 0;
  182. if (currentPath.Count > 0)
  183. {
  184. Debug.Log($"AIAgent {agentId}: Re-committed to exit {targetExitTile}");
  185. return;
  186. }
  187. }
  188. }
  189. // If in hallway (no room), just keep moving along current path
  190. // The hallway pathfinding will naturally move us toward exits
  191. if (currentRoomData == null)
  192. {
  193. // If we have a current path, keep following it through hallway
  194. if (currentPath.Count > 0 && currentPathIndex < currentPath.Count)
  195. {
  196. return; // Keep following path
  197. }
  198. // In hallway with no path - find next room to enter
  199. // PRIORITY 1: Find unvisited rooms, avoid the room we just exited
  200. // Collect all unvisited rooms
  201. List<MazeRoom> unvisitedRooms = new();
  202. foreach (var room in maze.Rooms)
  203. {
  204. // Skip the room we just exited (backtracking prevention)
  205. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  206. continue;
  207. // Prioritize unvisited rooms
  208. if (!roomMemory.HasVisited(room.Id))
  209. {
  210. unvisitedRooms.Add(room);
  211. }
  212. }
  213. MazeRoom targetRoom = null;
  214. // Random decision: 70% closest unvisited, 30% random unvisited (increases exploration variety)
  215. if (unvisitedRooms.Count > 0)
  216. {
  217. if (Random.value < 0.7f && unvisitedRooms.Count > 0)
  218. {
  219. // Pick closest unvisited room
  220. float closestUnvisitedDistance = float.MaxValue;
  221. foreach (var room in unvisitedRooms)
  222. {
  223. Vector2Int roomCenter = room.GetCenter();
  224. float distance = Vector2Int.Distance(currentPos, roomCenter);
  225. if (distance < closestUnvisitedDistance)
  226. {
  227. closestUnvisitedDistance = distance;
  228. targetRoom = room;
  229. }
  230. }
  231. }
  232. else
  233. {
  234. // Pick random unvisited room for variety
  235. targetRoom = unvisitedRooms[Random.Range(0, unvisitedRooms.Count)];
  236. }
  237. }
  238. // If no unvisited room found, pick nearest room (except the one we came from)
  239. if (targetRoom == null)
  240. {
  241. float closestDistance = float.MaxValue;
  242. foreach (var room in maze.Rooms)
  243. {
  244. // Skip the room we just exited
  245. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  246. continue;
  247. Vector2Int roomCenter = room.GetCenter();
  248. float distance = Vector2Int.Distance(currentPos, roomCenter);
  249. if (distance < closestDistance)
  250. {
  251. closestDistance = distance;
  252. targetRoom = room;
  253. }
  254. }
  255. }
  256. if (targetRoom != null)
  257. {
  258. currentPath = FindPathToNearestRoom(currentPos, targetRoom);
  259. currentPathIndex = 0;
  260. if (currentPath.Count > 0)
  261. {
  262. bool isUnvisited = !roomMemory.HasVisited(targetRoom.Id);
  263. return;
  264. }
  265. else
  266. {
  267. Debug.LogWarning($"AIAgent {agentId}: Failed to path to room {targetRoom.Id} from hallway at {currentPos}. Trying any adjacent room.");
  268. // Fallback: try to find ANY adjacent room and move directly toward it
  269. foreach (var room in maze.Rooms)
  270. {
  271. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  272. continue;
  273. currentPath = FindPathToNearestRoom(currentPos, room);
  274. if (currentPath.Count > 0)
  275. {
  276. return;
  277. }
  278. }
  279. Debug.LogError($"AIAgent {agentId}: STUCK in hallway at {currentPos} - no paths found to any room!");
  280. return;
  281. }
  282. }
  283. Debug.LogWarning($"AIAgent {agentId}: In hallway but no reachable rooms!");
  284. return;
  285. }
  286. // MAIN LOGIC: In regular room, find a hallway exit and path to it
  287. // Get all hallway tiles adjacent to this room
  288. List<Vector2Int> hallwayExits = FindHallwayExits(currentRoomData, currentPos);
  289. if (hallwayExits.Count > 0)
  290. {
  291. // Pick a random hallway exit to move toward (commit to it)
  292. Vector2Int chosenExit = hallwayExits[Random.Range(0, hallwayExits.Count)];
  293. // Path directly to that exit
  294. currentPath = FindPathInRoom(currentPos, chosenExit, currentRoomData);
  295. currentPathIndex = 0;
  296. if (currentPath.Count > 0)
  297. {
  298. targetExitTile = chosenExit;
  299. commitedToExit = true;
  300. // Add random delay before next decision to increase variety
  301. nextRandomWait = Time.time + Random.Range(1.5f, 3.5f);
  302. }
  303. else
  304. {
  305. Debug.LogWarning($"AIAgent {agentId}: Could not path to hallway exit");
  306. commitedToExit = false;
  307. }
  308. }
  309. else
  310. {
  311. Debug.LogWarning($"AIAgent {agentId}: No hallway exits found from room {currentRoomData.Id}");
  312. commitedToExit = false;
  313. }
  314. }
  315. /// <summary>
  316. /// Chooses the next room to move to
  317. /// Searches around the current room to find adjacent rooms
  318. /// Avoids recently visited rooms to prevent backtracking
  319. /// </summary>
  320. private MazeRoom ChooseNextRoom(MazeRoom currentRoom)
  321. {
  322. // Find all adjacent rooms by checking walkable tiles in all directions from room boundaries
  323. List<MazeRoom> connectedRooms = new();
  324. Vector2Int roomCenter = currentRoom.GetCenter();
  325. // Check from each direction outward from the room center
  326. Vector2Int[] directions = new Vector2Int[]
  327. {
  328. Vector2Int.up, Vector2Int.down, Vector2Int.left, Vector2Int.right,
  329. Vector2Int.up + Vector2Int.left, Vector2Int.up + Vector2Int.right,
  330. Vector2Int.down + Vector2Int.left, Vector2Int.down + Vector2Int.right
  331. };
  332. // Shuffle directions for randomness
  333. for (int i = directions.Length - 1; i > 0; i--)
  334. {
  335. int randomIndex = Random.Range(0, i + 1);
  336. var temp = directions[i];
  337. directions[i] = directions[randomIndex];
  338. directions[randomIndex] = temp;
  339. }
  340. // Try each direction and look for tiles that lead to other rooms
  341. foreach (var dir in directions)
  342. {
  343. for (int dist = 1; dist < 20; dist++) // Search up to 20 tiles away
  344. {
  345. Vector2Int testPos = roomCenter + (dir * dist);
  346. if (!maze.IsInBounds(testPos.x, testPos.y) || !maze.IsWalkable(testPos.x, testPos.y))
  347. continue;
  348. MazeRoom testRoom = maze.GetRoomAtTile(testPos.x, testPos.y);
  349. if (testRoom != null && testRoom.Id != currentRoom.Id && !connectedRooms.Contains(testRoom))
  350. {
  351. connectedRooms.Add(testRoom);
  352. break; // Found a room in this direction, move to next direction
  353. }
  354. }
  355. }
  356. if (connectedRooms.Count == 0)
  357. {
  358. Debug.LogWarning($"AIAgent {agentId}: No adjacent rooms found from room {currentRoom.Id}");
  359. return null;
  360. }
  361. // Filter out recently visited rooms (to avoid backtracking)
  362. List<MazeRoom> nonRecentRooms = connectedRooms.Where(r => !recentRooms.Contains(r.Id)).ToList();
  363. // PRIORITY 1: Strongly prefer completely unvisited rooms (not recently visited either)
  364. var completelyUnvisited = nonRecentRooms.Where(r => !roomMemory.HasVisited(r.Id)).ToList();
  365. if (completelyUnvisited.Count > 0)
  366. {
  367. MazeRoom chosen = completelyUnvisited[Random.Range(0, completelyUnvisited.Count)];
  368. return chosen;
  369. }
  370. // PRIORITY 2: Try non-recent rooms even if visited by this character type
  371. if (nonRecentRooms.Count > 0)
  372. {
  373. // Among non-recent rooms, prefer unvisited by this agent's character type
  374. var unvisitedByType = nonRecentRooms.Where(r => !roomMemory.HasVisited(r.Id)).ToList();
  375. if (unvisitedByType.Count > 0)
  376. {
  377. MazeRoom chosen = unvisitedByType[Random.Range(0, unvisitedByType.Count)];
  378. return chosen;
  379. }
  380. // Otherwise just pick a random non-recent room
  381. MazeRoom chosen2 = nonRecentRooms[Random.Range(0, nonRecentRooms.Count)];
  382. return chosen2;
  383. }
  384. // PRIORITY 3: If all rooms are recent, pick one that's been visited least recently
  385. // Find the room in connectedRooms that was added to recentRooms earliest (will be dequeued first)
  386. MazeRoom leastRecentRoom = connectedRooms[0];
  387. foreach (var room in connectedRooms)
  388. {
  389. if (!roomMemory.HasVisited(room.Id))
  390. {
  391. leastRecentRoom = room;
  392. break;
  393. }
  394. }
  395. Debug.Log($"AIAgent {agentId}: All rooms recent, choosing least-recent room {leastRecentRoom.Id}");
  396. return leastRecentRoom;
  397. }
  398. /// <summary>
  399. /// Finds the nearest room from a position (used when in hallway)
  400. /// </summary>
  401. private MazeRoom FindNearestRoom(Vector2Int position)
  402. {
  403. MazeRoom nearest = null;
  404. float nearestDistance = float.MaxValue;
  405. foreach (var room in maze.Rooms)
  406. {
  407. Vector2Int roomCenter = room.GetCenter();
  408. float distance = Vector2Int.Distance(position, roomCenter);
  409. if (distance < nearestDistance)
  410. {
  411. nearestDistance = distance;
  412. nearest = room;
  413. }
  414. }
  415. return nearest;
  416. }
  417. /// <summary>
  418. /// Finds all hallway exit tiles adjacent to a room
  419. /// These are walkable tiles just outside the room boundary
  420. /// </summary>
  421. private List<Vector2Int> FindHallwayExits(MazeRoom room, Vector2Int currentPos)
  422. {
  423. List<Vector2Int> exits = new();
  424. HashSet<Vector2Int> addedExits = new();
  425. // Check all tiles on the boundary of the room
  426. // North boundary
  427. for (int x = room.MinX; x <= room.MaxX; x++)
  428. {
  429. int y = room.MinY - 1;
  430. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  431. {
  432. exits.Add(new Vector2Int(x, y));
  433. addedExits.Add(new Vector2Int(x, y));
  434. }
  435. }
  436. // South boundary
  437. for (int x = room.MinX; x <= room.MaxX; x++)
  438. {
  439. int y = room.MaxY + 1;
  440. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  441. {
  442. exits.Add(new Vector2Int(x, y));
  443. addedExits.Add(new Vector2Int(x, y));
  444. }
  445. }
  446. // West boundary
  447. for (int y = room.MinY; y <= room.MaxY; y++)
  448. {
  449. int x = room.MinX - 1;
  450. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  451. {
  452. exits.Add(new Vector2Int(x, y));
  453. addedExits.Add(new Vector2Int(x, y));
  454. }
  455. }
  456. // East boundary
  457. for (int y = room.MinY; y <= room.MaxY; y++)
  458. {
  459. int x = room.MaxX + 1;
  460. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  461. {
  462. exits.Add(new Vector2Int(x, y));
  463. addedExits.Add(new Vector2Int(x, y));
  464. }
  465. }
  466. return exits;
  467. }
  468. /// <summary>
  469. /// Finds a path from current position to the nearest room (when in hallway)
  470. /// </summary>
  471. private List<Vector2Int> FindPathToNearestRoom(Vector2Int start, MazeRoom targetRoom)
  472. {
  473. // Simple pathfinding through hallways using A*
  474. var openSet = new List<Vector2Int> { start };
  475. var cameFrom = new Dictionary<Vector2Int, Vector2Int>();
  476. var gScore = new Dictionary<Vector2Int, float> { [start] = 0 };
  477. var targetCenter = targetRoom.GetCenter();
  478. var fScore = new Dictionary<Vector2Int, float> { [start] = Vector2Int.Distance(start, targetCenter) };
  479. int iterations = 0;
  480. const int maxIterations = 2000; // Increased from 500 to handle larger mazes
  481. while (openSet.Count > 0 && iterations < maxIterations)
  482. {
  483. iterations++;
  484. // Find node with lowest fScore
  485. Vector2Int current = openSet[0];
  486. float lowestF = fScore[current];
  487. for (int i = 1; i < openSet.Count; i++)
  488. {
  489. if (fScore[openSet[i]] < lowestF)
  490. {
  491. current = openSet[i];
  492. lowestF = fScore[current];
  493. }
  494. }
  495. // If we reached the target room, we're done
  496. MazeRoom currentRoom = maze.GetRoomAtTile(current.x, current.y);
  497. if (currentRoom != null && currentRoom.Id == targetRoom.Id)
  498. {
  499. return ReconstructPath(cameFrom, current);
  500. }
  501. openSet.Remove(current);
  502. // Check neighbors
  503. Vector2Int[] neighbors = new[]
  504. {
  505. new Vector2Int(current.x + 1, current.y),
  506. new Vector2Int(current.x - 1, current.y),
  507. new Vector2Int(current.x, current.y + 1),
  508. new Vector2Int(current.x, current.y - 1),
  509. };
  510. foreach (var neighbor in neighbors)
  511. {
  512. if (!maze.IsInBounds(neighbor.x, neighbor.y) || !maze.IsWalkable(neighbor.x, neighbor.y))
  513. continue;
  514. float tentativeG = gScore[current] + 1;
  515. if (!gScore.ContainsKey(neighbor) || tentativeG < gScore[neighbor])
  516. {
  517. cameFrom[neighbor] = current;
  518. gScore[neighbor] = tentativeG;
  519. fScore[neighbor] = tentativeG + Vector2Int.Distance(neighbor, targetCenter);
  520. if (!openSet.Contains(neighbor))
  521. {
  522. openSet.Add(neighbor);
  523. }
  524. }
  525. }
  526. }
  527. Debug.LogWarning($"AIAgent {agentId}: FindPathToNearestRoom FAILED after {iterations} iterations. Start: {start}, Target room {targetRoom.Id} center: {targetCenter}");
  528. return new List<Vector2Int>();
  529. }
  530. /// <summary>
  531. /// Finds a boundary tile of the current room that points toward the next room
  532. /// </summary>
  533. private Vector2Int FindBoundaryTileToward(MazeRoom currentRoom, MazeRoom nextRoom, Vector2Int currentPos)
  534. {
  535. Vector2Int nextRoomCenter = nextRoom.GetCenter();
  536. Vector2Int closestBoundary = currentRoom.GetCenter();
  537. float closestDistance = float.MaxValue;
  538. // Check all boundary tiles of current room
  539. for (int x = currentRoom.MinX; x <= currentRoom.MaxX; x++)
  540. {
  541. for (int y = currentRoom.MinY; y <= currentRoom.MaxY; y++)
  542. {
  543. // Only check boundary and walkable tiles
  544. if ((x == currentRoom.MinX || x == currentRoom.MaxX || y == currentRoom.MinY || y == currentRoom.MaxY) &&
  545. maze.IsWalkable(x, y))
  546. {
  547. // Find boundary tile closest to next room center
  548. float distToNext = Vector2Int.Distance(new Vector2Int(x, y), nextRoomCenter);
  549. if (distToNext < closestDistance)
  550. {
  551. closestDistance = distToNext;
  552. closestBoundary = new Vector2Int(x, y);
  553. }
  554. }
  555. }
  556. }
  557. return closestBoundary;
  558. }
  559. /// <summary>
  560. /// Finds a path within a single room (limited knowledge)
  561. /// </summary>
  562. private List<Vector2Int> FindPathInRoom(Vector2Int start, Vector2Int goal, MazeRoom room)
  563. {
  564. // Use simple A* within room bounds
  565. var openSet = new List<Vector2Int> { start };
  566. var cameFrom = new Dictionary<Vector2Int, Vector2Int>();
  567. var gScore = new Dictionary<Vector2Int, float> { [start] = 0 };
  568. var fScore = new Dictionary<Vector2Int, float> { [start] = Vector2Int.Distance(start, goal) };
  569. int iterations = 0;
  570. const int maxIterations = 1000;
  571. while (openSet.Count > 0 && iterations < maxIterations)
  572. {
  573. iterations++;
  574. // Find node with lowest fScore
  575. Vector2Int current = openSet[0];
  576. float lowestF = fScore[current];
  577. for (int i = 1; i < openSet.Count; i++)
  578. {
  579. if (fScore[openSet[i]] < lowestF)
  580. {
  581. current = openSet[i];
  582. lowestF = fScore[current];
  583. }
  584. }
  585. if (current == goal)
  586. {
  587. return ReconstructPath(cameFrom, current);
  588. }
  589. openSet.Remove(current);
  590. // Check only neighbors within the room
  591. var neighbors = GetRoomNeighbors(current, room);
  592. foreach (var neighbor in neighbors)
  593. {
  594. float tentativeG = gScore[current] + 1;
  595. if (!gScore.ContainsKey(neighbor) || tentativeG < gScore[neighbor])
  596. {
  597. cameFrom[neighbor] = current;
  598. gScore[neighbor] = tentativeG;
  599. fScore[neighbor] = tentativeG + Vector2Int.Distance(neighbor, goal);
  600. if (!openSet.Contains(neighbor))
  601. {
  602. openSet.Add(neighbor);
  603. }
  604. }
  605. }
  606. }
  607. return new List<Vector2Int>();
  608. }
  609. /// <summary>
  610. /// Gets walkable neighbors within a room or at room boundary
  611. /// Allows pathfinding to reach hallway exits outside room
  612. /// </summary>
  613. private List<Vector2Int> GetRoomNeighbors(Vector2Int position, MazeRoom room)
  614. {
  615. var neighbors = new List<Vector2Int>();
  616. Vector2Int[] directions = new[]
  617. {
  618. new Vector2Int(position.x + 1, position.y),
  619. new Vector2Int(position.x - 1, position.y),
  620. new Vector2Int(position.x, position.y + 1),
  621. new Vector2Int(position.x, position.y - 1),
  622. };
  623. foreach (var dir in directions)
  624. {
  625. // Allow tiles within room OR immediately adjacent to room (boundary)
  626. bool inBounds = maze.IsInBounds(dir.x, dir.y);
  627. bool isWalkable = maze.IsWalkable(dir.x, dir.y);
  628. bool inRoom = room.Contains(dir.x, dir.y);
  629. bool nearBoundary = (dir.x == room.MinX - 1 || dir.x == room.MaxX + 1 ||
  630. dir.y == room.MinY - 1 || dir.y == room.MaxY + 1);
  631. if (inBounds && isWalkable && (inRoom || nearBoundary))
  632. {
  633. neighbors.Add(dir);
  634. }
  635. }
  636. return neighbors;
  637. }
  638. /// <summary>
  639. /// Reconstructs path from A* results
  640. /// </summary>
  641. private List<Vector2Int> ReconstructPath(Dictionary<Vector2Int, Vector2Int> cameFrom, Vector2Int current)
  642. {
  643. var path = new List<Vector2Int> { current };
  644. while (cameFrom.ContainsKey(current))
  645. {
  646. current = cameFrom[current];
  647. path.Insert(0, current);
  648. }
  649. return path;
  650. }
  651. /// <summary>
  652. /// Follows the current path
  653. /// </summary>
  654. private void FollowPath()
  655. {
  656. if (currentPath.Count == 0) return;
  657. Vector2Int currentTarget = currentPath[currentPathIndex];
  658. // Maze coordinates: X,Y → World: X,Z (Y=0 is ground level)
  659. // Keep Y at 1f to stay above the maze floor
  660. Vector3 targetWorldPos = new Vector3(currentTarget.x + 0.5f, 1f, currentTarget.y + 0.5f);
  661. Vector3 direction = (targetWorldPos - transform.position).normalized;
  662. // Move directly instead of using Translate (no rigidbody)
  663. transform.position += direction * actualMovementSpeed * Time.deltaTime;
  664. // Check if we've exited the room (entered hallway)
  665. Vector2Int currentPos = WorldToTile(transform.position);
  666. MazeRoom roomAtPos = maze.GetRoomAtTile(currentPos.x, currentPos.y);
  667. if (roomAtPos == null && currentRoom.x != -1)
  668. {
  669. // We've entered a hallway - track which room we came from to prevent immediate backtracking
  670. lastRoomExitedFrom = maze.Rooms.FirstOrDefault(r => r.Id == currentRoom.x);
  671. commitedToExit = false; // No longer committed to that exit, now in hallway
  672. targetExitTile = Vector2Int.zero; // Clear the target exit
  673. }
  674. // Move to next waypoint when close enough
  675. if (Vector3.Distance(transform.position, targetWorldPos) < stoppingDistance)
  676. {
  677. currentPathIndex++;
  678. if (currentPathIndex >= currentPath.Count)
  679. {
  680. currentPath.Clear();
  681. }
  682. }
  683. }
  684. /// <summary>
  685. /// Updates the path visualization
  686. /// </summary>
  687. private void UpdatePathVisualization()
  688. {
  689. if (currentPath.Count == 0)
  690. {
  691. pathRenderer.positionCount = 0;
  692. return;
  693. }
  694. var positions = new Vector3[currentPath.Count];
  695. for (int i = 0; i < currentPath.Count; i++)
  696. {
  697. // Maze coordinates: X,Y → World: X,Z (Y=0 is ground level)
  698. // Keep Y at 1f to stay above the maze floor
  699. positions[i] = new Vector3(currentPath[i].x + 0.5f, 1f, currentPath[i].y + 0.5f);
  700. }
  701. pathRenderer.positionCount = positions.Length;
  702. pathRenderer.SetPositions(positions);
  703. }
  704. /// <summary>
  705. /// Converts world position to tile coordinate
  706. /// Maze coordinates: X,Y ← World: X,Z (Y=0 is ground level)
  707. /// </summary>
  708. private Vector2Int WorldToTile(Vector3 worldPos)
  709. {
  710. return new Vector2Int(Mathf.FloorToInt(worldPos.x), Mathf.FloorToInt(worldPos.z));
  711. }
  712. /// <summary>
  713. /// Gets agent ID
  714. /// </summary>
  715. public int AgentId => agentId;
  716. /// <summary>
  717. /// Gets agent character type
  718. /// </summary>
  719. public string CharacterType => agentCharacterType;
  720. /// <summary>
  721. /// Gets current room
  722. /// </summary>
  723. public Vector2Int CurrentRoom => currentRoom;
  724. /// <summary>
  725. /// Gets room memory
  726. /// </summary>
  727. public AIRoomMemory RoomMemory => roomMemory;
  728. /// <summary>
  729. /// Gets agent ID (public accessor for triggers)
  730. /// </summary>
  731. public int GetAgentId() => agentId;
  732. /// <summary>
  733. /// Called by ExitRoomTrigger when agent enters the goal room
  734. /// Immediately stops all movement
  735. /// </summary>
  736. public void StopAtGoal()
  737. {
  738. hasReachedGoal = true;
  739. currentPath.Clear();
  740. currentPathIndex = 0;
  741. commitedToExit = false;
  742. }
  743. /// <summary>
  744. /// Gets whether this agent has reached the goal
  745. /// </summary>
  746. public bool HasReachedGoal => hasReachedGoal;
  747. }