Sign in to follow this  

Unity Trying to spawn boxes just outside the cameras viewing rect

This topic is 403 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to spawn a bunch of boxes at random positions between the camera rect's minimum x and minimum y point, and slightly over the cameras Y point.

 

But I have no idea at all how I should go about calculating where those points are in world space.

 

Here's a picture of the points I want to get, the rectangle is the cameras viewing rect.

 

4bOcGJk.png

 

Also, if you didn't read the tags, I'm using Unity for this project, and it's a 2D (prtographic) camera.

Share this post


Link to post
Share on other sites
He mentioned he is using an orthographic camera, so the depth shouldn't be a problem.

Take a look at the (orthographic) size of the camera. This value is half of what the camera whill capture on the vertical axis. If you add/subtract it to/from the y-position of the camera, you'll get the upper/lower edge. To get the left/right edge, you'll have to multiply it with the cameras espect ratio, and add/subtract the result to/from the x value. The property "aspect" should be the one you can use for that, otherwise you can calculate it by deviding the viewport width by the viewport height.
After you got the the corner, you'll need to add/subtract half the objects size you want to spawn in order for it to be just outside the cameras view.
(All this assumes your camera is not rotated. If it's rotated in 90° steps, you'll just need to swap some angles or invert some values. If it is another angle, you'll need to do some more math, but the basic calculation should be the same.)

Btw: The C# tag is visible in the topic overview, the Unity tag is not. You might want to change the order of the tags, since Unity is the most important information in this case. Edited by Sacaldur

Share this post


Link to post
Share on other sites

He mentioned he is using an orthographic camera, so the depth shouldn't be a problem.

Take a look at the (orthographic) size of the camera. This value is half of what the camera whill capture on the vertical axis. If you add/subtract it to/from the y-position of the camera, you'll get the upper/lower edge. To get the left/right edge, you'll have to multiply it with the cameras espect ratio, and add/subtract the result to/from the x value. The property "aspect" should be the one you can use for that, otherwise you can calculate it by deviding the viewport width by the viewport height.
After you got the the corner, you'll need to add/subtract half the objects size you want to spawn in order for it to be just outside the cameras view.
(All this assumes your camera is not rotated. If it's rotated in 90° steps, you'll just need to swap some angles or invert some values. If it is another angle, you'll need to do some more math, but the basic calculation should be the same.)

Btw: The C# tag is visible in the topic overview, the Unity tag is not. You might want to change the order of the tags, since Unity is the most important information in this case.

 

Fixed the tags, though I don't understand why you need to multiply with the aspect ratio? :o

Share this post


Link to post
Share on other sites
The value stored in orthographic size is just the "vertical size". Since the camera is most certainly not showing a perfectly rectengular view of the game, the "horizontal size" is a different value. You can calculate that by [tt]horizontal size = vertical size / height * width[/tt]. Since the aspect ratio is already calculated with a [tt]aspect ratio = width / height[/tt], you can shorten the calculation to just [tt]horizontal size = vertical size * aspect ratio[/tt]

Share this post


Link to post
Share on other sites

The value stored in orthographic size is just the "vertical size". Since the camera is most certainly not showing a perfectly rectengular view of the game, the "horizontal size" is a different value. You can calculate that by [tt]horizontal size = vertical size / height * width[/tt]. Since the aspect ratio is already calculated with a [tt]aspect ratio = width / height[/tt], you can shorten the calculation to just [tt]horizontal size = vertical size * aspect ratio[/tt]

 

Oh, I see.

Managed to get the left and right sides working, however I'm still having problems with the upper side of the camera.

 

Here's my current code which results in the objects spawning too much over the upper side of the camera rect : 

objectY = Camera.main.transform.position.y + Camera.main.orthographicSize;

Share this post


Link to post
Share on other sites

Camera.main.transform.position.y might be the top edge, so you might just be able to spawn the object there (or ObjectHeight above).

 
Yeah, that worked, thanks :)


No, that value is not the top edge of the camera, but it is its center. If it results in the desired behavior, the problem lies at another place. The camera in use might not be the main camera, resulting in [tt]Camera.main[/tt] returning the wrong camera. The spawned object might not be "centered" properly, meaning its position is not in its center. Without further knowledge about the GameObjects in the scene and the other code, I can't say with certainty what the reason for this actually is.

Btw: you're better of not using [tt]Camera.main[/tt], since it probably makes a search for the proper camera by the Tag "MainCamera" every time you want to retrieve the camera. Depending on how often you use it, this could affect the performance of the game. Also, by not searching for the object you want to use, but by getting it assigned from outside, your code is getting rid of dependencies. (See "inversion of control".)

Share this post


Link to post
Share on other sites

 

 

Camera.main.transform.position.y might be the top edge, so you might just be able to spawn the object there (or ObjectHeight above).

 
Yeah, that worked, thanks :)

 


