83 lines
2.2 KiB
C#
83 lines
2.2 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
#if UNITY_EDITOR
|
|
using UnityEditor;
|
|
#endif
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class UILineRenderer : Graphic
|
|
{
|
|
public List<Vector2> points = new List<Vector2>();
|
|
public float thickness = 10f;
|
|
|
|
float GetAngle(Vector2 source, Vector2 target)
|
|
{
|
|
return (float)(Mathf.Atan2(target.y - source.y, target.x - source.x)) * Mathf.Rad2Deg;
|
|
}
|
|
protected override void OnPopulateMesh(VertexHelper vh)
|
|
{
|
|
vh.Clear();
|
|
|
|
if (points.Count < 2) return;
|
|
|
|
float angle = 0;
|
|
for (int i = 0; i < points.Count; i++)
|
|
{
|
|
Vector2 point = points[i];
|
|
|
|
if (i < points.Count - 1)
|
|
{
|
|
angle = GetAngle(points[i], points[i + 1]) + 45f;
|
|
}
|
|
|
|
DrawVertices(point, vh, angle);
|
|
}
|
|
|
|
for (int i = 0; i < points.Count - 1; ++i)
|
|
{
|
|
int index = i * 2;
|
|
vh.AddTriangle(index + 0, index + 1, index + 3);
|
|
vh.AddTriangle(index + 3, index + 2, index + 0);
|
|
}
|
|
}
|
|
|
|
void DrawVertices(Vector2 point, VertexHelper vh, float angle)
|
|
{
|
|
UIVertex vertex = UIVertex.simpleVert;
|
|
vertex.color = color;
|
|
|
|
vertex.position = Quaternion.Euler(0, 0, angle) * new Vector3(-thickness / 2, 0);
|
|
vertex.position += new Vector3(point.x, point.y);
|
|
vh.AddVert(vertex);
|
|
|
|
vertex.position = Quaternion.Euler(0, 0, angle) * new Vector3(thickness / 2, 0);
|
|
vertex.position += new Vector3(point.x, point.y);
|
|
vh.AddVert(vertex);
|
|
}
|
|
|
|
private Color previousColor;
|
|
public void Select()
|
|
{
|
|
previousColor = color;
|
|
color = Color.yellow;
|
|
transform.SetAsLastSibling();
|
|
}
|
|
public void Deselect()
|
|
{
|
|
color = previousColor;
|
|
}
|
|
|
|
#if UNITY_EDITOR
|
|
[MenuItem("GameObject/Gather and Defend/UILineRenderer")]
|
|
public static void CreateUILineRenderer()
|
|
{
|
|
var line = new GameObject("UILineRenderer");
|
|
line.transform.parent = Selection.activeTransform;
|
|
line.AddComponent<CanvasRenderer>();
|
|
line.AddComponent<UILineRenderer>();
|
|
EditorUtility.SetDirty(line);
|
|
}
|
|
#endif
|
|
}
|