- Home /
ViewportToWorldPoint returns same value regardless of input
I'm trying to use ViewportToWorldPoint which seems pretty basic, yet I cannot get it to work. Using the docs ( http://docs.unity3d.com/ScriptReference/Camera.ViewportToWorldPoint.html ), I've created this simple test code:
Camera curCamera = Camera.main;
Vector3 pos1 = new Vector3 (0.0f, 0.0f, curCamera.nearClipPlane);
Vector3 pos2 = new Vector3 (1.0f, 1.0f, curCamera.nearClipPlane);
Vector3 pos3 = new Vector3 (99999.0f, 0.0f, curCamera.nearClipPlane);
Vector3 world1 = curCamera.ViewportToWorldPoint(pos1);
Vector3 world2 = curCamera.ViewportToWorldPoint(pos1);
Vector3 world3 = curCamera.ViewportToWorldPoint(pos1);
Debug.Log("pos1 >> world1: " + pos1 + " >> " + world1);
Debug.Log("pos2 >> world2: " + pos2 + " >> " + world2);
Debug.Log("pos3 >> world3: " + pos3 + " >> " + world3);
From the above, I get this output:
pos1 >> world1: (0.0, 0.0, 1.0) >> (-1.0, -0.6, -23.0) pos2 >> world2: (1.0, 1.0, 1.0) >> (-1.0, -0.6, -23.0) pos3 >> world3: (99999.0, 0.0, 1.0) >> (-1.0, -0.6, -23.0)
My expectations are that I should get back my lower left viewport position, my upper right viewport position and some wildly different value for my out of bounds '99999.0'. However I get exactly the same thing returned for all.
What have I messed up?
Answer by Eric5h5 · Oct 19, 2014 at 05:06 PM
I would assume that you have a very small size or field of view for the camera, so the values are close but not actually identical. Print out the individual x/y/z elements of world1 etc.
You're correct, and I also messed up my example; I passed 'pos1' to each call to ViewportToWorldPoint. Fixing that, I get
pos1 >> world1: (0.0, 0.0, 0.3) >> (-0.3, -0.2, -23.7) pos2 >> world2: (1.0, 1.0, 0.3) >> (0.3, 0.2, -23.7) pos3 >> world3: (99999.0, 0.0, 0.3) >> (61552.2, -0.2, -23.7)
The values are very small and I was not expecting them to vary around (0, 0) from negative to positive. I'll have to play with this a bit more to improve my understanding.
Thanks for your help.
Your answer
Follow this Question
Related Questions
ViewportToWorldPoint relative to camera angle 2 Answers
How to position UI elements on the Minimap's rectangle relative to the elements target position? 1 Answer
Move an object in world space on the viewport 0 Answers
Move a 3d object from world space in the camera UI 2 Answers
How to clamp player to viewport constraints when rotating 1 Answer