使对象在不同的​​屏幕宽度大小统一内正确生成

Make objects spawn correctly within different screen widths sizes unity

我在 Unity 中制作了我的第一款游戏。它应该发布到 Android 和 iOS。一切正常,除了当我将屏幕比例更改为 9:18(Samsung S8, Lg G6...) 时小行星被切断因为生成点固定为 -2.4f 到 2.4,小行星被切断F。我尝试了各种方法,但没有任何效果......我已经被告知使用 screen.width 然后制作一些逻辑,但我不知道如何制作逻辑以使其真正起作用。 enter image description here

这是我在场景中生成小行星的代码:Instantiate(asteroid1prefab, new Vector3(Random.Range(-2.4f, 2.4f), 6, 0), Quaternion.identity);

如有任何帮助,我们将不胜感激,谢谢

您需要将生成范围替换为基于屏幕尺寸的范围。 为此,您可以将 视口坐标 投影到 世界坐标

引用文档:

A viewport space point is normalized and relative to the Camera. The bottom-left of the Camera is (0,0); the top-right is (1,1). The z position is in world units from the Camera.

使用 Camera.ViewportToWorldPoint 输入 (0, 0) 和 (1, 1) 获取屏幕右上角和左下角的世界坐标。这些将允许您设置适当的范围来生成您的对象

编辑:

这应该会给你一些看起来像

的东西
Vector3 bottomLeftWorld = camera.ViewportToWorldPoint(new Vector3(0, 0, camera.nearClipPlane));
Vector3 topRightWorld = camera.ViewportToWorldPoint(new Vector3(1, 1, camera.nearClipPlane));

Instantiate(asteroid1prefab, new Vector3(Random.Range(bottomLeftWorld.x, topRightWorld.x), topRightWorld.y, 0), Quaternion.identity);