
在本教程中,将了解运行时如何在Unity3D中绘制线条,将使用Line Renderer组件在运行时绘制线条,将会学到俩个知识点:在两点之间画线、用鼠标拖动画线。
在两点之间画线
- 使用线渲染器组件创建一个游戏对象,目标位置为菜单
游戏对象 → 效果 → 线条。 - 使用以下脚本在两个游戏对象之间画线。
using UnityEngine;
public class DrawLine : MonoBehaviour
{
// Apply these values in the editor
public LineRenderer LineRenderer;
public Transform TransformOne;
public Transform TransformTwo;
void Start()
{
// set the color of the line
LineRenderer.startColor = Color.red;
LineRenderer.endColor = Color.red;
// set width of the renderer
LineRenderer.startWidth = 0.3f;
LineRenderer.endWidth = 0.3f;
// set the position
LineRenderer.SetPosition(0, TransformOne.position);
LineRenderer.SetPosition(1, TransformTwo.position);
}
}
最终结果
可以看到俩个体球之间链接了一根线条,且会随着对象的移动而改变。

在运行时用鼠标拖动画线
使用下面的脚本通过鼠标拖动来画线。
using UnityEngine;
public class DrawLineMouseDrag : MonoBehaviour
{
public LineRenderer Line;
public float lineWidth = 0.04f;
public float minimumVertexDistance = 0.1f;
private bool isLineStarted;
void Start()
{
// set the color of the line
Line.startColor = Color.red;
Line.endColor = Color.red;
// set width of the renderer
Line.startWidth = lineWidth;
Line.endWidth = lineWidth;
isLineStarted = false;
Line.positionCount = 0;
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Line.positionCount = 0;
Vector3 mousePos = GetWorldCoordinate(Input.mousePosition);
Line.positionCount = 2;
Line.SetPosition(0, mousePos);
Line.SetPosition(1, mousePos);
isLineStarted = true;
}
if (Input.GetMouseButton(0) && isLineStarted)
{
Vector3 currentPos = GetWorldCoordinate(Input.mousePosition);
float distance = Vector3.Distance(currentPos, Line.GetPosition(Line.positionCount - 1));
if (distance > minimumVertexDistance)
{
Debug.Log(distance);
UpdateLine();
}
}
if (Input.GetMouseButtonUp(0))
{
isLineStarted = false;
}
}
private void UpdateLine()
{
Line.positionCount++;
Line.SetPosition(Line.positionCount - 1, GetWorldCoordinate(Input.mousePosition));
}
private Vector3 GetWorldCoordinate(Vector3 mousePosition)
{
Vector3 mousePos = new Vector3(mousePosition.x, mousePosition.y, 1);
return Camera.main.ScreenToWorldPoint(mousePos);
}
}
最终结果
当按住鼠标左键在窗口中绘制时,此时会画出一条连续的线条,已脚本中定义的红色显示。

…
以上是3D天堂关于在运行时如何在Unity中绘制线条的全部内容,如果你有任何反馈,请随时在本页面下方留言。