Line.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace LineUI
  5. {
  6. // 定义 ArrowInfo 类
  7. public class ArrowInfo
  8. {
  9. public Vector2 Position { get; set; }
  10. public Vector2 Direction { get; set; }
  11. public ArrowInfo(Vector2 position, Vector2 direction)
  12. {
  13. Position = position;
  14. Direction = direction;
  15. }
  16. }
  17. [RequireComponent(typeof(CanvasRenderer))]
  18. [RequireComponent(typeof(RectTransform))]
  19. public class Line : Graphic
  20. {
  21. [Header("绘制线段")]
  22. [SerializeField] private bool loop = false;
  23. [SerializeField] private float thickness = 1f;
  24. [SerializeField] private int roundCount = 0;
  25. [SerializeField] private List<Vector2> screenPositions = new List<Vector2>();
  26. //获取当前的points
  27. [HideInInspector]
  28. public List<Vector2> ScreenPositions => screenPositions;
  29. [Header("绘制内四边形")]
  30. //是否绘制内四边形
  31. [SerializeField] bool bDrawQuad = true;
  32. [SerializeField] private Vector2 quadrilateralSize = new Vector2(100, 100);
  33. [SerializeField] private Color quadColor = Color.red;
  34. [Header("绘制外围蒙板")]
  35. //是否绘制外围蒙板
  36. [SerializeField] bool bDrawMask = false;
  37. [SerializeField] private Color maskColor = Color.red;
  38. //控制扇形角绘制
  39. [Header("扇形角绘制")]
  40. [SerializeField] private bool bDrawFan = false;
  41. [SerializeField] private Color fanColor = Color.white;
  42. [SerializeField] private int fanSegments = 20; // 扇形的平滑度
  43. [SerializeField] private float fanOuterRadius = 150f; // 扇形的半径
  44. private float fanInnerRadius = 0f;
  45. [Tooltip("扇形指向箭头")]
  46. [SerializeField] private bool bDrawArrow = false;
  47. [SerializeField] private Color arrowColor = Color.white;
  48. [SerializeField] float arrowLength = 50f;
  49. [SerializeField] float arrowWidth = 50f;
  50. [SerializeField] float arrowHeadHeight = 30f;
  51. [SerializeField] float arrowDis = 100f;
  52. private List<ArrowInfo> arrowInfos = new List<ArrowInfo>();
  53. //获取当前的points
  54. [HideInInspector]
  55. public List<ArrowInfo> ArrowInfos => arrowInfos;
  56. //[SerializeField] private Color quadTextColor = Color.black;
  57. //[SerializeField] private int quadFontSize = 14;
  58. //private List<Vector2> quadsToDraw = new List<Vector2>();
  59. //private List<string> quadTextToDraw = new List<string>();
  60. //private List<GameObject> quadObjects = new List<GameObject>();
  61. //private Stack<GameObject> objectPool = new Stack<GameObject>();
  62. private const int ObjectPoolLimit = 4;
  63. public RectTransform RectTr => rectTransform;
  64. public float MyThickness
  65. {
  66. get => thickness;
  67. set
  68. {
  69. if (value >= 1)
  70. {
  71. thickness = value;
  72. }
  73. }
  74. }
  75. public float MyFanWidth
  76. {
  77. get => fanOuterRadius;
  78. set
  79. {
  80. if (value >= 1)
  81. {
  82. fanOuterRadius = value;
  83. }
  84. }
  85. }
  86. public void SetLine(List<Vector2> screenPositions)
  87. {
  88. this.screenPositions = screenPositions;
  89. SetVerticesDirty();
  90. }
  91. public void SetDrawQuad(bool value) {
  92. bDrawQuad = value;
  93. SetVerticesDirty();
  94. }
  95. public void SetDrawMask(bool value)
  96. {
  97. bDrawMask = value;
  98. SetVerticesDirty();
  99. }
  100. public void SetDrawFan(bool value)
  101. {
  102. bDrawFan = value;
  103. SetVerticesDirty();
  104. }
  105. protected override void OnPopulateMesh(VertexHelper vh)
  106. {
  107. vh.Clear();
  108. arrowInfos.Clear();
  109. //quadsToDraw.Clear();
  110. //quadTextToDraw.Clear();
  111. if (screenPositions.Count < 2)
  112. return;
  113. SetLineVertices(vh);
  114. SetLineTriangles(vh);
  115. if(bDrawQuad) SetQuadrilateralVertices(vh);
  116. if(bDrawMask) DrawMask(vh); // 绘制蒙版
  117. if (bDrawFan) DrawFansAtCorners(vh); // 在转折角绘制扇形
  118. }
  119. private void SetLineVertices(VertexHelper vh)
  120. {
  121. UIVertex vert = UIVertex.simpleVert;
  122. vert.color = color;
  123. List<Vector2> _screenPositions = new List<Vector2>(screenPositions);
  124. if (loop)
  125. {
  126. _screenPositions.Add(screenPositions[0]);
  127. _screenPositions.Add(screenPositions[1]);
  128. }
  129. float lastAngle = 0;
  130. for (int i = 1; i < _screenPositions.Count; i++)
  131. {
  132. Vector2 previousPos = _screenPositions[i - 1];
  133. Vector2 currentPos = _screenPositions[i];
  134. Vector2 dif = currentPos - previousPos;
  135. float angle = Vector2.SignedAngle(Vector2.right, dif);
  136. Vector2 offset = Quaternion.Euler(0, 0, angle) * Vector3.up * thickness;
  137. if (i > 1)
  138. {
  139. float anglePerRound = (angle - lastAngle) / roundCount;
  140. for (int j = 0; j <= roundCount; j++)
  141. {
  142. float ang = lastAngle + anglePerRound * j;
  143. Vector2 roundOffset = Quaternion.Euler(0, 0, ang) * Vector2.up * thickness;
  144. vert.position = previousPos - roundOffset;
  145. vh.AddVert(vert);
  146. vert.position = previousPos + roundOffset;
  147. vh.AddVert(vert);
  148. }
  149. }
  150. lastAngle = angle;
  151. vert.position = previousPos - offset;
  152. vh.AddVert(vert);
  153. vert.position = previousPos + offset;
  154. vh.AddVert(vert);
  155. vert.position = currentPos - offset;
  156. vh.AddVert(vert);
  157. vert.position = currentPos + offset;
  158. vh.AddVert(vert);
  159. }
  160. }
  161. private void SetQuadrilateralVertices(VertexHelper vh)
  162. {
  163. UIVertex vert = UIVertex.simpleVert;
  164. vert.color = quadColor;
  165. List<Vector2> _screenPositions = new List<Vector2>(screenPositions);
  166. if (loop)
  167. {
  168. _screenPositions.Add(screenPositions[0]);
  169. _screenPositions.Add(screenPositions[1]);
  170. }
  171. for (int i = 1; i < _screenPositions.Count; i++)
  172. {
  173. Vector2 previousPos = _screenPositions[i - 1];
  174. Vector2 currentPos = _screenPositions[i];
  175. if (i > 1)
  176. {
  177. Vector2 prevDir = (_screenPositions[i - 1] - _screenPositions[i - 2]).normalized;
  178. Vector2 currentDir = (currentPos - previousPos).normalized;
  179. int index = i == 4 ? 4 : i % 4;
  180. if (index == 4 || index == 2)
  181. {
  182. DrawSquareAtCorner(vh, previousPos, prevDir, currentDir, quadrilateralSize.x, quadrilateralSize.y, index);
  183. }
  184. else {
  185. DrawSquareAtCorner(vh, previousPos, prevDir, currentDir, quadrilateralSize.y, quadrilateralSize.x, index);
  186. }
  187. }
  188. }
  189. }
  190. private void DrawSquareAtCorner(VertexHelper vh, Vector2 corner, Vector2 prevDir, Vector2 currentDir, float width, float height, int index)
  191. {
  192. UIVertex vert = UIVertex.simpleVert;
  193. vert.color = quadColor;
  194. Vector2[] corners = new Vector2[4];
  195. corners[0] = corner;
  196. corners[1] = corner + prevDir * -width;
  197. corners[2] = corner + prevDir * -width + currentDir * height;
  198. corners[3] = corner + currentDir * height;
  199. foreach (Vector2 pos in corners)
  200. {
  201. vert.position = pos;
  202. vh.AddVert(vert);
  203. }
  204. int startIndex = vh.currentVertCount - 4;
  205. vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2);
  206. vh.AddTriangle(startIndex + 2, startIndex + 3, startIndex);
  207. // Store the quad's center position and text for later use
  208. //Vector2 quadCenter = corner + (prevDir * -width + currentDir * height) / 2;
  209. //quadsToDraw.Add(quadCenter);
  210. //quadTextToDraw.Add(index.ToString());
  211. }
  212. private void SetLineTriangles(VertexHelper vh)
  213. {
  214. for (int i = 0; i < vh.currentVertCount - 2; i += 2)
  215. {
  216. int index = i;
  217. vh.AddTriangle(index, index + 1, index + 3);
  218. vh.AddTriangle(index + 3, index + 2, index);
  219. }
  220. }
  221. private void DrawMask(VertexHelper vh)
  222. {
  223. UIVertex vert = UIVertex.simpleVert;
  224. vert.color = maskColor;
  225. //// 屏幕四个角的坐标
  226. //Vector2[] screenCorners = new Vector2[]
  227. //{
  228. // new Vector2(-Screen.width / 2, -Screen.height / 2), // 左下角
  229. // new Vector2(Screen.width / 2, -Screen.height / 2), // 右下角
  230. // new Vector2(Screen.width / 2, Screen.height / 2), // 右上角
  231. // new Vector2(-Screen.width / 2, Screen.height / 2), // 左上角
  232. //};
  233. // 获取 RectTransform 的实际四个角坐标
  234. Rect rect = rectTransform.rect;
  235. Vector2[] screenCorners = new Vector2[]
  236. {
  237. new Vector2(rect.xMin, rect.yMin), // 左下角
  238. new Vector2(rect.xMax, rect.yMin), // 右下角
  239. new Vector2(rect.xMax, rect.yMax), // 右上角
  240. new Vector2(rect.xMin, rect.yMax), // 左上角
  241. };
  242. // 添加四个点作为内框(中间区域的四个顶点)
  243. Vector2[] innerCorners = screenPositions.ToArray();
  244. // 分别绘制四个蒙版区域
  245. // 1. 左上区域:围绕左上角和内框左上、右上
  246. AddQuad(vh, screenCorners[3], innerCorners[3], innerCorners[2], screenCorners[2]);
  247. // 2. 右上区域:围绕右上角和内框右上、右下
  248. AddQuad(vh, innerCorners[2], screenCorners[2], screenCorners[1], innerCorners[1]);
  249. // 3. 右下区域:围绕右下角和内框右下、左下
  250. AddQuad(vh, innerCorners[0], innerCorners[1], screenCorners[1], screenCorners[0]);
  251. // 4. 左下区域:围绕左下角和内框左下、左上
  252. AddQuad(vh, screenCorners[3], screenCorners[0], innerCorners[0], innerCorners[3]);
  253. }
  254. private void AddQuad(VertexHelper vh, Vector2 corner1, Vector2 corner2, Vector2 corner3, Vector2 corner4)
  255. {
  256. UIVertex vert = UIVertex.simpleVert;
  257. vert.color = maskColor;
  258. vert.position = corner1;
  259. vh.AddVert(vert);
  260. vert.position = corner2;
  261. vh.AddVert(vert);
  262. vert.position = corner3;
  263. vh.AddVert(vert);
  264. vert.position = corner4;
  265. vh.AddVert(vert);
  266. //Debug.Log("vh.currentVertCount:"+ vh.currentVertCount);
  267. int startIndex = vh.currentVertCount - 4;
  268. vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2);
  269. vh.AddTriangle(startIndex + 2, startIndex + 3, startIndex);
  270. }
  271. /// <summary>
  272. /// 1. 计算角度方向:
  273. /// 使用 Vector2.Angle 可以得到两个向量之间的夹角大小,但它不能确定角度的方向。为此,我们需要使用 Mathf.Atan2 来计算相对坐标的角度。Atan2 可以返回一个在 -π 到 π 之间的角度值,并且考虑了顺时针和逆时针的方向。
  274. /// 2. 从 X 轴正方向为 0 计算角度:
  275. /// 将角度计算为相对于 x 轴正方向的角度,并根据 Atan2 结果进行调整。
  276. /// </summary>
  277. /// <param name="vh"></param>
  278. private void DrawFansAtCorners(VertexHelper vh)
  279. {
  280. List<Vector2> _screenPositions = new List<Vector2>(screenPositions);
  281. if (loop)
  282. {
  283. _screenPositions.Add(screenPositions[0]);
  284. _screenPositions.Add(screenPositions[1]);
  285. }
  286. //比如现在是6个点,实际从第二个点开始绘制
  287. for (int i = 1; i < _screenPositions.Count - 1; i++)
  288. {
  289. Vector2 previousPos = _screenPositions[i - 1];
  290. Vector2 currentPos = _screenPositions[i];
  291. Vector2 nextPos = _screenPositions[i + 1];
  292. // 计算当前点到前一点的方向
  293. Vector2 prevDir = (currentPos - previousPos).normalized;
  294. // 计算当前点到下一点的方向
  295. Vector2 currentDir = (nextPos - currentPos).normalized;
  296. // 使用 Atan2 计算方向相对于 x 轴的角度
  297. float prevAngle = Mathf.Atan2(prevDir.y, prevDir.x) * Mathf.Rad2Deg; // 前一个方向相对于 x 轴的角度
  298. float currentAngle = Mathf.Atan2(currentDir.y, currentDir.x) * Mathf.Rad2Deg; // 当前方向相对于 x 轴的角度
  299. // 计算两个方向之间的角度差
  300. float angleBetween = Vector2.Angle(prevDir, currentDir);
  301. // 判断旋转方向
  302. float cross = prevDir.x * currentDir.y - prevDir.y * currentDir.x;
  303. if (cross < 0)
  304. {
  305. // 逆时针旋转
  306. angleBetween = 360f - angleBetween;
  307. }
  308. // 内角的计算(补充180度)
  309. float innerAngle = 180f - angleBetween;
  310. // 计算开始角度,这里用的是 x 轴为起始点来计算
  311. float startAngle = currentAngle;
  312. //Debug.Log($"Index {i}: startAngle = {startAngle}, innerAngle = {innerAngle}");
  313. // 根据当前角的位置调整内角和起始角
  314. DrawFanAtCorner(vh, currentPos, startAngle, innerAngle, fanInnerRadius, fanOuterRadius, fanSegments, fanColor);
  315. // 计算箭头的中心角度,确保角度在 0-360° 范围内
  316. float centerAngle = (startAngle + innerAngle / 2) % 360f;
  317. float radians = Mathf.Deg2Rad * centerAngle;
  318. // 计算箭头位置:在扇形外半径的基础上延长一定距离(箭头偏移量)
  319. float arrowOffset = fanOuterRadius + arrowDis;
  320. Vector2 arrowPosition = currentPos + new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * arrowOffset;
  321. // 箭头方向
  322. Vector2 arrowDirection = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)).normalized;
  323. // 将箭头信息保存到列表中
  324. arrowInfos.Add(new ArrowInfo(arrowPosition, arrowDirection));
  325. // 在所有扇形处绘制箭头
  326. // 在扇形中心绘制箭头
  327. if (bDrawArrow)
  328. {
  329. // 调试信息
  330. //Debug.Log($"Index {i}: arrowPosition = {arrowPosition}, startAngle = {startAngle}, centerAngle = {centerAngle}, direction = {arrowDirection}");
  331. // 绘制箭头
  332. DrawArrow(vh, arrowPosition, arrowDirection, arrowLength, arrowWidth, arrowHeadHeight);
  333. }
  334. }
  335. }
  336. private void DrawFanAtCorner(VertexHelper vh, Vector2 center, float startAngle, float angleDegree, float innerRadius, float outerRadius, int segments ,Color color)
  337. {
  338. UIVertex vert = UIVertex.simpleVert;
  339. vert.color = color;
  340. float angleRad = Mathf.Deg2Rad * angleDegree; // 将绘制角度转换为弧度
  341. float startAngleRad = Mathf.Deg2Rad * startAngle; // 将起始角度转换为弧度
  342. float angleStep = angleRad / segments; // 每个扇形段的角度步长
  343. int initialVertCount = vh.currentVertCount; // 记录当前顶点数量
  344. // 添加中心点顶点
  345. vert.position = center;
  346. vert.uv0 = new Vector2(0.5f, 0.5f); // 中心UV值
  347. vh.AddVert(vert);
  348. // 绘制外圈和内圈的顶点
  349. for (int i = 0; i <= segments; i++)
  350. {
  351. float currentAngle = startAngleRad + i * angleStep;
  352. float cosA = Mathf.Cos(currentAngle);
  353. float sinA = Mathf.Sin(currentAngle);
  354. // 外圈顶点
  355. vert.position = center + new Vector2(cosA * outerRadius, sinA * outerRadius);
  356. vert.uv0 = new Vector2(0.5f + cosA * 0.5f, 0.5f + sinA * 0.5f);
  357. vh.AddVert(vert);
  358. // 内圈顶点
  359. vert.position = center + new Vector2(cosA * innerRadius, sinA * innerRadius);
  360. vert.uv0 = new Vector2(0.5f + cosA * innerRadius / outerRadius * 0.5f, 0.5f + sinA * innerRadius / outerRadius * 0.5f);
  361. vh.AddVert(vert);
  362. }
  363. // 创建三角形索引来绘制扇形
  364. for (int i = 1; i <= segments; i++)
  365. {
  366. int baseIndex = initialVertCount + (i - 1) * 2;
  367. vh.AddTriangle(initialVertCount, baseIndex + 1, baseIndex + 3); // 中心点连接外圈
  368. vh.AddTriangle(baseIndex + 1, baseIndex + 2, baseIndex + 3); // 内圈连接外圈
  369. }
  370. }
  371. // 新增箭头绘制方法
  372. private void DrawArrow(VertexHelper vh, Vector2 position, Vector2 direction, float arrowLength, float arrowWidth, float arrowHeadHeight)
  373. {
  374. // 标准化方向向量
  375. direction.Normalize();
  376. // 反向箭头的方向(箭头指向扇形方向)
  377. Vector2 reversedDirection = -direction;
  378. // 箭头尾部位置
  379. Vector2 basePosition = position - reversedDirection * arrowLength;
  380. // 计算垂直向量用于箭头宽度
  381. Vector2 perpendicular = new Vector2(-reversedDirection.y, reversedDirection.x);
  382. // 让箭头矩形部分的宽度比三角形的底边窄
  383. float adjustedArrowWidth = arrowWidth * 0.6f; // 调整宽度,使矩形比三角形窄
  384. // 箭头矩形部分的四个顶点
  385. Vector2 baseLeft = basePosition + perpendicular * (adjustedArrowWidth / 2);
  386. Vector2 baseRight = basePosition - perpendicular * (adjustedArrowWidth / 2);
  387. Vector2 headLeft = position + perpendicular * (adjustedArrowWidth / 2);
  388. Vector2 headRight = position - perpendicular * (adjustedArrowWidth / 2);
  389. Vector2 triangleHeadLeft = position + perpendicular * (arrowHeadHeight / 2);
  390. Vector2 triangleHeadRight = position - perpendicular * (arrowHeadHeight / 2);
  391. // 顶点颜色
  392. UIVertex vert = UIVertex.simpleVert;
  393. vert.color = arrowColor;
  394. // 先添加矩形部分的顶点
  395. int rectStartIndex = vh.currentVertCount;
  396. vert.position = baseLeft;
  397. vh.AddVert(vert);
  398. vert.position = baseRight;
  399. vh.AddVert(vert);
  400. vert.position = headLeft;
  401. vh.AddVert(vert);
  402. vert.position = headRight;
  403. vh.AddVert(vert);
  404. // 添加矩形部分的两条三角形索引
  405. vh.AddTriangle(rectStartIndex, rectStartIndex + 1, rectStartIndex + 2);
  406. vh.AddTriangle(rectStartIndex + 1, rectStartIndex + 3, rectStartIndex + 2);
  407. // 然后添加三角形头部的顶点
  408. Vector2 headPosition = position + reversedDirection * arrowHeadHeight;
  409. int headStartIndex = vh.currentVertCount;
  410. vert.position = triangleHeadLeft;
  411. vh.AddVert(vert);
  412. vert.position = triangleHeadRight;
  413. vh.AddVert(vert);
  414. vert.position = headPosition; // 添加箭头尖端
  415. vh.AddVert(vert);
  416. // 添加三角形的索引
  417. int triangleStartIndex = vh.currentVertCount - 3; // 三角形部分的开始索引
  418. vh.AddTriangle(triangleStartIndex, triangleStartIndex + 1, triangleStartIndex + 2); // 三角形索引
  419. }
  420. //private void LateUpdate()
  421. //{
  422. // foreach (var quadObj in quadObjects)
  423. // {
  424. // if (quadObj != null)
  425. // {
  426. // objectPool.Push(quadObj);
  427. // }
  428. // }
  429. // quadObjects.Clear();
  430. // for (int i = 0; i < quadsToDraw.Count; i++)
  431. // {
  432. // GameObject quadGO = GetQuadObject();
  433. // if (quadGO != null)
  434. // {
  435. // quadGO.SetActive(true);
  436. // quadGO.GetComponent<RectTransform>().anchoredPosition = quadsToDraw[i];
  437. // Text quadTextComponent = quadGO.GetComponent<Text>();
  438. // quadTextComponent.text = quadTextToDraw[i];
  439. // quadTextComponent.fontSize = quadFontSize;
  440. // quadTextComponent.color = quadTextColor;
  441. // quadTextComponent.alignment = TextAnchor.MiddleCenter;
  442. // }
  443. // }
  444. // quadsToDraw.Clear();
  445. // quadTextToDraw.Clear();
  446. //}
  447. //private GameObject GetQuadObject()
  448. //{
  449. // if (objectPool.Count > 0)
  450. // {
  451. // GameObject quadGO = objectPool.Pop();
  452. // if (quadGO != null)
  453. // {
  454. // quadObjects.Add(quadGO);
  455. // return quadGO;
  456. // }
  457. // }
  458. // if (quadObjects.Count < ObjectPoolLimit)
  459. // {
  460. // GameObject newQuadGO = new GameObject("QuadText", typeof(RectTransform), typeof(Text));
  461. // newQuadGO.transform.SetParent(this.transform);
  462. // Text quadTextComponent = newQuadGO.GetComponent<Text>();
  463. // quadTextComponent.alignment = TextAnchor.MiddleCenter;
  464. // quadTextComponent.rectTransform.sizeDelta = new Vector2(quadrilateralSize.x, quadrilateralSize.y);
  465. // quadObjects.Add(newQuadGO);
  466. // return newQuadGO;
  467. // }
  468. // return null;
  469. //}
  470. }
  471. }