Thursday, December 29, 2005
 
Modulo is your friend

I've found myself using modulo a lot recently. I thought I'd post a couple of useful examples of where and how it can be used.

For anyone who doesn't know already, modulo (%) returns the remainder of a division. Divide 11 by 5 and the remainder is 1. That's simple enough. If we trace the modulo of a calculation we can see a pattern emerging:

for(var i=0; i<10; i++){
trace(i%3);
}
/*************************
0/3 divides:0 remainder:0
1/3 divides:0 remainder:1
2/3 divides:1 remainder:2
3/3 divides:1 remainder:0
4/3 divides:1 remainder:1
5/3 divides:1 remainder:2
6/3 divides:2 remainder:0
...etc...
*************************/

As you can see from the traces, the numbers 0-2 will repeat over and over until the for-loop has finished iterating. If you were to trace i%5 instead, the numbers 0-4 would repeat.

One simple use of modulo is as a binary switch: i%2 will always return either 0 or 1. The Boolean values "true" and "false" equate to 1 and 0 respectively. This could be used in any number of situations. A simple visual example would be where you have a line or grid of movieclips and want to change the visibility of each alternate clip:
 
this["mc" +i]._visible = i%2;

More often modulo is used to "repeat & reset". In the example below I've used result of the modulo calculation to loop through an array of colours (the calculation returns a useful array-counter). The for-loop will iterate 9 times; The number of items in the colour array is less than 9, but it will keep on tracing through the 3 values in the array until the outer loop has stopped. In other words, when the array index matches the length of the array-1, the index will 'automatically' set itself back to zero - thus saving me from having to check/reset/increment the value of some counter using a conditional statement.

var cols = ["red", "yellow", "purple"];
var len = cols.length;
for(var i=0; i<9; i++){
trace(cols[i%len]);
}




Thursday, December 22, 2005
 
MERRY XMAS!




Sunday, December 04, 2005
 
Excellent Ikea site with that multi-angle Matrix camera effect




ARCHIVES

  AS Hero   blog feed

nwebb.co.uk - flash tutorials, php and more.