- Home /
Screen width to world coordinates
Hello =) I know it's easy question, but i couldn't solve it :( I want to randomly spawn enemies on top of the screen, depending on resolution, smth like:
transform.position.x = Random.range(0,Screen.width);
but it's all bullshit. Show me the way please (:
Answer by robertbu · Feb 22, 2014 at 10:56 PM
One way is to use Viewport coordinates. Viewport coordinates go from (0,0) in the lower left of the screen to (1,1) in the upper right. In order to make a conversion, you should decide on the distance in front of the camera. For a perspective camera the width of the screen in world units varies with the distance from the camera. For Orthographic, you only have to worry about layering.
So say you want a random position at 10 units in front of the camera;
var pos = Camera.main.ViewportToWorldPoint(Random.value, 1.0, 10.0);
'pos' will be right along the top edge of the window. You could then assign the 'x' to your position (or assign pos to transform.position):
transform.position.x = pos.x;
Your answer
![](https://koobas.hobune.stream/wayback/20220613134412im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
getting screen coordinates for 3d object? 1 Answer
Is there a function for converting transform to screen coordinates? 1 Answer
Screen Coordinates of an object's corners 2 Answers
screenviewcoord[1] < 0 || screenviewcoord[3] < 0 5 Answers
Converting pixel dimensions to Unity's floating-point coordinates 1 Answer