I’ve been working a lot with rendering, command buffers, and setting projection / view matrices these past few days and it seems I’ve run into a really strange issue.
I created what I thought was a standard view matrix using Matrix4x4.TRS
and Quaternion.LookAt
and it somehow flips all the axes? What’s particularly jarring is that triangles further away get rendered on top of closer triangles. It turns any mesh visible inside out.
Here is my code that gives the problem :
Vector3 dir = Random.onUnitSphere;
Vector3 tan = Vector3.ProjectOnPlane(Random.onUnitSphere, dir).normalized;
Vector3 position = meshEnvironment.position + 3*dir;
Quaternion orientation = Quaternion.LookRotation(dir,tan);
Vector3 scale = Vector3.one;
float width = 2f;
Matrix4x4 viewMatrix = Matrix4x4.TRS(
position,
orientation,
scale
).inverse;
Matrix4x4 projMatrix = Matrix4x4.Ortho(-width / 2, width / 2, -width / 2, width / 2, 0.03f, 1000f);
Camera.main.worldToCameraMatrix = viewMatrix;
Camera.main.projectionMatrix = projMatrix;
The above image is what results. The arrow is supposed to be pointing at the surface oriented to the normal. The light should be coming from above which tells me the axes have been flipped. Both the arrow and the rock mesh are inside out, the arrow is actually behind the rock in world space relative to the camera yet it’s being rendered on top.
What I did to fix the issue was make the scale negative and then correspond that with changing the sign of the position offset direction. The code that surprisingly “worked” :
Vector3 position = meshEnvironment.position - 3*dir;
Quaternion orientation = Quaternion.LookRotation(dir,tan);
Vector3 scale = -Vector3.one;
The above image is what resulted from the negative scale. The arrow now points towards the surface oriented to the correct normal, a shadow is casted, the axes are correctly oriented in the image, there is a correct draw order.
But I have no idea why this worked. In my mind this should not have worked. Since I’m working a lot with cameras, rendering, graphics.drawmesh, command buffers, it’s really unsettling to have this negative scale lying around because I might run into errors it causes further down the line. I must be doing something wrong.
Any help would be appreciated!