绘制线条的组件
1. 参数列表
参数名 | 描述 |
---|
大小 | 绘制线条关键点的数量,将点依次连接 |
颜色 | 绘制线条的颜色 |
角顶点 | 折点处顶点数量 |
末端顶点 | 末端处顶点数量 |
2. 代码参数列表
GameObject go = new GameObject();
go.AddComponent<LineRenderer>();
参数名 | 描述 |
---|
material | 材质 |
startWidth | 起始宽度 |
endWidth | 末端宽度 |
startColor | 起始颜色 |
endColor | 末端颜色 |
numCornerVertices | 角顶点 |
numCapVertices | 末端顶点 |
positionCount | 顶点数量 |
2. 函数列表
参数名 | 描述 |
---|
SetPositions(Vector3[]) | 顶点集合 |
3. 画笔示例
[SerializeField] Color paintColor = Color.red;
[SerializeField] float paintSize = 0.2f;
[SerializeField] Material lineMaterial;
LineRenderer currentLine;
List<Vector3> positions = new List<Vector3>();
bool IsMouseDown = false;
public void ChangeColor(int value)
{
if(value == 0)
paintColor = Color.red;
if (value == 1)
paintColor = Color.green;
if (value == 2)
paintColor = Color.blue;
}
public void ChangeSize(float pse)
{
paintSize = pse;
}
private 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;
positions.Clear();
AddPosition();
IsMouseDown = true;
}
if(IsMouseDown)
{
AddPosition();
}
if (Input.GetMouseButtonUp(0))
{
IsMouseDown = false;
}
}
void AddPosition()
{
Vector3 position = GetMousePoint();
positions.Add(position);
currentLine.positionCount = positions.Count;
currentLine.SetPositions(positions.ToArray());
}
Vector3 GetMousePoint()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool flag = Physics.Raycast(ray, out hit);
if(flag)
{
return hit.point - Vector3.forward / 100;
}
return Vector3.zero;
}
4. 附加项
- 存在类似的组件,名为trail renderer,可用于绘制拖尾效果
- 对每个点添加碰撞器。长度为两个点之间长度,角度设置右方向为该点到下一个点的向量