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 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(); } }四、画四边形
using UnityEngine; using System.Collections; public class DrawQuad : MonoBehaviour { public Material material; void OnPostRender() { //绘制正四边形,提供的坐标必须是顺时针或者逆时针 Draw(100, 100, 100, 200, 200, 200, 200, 100); //绘制无规则四边形 Draw(5, 5, 10, 100, 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(); } }五、画3D图形
将代码 GL.LoadOrtho();注释掉就可以了
原来画的图形不会随相机移动,现在的会。