AS3 Simple Grids
Sat Nov 14 16:16:16 2009
I have decided to share a class with you that I recently developed for an ActionScript project that required a grid layout of MovieClips. Making grids in AS3 isn't really that difficult, but the class I've developed will save me a lot of typing and since building grid layouts is something that I may do a lot more of in future projects it seemed like a sensible thing to do.
It is quite a simple class but may come in handy from time to time. Please feel free to edit the code and do as you will. It's usage is simple. Just import it, create however many instances of an object you want to have in your grid, and apply the public static function createGrid();
from the Grid class. In the example grid below I used dark grey, 40 x 40 px MovieClips
Grid.createGrid(); The parameters are (1:StageObject, 2:Array, 3:{Object})
Instructions of Use
1. The StageObject is simple. Just pass the stage of the first MovieClip your are throwing inside the grid. This will give us the ability to call the public static method without instancing the class itself, which I always find beneficial and try to do when I can.
2. The Array should be an array of all the names of the objects you want to place inside the grid. Objects will be ordered in the same order as they are placed inside this Array.
3. The Object can contain any of the 4 options available, which include col
, spaceX
, spaceY
, and centered
. col
receives a Number
and defines the number of columns the grid should have. spaceX
and spaceY
also receive a Number
and respectively control the vertical and horizontal spacing between each object inside the grid. In other words, they control how big the gaps are inside the grid. The final parameter center:Boolean
gives the option to offset the grid to the right by half the width of each instance fed into the array, so that the grid appears centered. If no parameters are given (Note* curly brackets are required {} even without parameters), the grid will set to a default of a non-centered, 6-columns grid with 10px vertical and horizontal spacing
Example Code
Grid.createGrid(this, nameArr, {cols:10, spaceX:10, spaceY:10, centered:false} );
For more info, just take a look at the fully annotated example files I've set up. They can be downloaded here
I would love to hear your opinions about this, but since I don't normally share my code, please be gentle with any criticisms. If you would like to host this code on your own website, please make sure to credit back to yours truly. Happy grid making!
Tweet← back