首先我們來看下LineRenderer的一些參數屬性
image.png
Color里面的顏色想要設置成功需要把材質的Shader設置為Sprites->Default
image.png
image.png
下面是創(chuàng)建腳本LineRendererController寫入以下代碼掛載在LineRenderers游戲對象上
using System.Collections.Generic;
using UnityEngine;
public class LineRendererController : MonoBehaviour {
public Color color=Color.red;
public float painSize = 0.1f;
private LineRenderer CurrentLine;
public Material materia;
private List<Vector3> positions = new List<Vector3>();
private bool isMouseDown = false;//是否一直按住鼠標
private Vector3 lastMousePosition;//下一個位置
#region 選擇顏色
public void OnRedColorChanged(bool isOn)
{
if (isOn)
{
color = Color.red;
}
}
public void OnGreenColorChanged(bool isOn)
{
if (isOn)
{
color = Color.green;
}
}
public void OnBlueColorChanged(bool isOn)
{
if (isOn)
{
color = Color.blue;
}
}
#endregion
#region 選擇大小
public void OnPoint1Changed(bool isOn)
{
if (isOn)
{
painSize = 0.1f;
}
}
public void OnPoint2Changed(bool isOn)
{
if (isOn)
{
painSize =0.2f;
}
}
public void OnPoint4Changed(bool isOn)
{
if (isOn)
{
painSize =0.4f;
}
}
#endregion
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
//創(chuàng)建一個游戲對象命名并添加LineRenderer組件
GameObject go = new GameObject();
go.name = "LineRenderer";
CurrentLine = go.AddComponent<LineRenderer>();
go.transform.SetParent(this.transform);
//給Line添加material設置Lin寬度大小和顏色
CurrentLine.material = this.materia;
CurrentLine.startWidth=painSize;
CurrentLine.endWidth = painSize;
CurrentLine.startColor = color;
CurrentLine.endColor = color;
positions.Clear();
//設置Line轉折的時候的圓滑度
CurrentLine.numCornerVertices = 5;
//設置Line起始點和結束的圓滑度
CurrentLine.numCapVertices = 5;
Vector3 position = GetMousePoint();//獲取位置Position
//把Position添加到List
AddPosition(position);
isMouseDown = true;
}
//如果一直按著鼠標
if (isMouseDown)
{
//一直獲取位置Position
Vector3 position = GetMousePoint();
// 如果當前位置和下一個位置大于0.2才添加位置
if (Vector3.Distance(position,lastMousePosition)>0.2f)
AddPosition(position);
}
if (Input.GetMouseButtonUp(0))
{
CurrentLine = null;
positions.Clear();
isMouseDown = false;
}
}
//添加位置并畫線
void AddPosition(Vector3 position)
{
//把畫Line的位置想Z軸移動-1碾篡,就是不讓Line和Plane重合
position.z -= 0.1f;
positions.Add(position);//添加位置
//當前Line的總共需要描點的Count
CurrentLine.positionCount = positions.Count;
//把每次描點的位置添加到LinRenderer組建里
CurrentLine.SetPositions(positions.ToArray());
//下一個Lin位置設置為當前位置
lastMousePosition = position;
}
//發(fā)射射線獲取位置Position
Vector3 GetMousePoint()
{
Ray ray= Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray,out hit))
{
return hit.point;
}
return Vector3.zero;
}
}
最后把代碼里面三個選擇顏色和三個設置大小的方法對應綁上Toggle上的OnValueChanged上
image.png
這樣我畫圖的小程序就完成了
image.png