using System.Collections; using System.Collections.Generic; using Unity.VisualScripting; using UnityEngine; using UnityEngine.EventSystems; using XCharts.Runtime; public enum LineDir { Out, In }; public enum ZYTime { Before, After, }; public class LinePath : MonoBehaviour { public LineDir lineDir; public string startPos; public string endPos; public string linePathContent; public int manNum; public int homeNum; public int completeNum; public string dateTime; public LineRenderer lineRenderer; private List points = new List(); // Use this for initialization PolygonCollider2D polygonCollider; //添加多边形碰撞 private float colliderWidth; void Start() { lineRenderer = this.GetComponent(); polygonCollider = gameObject.GetComponent(); // 获取LineRenderer的点在世界坐标系中的位置 Vector3[] worldPositions = new Vector3[2]; lineRenderer.GetPositions(worldPositions); // 将世界坐标系中的点转换为局部坐标系 Vector2[] localPositions = new Vector2[worldPositions.Length]; for (int i = 0; i < worldPositions.Length; i++) { Vector3 localPos = transform.InverseTransformPoint(worldPositions[i]); localPositions[i] = new Vector2(localPos.x, localPos.y); // 只使用X和Y分量 } List colliderPath = GetColliderPath(localPositions); // 设置PolygonCollider2D的路径 polygonCollider.SetPath(0, colliderPath.ToArray()); // 调整PolygonCollider2D的位置以匹配LineRenderer的Z轴位置 AdjustColliderZPosition(worldPositions); } List GetColliderPath(Vector2[] pointList2) { // 碰撞体宽度 colliderWidth = lineRenderer.startWidth; List edgePointList = new List(); for (int j = 1; j < pointList2.Length; j++) { // 当前点指向前一点的向量 Vector2 distanceVector = pointList2[j - 1] - pointList2[j]; // 法线向量 Vector2 crossVector = new Vector2(-distanceVector.y, distanceVector.x); // 标准化,单位向量 Vector2 offsetVector = crossVector.normalized; // 沿法线方向与法线反方向各偏移一定距离 Vector2 up = pointList2[j - 1] + 0.5f * colliderWidth * offsetVector; Vector2 down = pointList2[j - 1] - 0.5f * colliderWidth * offsetVector; // 分别加到List的首位和末尾,保证List中的点位可以围成一个闭合且不交叉的折线 edgePointList.Insert(0, down); edgePointList.Add(up); // 加入最后一点 if (j == pointList2.Length - 1) { up = pointList2[j] + 0.5f * colliderWidth * offsetVector; down = pointList2[j] - 0.5f * colliderWidth * offsetVector; edgePointList.Insert(0, down); edgePointList.Add(up); } } // 返回点位 return edgePointList; } void AdjustColliderZPosition(Vector3[] worldPositions) { if (worldPositions.Length == 0) return; // 获取LineRenderer的平均Z位置 float averageZ = 0; foreach (var pos in worldPositions) { averageZ += pos.z; } averageZ /= worldPositions.Length; // 设置PolygonCollider2D的Z位置 var colliderTransform = polygonCollider.transform; var colliderPosition = colliderTransform.position; colliderTransform.position = new Vector3(colliderPosition.x, colliderPosition.y, averageZ); } public void OnShow() { if (RKZYLayer.lineInfoStatic) { RKZYLayer.lineInfoStatic.SetData(this); //RKZYLayer.lineInfoStatic.GetComponent().anchoredPosition = this.GetComponent().anchoredPosition; RKZYLayer.lineInfoStatic.linePaths.Add(this); } } }