Search code examples
c#unity-game-enginespawning

Unity 2D Help - Random Spawining Of Asteroids Without Having Them Spawn In Camera View


I'm currently making a "free roam" 2D space game from a birds-eye view.

I am trying to randomly spawn in asteroids around the scene so that they can be used to collide with ships, although I don't want these asteroids to spawn in the camera view because I don't want it to look like an asteroid appeared out of nowhere.

Can anyone explain to me how I can achieve this?

I don't think it is necessary for me to show my code because the only thing I really have is a simple movement script and a camera follow script.

Thank you in advance!


Solution

  • You can get the Position of your camera using

    Camera.main.transform.position;
    

    In the inspector you can set the size of your camera, which is half the height of the Area covered by your camera in world units. The only remaining information that you need would be the aspect ratio so you can calculate the width of the area covered by the camera.

    Then you can instantiate the asteroids at any point (x, y) where y > (Camera.main.transform.position.y + sizeOfYourCamera) and/or x > (Camera.main.transform.position.x + sizeOfYourCamera * aspectRatio).

    This only covers points above and to the right of your camera, but you get the idea.