ForceXRCardobardFOV

mail@pastecode.io avatar
unknown
csharp
2 years ago
1.2 kB
7
Indexable
Never
using UnityEngine;

public class SetXRFov : MonoBehaviour
{

    Camera cam;

    void Awake()
    {
        cam = Camera.main;
    }
    
    Matrix4x4 mat;
    float aspect, zNear, zFar;

    public void SetStereoFov(float fov)
    {
        //Left eye
        mat = cam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left);
        GetProjectionMatrixParameters(mat, out aspect, out zNear, out zFar);
        cam.SetStereoProjectionMatrix(Camera.StereoscopicEye.Left, Matrix4x4.Perspective(fov, aspect, zNear, zFar));

        //Right eye
        mat = cam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right);
        GetProjectionMatrixParameters(mat, out aspect, out zNear, out zFar);
        cam.SetStereoProjectionMatrix(Camera.StereoscopicEye.Right, Matrix4x4.Perspective(fov, aspect, zNear, zFar));
    }

    void GetProjectionMatrixParameters(Matrix4x4 mat, out float aspect, out float zNear, out float zFar)
    {
        float a = mat[0];
        float b = mat[5];
        float c = mat[10];
        float d = mat[14];

        aspect = b / a;

        float k = (c - 1.0f) / (c + 1.0f);
        zNear = (d * (1.0f - k)) / (2.0f * k);
        zFar = k * zNear;
    }
}