Camera.main.ViewportToWorldPoint doesn't work
I’ve been trying to get the screen edge coordinates of my game so I can keep the player from going offscreen (the camera doesn't move), and upon checking other questions here on Unity Answers, it seems that the camera’s ViewportToWorldPoint function is the key. So I tried it, but the results are just way off.
Messing around in the editor, the actual coordinates are approximately: Top: 7 Bottom: -4.5 Right: 7.5 Left: -7.5
Yet ViewPortToWorldPoint gives me these: Top: 1 Bottom: 1.5 Right: 0.77 Left: 0
Here is the code that gave me these results:
Float left = Camera.main.ViewportToWorldPoint(Vector3.zero).x;
Float right = Camera.main.ViewportToWorldPoint(Vector3.one).x;
Float top = Camera.main.ViewportToWorldPoint(Vector3.zero).y;
Float bottom = Camera.main.ViewportToWorldPoint(Vector3.one).y;
I think I might’ve gotten something wrong or misunderstood something. So, how do I actually get the screen edge coordinates, so that wherever I decide to place my camera, I can keep objects from going offscreen?
Answer by Priyanka-Rajwanshi · Dec 21, 2019 at 02:03 PM
@Tespy If you see the image, both the cubes A and B are placed towards the right corner, however, the x-position of A is 9 and of B is 6. This is due to the difference in the z-axis coordinates. As per your example, the right coordinate should be 7.5. With your approach, you have taken a viewport point with z-coordinate as 0 (Vector.zero is 0,0,0). This point might correspond to a different point C with a difference z-coordinate in the world space.
For getting the exact point as you expect through editor, take a GameObject say cube and use the below code:
Vector3 myViewPos = Camera.main.WorldToViewportPoint(cube.transform.position);
left = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, myViewPos.z)).x;
right = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, myViewPos.z)).x;
top = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, myViewPos.z)).y;
bottom = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, myViewPos.z)).y;
For better understanding of the points in unity, you can see the link http://codesaying.com/understanding-screen-point-world-point-and-viewport-point-in-unity3d/
Your answer
Follow this Question
Related Questions
Boolean variable is never true, even if declared true or ticked in the inspector 1 Answer
How I can make my camera keep a distance between two objects? 0 Answers
Set the rotation axis of the camera 0 Answers
How to do a wall jump? i am very novice 0 Answers
Issue with Rigidbody2D (I think) 2 Answers