- Home /
undrestanding WorldToScreenPoint and ViewportToWorldPoint
Hello,
I have created two cubes in the scene and then attached the following code to the main camera in the scene. The Cube 's position I have selected as the target for the camera which is (0,1.95,0). When I run the program, target is (273.6, 217.4, 6.8) pixels from the left is the output for the following lines: Vector3 screenPos = cam.WorldToScreenPoint(target.position); Debug.Log("target is " + screenPos + " pixels from the left");
and target world position (1.2, 3.5, -6.6) is the output for : Vector3 p = cam.ViewportToWorldPoint(target.position); Debug.Log("target world position " + p ); Non of the above outputs match the Cube (target) position which is (0,1.95,0). Can anyone by chance explain this to me? Thank you,
public Transform target; private Camera cam;
void Start()
{
cam = GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
//Transforms position from viewport space into world space
Vector3 screenPos = cam.WorldToScreenPoint(target.position);
Debug.Log("target is " + screenPos + " pixels from the left");
//Transforms position from world space into screen space
//which is defined in pixels
//The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.
Vector3 p = cam.ViewportToWorldPoint(target.position);
Debug.Log("target world position " + p );
}
}
The easiest explanation is that in the Inspector, you define transform positions in Local space. Depending on your Hierarchy, the cube may or may not be at (0, 1.95, 0) in World space. Additionally, Viewport space isn't the same as screen space. Viewports are parts of a screen, which may or may not consume the entirety of a screen. Think of window docking in Windows 10, where you can dock a window to the right or left side of the screen and pick another window to dock to the other side. The windows thus have a viewport of 0, 0.5 and 0.5, 1, while on a 1080p monitor, they'd be 0, 960 and 960, 1920 in screen space. World space is the space projected from world coordinates, through the viewport, and then to the screen. It's a fairly complicated subject involving linear algebra and 3D math, which I'm not great at, but I think I regurgitated the basics correctly at least.