在我的Unity2D
项目中,我正在尝试将我的精灵生成在彼此之上并跨越设备屏幕的整个高度。例如,为了给出一个想法,在整个设备的屏幕高度上想一个相互重叠的盒子。在我的情况下,我生成箭头精灵而不是盒子
我已经成功地将精灵产生在彼此之上。我现在的问题是如何计算产生多少精灵以确保它在屏幕的高度上传播。
我目前有这段代码:
public void SpawnInitialArrows()
{
// get the size of our sprite first
Vector3 arrowSizeInWorld = dummyArrow.GetComponent<Renderer>().bounds.size;
// get screen.height in world coords
float screenHeightInWorld = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height, 0)).y;
// get the bottom edge of the screen in world coords
Vector3 bottomEdgeInWorld = Camera.main.ScreenToWorldPoint(new Vector3(0,0,0));
// calculate how many arrows to spawn based on screen.height/arrow.size.y
int numberOfArrowsToSpawn = (int)screenHeightInWorld / (int)arrowSizeInWorld.y;
// create a vector3 to store the position of the previous arrow
Vector3 lastArrowPos = Vector3.zero;
for(int i = 0; i < numberOfArrowsToSpawn; ++i)
{
GameObject newArrow = this.SpawnArrow();
// if this is the first arrow in the list, spawn at the bottom of the screen
if(LevelManager.current.arrowList.Count == 0)
{
// we only handle the y position because we're stacking them on top of each other!
newArrow.transform.position = new Vector3(newArrow.transform.position.x,
bottomEdgeInWorld.y + arrowSizeInWorld.y/2,
newArrow.transform.position.z);
}
else
{
// else, spawn on top of the previous arrow
newArrow.transform.position = new Vector3(newArrow.transform.position.x,
lastArrowPos.y + arrowSizeInWorld.y,
newArrow.transform.position.z);
}
// save the position of this arrow so that we know where to spawn the next arrow!
lastArrowPos = new Vector3(newArrow.transform.position.x,
newArrow.transform.position.y,
newArrow.transform.position.z);
LevelManager.current.arrowList.Add(newArrow);
}
}
我当前代码的问题在于它没有产生正确数量的精灵来覆盖设备屏幕的整个高度。它只产生我的箭头精灵大约到屏幕中间。我想要的是它能够产生到屏幕的上边缘。
任何人都知道计算出错的地方?以及如何使当前代码更清洁?
答案 0 :(得分:1)
如果精灵是通过相机模式渲染的,并且精灵在屏幕上显示时看起来有不同的大小(远离相机的精灵小于靠近相机的精灵)那么一种新的方法来计算需要numberOfArrowsToSpawn值。
您可以尝试使用while循环添加精灵,而不是使用for循环,只需继续创建精灵,直到精灵的计算世界位置对相机不再可见。使用Jessy在此链接中提供的技术检查相机中是否可以看到某个点: http://forum.unity3d.com/threads/point-in-camera-view.72523/
答案 1 :(得分:0)
我认为您的screenHeightInWorld
实际上是screenTopInWorld
,点可以在空间的任何位置。
您需要世界坐标中的相对屏幕高度。 如果您使用ortographic投影,那么这就是相机平截头尺寸的一半,正如您所想的那样。
float screenHeightInWorld = Camera.main.orthographicSize / 2.0f;
我没有阅读其余的内容,但可能还不错,取决于你如何实现它。
我只需创建一个类似bool SpawnArrowAboveIfFits()
的箭头方法,它可以在新实例上迭代调用自己。