MazeAgentController.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. namespace MazeGen
  3. {
  4. /// <summary>
  5. /// Scene-facing wrapper around a MazeAgent: positions a GameObject at the agent's
  6. /// current room and drives exit traversal (generating the next room lazily if needed).
  7. /// </summary>
  8. public class MazeAgentController : MonoBehaviour
  9. {
  10. private const float BaseScale = 0.5f;
  11. private const float FollowedScale = 0.7f;
  12. private MazeGenerator _generator;
  13. private SpriteRenderer _sprite;
  14. public MazeAgent Agent { get; private set; }
  15. public void Initialize(MazeGenerator generator)
  16. {
  17. _generator = generator;
  18. }
  19. public void Spawn(Room startRoom, Color color)
  20. {
  21. Agent = new MazeAgent(gameObject.name, startRoom);
  22. transform.position = startRoom.Position;
  23. transform.localScale = Vector3.one * BaseScale;
  24. Agent.RoomEntered += room => transform.position = room.Position;
  25. _sprite = gameObject.AddComponent<SpriteRenderer>();
  26. _sprite.sprite = RoomView.SharedSquareSprite;
  27. _sprite.color = color;
  28. _sprite.sortingOrder = 3;
  29. }
  30. /// <summary>Visually calls out this agent as the one the camera is currently following.</summary>
  31. public void SetFollowed(bool followed)
  32. {
  33. transform.localScale = Vector3.one * (followed ? FollowedScale : BaseScale);
  34. if (_sprite != null) _sprite.sortingOrder = followed ? 5 : 3;
  35. }
  36. /// <summary>
  37. /// Attempts to move the agent through the given exit. Returns false if the exit
  38. /// doesn't belong to the agent's current room, if the next room couldn't be generated
  39. /// (extremely dense packing edge case), or if the exit is blocked. Backtracking through
  40. /// an already-used exit (moving back to a previously generated room) is allowed.
  41. /// </summary>
  42. public bool TryUseExit(Exit exit)
  43. {
  44. if (Agent == null || Agent.CurrentRoom == null) return false;
  45. if (exit.OwnerRoomId != Agent.CurrentRoom.Id) return false;
  46. Room nextRoom = exit.ConnectedRoomId.HasValue
  47. ? _generator.Graph.Get(exit.ConnectedRoomId.Value)
  48. : _generator.GenerateConnectedRoom(Agent.CurrentRoom, exit, Agent);
  49. if (nextRoom == null) return false; // generation failed or exit is blocked; agent picks again next tick
  50. Agent.EnterRoom(nextRoom, exit);
  51. return true;
  52. }
  53. }
  54. }