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
2
Question by CoCoMolly · Jan 23, 2013 at 12:10 AM · distancefor looprandom spawn

Instantiating objects at random positions with a certain distance between each other?

I have an Empty gameObject that creates 20 objects at the start of the game.

 var houses:Array = new Array();
 var hs:Transform;
 
 function Start () 
 {
 
     for(var a:int = 0; a < 20; a++)
     {
     ex = Random.Range(-200, 201);
     zee = Random.Range(-200, 201);
     newPos = Vector3(ex, 400, zee);
     newhs = Instantiate(hs, newPos, transform.rotation);
     houses.Push(newhs);
     }
 }

How can I make sure that all of the objects are a certain distance from each other? I know it probably involves a for-loop inside the initial for-loop to check the distances. Anyone have an example script? Or an idea of what i can do? Thanks

Comment
Add comment · Show 1
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 cdrandin · Jan 23, 2013 at 01:20 AM 0
Share

Starting to think about this, I suggest a while loop because it is possible to have values that don't satisfy the distance which in end will ignore Instantiate, yet continue the incremental of the for loop. $$anonymous$$eep a spawn counter.

5 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by aldonaletto · Jan 23, 2013 at 01:28 AM

You could create a function that draws a new location and check the neighborhood: if there are other objects closer than minDistance, draw another position, otherwise return the new position. For instance:

 var houses:Array = new Array();
 var hs:Transform;
 var minDistance: float = 30;
 var size: float = 200;
 
 function FindNewPos(): Vector3 {
   do {
     // draw a new position
     var newPos = Vector3(Random.Range(-size, size), 400, Random.Range(-size, size));
     // get neighbours inside minDistance:
     var neighbours: Collider[] = Physics.OverlapSphere(newPos, minDistance);
     // if there's any neighbour inside range, repeat the loop:
   } while (neighbours.length > 0);
   return newPos; // otherwise return the new position
 }
 
 function Start (){
   for(var a:int = 0; a < 20; a++){
     var newPos = FindNewPos();
     newhs = Instantiate(hs, newPos, transform.rotation);
     houses.Push(newhs);
   }
 }

There's a problem, however: Physics.OverlapSphere returns any colliders that touch the sphere - even the terrain, if it's inside the range. If there are other objects that must be ignored, set the house prefab layer to 8, for instance, and use a layer mask in OverlapSphere:

     var neighbours: Collider[] = Physics.OverlapSphere(newPos, minDistance, 1<<8);

This way, only the houses are counted.

Comment
Add comment · Show 3 · 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
avatar image cdrandin · Jan 23, 2013 at 01:31 AM 0
Share

What does the 1<<8 do? I am not familiar with that at all, but I keep seeing it in some code now.

avatar image aldonaletto · Jan 23, 2013 at 11:48 AM 0
Share

<< is the shift left operator: 1<<8 means shift 1 to the left 8 times. The layer number is actually the bit position in an integer that has only one bit set. Layer 8 has a bit mask equal to 00000100000000b (binary): bit 8 is one, and all others are zero (the rightmost bit is bit 0). The easiest way to generate this weird binary number is by shifting the number 1 left 8 times (1<<8). You will see things like this frequently in scripts that use layers.

avatar image sairaamin · Nov 16, 2018 at 04:58 AM 0
Share

can someone translate that to C# would be great.

avatar image
1

Answer by Pysassin · Jan 23, 2013 at 01:23 AM

Make another Vector3 variable for the last position used then use a if statement attached to a Vector3.distance or sqrmagnitude. If the result is lower then the desired distance make the if statement ignore it and re randomize the position. As CD said though I would use a while loop then said after x number of items have been made stop.

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
avatar image
1

Answer by cdrandin · Jan 23, 2013 at 01:28 AM

 var houses:Array = new Array();
 var hs:Transform;
 var spawnAmount : int = 20;
 var distance : float = 5;
 private var spawnCount : int = 0;
 private var isGood : boolean = false;
 
 function Start () 
 {
     while ( spawnCount < spawnAmount ){
       ex = Random.Range(-200, 201);
       zee = Random.Range(-200, 201);
       newPos = Vector3(ex, 400, zee);
       
       for( var i in houses ){
         //If new position is too close, don't bother with this random position
         if( Vector3.Distance(i.position, newPosition) < distance)
           isGood = false;
           break
         else
           isGood = true;
       }
       if(isGood){
         spawnCount++;
         newhs = Instantiate(hs, newPos, transform.rotation);
         houses.Push(newhs);
       }
     }
 }

Hoping that it works, but this is the idea. Check that the random coordinates is valid, if it isn't don't bother creating and wait for loop to start over to get new coordinates. If coordinates are good then create object, store into list, and increase spawn counter. This code is not test.

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
avatar image
0

Answer by robertbu · Jan 23, 2013 at 02:02 AM

