5

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

  • I don't if you are the one who upvoted my answer (if yes, thanks). Just in case (since I see that you are new here), the good practice is to **accept** an answer if you consider it answered your question. See [Here](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) how to do it – Basile Perrenoud Jan 31 '18 at 16:43

1 Answers1

6

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);
Basile Perrenoud
  • 4,039
  • 3
  • 29
  • 52