Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by poolts · Aug 12, 2013 at 01:34 PM · randomspawnoverlap

Randomly Place Cubes In Viewport Without Overlap

Hi all,

Been racking my brain on this for ages.

I want to randomly place cubes in the viewport, without them overlapping each other (but not based on pre-defined spawn points).

So first step was to randomise their position in the viewport.

Second step was to iterate through the collection of cube transforms and check the a potential random position is close to another others:

Two ways (both which haven't worked are) to use a Physics.Overlap at the position to check if there are any colliders there (aka other cubes), if there are try and new position, if not rinse and repeat.

The other way was to check the potential random position and then check the magnitude between all other places buildings to see if you are close, if so do it again, if not place it down.

Both of these seemed good solutions, but the physics overlap seems a bit heavy and doesn't seem to be returning any colliders (even though the cubes have box colliders) and then other solution, is 2 nested for loops, which (probably just my logic) don't seem to be working.

Any help would be greatly appreciated.

My code so far:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class BuildingManager : MonoSingleton<BuildingManager> {
     
     [SerializeField]
     Transform[] m_buildings;
     
     List<Vector3> placedBuildings = new List<Vector3>();
         
     //------------------------------------------------------------------------------------------------------
     
     void Awake()
     {        
         // Place initial building
         m_buildings[0].position = GetRandomTerrainPos(m_buildings[0]);
         
         m_buildings[0].position = new Vector3(m_buildings[0].position.x, 0f, m_buildings[0].position.z);
                         
         placedBuildings.Add(m_buildings[0].position);
         
         // Place the other buildings
         // Start index at 1
         for(int i = 1, n = m_buildings.Length; i < n; i++)
         {    
             Transform t = m_buildings[i];
             
             // Get a random position
             Vector3 randomPos = GetRandomTerrainPos(t);
                 
             // Check if this position is near any others
             for(int j = 0, k = placedBuildings.Count; j < k; j++)
             {    
                 // If the distance between the potential random position and
                 // the placed building is more than 2f (magic number) place
                 // the building there (this is a sutiable location)
                 if((randomPos - placedBuildings[j]).magnitude > 2f)
                 {
                     t.position = randomPos;
             
                     t.position = new Vector3(t.position.x, 0f, t.position.z);
                     
                     placedBuildings.Add(t.position);
                 }
                 // Else look for another location
                 else
                 {       
                     // j--;
                 }
             }
         }
     }
     
     //------------------------------------------------------------------------------------------------------
     
     Vector3 GetRandomTerrainPos(Transform t)
     {
         return Camera.main.ViewportToWorldPoint(new Vector3(Random.value, Random.value, (Camera.main.transform.position.y - t.position.y) - 5f));
     }
 }
 
Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Aug 12, 2013 at 03:10 PM 0
Share

The nested 'for' loop solution is the typical way suggested on this list to solve your problem. That is before placing a new object, compare the placement against a list of already placed object. If it conflicts, generate a new position and try again. Post your code, and someone can likely spot your problem.

avatar image ShadoX · Aug 12, 2013 at 03:47 PM 0
Share

Assu$$anonymous$$g that you have a list of the previously created cubes. Can't you just go through it and compare the location of the cube with the generated one and check the cubes size to make sure that the newly created one won't touch the old one? (and maybe order the lists content by the cube location to speed up the process in some way?)

avatar image poolts · Aug 12, 2013 at 07:17 PM 0
Share

Hi guys, I've added my code so far. I'm just getting in trouble with the nested loop.

The t.position = new Vector3(t.position.x, 0f, t.position.z) is to offset the transform to 0 (as it's a nav mesh agent) so needs to be touching the nav mesh.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · Aug 12, 2013 at 10:15 PM

You can fold it all into a single routine for performance, but unless you have a huge amount of buildings, I'll pull the building check out into it own function:

 bool FreeAndClear(Vector3 randomPos) {
     for(int i = 0, i < placedBuildings.Count; i++) {   
         if((randomPos - placedBuildings[i]).magnitude < acceptableDistance) {
             return false;
         }
     }
     return true;
 }

Then your find a position code becomes:

 Vector3 randomPos;
 for (int m = 0; m < 1000; m++) {
   randomPos = GetRandomTerrainPos(t);
   if (FreeAndClear(randomPos))
      break;
 }
 // At this point you would have a valid position
 //   or your code would have tried 1000 times to 
 //   find one and failed.

Note you want to put the check in a 'for' loop so there is a termination condition. If you put the check in a 'while(true)' there is a chance that the code could never find an acceptable position and the app would hang.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Instantiate Random 3D Objects/platforms that dont overlap 1 Answer

avoid overlap problem when randomly instantiating 0 Answers

Why do objects keep spawning on top of one another? 0 Answers

How To avoid random spawn to spawn at previously spawned object position so that they do not overlap 1 Answer

Quaternion.identity problem at random spawn 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges