Struggling to under...

Struggling to understand implementation of WorldToViewportPoint in project  



I'm working through the Udemy course and in the Player Bounds section I did some Googling to try to figure out a way to get the coordinates for the edge of the screen to determine where I should wrap or bound the player instead of hard coding it.  I found the following solution somewhere online and while the code works I'm completely confused as to how.  What I think I understand makes little sense:

        Camera cam = Camera.main;
float width = 1 / (cam.WorldToViewportPoint(new Vector3(1, 1, 0)).x - 0.5f);
float height = 1 / (cam.WorldToViewportPoint(new Vector3(1, 1, 0)).y - 0.5f);
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = new Vector3(width / 2, height / 2, 0);

The result here is a sphere is put in the upper right corner of the screen but I don't understand how.  Obviously both my limited understanding is wrong, then how some of the math translates isn't something I understand at all and I'm hoping someone will take pity on me and be able to help me understand.  I've read the API docs on the function and tried to find videos.  I understand the worldspace is the game coordinate system, viewport is a 2d vector that goes from lower left (0,0) to upper right (1,1).  

Confusion 1:  The WorldToViewportPoint makes no sense to me.  Passing it a Vector(1,1,0) would be a World Space vector which I expect to point the lower left of a 1x1 unit object at 0,0 if you reduce it by 0.5f.  So why is this useful to me?  Wouldn't this be the same as Viewspace (0.5f, 0.5f)?

Confusion 2.. really the rest:  I don't get at all how the math translates back to a world coordinate.  How does the 1/x give me the width or height?  How does dividing that by 2 give me the world coordinates at z=0?  

1 Answer

I didn't get an answer to this but went another way and am posting that here.  What I ended up doing was building a ViewManager in the general unity singleton pattern of returning the instances as a static etc.

As this is a 2D game I just kept the Viewmanager game object at 0,0, and had the script pull the main camera and calculate ViewporttoWorldPoint from there.




Scroll to Top

Please Login or Register