How calculated ScreenToWorldPoint

Hello

What does the ScreenToWorldPoint code look like?

It would be something like that, but it doesn’t return the value it should.

 public Vector3 ScreenToWorldPoint(Vector3 position) {
         float x = (2.0f * position.x / Camera.main.pixelWidth) - 1.0f;
         float y = (2.0f * position.y / Camera.main.pixelHeight) - 1.0f;
         float z = position.z * 2 - 1;
         Vector3 clip = new Vector3(x, y, -1.0f);
 
         Matrix4x4 viewInverse = Camera.main.cameraToWorldMatrix;
         Matrix4x4 projectionInverse = Matrix4x4.Inverse(Camera.main.projectionMatrix);
         Matrix4x4 viewProjectionInverse = viewInverse * projectionInverse;
 
         Vector3 worldPoint = viewProjectionInverse.MultiplyPoint(clip);
 
         return worldPoint;
     }

What’s the exact issue you have with your code? What value do you get back from your code? I don’t see a real issue with your code. Over here in the comment I posted two methods. One that calculates the unproject matrix from viewport space to world space and a second method which does the same as ViewportToRay. My code does pretty much the same thing that you did here. I’ve tested my code in Unity and it works just fine.

Note that using the cameras pixelwidth / height is pretty pointless if you ignore the potential offset. You usually would use Screen.width and Screen.height. If you use the camera specific values you should use the actual camera rect. Though If a camera only renders to a part of the screen the offset of that region also need to be taken into account. Though since you just talk about screen space to world space we usually assume a camera that renders to the full screen anyways.

Note that your code currently always returns the point on the near clipping plane since you hardcoded a z value of -1. If that’s your issue you probably want to replace the “-1” with “z”.