PolygonDrawer.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. /// <summary>
  3. /// 绘制多边形
  4. /// TODO: 存在两点重合时绘制有问题
  5. /// </summary>
  6. public class PolygonDrawer : MonoBehaviour
  7. {
  8. public Material material;
  9. public Transform[] vertices;
  10. private MeshRenderer mRenderer;
  11. private MeshFilter mFilter;
  12. void Start()
  13. {
  14. Draw();
  15. }
  16. void Update()
  17. {
  18. Draw();
  19. }
  20. [ContextMenu("Draw")]
  21. public void Draw()
  22. {
  23. Vector2[] vertices2D = new Vector2[vertices.Length];
  24. Vector3[] vertices3D = new Vector3[vertices.Length];
  25. for (int i = 0; i < vertices.Length; i++)
  26. {
  27. Vector3 vertice = vertices[i].localPosition;
  28. vertices2D[i] = new Vector2(vertice.x, vertice.y);
  29. vertices3D[i] = vertice;
  30. }
  31. Triangulator tr = new Triangulator(vertices2D);
  32. int[] triangles = tr.Triangulate();
  33. Mesh mesh = new Mesh();
  34. mesh.vertices = vertices3D;
  35. mesh.triangles = triangles;
  36. if (mRenderer == null)
  37. {
  38. mRenderer = gameObject.GetOrAddComponent<MeshRenderer>();
  39. }
  40. mRenderer.material = material;
  41. if (mFilter == null)
  42. {
  43. mFilter = gameObject.GetOrAddComponent<MeshFilter>();
  44. }
  45. mFilter.mesh = mesh;
  46. }
  47. }