1. 程式人生 > >Unity3d GL繪製一個跟隨滑鼠的曲線

Unity3d GL繪製一個跟隨滑鼠的曲線

  1.     public Material material;//材質,必須要有
  2.     private List<Vector3> lineInfo;//滑鼠座標的集合
  3.     void Start ()
  4.     {
  5.         lineInfo = new List<Vector3> ();//初始化集合
  6.     }
  7.     // Update is called once per frame
  8.     void Update ()
  9.     {
  10. //        if (Input.GetMouseButton (0)) {
  11. //            
  12. //            lineInfo.Add (Input.mousePosition);
  13. //        }
  14.         lineInfo.Add (Input.mousePosition);//將滑鼠座標加入到集合當中
  15.     }
  16.     void OnPostRender ()
  17.     {
  18. //        if (Input.GetMouseButton (0)) {
  19.         if (!material) {
  20.             Debug.LogError ("請給材質賦值");
  21.             return;
  22.         }
  23.         GL.PushMatrix ();
  24.         material.SetPass (0);
  25.         //material.color = Color.white;
  26.         GL.LoadOrtho ();//繪製物件顯示在平面上
  27.         GL.Begin (GL.LINES);//開始劃線
  28.         GL.Color (Color.red);//線的顏色,我這邊顏色是不會改變的,還沒找出問題,希望有人能幫我搞定這個顏色不變得問題。
  29.         int size = lineInfo.Count;
  30.         for (int i = 0; i < size - 1; i++) {
  31.             Vector3 start = lineInfo [i];
  32.             Vector3 end = lineInfo [i + 1];
  33.             DrawLine (start.x, start.y, end.x, end.y);
  34.         }
  35.         GL.End ();
  36.         GL.PopMatrix ();
  37. //        }    
  38.     }
  39.     void DrawLine (float x1, float y1, float x2, float y2)
  40.     {
  41.         GL.Vertex (new Vector3 (x1 / Screen.width, y1 / Screen.height, 0));
  42.         GL.Vertex (new Vector3 (x2 / Screen.width, y2 / Screen.height, 0));
  43.     }