No, that value is not the top edge of the camera, but it is its center. If it results in the desired behavior, the problem lies at another place. The camera in use might not be the main camera, resulting in [tt]Camera.main[/tt] returning the wrong camera. The spawned object might not be "centered" properly, meaning its position is not in its center. Without further knowledge about the GameObjects in the scene and the other code, I can't say with certainty what the reason for this actually is.

Btw: you're better of not using [tt]Camera.main[/tt], since it probably makes a search for the proper camera by the Tag "MainCamera" every time you want to retrieve the camera. Depending on how often you use it, this could affect the performance of the game. Also, by not searching for the object you want to use, but by getting it assigned from outside, your code is getting rid of dependencies. (See "inversion of control".)

 

 

My main camera has the correct tag, and I only retrieve the camera around 2 times per second so I don't think it should be a problem.

 

The GameObjects are instantiated from this prefab : 

 

068b72054247c3dd2111a850eb314282.png

 

And my code only spawns it at a randomized position, and a increasing scale.

 

Here's the code I have assigning the position to the object.

        /* Calculate the camera viewing rect's position, so that we can position the created objects over and inside it. */
        Vector2 minPos = new Vector2();
        Vector2 maxPos = new Vector2();
        minPos.x = Camera.main.transform.position.x - (Camera.main.orthographicSize * Camera.main.aspect) + newScale.x;
        minPos.y = Camera.main.transform.position.y;
        maxPos.x = Camera.main.transform.position.x + (Camera.main.orthographicSize * Camera.main.aspect) - newScale.x;
        maxPos.y = minPos.y;

        /* Create a random X position for the object, and give it a Y position just over the cameras visibility "field", and apply it to the object. */
        Vector2 position = new Vector2();
        position.x = Random.Range(minPos.x, maxPos.x);
        position.y = maxPos.y + newScale.y + 1; /* Make sure the object is spawned over the camera-viewing rect. */
        instantiatedObject.transform.position = position;

And this seems to work... :o

Share this post


Link to post
Share on other sites

This topic is 403 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628647
    • Total Posts
      2984035
  • Similar Content

    • By arash khalaqhdoust
      hey guys i hope you doing all well. last night i released my first game in google app store, i really appreciate you guys  to download it. and share your reviews about it
      the idea of game comes from mini hackgame of Bioshock.
       link of download:
      https://play.google.com/store/apps/details?id=com.RVBinary.piperist
      many thanks
    • By ForgedInteractive
      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! Currently, we're progressing very quickly with our first project and there are plenty of opportunities and work for new interested programmers. With this project, our development platform is Unity 5.5.2 and C# as our behavioral language. Since this project is our first release, the game itself is a smaller project though progress is moving quickly. We are looking to finalize the current project and get started on future projects in the near future and are expanding our team to do so.
       
      Who We Are Looking For:
      Programmer Level Designer  
      About the Game
      Ours is the tale of two siblings, thrown into a world of chaos. Living in the shadow of their parents' heroic deeds and their Uncle's colorful military career, Finn and Atia are about to become the next force to shape our world. How will you rise through the ranks of Hereilla and what will be your legacy? Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.
       
      Previous Work by Team
      Although we are working towards our first game as Forged Interactive, our team members themselves have worked on titles including and not limited to:
      Final Fantasy Kingsglaive FIFA 2017 Xcom 2 Civilization  
      What do we expect?
      Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
       
      What can we offer?
      Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
       
      Contact
      If you are interested in knowing more or joining, please email or PM us on Skype. A member of our management team will reply to you within 48 hours.
       
      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive
       
      Regards,
      David, Colin and Joseph
       
      Follow us on:
      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK3zhq5ToOeDpdI0Eik-Ug?view_as=subscriber
      Reddit: www.reddit.com/user/Forged_Interactive

    • By dell96
      I'm trying to make my first project but I'm stuck i don't know how to make my crate to start to spawn again when i hit the start button after i die.
      hoping someone can help!!!
      Crate.cs
      CrateSpawn.cs
      Cratework.cs
      GameController.cs
      GameManager.cs
  • Popular Now