I’m trying to manually perform an MVP transformation for a single point. I think (hope) I have it sort of figured out, except for one quirk: my Z coordinate in Viewport space is off.
Here is the code:
var pos = Vector3.zero;
var pos_homogeneous_coordinates = new Vector4(pos.x, pos.y, pos.z, 1);
var pos_local = cam.transform.localToWorldMatrix.inverse * pos_homogeneous_coordinates;
pos_local.z *= -1; // unity uses a left-handed coordinate system for the projection
var pos_in_clip_space = cam.projectionMatrix * pos_local;
var pos_in_NDC = (pos_in_clip_space / pos_in_clip_space.w);
var pos_in_viewport_space = (Vector3) ((pos_in_NDC + new Vector4(1,1,1,0)) / 2f);
print(pos_in_viewport_space);
print(cam.WorldToViewportPoint(pos));
where cam
is the camera. The result of this in my case is:
And I would expect them to be identical. Also, my code seems to produce strange results in edge cases or when the position is outside the clipping area. E.g. using pos = cam.transform.position
:
My question simply is where I am going wrong, as I don’t see it. Any pointers or help is highly appreciated =)