纳金网

标题: Unity3D开发之利用GL画曲线 [打印本页]

作者: 狂风大尉    时间: 2015-2-28 23:37
标题: Unity3D开发之利用GL画曲线

Unity3D开发之利用GL画曲线
  1. using UnityEngine;

  2. using System.Collections;

  3. using System;

  4. using System.Collections.Generic;

  5. public class DrawLine : MonoBehaviour {

  6. //绘制线段材质

  7. public Material material;

  8. private List<Vector3> lineInfo;

  9. private bool startDraw = false;

  10. Event e;

  11. void Start () {

  12. //初始化鼠标线段链表

  13. lineInfo = new List<Vector3>();

  14. }

  15. void OnGUI(){

  16. e = Event.current;

  17. }

  18. // Update is called once per frame

  19. void Update () {

  20. if(e.type == EventType.MouseDown)

  21. {

  22. startDraw = true;

  23. }

  24. if(e.type==EventType.MouseDrag)

  25. {

  26. if(startDraw == true){

  27. //将每次鼠标经过的位置存储进链表

  28. lineInfo.Add(Input.mousePosition);

  29. }

  30. }

  31. if(e.type==EventType.MouseUp)

  32. {

  33. startDraw = false;

  34. lineInfo.Clear();

  35. }

  36. }

  37. //GL的绘制方法系统回调

  38. void OnPostRender()

  39. {

  40. if(!material)

  41. {

  42. Debug.LogError(“material == null”);

  43. return;

  44. }

  45. //材质通道,0为默认。

  46. material.SetPass(0);

  47. //绘制2D图像

  48. GL.LoadOrtho();

  49. //得到鼠标点信息总数量

  50. GL.Begin(GL.LINES);

  51. //遍历鼠标点的链表

  52. int size = lineInfo.Count;

  53. for(int i =0; i < size - 1;i++)

  54. {

  55. Vector3 start = lineInfo[i];

  56. Vector3 end = lineInfo[i+1];

  57. //绘制线

  58. DrawLineFun(start.x,start.y,end.x,end.y);

  59. }

  60. //结束绘制

  61. GL.End();

  62. }

  63. void DrawLineFun(float x1,float y1,float x2,float y2)

  64. {

  65. //绘制线段

  66. GL.Vertex(new Vector3(x1 / Screen.width,y1 / Screen.height,0));

  67. GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height,0));

  68. }

  69. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5