Unity3D 画线函数(实现和虚线)

1.若只需要在调试场景Scene里查看,不需要在Game运行场景看到,可以使用

Debug.Draw

这个函数一般在Update/Fixed Update/LateUpdate里调用,并且不能设置材质,不过可以指定颜色,例子如下:

void Update()
    {
        Debug.DrawLine (Pos1, Pos2,Color.yellow);
    }

 

2.如需要在游戏运行场景中看到,则需要使用lineRender,这个可以直接在组件栏下直接添加

其中可以增加材质,在Positions里可以增加点,然后连直线,若需要实时更新直线,则需要添加脚本,在Update函数里面添加点,例子如下:

this.GetComponent<LineRenderer>().SetPosition(0, transform.position);

transform.position就是你需要时刻改变的点位置。

画直线有很多方法,现在我只是写了两个,若以后使用了其他方法,再来补充。

LineRender画圆的方法详见 https://blog.csdn.net/weixin_42513339/article/details/83210495

 

下面说一下画虚线的方法:

本人还是用了lineRender,主要是自己做一个虚线的材质赋给lineRender。

步骤如下:

1.下载一张只有带虚线的图,背景是透明的,一般为PNG格式,

2.新建一个material,然后材质把最上面的shader改成如下,贴图找到上面的图,然后把这个材质给lineRender即可,其中需要注意的是,画出虚线之后,看到的可能是实线,这里我们就需要条件下面的Tiling和Offset了,我这里调节了Tiling中的X得到了虚线。

 

 

 

 

 

 

图片来自:https://blog.csdn.net/dengshunhao/article/details/80402444

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Unity C#脚本,可用于绘制虚线: ```csharp using UnityEngine; public class DrawDashedLine : MonoBehaviour { public Material lineMaterial; public float lineWidth = 1.0f; public float dashLength = 0.1f; public float gapLength = 0.1f; private Vector3 startPoint; private Vector3 endPoint; void OnPostRender() { if (!lineMaterial) { Debug.LogError("Please assign a material on the inspector"); return; } GL.PushMatrix(); lineMaterial.SetPass(0); GL.LoadOrtho(); GL.Begin(GL.LINES); GL.Color(lineMaterial.color); Vector3 direction = (endPoint - startPoint).normalized; float distance = Vector3.Distance(startPoint, endPoint); Vector3 currentPos = startPoint; float currentLength = 0; while (currentLength < distance) { GL.Vertex(currentPos); currentLength += dashLength; currentPos += direction * dashLength; if (currentLength < distance) { GL.Vertex(currentPos); currentLength += gapLength; currentPos += direction * gapLength; } } GL.End(); GL.PopMatrix(); } public void SetPoints(Vector3 start, Vector3 end) { startPoint = start; endPoint = end; } } ``` 使用方法: 1. 将此脚本附加到一个空对象上。 2. 将要绘制虚线的两个点传递给 `SetPoints` 函数。 3. 将要使用的材质分配给 `lineMaterial` 变量。 4. 可选:更改线宽、虚线长度和间隙长度。 示例代码: ```csharp using UnityEngine; public class Example : MonoBehaviour { public DrawDashedLine dashedLine; void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 start = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 end = start + new Vector3(2, 0, 0); dashedLine.SetPoints(start, end); } } } ``` 此示例将在鼠标单击时绘制一条从鼠标位置开始的虚线

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值