详解Unity 中 Line Renderer

介绍

Line Renderer 是 Unity 中的一个组件,用于绘制一条连续的线段。它可以用于实现各种效果,如炫酷的拖尾效果、游戏中的弹道预览、路径指示等等。

Line Renderer 组件的主要作用是在场景中绘制一条连接多个点的线段,可以通过调整点的位置、颜色、宽度等属性,来实现不同的效果。

方法

以下是一些 Line Renderer 常用的方法及其参数:

SetPosition

void SetPosition(int index, Vector3 position);
  • index:要设置的点的索引,从 0 开始。
  • position:点的坐标,Vector3 类型。

该方法用于设置线段的某个点的位置,其中 index 参数表示要设置的点的索引,position 参数表示点的坐标。

SetPositions

void SetPositions(Vector3[] positions);
  • positions:点的坐标数组,Vector3[] 类型。

该方法用于设置线段的所有点的位置,其中 positions 参数是一个 Vector3 类型的数组,表示所有点的坐标。

SetColors

void SetColors(Color startColor, Color endColor);
  • startColor:线段起始点的颜色,Color 类型。
  • endColor:线段终止点的颜色,Color 类型。

该方法用于设置线段的起始点和终止点的颜色,其中 startColor 参数表示起始点的颜色,endColor 参数表示终止点的颜色。

SetWidth

void SetWidth(float startWidth, float endWidth);
  • startWidth:线段起始点的宽度,float 类型。
  • endWidth:线段终止点的宽度,float 类型。

该方法用于设置线段的起始点和终止点的宽度,其中 startWidth 参数表示起始点的宽度,endWidth 参数表示终止点的宽度。

举例子

以下是一些常见的 Line Renderer 代码示例:

绘制简单的直线

LineRenderer line = gameObject.AddComponent<LineRenderer>();
line.positionCount = 2;
line.SetPosition(0, new Vector3(0, 0, 0));
line.SetPosition(1, new Vector3(1, 0, 0));

该代码用于在场景中创建一个 Line Renderer 组件,设置它的起始点和终止点,绘制一条简单的直线。

绘制带有颜色的线段

LineRenderer line = gameObject.AddComponent<LineRenderer>();
line.positionCount = 2;
line.SetPosition(0, new Vector3(0, 0, 0));
line.SetPosition(1, new Vector3(1, 0, 0));
line.startColor = Color.red;
line.endColor = Color.blue;

该代码用于在场景中创建一个 Line Renderer 组件,设置它的起始点和终止点,并为起始点和终止点设置不同的颜色,绘制一条带有颜色的线段。

绘制带有宽度的线段

LineRenderer line = gameObject.AddComponent<LineRenderer>();
line.positionCount = 2;
line.SetPosition(0, new Vector3(0, 0, 0));
line.SetPosition(1, new Vector3(1, 0, 0));
line.startWidth = 0.1f;
line.endWidth = 0.3f;

该代码用于在场景中创建一个 Line Renderer 组件,设置它的起始点和终止点,并为起始点和终止点设置不同的宽度,绘制一条带有宽度的线段。

扫描二维码关注公众号,回复: 15117346 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_20179331/article/details/130673074