I really liked this question, so I made a quick test to test if linear matrix interpolation would do the trick. It seems to work.
Add the following script to your camera:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(Camera))]
public class MatrixBlender : MonoBehaviour
{
public static Matrix4x4 MatrixLerp(Matrix4x4 from, Matrix4x4 to, float time)
{
Matrix4x4 ret = new Matrix4x4();
for (int i = 0; i < 16; i++)
ret[i] = Mathf.Lerp(src[i], dest[i], time);
return ret;
}
private IEnumerator LerpFromTo(Matrix4x4 src, Matrix4x4 dest, float duration)
{
float startTime = Time.time;
while (Time.time - startTime < duration)
{
camera.projectionMatrix = MatrixLerp(src, dest, (Time.time - startTime) / duration);
yield return 1;
}
camera.projectionMatrix = dest;
}
public Coroutine BlendToMatrix(Matrix4x4 targetMatrix, float duration)
{
StopAllCoroutines();
return StartCoroutine(LerpFromTo(camera.projectionMatrix, targetMatrix, duration));
}
}
To use it, get a link to this script and call the BlendToMatrix function with the new matrix for your camera. The blender script will then make the smooth transition between the current matrix of its camera and the targetMatrix.
You can obtain this target matrix in a script by calling Matrix4x4.ProjectionMatrix(…), or Matrix4x4.Ortho(…). An example script that switches between an ortho and a perspective matrix (when the user presses space) is this:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(MatrixBlender))]
public class PerspectiveSwitcher : MonoBehaviour
{
private Matrix4x4 ortho,
perspective;
public float fov = 60f,
near = .3f,
far = 1000f,
orthographicSize = 50f;
private float aspect;
private MatrixBlender blender;
private bool orthoOn;
void Start()
{
aspect = (float) Screen.width / (float) Screen.height;
ortho = Matrix4x4.Ortho(-orthographicSize * aspect, orthographicSize * aspect, -orthographicSize, orthographicSize, near, far);
perspective = Matrix4x4.Perspective(fov, aspect, near, far);
camera.projectionMatrix = ortho;
orthoOn = true;
blender = (MatrixBlender) GetComponent(typeof(MatrixBlender));
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
orthoOn = !orthoOn;
if (orthoOn)
blender.BlendToMatrix(ortho, 1f);
else
blender.BlendToMatrix(perspective, 1f);
}
}
}
I don’t know if this linear lerp is the same as the one in the editor, as I simply don’t have the latest Unity version here to compare ;).
If you use javascript you should put these C# scripts in the Standard Assets/ folder, or translate them to JS.
I tested all the code, but I couldn’t copy paste, so the scripts may contain typo’s.