using System.Collections.Generic;
using UnityEngine;
public class Mspaint : MonoBehaviour
{
private Color paintColor = Color.red;
private float paintSize = 0.1f;
private LineRenderer currentLine;
public Material lineMaterial;
private List<Vector3> positions = new List<Vector3>();
private bool isMouseDown = false;
private Vector3 lastMousePosition = Vector3.zero;
private float lineDistance = 0.02f;
void Update()
{
if (Input.GetMouseButtonDown(0))// 2是鼠标滑轮,0是鼠标左键,1是鼠标右键
{
//创建空物体,添加LineRenderer并设置基础属性
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;
//使得LineRenderer线平滑,起始点圆滑,拐角点圆滑
currentLine.numCornerVertices = 5;
currentLine.numCapVertices = 5;
//给LineRenderer设置开始位置
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;
}
}
void AddPosition(Vector3 position)
{
//使得线靠近相机,不被Plane重叠一起,,使得后画线更靠近相机,实现后画点覆盖前面画的点
position.z -= lineDistance;
positions.Add(position);
currentLine.positionCount = positions.Count; //currentLine.numPositions = positions.Count; // numPositions 已弃用,使用positionCount代替
currentLine.SetPositions(positions.ToArray());
//记录上次添加的点
lastMousePosition = position;
}
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;
}
#region onvaluechanged method
public void OnRedColorChanged(bool isOn)
{
if (isOn)
paintColor = Color.red;
}
public void OnGreenColorChanged(bool isOn)
{
if (isOn)
paintColor = Color.green;
}
public void OnBlueColorChanged(bool isOn)
{
if (isOn)
paintColor = Color.blue;
}
public void OnPoint1SizeChanged(bool isOn)
{
if (isOn)
paintSize = 0.1f;
}
public void OnPoint2SizeChanged(bool isOn)
{
if (isOn)
paintSize = 0.2f;
}
public void OnPoint4SizeChanged(bool isOn)
{
if (isOn)
paintSize = 0.4f;
}
#endregion
}