Unity3D之OpenGL图像库

来源:互联网 发布:疯狂java讲义下载 编辑:程序博客网 时间:2024/06/12 22:11
OpenGL图像库主要用来绘制常见的2d和3d几何图形。下面我们来看下在unity3d使用GL图像库,可在屏幕中绘制2d几何图形,并且该几何图形将永远显示在屏幕当中,不会因为摄像机的移动而改变。
值得注意的是,绘制2d图像时,需要使用GL.LoadOrtho()方法来将图形映射在平面中;如果绘制的是3d图形,就无须使用此方法。
使用GL图像库时,需要将所有绘制相关的内容写在OnPostRender()方法中。有关GL图像库的脚本需要绑定在摄像机中,添加Material即可

GL图像库的平面坐标系:原点在左下角,x轴与y轴的最大值为1。

一、画直线

usingUnityEngine;
usingSystem.Collections;
 
publicclassDrawLine : MonoBehaviour {
 
publicMaterial material;
 
voidOnPostRender()
{
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();
}
 
//将屏幕中某个点的像素坐标进行转换
voidDraw(floatx1,floaty1,floatx2,floaty2)
{
GL.Vertex(newVector3(x1 / Screen.width, y1 / Screen.height, 0));
GL.Vertex(newVector3(x2 / Screen.width, y2 / Screen.height, 0));
}
}

二、画曲线

usingUnityEngine;
usingSystem.Collections.Generic;
 
/// <summary>
/// 记录鼠标坐标,再两两连线
/// </summary>
publicclassDrawCurve : MonoBehaviour {
 
publicMaterial material;
privateList<Vector3> lineInfo = newList<Vector3>();
 
voidUpdate ()
{
lineInfo.Add(Input.mousePosition);
}
 
voidOnPostRender()
{
material.SetPass(0);//设置该材质通道,0为默认值
GL.LoadOrtho();//设置绘制2d图像
GL.Begin(GL.LINES);//绘制类型为线段
 
for(inti = 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();
}
 
//将屏幕中某个点的像素坐标进行转换
voidDraw(floatx1,floaty1,floatx2,floaty2)
{
GL.Vertex(newVector3(x1 / Screen.width, y1 / Screen.height, 0));
GL.Vertex(newVector3(x2 / Screen.width, y2 / Screen.height, 0));
}
}

三、画三角形

usingUnityEngine;
usingSystem.Collections;
 
publicclass DrawTriangle : MonoBehaviour {
 
publicMaterial material;
 
voidOnPostRender()
{
Draw(100,0,100,200,200,100);
}
 
voidDraw(floatx1, floaty1, floatx2, floaty2, floatx3, floaty3)
{
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();
}
}

四、画四边形

usingUnityEngine;
usingSystem.Collections;
 
publicclass DrawQuad : MonoBehaviour {
 
publicMaterial material;
 
voidOnPostRender()
{
//绘制正四边形,提供的坐标必须是顺时针或者逆时针
Draw(100, 100, 100, 200, 200, 200, 200, 100);
//绘制无规则四边形
Draw(5, 5, 10, 100, 95, 110, 90, 10);
}
 
//绘制四边形,四个点坐标
voidDraw(floatx1, floaty1, floatx2, floaty2, floatx3, floaty3, floatx4, floaty4)
{
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();注释掉就可以了

原来画的图形不会随相机移动,现在的会。



原创粉丝点击