通過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());
//}
}