CUIPolygon.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //模拟凸多边形
  2. //UGUI最小的单元是一个矩形 所以顶点数必须是4的倍数
  3. //矩形模拟三角形最多组成凸多边形
  4. using UnityEngine;
  5. using System.Collections;
  6. using UnityEngine.UI;
  7. using System.Collections.Generic;
  8. public class CUIPolygon : Graphic
  9. {
  10. public Transform[] curTrnas;
  11. Vector3[] vertexs = null;
  12. protected override void Start()
  13. {
  14. this.transform.localPosition = Vector3.zero;
  15. base.Start();
  16. }
  17. public void InitVertexsCount(int num)
  18. {
  19. vertexs = new Vector3[6];
  20. }
  21. public void RefreshPolygonVertexs()
  22. {
  23. for (int i = 0; i < curTrnas.Length; ++i)
  24. {
  25. vertexs[i] = curTrnas[i].localPosition;
  26. }
  27. SetAllDirty();
  28. }
  29. protected override void OnPopulateMesh(VertexHelper vh)
  30. {
  31. if (vertexs == null || vertexs.Length < 3) return;
  32. int starsCount = vertexs.Length;
  33. Color32 color32 = this.color;
  34. vh.Clear();
  35. vh.AddVert(new Vector3(0, 0), color32, new Vector2(0f, 0f)); // 0
  36. for(int idx = 0; idx < starsCount; idx++)
  37. {
  38. vh.AddVert(vertexs[idx], color32, new Vector2(0f, 0f)); // 1
  39. }
  40. for (int idx =0; idx < starsCount; idx++)
  41. {
  42. int index2 = (idx + 2) > starsCount ? (idx + 2 - starsCount) : (idx + 2);
  43. vh.AddTriangle(0, idx+1, index2);
  44. }
  45. }
  46. }