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).

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 ?

All the worldToCameraMatrix is, is the worldToLocalMatrix using OpenGL standards.

As the documentation says:

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:

var m = Matrix4x4(camera.transform.position, camera.transform.rotation, Vector3.one); //no scale...
m = Matrix4x4.Inverse(m);
m.m20 *= -1f;
m.m21 *= -1f;
m.m22 *= -1f;
m.m23 *= -1f;