Spiral Code Snippet
by selene on Jun.27, 2012, under Blog
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.
var currDir:int = 0; var stepsPerSide:int = 1; var currSteps:int = 0; var x:int = startX; var y:int = startY; while (notDone()) { doThingAt(x, y); switch(currDir) { case 0: x += 1; break; case 1: y += 1; break; case 2: x -= 1; break; case 3: y -= 1; break; } currSteps++; if (currSteps >= stepsPerSide) { currDir = (currDir + 1) % 4; if (currDir == 0 || currDir == 2) { ++stepsPerSide; } currSteps = 0; } }