Here's a quick optimization for people making grids of things. The traditional method is a pair of loops, nested to make rows and columns:
const ROWS:int = 30;
const COLUMNS:int = 88;
for(var row:int = 0; row < ROWS; row++){
for(var column:int = 0; column < COLUMNS; column++){
var s:Shape = new Shape();
s.x = column * 5;
s.y = row * 5;
s.graphics.beginFill(0x666666);
s.graphics.drawRect(0, 0, 4, 4);
addChild(s);
}
}
This can be simplified and sped up by taking advantage of the relationship between division and modulus to generate the row and column dynamically:
const ROWS:int = 30;
const COLUMNS:int = 88;
const ITEMS:int = ROWS * COLUMNS;
for(var i:int = 0; i < ITEMS; i++){
var s:Shape = new Shape();
s.x = int(i / ROWS) * 5; // this is the same as Math.floor(i / ROWS), just faster
s.y = (i % ROWS) * 5;
s.graphics.beginFill(0x666666);
s.graphics.drawRect(0, 0, 4, 4);
addChild(s);
}
By upgrading to loop-invariants, we can cut the nested for-loop for a nice boost. And, as a bonus, this new code can work with sets that don't end squarely at the end of a column.
August 1st, 2009 at 2:07 pm
Just a headsup – in the RSS feed, this came up as:
Modulo Grids
by Rob
[insert loads of spam ads for drugs here]
August 1st, 2009 at 9:37 pm
Appreciate the heads-up RodeoClown – I’m working on it, and sorry for the spam :[
August 2nd, 2009 at 1:41 am
Not a problem, just wanted to make sure you were aware of it.
February 23rd, 2010 at 8:11 pm
[...] Modulo Grids http://www.calypso88.com/?p=453 [...]