Archive for May 19th, 2009

19
May
09

Modulo (%) – the designer’s best friend

I became a programmer because I was a lazy designer. That is lazy as in “Why create fifty animations that are almost the same”, not “bah – good enough, customer isn’t going to care”. I want top results with as little effort as possible. So actionscript was the way to cut down on unwieldy timelines.

The downside of not having a programming degree is that a few of the useful concepts and methods remain obscured in a corner. As with modulo. For those of you with a maths degree, just skip down a few paragraphs. Designers – bear with me.

Modulo is a maths operator like multiply and divide are. It is most similar to divide as it returns the remainder from an integer division. Quick example: 13 % 10 = 3 because 13 can be divided once by 10 with three remaining. 23 % 10 is also three as 23 can be divided twice by 10 with three remaining.

So why should I care, the designer asks, this is all very interesting, but what practical value does it have? One scenario is my contribution to this mini challenge from Apt, although SIN is probably better in that case. I’ve used it most when laying out n-objects in a grid to calculate x-position. As % returns the remainder, you can multiply count and x-step and do a modulo on total width.

An example:

function placeItems():void {
  var numItems:int=45;
  var xstep:int=15;
  var ystep:int=15;
  var totalWidth:int=150;
  var item:MovieClip;
  for (var i:int = 0; i<numItems; i++) {
    item=createAnItem();
    item.x = (i*xstep)%totalWidth;
    item.y = Math.floor((i*xstep)/totalWidth)*ystep;
  }
}

placeItems();

function createAnItem():MovieClip {
  var item:MovieClip = new myItem();
  addChild(item);
  return item;
}

Which results in this if you have a blue square in the library exported to actionscript as ‘myItem’

modulotest

All the magic is in the last two lines of the for…next loop, it places items in a grid without needing help counters.
Look at item.x = (i*xstep)%totalWidth. It multiplies item count with distance between items and does a modulo on total width. I.e., if i*step is 330, 330%150 = 30. Combined with stepping y down with whole multiplies, we get a nice grid. Y value – if i*step is 330, it gives  2.2 when divided by total width, lose the decimal and we know it in row 2.

It’s super easy to change parameters. Set x/y-step or total width and you’re done. Just keep total width divisible by x-step, else the gird gets staggered.

Anyone else with good examples of modulo for layout?

Advertisements