# Reproducing Camera's worldToCameraMatrix

Discussion in 'Scripting' started by kent13304, Nov 3, 2015.

1. ### kent13304

Joined:
Aug 15, 2012
Posts:
9
I'd like to be able to generate the worldToCameraMatrix myself without using the worldToCameraMatrix field on the Camera class (I'm planning on calculating an optimal camera position in a separate thread).

Code (csharp):
1.
2.     Matrix4x4 matrix1 = camera.worldToCameraMatrix;
3.     Matrix4x4 matrix2 = Matrix4x4.TRS (
4.         new Vector3(camera.transform.position.x, camera.transform.position.y, -camera.transform.position.z),
5.         camera.transform.rotation,
6.         Vector3.one
7.     );
8.
I believe the Z direction is flipped in camera space so I'm negating the z position. The code above doesn't result in the same matrix for matrix1 and matrix2. What is the right code to set the matrix2 variable above so matrix1 matches matrix2 without using camera.worldToCameraMatrix ?

Deleted User likes this.
2. ### kent13304

Joined:
Aug 15, 2012
Posts:
9
Awww, was hoping this was an easy answer for the right person.

3. ### lordofduct

Joined:
Oct 3, 2011
Posts:
7,778
All the worldToCameraMatrix is, is the worldToLocalMatrix using OpenGL standards.

As the documentation says:
http://docs.unity3d.com/ScriptReference/Camera-worldToCameraMatrix.html
So, if you can calculate the 'worldToLocalMatrix', just negate the entire 3rd row of the matrix (the z portions).

'worldToLocalMatrix' can be calculated as the inverse of 'localToWorldMatrix'. And the localToWorldMatrix is just a matrix of the world position, rotation, and scale (the TRS).

So something like this:

Code (csharp):
1.
2. var m = Matrix4x4(camera.transform.position, camera.transform.rotation, Vector3.one); //no scale...
3. m = Matrix4x4.Inverse(m);
4. m.m20 *= -1f;
5. m.m21 *= -1f;
6. m.m22 *= -1f;
7. m.m23 *= -1f;
8.

4. ### kent13304

Joined:
Aug 15, 2012
Posts:
9
Genius, that works. Much appreciated.

5. ### CyRaid

Joined:
Mar 31, 2015
Posts:
113
Or simply:

Code (CSharp):
1. viewMatrix = Matrix4x4.Inverse(Matrix4x4.TRS(
2.   camera.transform.position,
3.   camera.transform.rotation,
4.   new Vector3(1, 1, -1)
5. ) );
6.

naelstrof, Deleted User and forestrf like this. unityunity