PathVisualizer.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace MazeGen
  4. {
  5. /// <summary>
  6. /// Draws the agent's traveled path (start room -> current room) as a line, one segment
  7. /// per hop. Only the most recently added hop is drawn bright; every earlier hop is
  8. /// dimmed down so the eye is drawn to where the agent is right now, not the whole trail.
  9. /// </summary>
  10. [RequireComponent(typeof(LineRenderer))]
  11. public class PathVisualizer : MonoBehaviour
  12. {
  13. private static readonly Color BrightColor = new Color(1f, 0.1f, 0.75f);
  14. private static readonly Color DimColor = new Color(0.55f, 0.2f, 0.4f, 0.35f);
  15. private const float LineWidth = 0.15f;
  16. private readonly List<LineRenderer> _segments = new List<LineRenderer>();
  17. private Vector3? _lastPoint;
  18. private Material _lineMaterial;
  19. private void Awake()
  20. {
  21. // The LineRenderer required on this GameObject itself is left unused/empty -
  22. // each hop gets its own child LineRenderer so it can be colored independently.
  23. GetComponent<LineRenderer>().positionCount = 0;
  24. _lineMaterial = new Material(Shader.Find("Sprites/Default"));
  25. }
  26. public void AppendPoint(Vector2 worldPos)
  27. {
  28. Vector3 point = new Vector3(worldPos.x, worldPos.y, -0.5f);
  29. if (_lastPoint.HasValue)
  30. {
  31. DimExistingSegments();
  32. _segments.Add(CreateSegment(_lastPoint.Value, point));
  33. }
  34. _lastPoint = point;
  35. }
  36. private void DimExistingSegments()
  37. {
  38. foreach (var segment in _segments)
  39. {
  40. segment.startColor = DimColor;
  41. segment.endColor = DimColor;
  42. }
  43. }
  44. private LineRenderer CreateSegment(Vector3 a, Vector3 b)
  45. {
  46. var segmentGO = new GameObject("PathSegment");
  47. segmentGO.transform.SetParent(transform, false);
  48. var line = segmentGO.AddComponent<LineRenderer>();
  49. line.positionCount = 2;
  50. line.SetPositions(new[] { a, b });
  51. line.widthMultiplier = LineWidth;
  52. line.useWorldSpace = true;
  53. line.sortingOrder = 2;
  54. line.material = _lineMaterial;
  55. line.startColor = BrightColor;
  56. line.endColor = BrightColor;
  57. return line;
  58. }
  59. public void Clear()
  60. {
  61. foreach (var segment in _segments)
  62. if (segment != null) Destroy(segment.gameObject);
  63. _segments.Clear();
  64. _lastPoint = null;
  65. }
  66. }
  67. }