用GL画出人物的移动路径
注意:用Debug画的线会存在穿透问题
没啥好解释的,直接看代码:
using UnityEngine; using System.Collections; using System.Collections.Generic; /* * 找不到设置线宽的方法,目前的解决方法就是用画矩形代替画线来实现线的粗细 */ /// <summary> /// 必须将此脚本放在摄影机上才能看到绘画内容,DebugDraw可以不用,但DebugDraw画的内容 /// 只能在编辑模式下看得到。 /// </summary> [RequireComponent(typeof(Camera))] public class DrawTrack: MonoBehaviour { /// <summary> /// 画笔的材质 /// </summary> public Material Material; /// <summary> /// 绘画该目标的移动路径 /// </summary> public Transform Target; /// <summary> /// 画笔平滑度 /// </summary> public float Smooth = 1; /// <summary> /// 是否也在编辑器里绘画出线 /// </summary> public bool DebugDraw = true; /// <summary> /// 存放移动路径的点的集合 /// </summary> private List<Vector3> path; /// <summary> /// 目标的最后一个移动点 /// </summary> private Vector3 lastPosition; void Start() { if (Material == null) { Debug.LogError("请先赋予该脚本 Material !!"); } if (Target == null) { Debug.LogError("请设置目标"); } path = new List<Vector3>(); lastPosition = Target.position; } void Update() { if (Vector3.Distance(Target.position, lastPosition) > Smooth) { path.Add(Target.position); lastPosition = Target.position; } } /// <summary> /// GL绘图必须在这个函数中进行 /// </summary> 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(); } }