I am trying to randomly instantiate things within the screen in Unity 2d
I tried to use Screen.Width and Screen.Height but the objects were appearing way off the screen. I realized that this was because Screen.width/height returns the length in pixels and unity goes by its own unit.
For example, this didn't work. The bomb appears way off Screen
var randomX = Random.Range(-Screen.width/2, Screen.width/2);
var randomY = Random.Range(-Screen.height/2, Screen.height.2);
var spawnPoint:Vector2 = new Vector3(randomX , randomY);
Instantiate( bomb, spawnPoint, Quaternion.identity );
Is there a way to convert the Pixels to Unity units?
There sure is, use ScreenToWorldPoint .
Note that the API informs you the bottom left of the screen is 0,0, so you will want to change your randomX/Y accordingly.
Make this:
Vector3 worldToScreen = Camera.main.WorldToScreenPoint(transform.position);
var randomX = Random.Range(-worldToScreen.x , worldToScreen.x);
var randomY = Random.Range(-worldToScreen.y , worldToScreen.y);
var spawnPoint:Vector2 = new Vector3(randomX , randomY);
Instantiate( bomb, spawnPoint, Quaternion.identity );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.