MazeAgentController.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. Backtracking through an already-used
  39. /// exit (moving back to a previously generated room) is allowed.
  40. /// </summary>
  41. public bool TryUseExit(Exit exit)
  42. {
  43. if (Agent == null || Agent.CurrentRoom == null) return false;
  44. if (exit.OwnerRoomId != Agent.CurrentRoom.Id) return false;
  45. Room nextRoom = exit.ConnectedRoomId.HasValue
  46. ? _generator.Graph.Get(exit.ConnectedRoomId.Value)
  47. : _generator.GenerateConnectedRoom(Agent.CurrentRoom, exit, Agent);
  48. Agent.EnterRoom(nextRoom, exit);
  49. return true;
  50. }
  51. }
  52. }