Arranging objects in a grid

There are many ways to arrange objects in a grid using ActionScript and some ways of doing this are easier than others. The following way I have found is the easiest.
If you loop through all of your objects using a for(var i...) loop or something similar, you can set the x and y position of each one using only one line of code:

  1. // inside a for(var i:int...) loop
  2. gridObj.x = START_X + (i % COLUMNS) * (PAD_X + gridObj.width);
  3. gridObj.y = START_Y + Math.floor(i / COLUMNS) * (PAD_Y + gridObj.height);
  4.  

(COLUMNS is the number of required columns, PAD_X and PAD_Y are padding between objects along each axis.)
This uses the modulo (%) operator to determine the remainder of the division of the iterator and the number of columns. This is used for the X position of each object. The y position is calculated the other way, using Math.floor to get the highest exact number of divisions these two numbers will produce.
Note: int() can also be used instead of Math.floor().

One Comment

  1. sonicoliver says:

    that’s the same solution I came up with! 😀

    You can also flip it on it’s head… click-to-drag a display object and exclude that from the sort routine, and run the same code to evaluate ordering by position, tweenmaxing all the way of course.

Leave a Reply