screenunity-game-enginespawning

Make objects spawn correctly within different screen widths sizes unity


I made my first game in Unity. It should be published to Android and iOS. Everything is working fine except the asteroids are cut off when I change the screen ratio to 9:18(Samsung S8, Lg G6...) The asteroids are being cut off because the spawn points are fixed to -2.4f to 2.4f. I tried various things but nothing worked...I was already told to use screen.width and then to make some logic but I have no idea how to make the logic so that it actually works. enter image description here

Here is my code that is spawning the asteroid in scene: Instantiate(asteroid1prefab, new Vector3(Random.Range(-2.4f, 2.4f), 6, 0), Quaternion.identity);

Any kind of help would be appreciated thank you


Solution

  • You need to replace your spawn range with a range based on the screen size. For that you can project viewport coordinates to world coordinates

    Quoting the doc:

    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.

    Use Camera.ViewportToWorldPoint with input (0, 0) and (1, 1) to get the world coordinates of the top right and bottom left points of your screen. These will allow you to set the proper range to spawn your objects

    EDIT:

    This should give you something that looks like

    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);