GL的功能比较强,但unity中开放的接口比较少。(个人版不能用)
我在项目中是用两个相机,一个设置为不清处模式,渲染到RenderTexture上,另一个渲染主场景。
![](http://img.e-com-net.com/image/info8/b8d97b5613f94ed2ba791cad57d0b2ed.gif)
![](http://img.e-com-net.com/image/info8/2f88dd3f1cd145f59c0e47b51acdbd4b.gif)
1 public class GLLine : MonoBehaviour 2 { 3 /*GL比较底层,难控制,Unity开放的接口不多,能用到的不多, 4 *有时间继续学习深入研究 5 * 6 */ 7 private ListlinePos; 8 private bool startDraw = false; 9 private Vector3 oldMousePosition; 10 public float StepSize = 80f;//每次差值的步长 11 public float size = 60f;//每个单独模块的宽度 12 public Material LineMaterial; 13 public Color color = Color.red; 14 public float roud = 30; 15 16 void Start() 17 { 18 19 linePos = new List (); 20 21 22 } 23 24 void Update() 25 { 26 if (Input.GetMouseButtonDown(0)) 27 { 28 oldMousePosition = Input.mousePosition; 29 color = Color.red; 30 startDraw = true; 31 } 32 if (Input.GetMouseButtonUp(0)) 33 { 34 startDraw = false; 35 linePos.Clear();//清理绘制点,不然每帧都会重新绘制 36 } 37 if (Input.GetMouseButtonDown(1)) 38 { 39 oldMousePosition = Input.mousePosition; 40 startDraw = true; 41 color = Color.white; 42 } 43 if (Input.GetMouseButtonUp(1)) 44 { 45 startDraw = false; 46 linePos.Clear();//清理绘制点,不然每帧都会重新绘制 47 } 48 if (startDraw) 49 { 50 if (StepSize == 0) return; 51 var newMousePosition = (Vector2)Input.mousePosition; 52 if (Vector2.Distance(newMousePosition, oldMousePosition) < size) return; 53 float stepCount = Vector2.Distance(oldMousePosition, newMousePosition) / StepSize + 1; 54 for (int i = 0; i < stepCount; i++) 55 { 56 var subMousePosition = Vector3.Lerp(oldMousePosition, newMousePosition, i / stepCount); 57 linePos.Add(subMousePosition); 58 } 59 oldMousePosition = newMousePosition; 60 61 } 62 63 64 65 66 67 } 68 /// 69 /// 引擎自动调用 70 /// 71 public void OnRenderObject() 72 { 73 GL.PushMatrix(); 74 LineMaterial.SetPass(0); 75 for (int i = 0; i < linePos.Count - 1; i++) 76 { 77 Vector3 startPos = linePos[i]; 78 Vector3 endPos = linePos[i + 1]; 79 DrawLineFun(startPos.x, startPos.y, endPos.x, endPos.y); 80 } 81 GL.PopMatrix(); 82 83 } 84 void DrawLineFun(float x1, float y1, float x2, float y2) 85 { 86 87 DrawRect(x1 - roud, y1 - roud, 2 * roud, color); 88 } 89 90 void DrawRect(float x, float y, float width, Color myColor) 91 { 92 93 float height = width; 94 //绘制2D图像 95 GL.LoadOrtho(); 96 GL.Begin(GL.QUADS); 97 GL.Color(myColor); 98 GL.TexCoord3(0, 0, 0);//设置贴图 画纯色时去掉 99 GL.Vertex3(x / Screen.width, y / Screen.height, 0); 100 GL.TexCoord3(0, 1, 0);//设置贴图 画纯色时去掉 101 GL.Vertex3(x / Screen.width, (y + height) / Screen.height, 0); 102 GL.TexCoord3(1, 1, 0);//设置贴图 画纯色时去掉 103 GL.Vertex3((x + width) / Screen.width, (y + height) / Screen.height, 0); 104 GL.TexCoord3(1, 0, 0);//设置贴图 画纯色时去掉 105 GL.Vertex3((x + width) / Screen.width, y / Screen.height, 0); 106 GL.End(); 107 108 } 109 }