1. 程式人生 > >Unity3D 畫筆實現系列02-UnityGL

Unity3D 畫筆實現系列02-UnityGL

ret display fun unity3 inpu draw spa height void

GL的功能比較強,但unity中開放的接口比較少。(個人版不能用)

我在項目中是用兩個相機,一個設置為不清處模式,渲染到RenderTexture上,另一個渲染主場景。

技術分享圖片
  1 public class GLLine : MonoBehaviour
  2 {
  3     /*GL比較底層,難控制,Unity開放的接口不多,能用到的不多,
  4      *有時間繼續學習深入研究
  5      *
  6      */
  7     private List<Vector3> linePos;
  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<Vector3>(); 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 /// <summary> 69 /// 引擎自動調用 70 /// </summary> 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 }
具體代碼

Unity3D 畫筆實現系列02-UnityGL