- Home /
How can I get the x position for the left(and right) of the screen?
In Unity, I am making a game where spheres spawn at a random position. I want the spheres can spawn a little outside the screen. This is the code where the spheres spawn:
Instantiate (sphere_prefab, new Vector3 (Random.Range (-7, 7), 10, 0), Quaternion.identity);
On a mobile it works great and the cubes can spawn (half)outside the screen, but on my pc, the spheres will not spawn outside the screen cause the screen is bigger so I want to know the left position of the screen so the code can be like this
Instantiate (sphere_prefab, new Vector3 (Random.Range (screenLeft-2, screenRight+3), 10, 0), Quaternion.identity);
Sorry for my bad English. Thanks in advance!
What kind of camera are you using? Perspective or orthographic? You seem to place the object at a z position of 0. Is it a 2d or 3d game / application?
A perspective camera doesn't have a unique border as the viewable area is a trapezoid shaped frustum where the world space position depends also on the distance to the camera.
Answer by whaleinthesea · Aug 15, 2015 at 01:16 PM
I already figured out the answer, Use viewportpoint; 0,0 is left under 1,1 is upper right
Answer by nullgobz · Aug 09, 2015 at 03:49 PM
You can use Screen.width and Screen.height to get the size of the Screen.
But that is in pixel units.
So you would have to convert it.
What you could do is this:
float offset = 20; // Change this value to something you like.
Instantiate (sphere_prefab,
new Vector3(Random.Range (Screen.width / 2.0f - offset, Screen.width / 2.0f + offset),
10, 0), Quaternion.identity);
But the offset value need to change dependent on what aspect ratio you are running.
The aspect ratio is the (Screen.width / Screen.height).
So for example:
void Start()
{
if((Screen.width / Screen.height) == 1.6f)
offset = 25.0f; // Some value that works for this aspect
}
I hope this will help you abit. :)
I have tried your code but unfortunately it have not worked, all of the spheres are spawned 400 px(horizontally) away from the camera
Your answer
Follow this Question
Related Questions
problem with instance 1 Answer
Moving a transform behaves odd 0 Answers
Walking forward 2 Answers
Following Object can't find newly Instantiated Object (Solved) 1 Answer
Destroy a specific instantiated clone? 2 Answers