10 December 2008

Tiled Flash Backgrounds Tutorial PART I

Already scratched the backgrounds subject in two separate occasions and now I'm gonna finish this chapter. Once again, I'm sure there are other, better solutions on how to generate Flash backgrounds, but this is what I figured. Don't have a clue why I need to constantly warn readers how I don't produce best code out there - I got to stop doing it right now!

First solution doesn't require any Library movie clip, but background is generated dynamically, which means we use single function to create background pattern and entire tiled background based on that pattern. This first option is suitable for small pattern usually with dimensions like 6x6, 8x8 or 10x10 pixels. Off course, pattern can have not equal dimensions too. We will create drawBackground function and call it right away. All this happens in first root frame:

function drawBackground() {...};
drawBackground();

Now instead dots, our function have two parts, first one to create pattern and second one to tile it. Best practice for pattern creation is to take pen and paper and draw pattern there and then mark coordinates. This is what we are making with next code:


 this.createEmptyMovieClip("mc", this.getNextHighestDepth());
mc.lineStyle(1, 0x111111, 100);
mc.beginFill(0x111111, 100);
mc.moveTo(1,2);
mc.lineTo(4,2);
mc.lineTo(4,1);
mc.lineTo(5,1);
mc.lineTo(5,4);
mc.lineTo(4,4);
mc.lineTo(4,5);
mc.lineTo(1,5);
mc.endFill();

All is left to do is tile our pattern over entire document. We will do this using new 'back' movie clip. Variables mcw and mch will hold pattern dimensions, mc._width and mc._height. They are there just to shorten the code a little bit. OK, now we use Stage properties width and height to calculate limitWidth and limitHeight, borders of our pattern generator, when they are exceeded, we are done. For loops will draw our background until limits are reached. You can copy and paste pattern code and make small modifications, instead mc write back.

this.createEmptyMovieClip("back", this.getNextHighestDepth());
var mcw = mc._width;
var mch = mc._height;
var limitWidth = Math.floor(Stage.width / mcw)+1;
var limitHeight = Math.floor(Stage.height / mch)+1;
back.lineStyle(1, 0x111111, 100);
back.beginFill(0x111111, 100);
for(var i=0; i<limitWidth; i++) {
for(var j=0; j<limitHeight; j++) {
back.moveTo(i*mcw+1,j*mch+2);
back.lineTo(i*mcw+4,j*mch+2);
back.lineTo(i*mcw+4,j*mch+1);
back.lineTo(i*mcw+5,j*mch+1);
back.lineTo(i*mcw+5,j*mch+4);
back.lineTo(i*mcw+4,j*mch+4);
back.lineTo(i*mcw+4,j*mch+5);
back.lineTo(i*mcw+1,j*mch+5);
}
}
back.endFill();

That's all in part I of this tutorial on how to generate tiled Flash backgrounds. Next part will explore another technique which uses drawings as patterns.
.

0 comments:

 

template by blogger templates