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

Fill a circle with spheres of a given radius

Discussion in 'Scripting' started by hum642tic144, Jun 10, 2022.

  1. hum642tic144

    hum642tic144

    Joined:
    Feb 4, 2022
    Posts:
    18
    Hello. I have a circle of radius R and I want ti fill it with spheres of radius r. How can I do it? I achieved the circle but I don't know how to create the spheres inside at correct positions.
    Here is an example of what I want to do:

    EDIT: I found this web page where I can calculate the number of spheres of radius r that fits into a circle of radius R. But it doesn't say how to place them.

    Thanks!
     
    Last edited: Jun 10, 2022
  2. Peeling

    Peeling

    Joined:
    Nov 10, 2013
    Posts:
    401
    A very simple approximate algorithm would be:

    1. Calculate the radius of the outermost ring of spheres: A = R - r
    2. Calculate the circumference of that ring: C = 2Aπ
    3. Use this to calculate a first approximation of the number of spheres in that ring: N = (int)(C / (2r))
    4. Now calculate the actual length of a side of a polygon with N sides inscribed in a circle of radius A: s = 2Asin(π/N)
    5. While N > 1 and s < 2r (which would mean the spheres would overlap when placed), subtract 1 from N and recalculate (return to step 4)
    6. If N = 1, set A to 0 (place single sphere in centre, not offset to one side)
    7. Now that you have N, place N spheres around a circle of radius A:
    Code (CSharp):
    1. for (int i = 0; i < N; ++i)
    2. {
    3.    // make a sphere, then:
    4.    float angle = Mathf.Pi * 2f * i / N;
    5.    sphere.transform.position = new Vector3( A*Mathf.Cos(angle), 0f, A * Mathf.Sin(angle));
    6. }
    8. Subtract 2r from A. If the new value of A >= 0, go back to step 4 and continue reducing and fitting N and adding new rings of spheres.
     
    hum642tic144 likes this.
  3. hum642tic144

    hum642tic144

    Joined:
    Feb 4, 2022
    Posts:
    18
    I will try and post the results. Thanks!