- Home /
How to get world position to screen position matrix?
How to get a matrix that simulates behaviour of function Camera.WorldToScreenPoint? I need to be able to calculate Screen position of certain points being given their world position inside Compute Shader.
Answer by IgorAherne · Jun 24, 2017 at 09:37 AM
c#:
Matrix4x4 matrixVP = myCamera.projectionMatrix * myCamera.worldToCameraMatrix; //multipication order matters
Vector4 clipCoord = matrixVP.MultiplyPoint(myWorldXYZW);
notice, you can now check clipCoord.w
and if its -1, then you know the vertex will NOT be seen by the camera
Vector4 perspectiveCoord = clipCoord / clipCoord.w; //goes from -1 to 1 on each axis and z is 0 to 1, w is now 1
What we've done is taken frustum-shaped volume and shrunken it into a cube.
now, you need to take your perspectiveCoord.xy
and re-specify it relative to bot left corner (u said u need screen space)
perspectiveCoord = perspectiveCoord*0.5 + 0.5;
perspectiveCoord *= new Vector4(myCamera.width, myCamera.height,1,1);//screen space coord (bot left 0,0 top right 1920, 1080 or other resolution which u have)
Hi Igor
What version of Unity are you using? I'm using 5.5.2 and the API does not support your code. Eg $$anonymous$$atrix4x4.$$anonymous$$ultiplyPoint returns a Vector3, so I'd lose the w component of clipCoord.
There is a multiplication operator for $$anonymous$$atrix4x4 and Vector4 which returns a Vector4. I tried that and I'm not getting the correct results (I think). The clip coord has xy=0, but the position is actually offset left and down in the camera's view.
What am I doing wrong?
Your answer
Follow this Question
Related Questions
Calculation behind camera.WorldToScreenPoint 2 Answers
How calculated ViewportToWorldPoint 0 Answers
GL.MultMatrix multiple instances drawing 0 Answers
Advanced info on Unity's camera matrix 0 Answers
changing camera view 3 Answers