GL图像库主要用来绘制常见的2d和3d几何图形。使用GL图像库,可在屏幕中绘制2d几何图形,并且该几何图形将永远显示在屏幕当中,不会因为摄像机的移动而改变。
值得注意的是,绘制2d图像时,需要使用GL.LoadOrtho()方法来将图形映射在平面中;如果绘制的是3d图形,就无须使用此方法。
使用GL图像库时,需要将所有绘制相关的内容写在OnPostRender()方法中。有关GL图像库的脚本需要绑定在摄像机中。
GL图像库的平面坐标系:原点在左下角,x轴与y轴的最大值为1。
一、绘制线
using UnityEngine; using System.Collections; public class DrawLine : MonoBehaviour { public Material material; void OnPostRender() { material.SetPass(0);//设置该材质通道,0为默认值 GL.LoadOrtho();//设置绘制2d图像 GL.Begin(GL.LINES);//绘制类型为线段 Draw(0, 0, 200, 100); Draw(0, 50, 200, 150); Draw(0, 100, 200, 200); GL.End(); } //将屏幕中某个点的像素坐标进行转换 void Draw(float x1,float y1,float x2,float y2) { GL.Vertex(new Vector3(x1 / Screen.width, y1 / Screen.height, 0)); GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height, 0)); } }
二、绘制曲线
using UnityEngine; using System.Collections.Generic; /// <summary> /// 记录鼠标坐标,再两两连线 /// </summary> public class DrawCurve : MonoBehaviour { public Material material; private List<Vector3> lineInfo = new List<Vector3>(); void Update () { lineInfo.Add(Input.mousePosition); } void OnPostRender() { material.SetPass(0);//设置该材质通道,0为默认值 GL.LoadOrtho();//设置绘制2d图像 GL.Begin(GL.LINES);//绘制类型为线段 for (int i = 0; i < lineInfo.Count - 1; i++) { Vector3 start = lineInfo[i]; Vector3 end = lineInfo[i + 1]; Draw(start.x,start.y,end.x,end.y); } GL.End(); } //将屏幕中某个点的像素坐标进行转换 void Draw(float x1, float y1, float x2, float y2) { GL.Vertex(new Vector3(x1 / Screen.width, y1 / Screen.height, 0)); GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height, 0)); } }
三、绘制四边形
using UnityEngine; using System.Collections; public class DrawQuad : MonoBehaviour { public Material material; void OnPostRender() { //绘制正四边形,提供的坐标必须是顺时针或者逆时针 Draw(100, 100, 100, 200, 200, 200, 200, 100); //绘制无规则四边形 Draw(15, 5, 10, 115, 95, 110, 90, 10); } //绘制四边形,四个点坐标 void Draw(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { GL.PushMatrix(); material.SetPass(0);//设置该材质通道,0为默认值 GL.LoadOrtho();//设置绘制2d图像 GL.Begin(GL.QUADS);//绘制类型为四边形 GL.Vertex3(x1 / Screen.width, y1 / Screen.height, 0); GL.Vertex3(x2 / Screen.width, y2 / Screen.height, 0); GL.Vertex3(x3 / Screen.width, y3 / Screen.height, 0); GL.Vertex3(x4 / Screen.width, y4 / Screen.height, 0); GL.End(); GL.PopMatrix(); } }
四、绘制三角形
using UnityEngine; using System.Collections; public class DrawTriangle : MonoBehaviour { public Material material; void OnPostRender() { Draw(100,0,100,200,200,100); } void Draw(float x1, float y1, float x2, float y2, float x3, float y3) { material.SetPass(0);//设置该材质通道,0为默认值 GL.LoadOrtho();//设置绘制2d图像 GL.Begin(GL.TRIANGLES);//绘制类型为三角形 GL.Vertex3(x1 / Screen.width, y1 / Screen.height, 0); GL.Vertex3(x2 / Screen.width, y2 / Screen.height, 0); GL.Vertex3(x3 / Screen.width, y3 / Screen.height, 0); GL.End(); } }
五、绘制3d几何图形
操作十分简单,就是将GL.LoadOrtho();注释掉即可
原来图形不会随摄像机的移动、旋转而变化,现在则会。