我正在构建一个非常简单的平台游戏,使用 2D 数组来构建基于它的地图。
我想要两个简单的目标,但目前还没有找到答案:
- 确保相机为 16:9 并且我的场景将 100% 显示在其中
- 像在数组中一样构建 2D 平台图块集
我的环境:
- Unity 5.5.0f3(2D 模式)
- 相机投影正交尺寸10.9
- 游戏以16:9的比例显示
- 图块集尺寸为 128x128 像素
这是我当前的代码:
public Camera camera;
public GameObject prefab;
void Start () {
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (0, 0, 0));
Vector3 nextPosition = pos;
for (int i = 0; i < 32; i++)
{
for(int j=0; j < 18; j++)
{
GameObject a = Instantiate(prefab, new Vector3(nextPosition.x, nextPosition.y, 0), Quaternion.identity);
nextPosition = new Vector3(pos.x+(prefab.GetComponent<Renderer>().bounds.size.x)*i, pos.y+(prefab.GetComponent<Renderer>().bounds.size.y)*j,0);
}
}
}
对此有3点需要注意:
- 我正在使用 ScreenToWorldPoint 获取 0,0,0 的位置
- 我的构建顺序从左下角到右上角,每次迭代都作为过去的位置+块宽度/高度(x和y)
- 我使用 16:9 的方案,结果是 32:18
Using it, this is my result:
正如您所看到的,它超出了相机边界,即使相机和代码都是 16:9,它也超过了 1 列。另请注意,实例化点恰好位于游戏对象的中间,因此我开始将其实例化为游戏对象宽度和高度的一半,这意味着:
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (64, 64, 0));
And the reuslt is the following:
根本不是我所期望的,通过反复试验,我发现它应该在 16,16:
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (16, 16, 0));
Now its a perfect fit, but it exceeds 1 line at the top and 1,5 columns at the right. Which shouldn't because they are both 16:9
我显然做错了什么,但我不知道是什么,我过去曾经遇到过这个问题,但我不记得我发现了什么。