Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Comparing Vector3's in List

Discussion in 'Scripting' started by Aramyth, Jun 5, 2014.

  1. Aramyth

    Aramyth

    Joined:
    Oct 11, 2012
    Posts:
    12
    I'm placing game objects in my scene by generating a random position for them (they all have the same position along the y-axis) and I want to compare their x and z coordinates when placing them to ensure that objects aren't being placed on top of each other.

    Right now I am storing the GameObjects in a list after generating their positions and also storing their positions in another list for rotations and movements later.

    What's the best way to ensure that these objects aren't being placed near each other when I initialize them?

    Code (csharp):
    1.  
    2. for (inti = 0; i < godRaySize; i++) {
    3. //Assign random positions
    4. startPosition = newVector3(Random.Range (-45.0f, 140.0f) + 2.0f, 15, Random.Range(-60.0f, 60.0f) + 2.0f);
    5.  
    6. //Storethepositions
    7. raysPosition.Add(startPosition);
    8.  
    9.  
    10. //Need a check to ensure that objects don't over lap
    11.  
    12.  
    13. GameObject rays = Instantiate(godRayPrefab, startPosition, transform.rotation * Quaternion.Euler(0, 0, 100)) asGameObject;
    14.  
    15. rays.transform.parent = transform;
    16.  
    17. //Populate
    18. godRaysList.Add(rays);
    19.  
    20. }//Endfor
    21.  
    22.  
    23. }
     
  2. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    For instance, if you want your objects to always be minimum of 40 units away from each other:

    Code (CSharp):
    1. for(int i=0;i<max;i++)
    2. {
    3. //...instantiate
    4. instantiatedObject.position = new Vector3((i*40.0f),0,0);
    5. }
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    isn't that just going to equally space out the objects rather than randomly place them?
     
  4. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    Yes, I was pointing out how to do it in its most simplest form. Modifying to use random start position based on a minimum offset is trivial if you know this
     
  5. Aramyth

    Aramyth

    Joined:
    Oct 11, 2012
    Posts:
    12
    That doesn't seem to produce the results I want.

    Right so if you do something like

    Code (csharp):
    1.  
    2. startPosition = newVector3 (Random.Range (-45.0f, 140.0f) + ( i * 10.0f) , 15, Random.Range(-60.0f, 60.0f) + (i * 10.0f));
    3.  
    However, even with small values, it's spacing my objects out too much. Maybe I'm still missing something.