- Home /
Make sure objects are not instantiated on each other
I am currently working on a 2d endless runner. when i generate platforms, i randomly decide if there is a coin on the platform and if there's an obstacle, then i calculate where they are above the platform. If both a coin and obstacle are instantiated, how would i make sure they aren't instantiated on each other?
Answer by MikeNewall · Feb 02, 2014 at 02:22 AM
Instantiate your obstacle at a random point, then Instantiate the coin at a random point. Check if the coin intersects with the obstacle. If not then you're done, else you wanna pick a new random position and repeat the check until you find a position that's free.
Something like this in code:
 public GameObject coin = null;
 public GameObject obstacle = null;
 void Start()
 {
     GameObject obstacleInstance = null;
     // Decide if we want an obstacle
     if(Random.value < 0.5f){
         Vector3 position = Vector3.zero; // Add your logic tp Calculate a new position here
         obstacleInstance  = (GameObject)Instantiate(obstacle, position, Quaternion.identity); // Instantiate obstacle at calculated position
     }
     // Decide if we want a coin
     if(Random.value > 0.5f){
         // Create a coin at a random position
         Vector3 position = Vector3.zero; // Add your logic to Calculate a new position here
         GameObject coinInstance = (GameObject)Instantiate(coin, position, Quaternion.identity);
         if(obstacleInstance){
             
             // If there is an obstacle calculate a new position until the  objects don't intersect
             while (coinInstance.renderer.bounds.Intersects(obstacleInstance.renderer.bounds)) {
                 position = Vector3.zero; // Add your logic to Calculate a new position here
                 coinInstance.transform.position = position;
             }
         }
     }
 }
Answer by morgan23 · Feb 02, 2014 at 12:54 AM
you can use random.range too make it spawn a different Gameobject and location.
I know, but what if they generate similar locations? Then they will overlap.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                