Create a flag animation with actionscript 3 perlinNoise and displacementMapFilter

 I will show you how to create an animated flag using actionscript only!

 We will  animate a perlinNoise effect and use it as a displacement map for our flag. I used a pirate flag for the example below but any image will work.

 

You can download the source code here

First you will need to import the bitmap image you want to use as a flag into flash:

go to file -> import -> import to library and choose the image you want to import.

The image will appear in the library, right-click on it select linkage. In the pop up window make sure export for actionscript and export in first frame are both checked. Give it a class name of myflag. Then set your Document class to  flag.

Now onto the flag.as code...

The following code take the bitmap you imported onto the library and display it in the stage:

var flagBitmap:myflag = new myflag(180,110);
myFlag = new Bitmap(flagBitmap);
myFlag.x = 21;
myFlag.y = 30
this.addChildAt(myFlag, 0);

Then we create another bitmap that we will use as our displacement map with a width of 230 and a heigth of 150:

perlinBitmap = new BitmapData(230, 150, true, 0xFFFFFF);

And add an ENTER_FRAME event listener:

this.addEventListener(Event.ENTER_FRAME, perFrame,false,0,true);

The method perFrame will be called on every frame and will will use it to apply a perlin noise and modify it on every frame:

var point:Point = new Point(offset, 0);
perlinBitmap.perlinNoise(230,150,15,100,true,true,8,false,[point,point]);
offset -= 40;

The perlinNoise method is applied to a bitmapdata object. The last parameter, offset is the one we will change onevery frame, creating an animated perlin noise effect. You can try changing the third and fourth to see the different effects you can achieve.

Then we create a new displacementMapfilter with the perlin Noise bitmap we generated:

filter= new DisplacementMapFilter(perlinBitmap,new Point(0,0),8,8,scaleX,scaleY);

The last two parameters, scaleX and scaleY correspond to how intense will be the effect horizontally and vertically.

And finally, we apply the filter to our flag:

filterArray[0] = filter;
myFlag.filters = filterArray;

To prevent the animation from being  resource intensive, keep the flag bitmap and the perlin noise bitmap dimensions small.