關於用LineRenderer實現畫圖功能
// A code block
var foo = 'bar';
// An highlighted block
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
private LineRenderer currentLine;
public Material lineMaterial;
private float paintSize = 0.4f;
private Color paintColor = Color.blue;
private List<Vector3> positions = new List<Vector3>();
private bool isMouseDown;
private Vector3 lastMousePosition = Vector3.zero;
private float lineDistance = 0.02f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = new GameObject();
go.transform.SetParent(this.transform);
currentLine = go.AddComponent<LineRenderer>();
currentLine.material = lineMaterial;
currentLine.startWidth = paintSize;
currentLine.endWidth = paintSize;
currentLine.startColor = paintColor;
currentLine.endColor = paintColor;
currentLine.numCornerVertices = 5;
currentLine.numCapVertices = 5;
Vector3 position = GetMousePoint();
AddPosition(position);
isMouseDown = true;
lineDistance+=0.02f;
}
if (isMouseDown)
{
Vector3 position = GetMousePoint();
if (Vector3.Distance(position,lastMousePosition)> 0.1f)
{
AddPosition(position);
}
}
if (Input.GetMouseButtonUp(0))
{
currentLine = null;
positions.Clear();
isMouseDown = false;
}
}
Vector3 GetMousePoint()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool isCollider = Physics.Raycast(ray,out hit);
if (isCollider)
{
return hit.point;
}
return Vector3.zero;
}
void AddPosition(Vector3 position)
{
position.z -= lineDistance;
positions.Add(position);
currentLine.positionCount = positions.Count;
currentLine.SetPositions(positions.ToArray());
lastMousePosition = position;
}
}