Generate a Unity 2d Game Object Dynamically within the different devices screen bounds

156 views Asked by At

I am new to unity and I am developing a game where I wish to create a game object dynamically. My problem is how do I calculate the random position for the game object so that it remains within the screen on different android devices. Here is something I have tried, but is my approach correct? Will this give me a proper random position on all android and iOS devices?

//Calculate the screen width and screen height
screenheight = Camera.main.orthographicSize * 2.0f;
screenwidth = screenheight * Screen.width / Screen.height;

//get a random number in width of the screen
float randomX = Random.Range(-screenwidth / 2, screenwidth / 2);

//get a random number in height of the screen
float randomY = Random.Range(-screenheight / 2, screenheight / 2);

Now the game objects position will be (randomX, randomY).

0

There are 0 answers