Quantcast
Channel: selene – selene tan
Viewing all articles
Browse latest Browse all 13

Spiral Code Snippet

$
0
0

I recently needed to make something spiral outwards on a grid. With a bit of experimentation, I found that the steps taken by the spiral always have a pattern like Left Up RightRight DownDown LLL UUU etc. Here’s the snippet I came up with. You can change the starting direction and spiral direction by changing the values in the switch statement.

  1. var currDir:int = 0;
  2. var stepsPerSide:int = 1;
  3. var currSteps:int = 0;
  4. var x:int = startX;
  5. var y:int = startY;
  6.  
  7. while (notDone())
  8. {
  9.     doThingAt(x, y);
  10.    
  11.     switch(currDir)
  12.     {
  13.         case 0:
  14.             x += 1;
  15.             break;
  16.         case 1:
  17.             y += 1;
  18.             break;
  19.         case 2:
  20.             x -= 1;
  21.             break;
  22.         case 3:
  23.             y -= 1;
  24.             break;
  25.     }
  26.    
  27.     currSteps++;
  28.     if (currSteps >= stepsPerSide)
  29.     {
  30.         currDir = (currDir + 1) % 4;
  31.         if (currDir == 0 || currDir == 2)
  32.         {
  33.             ++stepsPerSide;
  34.         }
  35.         currSteps = 0;
  36.     }
  37. }

Viewing all articles
Browse latest Browse all 13

Trending Articles