注意:用Debug画的线会存在穿透问题
没啥好解释的,直接看代码:
using UnityEngine;using System.Collections;using System.Collections.Generic; /* * 找不到设置线宽的方法,目前的解决方法就是用画矩形代替画线来实现线的粗细 */////// 必须将此脚本放在摄影机上才能看到绘画内容,DebugDraw可以不用,但DebugDraw画的内容/// 只能在编辑模式下看得到。/// [RequireComponent(typeof(Camera))]public class DrawTrack: MonoBehaviour{ ////// 画笔的材质 /// public Material Material; ////// 绘画该目标的移动路径 /// public Transform Target; ////// 画笔平滑度 /// public float Smooth = 1; ////// 是否也在编辑器里绘画出线 /// public bool DebugDraw = true; ////// 存放移动路径的点的集合 /// private Listpath; /// /// 目标的最后一个移动点 /// private Vector3 lastPosition; void Start() { if (Material == null) { Debug.LogError("请先赋予该脚本 Material !!"); } if (Target == null) { Debug.LogError("请设置目标"); } path = new List(); lastPosition = Target.position; } void Update() { if (Vector3.Distance(Target.position, lastPosition) > Smooth) { path.Add(Target.position); lastPosition = Target.position; } } /// /// GL绘图必须在这个函数中进行 /// void OnPostRender() { GL.PushMatrix(); Material.SetPass(0); // 若要绘制2D线段,则取消注释GL.LoadOrtho(); //GL.LoadOrtho(); GL.Begin(GL.LINES); /*******在此处进行绘画*********/ DrawLines(path.ToArray()); GL.End(); GL.PopMatrix(); } private void DrawLine(Vector3 start, Vector3 end) { GL.Vertex3(start.x, start.y, start.z); GL.Vertex3(end.x, end.y, end.z); if (DebugDraw) { Debug.DrawLine(start, end, Color.red, 1); } } private void DrawLines(Vector3[] points) { if (points.Length == 0) { return; } for (int i = 0; i < points.Length - 1; ++i) { var start = points[i]; var end = points[i + 1]; GL.Vertex3(start.x, start.y, start.z); GL.Vertex3(end.x, end.y, end.z); if (DebugDraw) { Debug.DrawLine(start, end, Color.red, 1); } } } public void ClearLine() { path.Clear(); } }