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.


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)

@ColinAmuzo you don’t need to divide by w component as MultiplyPoint is already taking care of that

public Vector3 MultiplyPoint (Vector3 point)
Vector3 result = default(Vector3);
result.x = m00 * point.x + m01 * point.y + m02 * point.z + m03;
result.y = m10 * point.x + m11 * point.y + m12 * point.z + m13;
result.z = m20 * point.x + m21 * point.y + m22 * point.z + m23;
float num = m30 * point.x + m31 * point.y + m32 * point.z + m33;
num = 1f / num; ////check this line
result.x *= num;
result.y *= num;
result.z *= num;
return result;

clipCoord is already normalized from -1 to 1 for x and y you only need to multiply it with screen width and height to get screen coordinate