问题描述
我试图在Unity 2d中随机实例化屏幕中的内容
I am trying to randomly instantiate things within the screen in Unity 2d
我尝试使用Screen.Width和Screen.Height,但是对象出现在屏幕之外.我意识到这是因为Screen.width/height返回以像素为单位的长度,而单位以其自己的单位表示.
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 );
是否可以将像素转换为Unity单位?
Is there a way to convert the Pixels to Unity units?
推荐答案
当然可以,使用 ScreenToWorldPoint .
请注意,API会通知您屏幕的左下角是0,0,因此您需要相应地更改randomX/Y.
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.
这篇关于如何利用Screen.Width/height? --Unity3d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!