GL基础教程
1.什么是GL
GL(Graphics Library)是底层图像库,主要是可以使用程序来绘制2D或者3D图形。绘制出来的2D或者3D图形都是以面的形式渲染。
2D图形与3D图形的区别是2D图形在所有3D物体的上方,不会随摄像机的移动而改变,而3D图形会根据摄像机的移动而移动。绘制2D图形需要用到GL库 中的LoadOrtho方法,该方法的作用是做一个正交投影变换,将图形映射在屏幕中,而绘制3D图形与绘制2D唯一不同的是无需调用LoadOrtho方法。
GL可以绘制线段、三角形、三角形带(前三个点组成一个简单三角形,第四个点和前面两个点组成三角形,依次类推)和四边形。
值得注意的是,需要将绘制的内容写在OnPostRender方法中,该方法由系统调用,无法手动调用。只有将绘制图形的脚本 附于相机并启用时才会调用该方法,否则无法显示绘制的图形。
2.绘制直线
using UnityEngine;using System.Collections;public class DrawLineDemo : MonoBehaviour{ private Material mat; // Use this for initialization void Start() { mat = new Material("Shader \"Lines/Colored Blended\" {" + "SubShader { Pass {" + " BindChannels { Bind \"Color\",color }" + " Blend SrcAlpha OneMinusSrcAlpha" + " ZWrite Off Cull Off Fog { Mode Off }" + "} } }"); } void OnPostRender() { GL.PushMatrix(); mat.SetPass(0); //绘制2D线段,注释掉GL.LoadOrtho();则绘制3D图形 GL.LoadOrtho(); //开始绘制直线类型,需要两个顶点 GL.Begin(GL.LINES); //绘制起点,绘制的点需在Begin和End之间 GL.Vertex3(0, 0, 0); GL.Vertex3(1, 1, 0); GL.End(); GL.PopMatrix(); }}
2.绘制三角形
using UnityEngine;using System.Collections;public class DrawTriangle : MonoBehaviour { public Material mat; void Start() { mat = new Material("Shader \"Lines/Colored Blended\" {" +"SubShader { Pass {" +" BindChannels { Bind \"Color\",color }" +" Blend SrcAlpha OneMinusSrcAlpha" +" ZWrite Off Cull Off Fog { Mode Off }" +"} } }"); mat.hideFlags = HideFlags.HideAndDontSave; mat.shader.hideFlags = HideFlags.HideAndDontSave; } void Update() { if (Input.GetMouseButtonDown(0)) { Debug.Log("press mousedown"); } } private void DrawATriangle( Material mat) { GL.PushMatrix(); mat.SetPass(0); GL.LoadOrtho(); GL.Begin(GL.TRIANGLES); GL.Vertex3(0.2f, 0.2f, 0); GL.Vertex3(0.3f, 0.6f, 0); GL.Vertex3(0.7f, 0.5f, 0); GL.End(); GL.PopMatrix(); } void OnPostRender() { DrawATriangle( mat); }}
画四边形
Unity中原点(0,0)是在屏幕的左下角,右上角为(1,1)
using UnityEngine;using System.Collections;public class Draw3DRect : MonoBehaviour { private Material mat; // Use this for initialization void Start () { mat = new Material("Shader \"Lines/Colored Blended\" {" + "SubShader { Pass {" + " BindChannels { Bind \"Color\",color }" + " Blend SrcAlpha OneMinusSrcAlpha" + " ZWrite Off Cull Off Fog { Mode Off }" + "} } }"); mat.hideFlags = HideFlags.HideAndDontSave; mat.shader.hideFlags = HideFlags.HideAndDontSave; } // Update is called once per frame void Update () { } void OnPostRender() { GL.PushMatrix(); mat.SetPass(0); GL.LoadOrtho(); GL.Begin(GL.QUADS); GL.Color(Color.red); GL.Vertex3(0, 0.5F, 0); GL.Vertex3(0.5F, 1, 0); GL.Vertex3(1, 0.5F, 0); GL.Vertex3(0.5F, 0, 0); GL.Color(Color.cyan); GL.Vertex3(0, 0, 0); GL.Vertex3(0, 0.25F, 0); GL.Vertex3(0.25F, 0.25F, 0); GL.Vertex3(0.25F, 0, 0); GL.End(); GL.PopMatrix(); }}