NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/Utils/DrawLine.cs

72 lines
2.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DrawLine : MaskableGraphic, ICanvasRaycastFilter
{
List<List<UIVertex>> vertexQuadList = new List<List<UIVertex>>();
public Vector3 startPos;
public Vector3 endPos;
void Update()
{
//设定rect大小正好能圈住线
rectTransform.position = endPos + (startPos - endPos) / 2f;
rectTransform.sizeDelta = new Vector2(Mathf.Abs(endPos.x - startPos.x), Mathf.Abs(endPos.y - startPos.y));
}
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
bool isEnterMesh = false;
for (int i = 0; i < vertexQuadList.Count; i++)
{
if (IsContainInQuad(sp, transform.position + vertexQuadList[i][0].position, transform.position + vertexQuadList[i][1].position, transform.position + vertexQuadList[i][2].position, transform.position + vertexQuadList[i][3].position))
{
isEnterMesh = true;
break;
}
}
return isEnterMesh;
}
bool IsContainInQuad(Vector3 point, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
// p1-----p2
// | |
// | point |
// | |
// p4-----p3
Vector2 p1p2 = p1 - p2;
Vector2 p1p = p1 - point;
Vector2 p3p4 = p3 - p4;
Vector2 p3p = p3 - point;
Vector2 p4p1 = p4 - p1;
Vector2 p4p = p4 - point;
Vector2 p2p3 = p2 - p3;
Vector2 p2p = p2 - point;
bool isBetweenP1P2_P3P4 = CrossAB(p1p2, p1p) * CrossAB(p3p4, p3p) > 0;
bool isBetweenP4P1_P2P3 = CrossAB(p4p1, p4p) * CrossAB(p2p3, p2p) > 0;
return isBetweenP1P2_P3P4 && isBetweenP4P1_P2P3;
}
float CrossAB(Vector2 a, Vector2 b)
{
return a.x * b.y - b.x * a.y;
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear(); // 清空顶点和索引数据
for (int i = 0; i < vertexQuadList.Count; i++)
{
vh.AddUIVertexQuad(vertexQuadList[i].ToArray());
}
}
}