Question by
Sadlercs · Jan 04, 2017 at 03:58 AM ·
cameramatrixscreentoworldpointmatrix4x4
Calculation behind camera.ScreenToWorldPoint
Hello everyone,
Is there any way to reproduce camera.ScreenToWorldPoint using matrix calculation? One has been produced on here for the opposite by user zach-r-d.
Comment
Answer by zhentao · Feb 26, 2019 at 08:25 AM
Vector3 manualScreenPointToWorld(Camera cam, Vector3 sp)
{
Matrix4x4 world2Screen = cam.projectionMatrix * cam.worldToCameraMatrix;
Matrix4x4 screen2World = world2Screen.inverse;
float[] inn = new float[4];
inn[0] = 2.0f * (sp.x / cam.pixelWidth) - 1.0f;
inn[1] = 2.0f * (sp.y / cam.pixelHeight) - 1.0f;
inn[2] = cam.nearClipPlane;
inn[3] = 1.0f;
Vector4 pos = screen2World * new Vector4(inn[0], inn[1] , inn[2], inn[3]);
pos.w = 1.0f / pos.w;
pos.x *= pos.w;
pos.y *= pos.w;
pos.z *= pos.w;
return new Vector3(pos.x,pos.y,pos.z);
}
Reference2:https://answers.unity.com/questions/1014337/calculation-behind-cameraworldtoscreenpoint.html