PieceShadows.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace TowerDevil
  5. {
  6. // All contact shadows share a mesh underneath the removable and animated pieces.
  7. [RequireComponent(typeof(CanvasRenderer))]
  8. public sealed class PieceShadows : MaskableGraphic
  9. {
  10. Dictionary<Piece, RawImage> figures;
  11. const int Segments = 16;
  12. static readonly Vector2[] circle = BuildCircle();
  13. static Vector2[] BuildCircle()
  14. {
  15. var points = new Vector2[Segments];
  16. for (int i = 0; i < Segments; i++)
  17. {
  18. float angle = i * 2 * Mathf.PI / Segments;
  19. points[i] = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
  20. }
  21. return points;
  22. }
  23. internal void Bind(Dictionary<Piece, RawImage> pieces) => figures = pieces;
  24. protected override void OnPopulateMesh(VertexHelper mesh)
  25. {
  26. mesh.Clear();
  27. if (figures == null) return;
  28. foreach (var pair in figures)
  29. {
  30. RectTransform rt = pair.Value.rectTransform;
  31. float width = rt.rect.width * rt.localScale.x;
  32. Vector2 center = rt.anchoredPosition + new Vector2(width * .055f, width * .055f);
  33. Vector2 radius = new Vector2(width * .54f, width * .15f);
  34. int start = mesh.currentVertCount;
  35. mesh.AddVert(center, new Color32(12, 8, 13, 179), Vector2.zero);
  36. for (int i = 0; i < Segments; i++)
  37. {
  38. Vector2 d = Vector2.Scale(circle[i], radius);
  39. mesh.AddVert(center + d * .47f, new Color32(14, 10, 14, 142), Vector2.zero);
  40. mesh.AddVert(center + d, new Color32(14, 10, 14, 0), Vector2.zero);
  41. }
  42. for (int i = 0; i < Segments; i++)
  43. {
  44. int a = start + 1 + i * 2, b = start + 1 + ((i + 1) % Segments) * 2;
  45. mesh.AddTriangle(start, a, b);
  46. mesh.AddTriangle(a, a + 1, b);
  47. mesh.AddTriangle(a + 1, b + 1, b);
  48. }
  49. }
  50. }
  51. }
  52. }