| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- using UnityEngine.UI;
- namespace LineUI
- {
- [RequireComponent(typeof(CanvasRenderer))]
- [RequireComponent(typeof(RectTransform))]
- public class Line : Graphic
- {
- [SerializeField] private bool loop = false;
- [SerializeField] private float thickness = 1f;
- [SerializeField] private int roundCount = 0;
- [SerializeField] private List<Vector2> screenPositions = new List<Vector2>();
- public RectTransform RectTr { get => rectTransform; }
- //调用的话最少10宽度
- public float MyThickness
- {
- get { return thickness; }
- set {
- if (value >= 10)
- {
- thickness = value;
- }
- }
- }
- public void SetLine(List<Vector2> screenPositions)
- {
- this.screenPositions = screenPositions;
- SetVerticesDirty();
- }
- protected override void OnPopulateMesh(VertexHelper vh)
- {
- vh.Clear();
- SetVertex(vh);
- SetTriangles(vh);
- }
- private void SetVertex(VertexHelper vh)
- {
- UIVertex vert = UIVertex.simpleVert;
- vert.color = color;
- if (screenPositions.Count < 2)
- return;
- List<Vector2> _screenPositions = screenPositions.ToList();
- if (loop) {
- //添加多两个顶点。形成闭环
- _screenPositions.Add(screenPositions[0]);
- _screenPositions.Add(screenPositions[1]);
- }
- float lastAngle = 0;
- for (int i = 1; i < _screenPositions.Count; i++)
- {
- Vector2 previousPos = _screenPositions[i - 1];
- Vector2 currentPos = _screenPositions[i];
- Vector2 dif = currentPos - previousPos;
- float angle = Vector2.SignedAngle(Vector2.right, dif);
- if (i > 1)
- {
- float anglePerRound = (angle - lastAngle) / roundCount;
- for (int j = 0; j < roundCount; j++)
- {
- float ang = lastAngle + anglePerRound * j;
- Vector2 roundOffset = Quaternion.Euler(0, 0, ang) * Vector2.up * thickness;
- vert.position = previousPos - roundOffset;
- vh.AddVert(vert);
- vert.position = previousPos + roundOffset;
- vh.AddVert(vert);
- }
- }
- lastAngle = angle;
- Vector2 offset = (Vector2)(Quaternion.Euler(0, 0, angle) * Vector3.up * thickness);
- vert.position = previousPos - offset;
- vh.AddVert(vert);
- vert.position = previousPos + offset;
- vh.AddVert(vert);
- vert.position = currentPos - offset;
- vh.AddVert(vert);
- vert.position = currentPos + offset;
- vh.AddVert(vert);
- }
-
- }
- private static void SetTriangles(VertexHelper vh)
- {
- for (int i = 0; i < vh.currentVertCount - 2; i += 2)
- {
- int index = i;
- vh.AddTriangle(index, index + 1, index + 3);
- vh.AddTriangle(index + 3, index + 2, index);
- }
- }
- }
- }
|