GL是底层图像库,主要是可以使用程序来绘制2D或者3D图形。绘制出来的2D或者3D图形都是以面的形式渲染。 2D图形与3D图形的区别是2D图形在所有3D物体的上方,不会随摄像机的移动而改变,而3D图形会根据摄像机的移动而移动。绘制2D图形需要用到GL库 中的LoadOrtho方法,该方法的作用是做一个正交投影变换,将图形映射在屏幕中,而绘制3D图形与绘制2D唯一不同的是无需调用LoadOrtho 方法。 值得注意的是,需要将绘制的内容写在OnPostRender方法中,该方法由系统调用,无法手动调用。只有将绘制图形的脚本附于相机并启用时才会调用该方法,否则无法显示绘制的图形 GL可以绘制线段、三角形、三角形带(前三个点组成一个简单三角形,第四个点和前面两个点组成三角形,依次类推)和四边形。 下面来看下具体的例子: 绘制直线: 绘制2D直线 C# 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();
}
} 线段 绘制三角形: 绘制2D三角形 C# 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);
}
} 三角形 绘制四边形: 绘制四边形 C# 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();
}
} 四边形 unity中,原点的坐标与flash中的原点不一样,flash的原点是在左上角,而unity中原点是在左下角,坐标点为(0,0),右上角为(1,1)。 |
|
来自: 雪柳花明 > 《Unity3D 进阶》