Search code examples
c#for-loopmeshterrainprocedural-generation

How to spawn in loop like snail but in square


Hello I am French so excuse my bad English please, I created a generation of land with a seed with prefabricated gameobjects but they spawn from column to column so I would like to create this but starting from the center to outside like a snail but in square

I partially succeeded, the first image shows the generation in columne but also the desired final result with the generation in snail and the second shows what I managed to do therefore in snail but my pieces of land are square it looks bad

  • First:
    1
  • Second:
    2
  • It works like:
    3
  • And I want it Work like:
    4

Solution

  • Let's assume you start from the origin O and the other 4 directions are E,S,W,N

      N
    W O E
      S
    

    Then the step sequence you'll move is

    E S
    W W N N
    E E E S S S
    W W W W N N N N
    ...
    

    You may notice that every time you turn twice, you need to increase the number of times you move in this direction by one.

    Some pseudocode:

    var dirs = new Vector3[] { E, S, W, N } // 4 directions
    Vector3 pos = O; // origin
    
    do
    {
        var dir = 0
        var moveTimes = 1
    
        for (i = 0; i != 2; ++i)
        {
            for (j = 0; j != moveTimes; ++j)
            {
                pos += dirs[dir]; // step forward
            }
            dir = (dir + 1) % 4; // turn
        }
    
        moveTimes++;
    }
    while(/* condition to stop */);