Search Unity

Spawning GameObjects randomly on a sphere

Discussion in 'World Building' started by lukesaudio, Jun 18, 2020.

  1. lukesaudio

    lukesaudio

    Joined:
    Sep 8, 2017
    Posts:
    4
    Hey folks!

    I'm looking to create some randomised planets with objects on them (trees, rocks etc...).

    I'm using ProBuilder to make a few basic icospheres and want to place the objects randomly along its surface, rotated to align with up/the normal of the surface. I'm aligning to normals using:

    Code (CSharp):
    1.    Physics.Raycast(instTrees[i].transform.position, transform.position - instTrees[i].transform.position, out hit);
    2.  
    3.                 Vector3 newNormal = hit.normal;
    4.  
    5.                 instTrees[i].transform.up = newNormal;
    Where instTrees is an array of instantiated trees from Random.UnitOnSphere.

    Any suggestions on how to approach this? I'm using Random.UnitOnSphere but its clunky and won't cater for (hopefully) uneven terrains (to my knowledge).

    Thanks in advance!
     
  2. antoinebr_unity

    antoinebr_unity

    Unity Technologies

    Joined:
    Nov 16, 2018
    Posts:
    23
    Hey!

    You could use Random.onUnitSphere multiplied by a bigger radius than your sphere and use that as the origin of your ray. After that you use hit.point and hit.normal to place your object. Something like this:

    Code (CSharp):
    1. Vector3 direction = Random.onUnitSphere * planetRadius * 2;
    2. Physics.Raycast(transform.position + direction, -direction, out RaycastHit hit);
    3. instTrees[i].transform.position = hit.point;
    4. instTrees[i].transform.up = hit.normal;
    As you said, using Random.onUnitSphere might not be the best as you'll probably get some overlap. I'd advise to look into Object Scattering if you want to go deeper into the subject. Here's a video of Polybrush's (Unity's mesh painting package) implementation of object scattering.

     
    TheSituation likes this.