通过unity内置的LineRenderer 绘制线条。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Painter : MonoBehaviour
{
//颜色
public Color painterColor = Color.yellow;
//宽度
public float Width=0.2f;
private LineRenderer currentLineRenderer;
private int currentPoint = -1;
private Vector3 lastPoint;
private bool isStart=false;
public void EndDraw()
{
//鼠标抬起后,清除上一次的笔记记录。
currentLineRenderer = null;
currentPoint = -1;
}
public bool IsLine = true;
public void Draw()
{
if(IsLine)
{
DrawLine();
}
else
{
DrawSeal();
}
}
//划线
public void DrawLine()
{
Vector3 point = transform.position;
//判断现在是否有LineRenderer,配合鼠标抬起,可以再次下笔的时候新建一个画笔
if (!currentLineRenderer)
{
GameObject line = new GameObject("Line");
currentLineRenderer = line.AddComponent<LineRenderer>();
currentLineRenderer.numCapVertices = 90;
//设置你喜欢的宽度
currentLineRenderer.startWidth = currentLineRenderer.endWidth = Width;
//给一个你喜欢的材质球
currentLineRenderer.material = new Material(Shader.Find("Particles/Additive"));
currentLineRenderer.startColor = painterColor;
currentLineRenderer.endColor = painterColor;
currentLineRenderer.material.SetColor("_TintColor", painterColor);
currentLineRenderer.positionCount = 0;
PainterContrl.Instance.AllLine.Add(currentLineRenderer);
}
//如果鼠标停在一个地方,就没必要一直加点了,提升效率
if (lastPoint != point)
{
//画之前,先给LineRenderer扩容,它并不聪明
currentLineRenderer.positionCount++;
//把点给它,它自己会画
currentLineRenderer.SetPosition(++currentPoint, point);
lastPoint = point;
}
}
//画印章
public void DrawSeal()
{
Vector3 point = transform.position;
if(IsOne)
{
IsOne = false;
CreatSeal(point);
}
else
{
float Dis = Vector3.Distance(lastPoint, point);
if(Dis > SealMidOffset)
{
CreatSeal(point);
}
}
}
private bool IsOne = true;
public float SealMidOffset = 1f;
[HideInInspector]public float SealWidth = 1;
[HideInInspector] public float SealHeight = 1f;
private void CreatSeal(Vector3 Point)
{
GameObject line = new GameObject("Line");
currentLineRenderer = line.AddComponent<LineRenderer>();
//给一个你喜欢的材质球
currentLineRenderer.material = new Material(Shader.Find("Particles/Additive"));
//设置你喜欢的宽度
currentLineRenderer.startWidth = SealHeight;
currentLineRenderer.endWidth = SealHeight;
currentLineRenderer.material.SetTexture("_MainTex", PainterContrl.Instance.Seals[PainterContrl.Instance.SealIndex]);
currentLineRenderer.positionCount = 2;
currentLineRenderer.SetPosition(0, Point - Vector3.up * SealWidth / 2);
currentLineRenderer.SetPosition(1, Point + Vector3.up * SealWidth / 2);
PainterContrl.Instance.AllLine.Add(currentLineRenderer);
lastPoint = Point;
currentLineRenderer = null;
}
//private void OnGUI()
//{
// GUI.skin.label.fontSize = 50;
// GUI.color = Color.red;
// GUILayout.Label(painterColor.ToString());
//}
}