最近项目里需要做一个画线的小游戏,LineRenderer不是很好用,自己撸了一个小工具,效果如下
下面上代码
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using FMCShape;
public class MyLineDrawer : Image
{
public List<Vector2> pointer = new List<Vector2>();
public float radio = 30;
private int headPointCount = 7;//头部顶点数量
private Vector2 offset;
protected override void Awake()
{
base.Awake();
offset = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
}
protected override void OnPopulateMesh(VertexHelper toFill)
{
toFill.Clear();
if (pointer.Count >= 2)
{
for (int i = 1; i < pointer.Count; i++)
{
Draw(toFill, pointer[i - 1], pointer[i]);
}
}
}
public void AddPointer(Vector2 pointer)
{
this.pointer.Add(pointer);
ReDraw();
}
public void ReDraw()
{
SetVerticesDirty();
}
void Draw(VertexHelper vh, Vector2 start, Vector2 end)
{
Vector2 to = end - start;
Vector2 nor_to = to.normalized * radio + start;
Vector2 up = MathHepler.RotateVector2(90, nor_to, start);
Vector2 down = MathHepler.RotateVector2(-90, nor_to, start);
Vector2 up_end = up + to;
Vector2 down_end = down + to;
//添加直线
AddQuad(vh, up, down, up_end, down_end);
List<Vector2> tempPointer = ListPool<Vector2>.Get();
//添加左边头部
float angel = 180 / (headPointCount + 1);
tempPointer.Add(down);
for (float i = -angel; i > -180; i -= angel)
{
tempPointer.Add(MathHepler.RotateVector2(i, down, start));
}
tempPointer.Add(up);
for (int i = 1; i < tempPointer.Count; i++)
{
AddVert(vh, tempPointer[i - 1], tempPointer[i], start);
}
//添加右边头部
tempPointer.Clear();
tempPointer.Add(up_end);
for (float i = -angel; i > -180; i -= angel)
{
tempPointer.Add(MathHepler.RotateVector2(i, up_end, end));
}
tempPointer.Add(down_end);
for (int i = 1; i < tempPointer.Count; i++)
{
AddVert(vh, tempPointer[i - 1], tempPointer[i], end);
}
ListPool<Vector2>.Release(tempPointer);
}
void AddVert(VertexHelper vh, Vector2 pos1, Vector2 pos2, Vector2 pos3)
{
AddVert(vh, CreateEmptyVertex(pos1), CreateEmptyVertex(pos2), CreateEmptyVertex(pos3));
}
void AddVert(VertexHelper vh, UIVertex v1, UIVertex v2, UIVertex v3)
{
int index = vh.currentVertCount;
vh.AddVert(v1);
vh.AddVert(v2);
vh.AddVert(v3);
vh.AddTriangle(index, index + 1, index + 2);
}
void AddQuad(VertexHelper vh, Vector2 pos1, Vector2 pos2, Vector2 pos3, Vector2 pos4)
{
AddQuad(vh, CreateEmptyVertex(pos1), CreateEmptyVertex(pos2), CreateEmptyVertex(pos3), CreateEmptyVertex(pos4));
}
void AddQuad(VertexHelper vh, UIVertex v1, UIVertex v2, UIVertex v3, UIVertex v4)
{
int index = vh.currentVertCount;
vh.AddVert(v1);
vh.AddVert(v2);
vh.AddVert(v3);
vh.AddVert(v4);
vh.AddTriangle(index, index + 1, index + 2);
vh.AddTriangle(index + 2, index + 3, index + 1);
}
UIVertex CreateEmptyVertex(Vector2 pos)
{
UIVertex v = new UIVertex();
v.position = pos;
//需要修改颜色,在这里改就可以了
v.color = color;
v.uv0 = Vector2.zero;
return v;
}
}
使用时当做一个image就可以,代码如下
public MyLineDrawer line;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
line.AddPointer(Input.mousePosition-new Vector3(540,960));
}
}