• 您的位置:首頁 > 新聞動態(tài) > Unity3D

    UNITY3D自定義相機(jī)三行四列投影矩陣

    2020/6/13??????點(diǎn)擊:

    在UNITY3D中,Camera.projectionMatrix 為相機(jī)的投影矩陣

    如果你改變這個矩陣,相機(jī)的渲染不再基于它的fieldOfView更新,直到調(diào)用ResetProjectionMatrix. 只有當(dāng)真正需要一個非標(biāo)準(zhǔn)的投影時,才使用自定義投影。這個屬性被Unity的水渲染使用來設(shè)置一個oblique projection 矩陣。使用自定義投影需要了解變換和投影矩陣。

    using UnityEngine;
    using System.Collections;

    //讓相機(jī)以流行的方式晃動
    public class example : MonoBehaviour {
     public Matrix4x4 originalProjection;
     void Update() {
      //改變原始矩陣的某些值
                 Matrix4x4 p = originalProjection;
      p.m01 += Mathf.Sin(Time.time * 1.2F) * 0.1F;
      p.m10 += Mathf.Sin(Time.time * 1.5F) * 0.1F;
      camera.projectionMatrix = p;
     }
     public void Awake() {
      originalProjection = camera.projectionMatrix;
     }
    }

    可以發(fā)現(xiàn)攝像機(jī)投影矩陣是個三行四列的矩陣;

    //設(shè)置一個偏移中心的投影,這個透視的消失點(diǎn)沒有必要在屏幕的中心
    //定義近載面大小,例如相機(jī)的近裁面偏移中心多少
    //改變這個值你就能看到相機(jī)視圖的變化
    using UnityEngine;
    using System.Collections;

    public class example : MonoBehaviour {
     public float left = -0.2F;
     public float right = 0.2F;
     public float top = 0.2F;
     public float bottom = -0.2F;
     void LateUpdate() {
      Camera cam = camera;
      Matrix4x4 m = PerspectiveOffCenter(left, right, bottom, top, cam.nearClipPlane, cam.farClipPlane);
      cam.projectionMatrix = m;
     }
     static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far) {
      float x = 2.0F * near / right - left;
      float y = 2.0F * near / top - bottom;
      float a = right + left / right - left;
      float b = top + bottom / top - bottom;
      float c = -far + near / far - near;
      float d = -2.0F * far * near / far - near;
      float e = -1.0F;
      Matrix4x4 m;
      m[0, 0] = x;
      m[0, 1] = 0;
      m[0, 2] = a;
      m[0, 3] = 0;
      m[1, 0] = 0;
      m[1, 1] = y;
      m[1, 2] = b;
      m[1, 3] = 0;
      m[2, 0] = 0;
      m[2, 1] = 0;
      m[2, 2] = c;
      m[2, 3] = d;
      m[3, 0] = 0;
      m[3, 1] = 0;
      m[3, 2] = e;
      m[3, 3] = 0;
      return m;
     }
    }