Skip to content

Instantly share code, notes, and snippets.

@chadobado
Last active November 26, 2018 21:41
Show Gist options
  • Save chadobado/6e9df73ddb263674e323ae57e1fc51b5 to your computer and use it in GitHub Desktop.
Save chadobado/6e9df73ddb263674e323ae57e1fc51b5 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModifyProjectionMatrix : MonoBehaviour {
public Camera camera;
public Matrix4x4 currentMatrix;
public Matrix4x4 newMatrix;
// Use this for initialization
void Start () {
camera = GetComponent<Camera>();
currentMatrix = camera.projectionMatrix;
newMatrix = modifyProjection(currentMatrix, newMatrix);
camera.projectionMatrix = newMatrix;
}
Matrix4x4 modifyProjection(Matrix4x4 mat, Matrix4x4 matOut)
{
Debug.Log("Generating new matrix");
//get current near and far
float k = (mat[10] - 1.0f) / (mat[10] + 1.0f);
float near = (mat[14] * (1.0f - k)) / (2.0f * k);
float far = k * near;
//extract constants
float n2 = (near + near);
float diffNF = (near - far);
float diffRL = n2 / mat[0];
float diffTB = n2 / mat[5];
float sumRL = mat[8] * diffRL;
float sumTB = mat[9] * diffTB;
float sumNF = mat[10] * diffNF;
//New near and far plane
float newNear = 0.011f;
float newFar = 100.0f;
sumNF = (newNear + newFar);
diffNF = (newNear - newFar);
n2 = (newNear + newNear);
float factor = newNear / near;
diffRL *= factor;
diffTB *= factor;
sumRL *= factor;
sumTB *= factor;
matOut = new Matrix4x4();
//generate the new matrix
matOut[0] = n2 / diffRL;
matOut[1] = 0.0f;
matOut[2] = 0.0f;
matOut[3] = 0.0f;
matOut[4] = 0.0f;
matOut[5] = n2 / diffTB;
matOut[6] = 0.0f;
matOut[7] = 0.0f;
matOut[8] = sumRL / diffRL;
matOut[9] = sumTB / diffTB;
matOut[10] = sumNF / diffNF;
matOut[11] = -1.0f;
matOut[12] = 0.0f;
matOut[13] = 0.0f;
matOut[14] = (n2 / diffNF) * newFar;
matOut[15] = 0.0f;
Debug.Log(matOut);
return matOut;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment