obsidian/笔记文件/2.笔记/GL.LoadOrtho.md
2025-03-26 00:02:56 +08:00

1.7 KiB

#unity/日常积累

描述

Helper 函数,用于设置正交投影。

将正交投影加载到投影矩阵中,将标识加载到 模型和视图矩阵中。

生成的投影将执行以下映射:
1. x = 0..1 to x = -1..1 (left..right)
2. y = 0..1 to y = -1..1 (bottom..top)
3. z = 1..-100 to z = -1..1 (near..far)

这等效于以下操作:

using UnityEngine;

public class Example : MonoBehaviour
{
    void OnPostRender()
    {
        // ...

        GL.LoadOrtho();

        // is equivalent to:

        GL.LoadIdentity();
        var proj = Matrix4x4.Ortho(0, 1, 0, 1, -1, 100);
        GL.LoadProjectionMatrix(proj);

        // ...
    }
}

更改模型、视图或投影矩阵会覆盖当前的渲染矩阵。 最好使用 GL.PushMatrix 和 GL.PopMatrix 保存和恢复这些矩阵。

using UnityEngine;

public class Example : MonoBehaviour
{
    // Draws a triangle under an already drawn triangle
    Material mat;

    void OnPostRender()
    {
        if (!mat)
        {
            Debug.LogError("Please Assign a material on the inspector");
            return;
        }
        GL.PushMatrix();
        mat.SetPass(0);
        GL.LoadOrtho();
        GL.Color(Color.red);
        GL.Begin(GL.TRIANGLES);
        GL.Vertex3(0.25f, 0.1351f, 0);
        GL.Vertex3(0.25f, 0.3f, 0);
        GL.Vertex3(0.5f, 0.3f, 0);
        GL.End();

        GL.Color(Color.yellow);
        GL.Begin(GL.TRIANGLES);
        GL.Vertex3(0.5f, 0.25f, -1);
        GL.Vertex3(0.5f, 0.1351f, -1);
        GL.Vertex3(0.1f, 0.25f, -1);
        GL.End();

        GL.PopMatrix();
    }
}