- Home /
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;
}
Answer by Bunny83 · May 18, 2020 at 01:43 AM
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".
Note that your as well as my method does not resemble what Unity's "ScreenToWorldPoint" method does. This method interprets the z value as the worldspace distance from the camera origin. So it's not related to the actual projection or the viewing frustum. How exactly Unity performs this conversion internally we don't know. They might use a similar approach to my method to deter$$anonymous$$e the worldspace direction and then just scale the normalized direction with the inco$$anonymous$$g z value and add the camera origin.
Your answer
Follow this Question
Related Questions
How calculated ViewportToWorldPoint 0 Answers
GL.MultMatrix multiple instances drawing 0 Answers
Advanced info on Unity's camera matrix 0 Answers
Calculation behind camera.WorldToScreenPoint 2 Answers
changing camera view 3 Answers