Code to create sphere out of cubes

Updated on November 24, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on November 24, 2019

Hello everybody,

I am struggling at the moment to create a sphere out of cubes. My idea was the following:

  • First, I create a loop which would create a 3D cube out of cubes.
  • Second, I would skip the positions, which are not neccessary for the sphere.

It should look like this:

So I just give as an input a diameter and the code generates a sphere out of blocks/cubes. But to code this is harder than I had imagined. I had tried a lot of different continue conditions, but nothing gets me the sphere as a result.

private void CreateSphere(int diameter)
    {
        int radius = diameter / 2;
        //create blocks in all three dimensions
        for (int x = 0; x < diameter; x++)
        {
            for (int y = 0; y < diameter; y++)
            {
                for (int z = 0; z < diameter; z++)
                {
                    //skip outer ring
                    if ((x < y || x >= diameter- y) || (z < y || z >= diameter- y))
                        continue;
                    CreateBlock(x, y, z);
                }
            }
        }
    }

So I am just asking, if you have a better idea how to do it?

  • Liked by
Reply