Unity LineRenderer画曲线
一、新建一个空物体
第一步:在场景中新建一个空物体,以便后面步骤挂载脚本。
二、编写脚本
代码如下(示例):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class test : MonoBehaviour
{
//线条粗细
private float paintSize = 0.1f;
//用来存储鼠标位置
private List<Vector3> mousePos = new List<Vector3>();
//鼠标是否长按
private bool isLongPressed;
private LineRenderer lr;
private Vector3 lastPos;
//线条材质
public Material material;
//设置父容器
public Transform fatherTrasform;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
//动态添加LineRenderer组件
GameObject line = new GameObject();
line.transform.SetParent(transform);
lr = line.AddComponent<LineRenderer>();
line.transform.parent = fatherTrasform.transform;
//初始化
InitLineRender();
}
if (Input.GetMouseButtonUp(0))
{
isLongPressed = false;
mousePos.Clear();
lr = null;
}
if (isLongPressed)
{
//长按绘制且两点距离大于0.2才开始添加点
if (Vector3.Distance(lastPos, GetMousePosition()) > =0.2f)
{
paintPos.Add(GetMousePosition());
lastPos = GetMousePosition();
}
lr.positionCount = mousePos.Count;
lr.SetPositions(mousePos.ToArray());
}
}
void InitLineRender()
{
lr.material = material;//设置材质
lr.endColor = paintColor;
lr.startWidth = paintSize;//设置线的宽度
lr.endWidth = paintSize;
lr.numCapVertices = 2;//设置端点圆滑度
lr.numCornerVertices = 2;//设置拐角圆滑度,顶点越多越圆滑
lastPos = GetMousePosition();//获取鼠标在世界坐标中的位置
mousePos.Add(lastPos);
lr.positionCount = paintPos.Count;//设置构成线条的点的数量
lr.SetPositions(paintPos.ToArray());
}
// 获取鼠标位置,将屏幕坐标转为世界坐标
private Vector3 GetMousePosition()
{
Vector3 screenPosition;//将物体从世界坐标转换为屏幕坐标
Vector3 mousePositionOnScreen;//获取到点击屏幕的屏幕坐标
Vector3 mousePositionInWorld;//将点击屏幕的屏幕坐标转换为世界坐标
//获取鼠标在相机中(世界中)的位置,转换为屏幕坐标;
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
//获取鼠标在场景中坐标
mousePositionOnScreen = Input.mousePosition;
//让场景中的Z=鼠标坐标的Z
mousePositionOnScreen.z = screenPosition.z;
//将相机中的坐标转化为世界坐标
mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
return mousePositionInWorld;
}
}
三、补充
这段代码可以获取Line Render所画线的平均中心位置
Vector3 pos= lr.bounds.center;