LineRenderer线渲染器主要是用于在3D中渲染线段,在这里要注意LineRenderer渲染出的线段的两个端点是3D世界中的点,即它是属于世界坐标(World
Space)中的。

这里我设置了一组单选按钮,通过单选按钮控制线条颜色和粗细。为了方便查看线条,我新建了一个Plane作为背景,根据鼠标按下时的位置,来持续绘制线段

以下为主要代码
using System.Collections; using System.Collections.Generic; using UnityEngine;
using UnityEngine.EventSystems; public class MsPaint : MonoBehaviour { //线条颜色
private Color paintColor = Color.red; //线条粗细 private float paintSize = 0.1f;
//用来存储鼠标位置 private List<Vector3> paintPos = new List<Vector3>(); private bool
isPressed;//鼠标是否长按 private LineRenderer ren; private Vector3 lastPos; //线条材质
public Material material; #region 单选框点击事件 public void OnRedChange(bool isOn) {
if (isOn) { paintColor = Color.red; } } public void OnGreenChange(bool isOn) {
if (isOn) { paintColor = Color.green; } } public void OnBlueChange(bool isOn) {
if (isOn) { paintColor = Color.blue; } } public void OnPaint1(bool isOn) { if
(isOn) { paintSize = 0.1f; } } public void OnPaint2(bool isOn) { if (isOn) {
paintSize = 0.2f; } } public void OnPaint4(bool isOn) { if (isOn) { paintSize =
0.4f; } } #endregion private void Update() { if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject()) { //判断是否点击UI return; }
//创建一个空物体,给他动态添加LineRenderer组件 GameObject line = new GameObject();
line.transform.SetParent(transform); ren = line.AddComponent<LineRenderer>();
ren.material = material;//设置材质 ren.startColor = paintColor;//设置颜色 ren.endColor
= paintColor; ren.startWidth = paintSize;//设置线的宽度 ren.endWidth = paintSize;
ren.numCapVertices = 2;//设置端点圆滑度 ren.numCornerVertices = 2;//设置拐角圆滑度,顶点越多越圆滑
lastPos = GetMousePosition();//获取鼠标在世界坐标中的位置 paintPos.Add(lastPos);
ren.positionCount = paintPos.Count;//设置构成线条的点的数量
ren.SetPositions(paintPos.ToArray()); isPressed = true; } if (isPressed) {
//鼠标长按开始绘制,两点距离大于0.1开始添加点 if (Vector3.Distance(lastPos, GetMousePosition()) >
0.1f) { paintPos.Add(GetMousePosition()); lastPos = GetMousePosition(); }
ren.positionCount = paintPos.Count; ren.SetPositions(paintPos.ToArray()); } if
(Input.GetMouseButtonUp(0)) { isPressed = false; paintPos.Clear(); ren = null;
} } /// <summary> /// 获取鼠标位置,将屏幕坐标转为世界坐标 /// </summary> /// <returns></returns>
private Vector3 GetMousePosition() { Ray ray =
Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; bool
isCollider = Physics.Raycast(ray, out hit); if (isCollider) { return hit.point
- new Vector3(0, 0, 0.01f);//避免遮挡 } return Vector3.zero; } }
 

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信