Here is a quick take on the problem using a brute force approach. It generates a list of positions first and then creates the objects. The code repeatedly tries to find random values for a position (up to iMaxTries) that meet the distance criteria. If it fails, it bails out and then creates objects for positions that succeeded. For any reasonable settings of fMinDist and range of x and z values, it will almost always succeed in creating all 20. It is in C#.

 void RandomGenerate() {
     Vector3 v3T = Vector3.zero;
     Vector3[] arv3 = new Vector3[20];
     float fMinDist = 10.0f;   // Minimum distance they need to be apart
     int iMaxTries = 1000;    // Number of times to try to generate a position
     float fMinTry = Mathf.Infinity;
     
     int i;
     for (i = 0; i < 20; i++) {
         
         for (int j = 0; j < iMaxTries; j++) {
             v3T.x = Random.Range (-100.0f, 100.0f);
             v3T.z = Random.Range (-100.0f, 100.0f);
             
             fMinTry = Mathf.Infinity; 
             for (int k = 0; k < i; k++)
                 fMinTry = Mathf.Min ((v3T - arv3[k]).magnitude, fMinTry);
             
             if (fMinTry > fMinDist) // Far enough apart
                 break;
         }
         if (fMinTry < fMinDist) {
             Debug.Log ("Generation failed -- only found " + i + " points");
             break;
         }
         arv3[i] = v3T;
     }
     
     for (int j = 0; j < i; j++) {
         GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
         go.transform.position = arv3[j];
     }
 

}

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
avatar image
0

Answer by dan_cmj · Apr 24, 2019 at 09:15 PM

This is my take on it. I created an area on which objects are meant to spawn. I made it draw the radiuses and the spawn area of the "houses". Something to note is that whatever object you declare as "House" must have a boolean as a property to keep track of it's spawn status and draw the gizmos accordingly.

This spawner in particular spawns houses every frame and repeats. So it's easy to visualize frame by frame within the editor

C# Not perfect but works!

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class HouseSpawner : MonoBehaviour
 {
 
     public House housePrefab;
     public int spawnQuantity = 10;
     public static List<House> Houses = new List<House>();
     [Range(0.01f, 2)]
     public float toleranceRadius = 1.0f;
     public Vector3 size = new Vector3(1,1,1); //The area on which we can spawn.
     bool cooldown = false;
 
     void Start()
     {
         House newHouse;
 
         for (int i = 0; i < spawnQuantity; i++)
         {
             newHouse = (House)Instantiate(housePrefab, Vector3.zero, Quaternion.identity);
             Houses.Add(newHouse);
         }
     }
 
     private void LateUpdate()
     {
         if (!cooldown)
             StartCoroutine(AutoRespawner());
     }
 
     IEnumerator AutoRespawner() {
         cooldown = true;
 
         foreach (var house in Houses) { 
             house.transform.position = new Vector3();
             house.placedByForce = false;
         }
 
         foreach (var house in Houses)
         { 
             house.transform.position = FindNewPos(ref house.placedByForce);
             yield return null;
         }
         
         cooldown = false;
     }
 
     public Vector3 FindNewPos(ref bool placedByforce)
     {
         Vector3 newPos = new Vector3();
         int neighbours = 0;
         int searchLimit = 60;
         int i = 0;
         Collider[] results = new Collider[spawnQuantity];
 
         do {
             if (i >= searchLimit)
             {
                 Debug.Log("Placed by force.");
                 placedByforce = true;
                 break;
             }
 
             newPos = transform.position + new Vector3(Random.Range(-size.x / 2, size.x / 2), 0, Random.Range(-size.z / 2, size.z / 2));
             neighbours = Physics.OverlapSphereNonAlloc(newPos, toleranceRadius, results, 1 << 9);
 
             i++;
         } while (neighbours > 0);
         // This loop doesn't guarantee 100% success,
         // so be mindful of the size of the colliders
         // being used and the searchLimit and toleranceRadius.
 
 
         return newPos;
     }
 
     void OnDrawGizmosSelected()
     {
 
         if (Houses.Count > 0)
         {
             foreach (var house in Houses)
             {
                 Gizmos.color = new Color(1, 1, 0, 0.5f);
                 if (house.placedByForce)
                     Gizmos.color = new Color(1, 0, 0, 0.5f);
 
                 // Draw a line depicting the tolerance radius.
                 Debug.DrawLine(house.transform.position, (toleranceRadius * house.transform.forward) + house.transform.position, Gizmos.color, 0);
                 // Draw a sphere depicting the tolerance bubble.
                 Gizmos.DrawSphere(house.transform.position, toleranceRadius);
             }
         }
 
         Gizmos.color = new Color(1, 1, 1, 0.5f);
         // Draws the area on which objects can spawn on.
         Gizmos.DrawCube(transform.position, new Vector3(size.x, 1, size.z));
     }
 }
 



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

14 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

Related Questions

Distance from raycast. 1 Answer

Frustum culling question 1 Answer

White textures when objects are really far away on android? 1 Answer

check if an always changing int variable suddenly stop changing 1 Answer

How to check distance between two players (photon multiplayer) 2 Answers


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