Jun 30

I did a little experimenting with the BitmapData class, and came up with this.
I found this effect from a gallery somewhere, and thought it would be cool to try my hand at it, for learning purposes.

Click on the image below to see the effect.

What’s happening is, I get the size of the image, divide it by the size of the “pixels” I want, then create an array of Rectangles positioned in a grid over the image.
I then fill each Rectangle with the color of the pixel in it’s center by using the getPixel() and fillRect() methods of the BitmapData class.
Here is the central function doing the pixelating.
[sourcecode language='js']
private function pixelate(bitmap:Bitmap, strength:Number):void {
var _x:int = 0; // position of the rectangle
var _y:int = 0;
if (strength > 1){
_strength = 1;
}
var _strength:Number = strength; // multiplier for size of “pixels”

var _w:Number = bitmap.bitmapData.width * _strength; //size of “pixels”
var _h:Number = bitmap.bitmapData.height * _strength;

var nH:int = Math.ceil(bitmap.bitmapData.width / _w); // number of rectangles needed horizontally
var nV:int = Math.ceil(bitmap.bitmapData.height / _h);// number of rectangles needed vertically

var rectangles:Array = []; // Rectangles array

//create rectangles
for (var i:int = 0; i < nV; i ++){
var targH:Number = _h;
if (i >= nV - 1){
targH = bitmap.bitmapData.height - _y;
}
for (var j:int = 0; j < nH; j ++){
var targW:Number = _w;
if (j >= nH - 1){
targW = bitmap.bitmapData.width - _x;
}
rectangles.push(new Rectangle(_x, _y, targW, targH));
_x += _w;
}
_x = 0;
_y += _h;

}
//fill in rectangles
for (i = 0; i < rectangles.length; i++){

var rect:Rectangle = rectangles[i];
var pix:uint = _states[0].getPixel((rect.x + rect.width / 2), (rect.y + rect.height / 2));
bitmap.bitmapData.fillRect(rect, pix);
}

saveCurrentState(bitmap.bitmapData);

}
[/sourcecode]

Now for the reverting to the original image part, I had to improvise. Since I overwrote the BitmapData with a bunch of filled rectangles, I couldn’t do much with it.
So I used an array which stores each “state” the BitmapData is in. And I could just retrieve the BitmapData in the array and copy it into the original BitmapData.
[sourcecode language='js']
private function saveCurrentState(bitmapData:BitmapData):void {
_states.push(bitmapData.clone());
}
private function revertToState(stage:int):void {
try{
bmData.copyPixels(_states[stage], bmData.rect, new Point(bmData.rect.x, bmData.rect.y));
}catch (e:Error){
throw new Error(”Invalid state. “);
}
}
[/sourcecode]
To create the animation, I just called the pixelate() function through a Timer at 300 milliseconds.


Jun 30

Just found this great resource for learning AS3. It is a slideshow created by Grant Skinner showing the basics of the language and some optimization tips. Each page worth an article itself, all 167 of them. It not only sounds good, it looks good. ;)

http://gskinner.com/talks/as3workshop/


Jun 27

I want to give a heads-up to all those just beginning with AS3 about how it handles memory. I had to find out about this the hard way, and now have to redo a lot of stuff.

Flash Player 9 introduced a new system management feature called a garbage collector (GC). Basically, what it does is “sweep” for objects that can not be used/accessed anymore, and delete them, freeing memory. Until those ‘null’ objects are removed by the GC, they will sit in memory until the Player is closed.

So, whenever you want something to be deleted (escpecially with CPU intensive particle systems), you must be aware of what and where you are referencing your objects, so you could easily remove them.  You have to do this by hand. One method is to set all objects you want to delete, and all references to it,  to null. Even then, you have to wait for the GC to do its “sweeping motion” for those objects to be deleted.

Another thing to watch out for are event listeners. Make sure you remove any listeners (by calling removeEventListener()) from objects you want to delete, since they also hold a reference to your objects.

Check this article series for more details and info about the GC and resource management in Flash Player 9/AS3.

And lastly, it is about unloading external swf’s through Loader. You might think that using unload() from a Loader would remove that swf completely, but that isn’t the case.  In fact, unload() does a pretty poor job at “unloading” swfs. Here is a quote from another article that explains this in great detail:

In AS3, calling Loader.unload() simply removes the reference to the loaded movie. If any other references exist to the loaded content, it will not be unloaded.

My site has been delayed by almost a month now, trying to figure out and fix my memory leak problem. I finally have an idea of what’s wrong, now I have to figure out a solution.


Jun 14

TweenLite is a light-weight tweening engine for AS2 and AS3.

Tweening engines make animating objects through code a breeze. Instead of figuring out how to get to a certain point or value of an object’s property, all you need to do is figure out where you want that property to be (or where you want it to come from), the time it takes to get there, and you have movement.

There are a lot of tweening engines out there, but I prefer TweenLite because it is light (only 3kb), it is easy to use, does what I want it to do, and if I want more functionality, it has two older brothers*.

To get started, first you need to download TweenLite (I’ll be discussing the AS3 version here), and save it into your classpath.

There are 2 static methods you need to know, TweenLite.to() and TweenLite.from().

Those two methods take in three arguments:

  • The object you want to animate
  • The time, in seconds, the animation will span
  • A dynamic Object instance target with predefined properties (this is where you put the values you want to reach)

So, to animate a box, it only takes one line to make it do some crazy stuff.
[sourcecode language='js']
import gs.TweenLite; // import TweenLite

box_mc.x = 0;
box_mc.y = 100;

TweenLite.to(box_mc, 2, {x: stage.stageWidth, y: 200, rotation: 360, scaleX: 2, scaleY:2, alpha: .5});
//this will move the box to the edge of the stage, move it down 100 px, rotate it, scale it to 2x its
//size, and make it transparent, for 2 seconds.
[/sourcecode]

Note that the TweenLite.from() method does the exact opposite of TweenLite.to(). It transforms your object to your third argument properties, and animates them towards the state the object has on the stage (very useful).
There are comments in the .as file itself, and explains some important things. This was to show how useful and indispensible tweening engines are. I can’t beleive how long I’ve strayed away from them, but now, I can’t live without them.

*TweenFilterLite - TweenLite + filtering capabilities
TweenMax - TweenFilterLite + bezier curves


Jun 5

Here is another class I made for my site… It’s nothing fancy, and in fact it could easily be done without this class, but basically, this class creates a rectangular object and fills it with an image from an outside source, tiles it, and you could easily adjust the width and height of the object, and load a new pattern.
Usage:
[sourcecode language='js']
import com.mindfock.display.TiledBG; //import class

tiledBG = new TiledBG(”path/to/pattern.gif”, 800, 600);
addChild(tiledBG);

tiledBG.tileWidth = 500 // change width
tiledBG.tileHeight = 500 // change height

tiledBG.newPattern(”path/to/new/pattern.gif”); //changing pattern image
[/sourcecode]

Download here.


Jun 3

I’ve been working on my site for a few weeks now, and I have developed a class that will handle how I display assets on my site.

Basically, it “throws” in items into the stage, and you could shuffle them around or you could stack them up. I’ve made it very easy to use, and it’s still under development, but I think it’s ready to be used by others. This is my first class I’ve ever shared, and though it’s not much, I hope someone likes it or maybe even use it. ;-)

You can use any DisplayObject as the ‘items’ of the Shuffler.
There are explanations in the code, but here are some important points

  • shuffle() - shuffles the items
  • stack() - stacks the items
  • setFocusOn(item:DisplayObject) - sets the item param as the focused item
  • addItem(item:DisplayObject) - adds item param to the shuffler
  • deleteItem(index:int) - deletes the item at index
  • has max property for maximum number of boxes allowed. 0 for infinite.

    Here is an example:

    Sample usage in code:
    [sourcecode language='js']
    package{
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.*;
    import flash.text.TextField;
    import com.mindfock.ui.Shuffler;

    public class TestShuffler extends Sprite{
    private var boxes:Array;
    private var shuffler:Shuffler;
    private var stacker:TextField;
    private var shuffle:TextField;
    private var adder:TextField;

    public function TestShuffler(){
    init();
    }
    public function init():void{
    shuffler = new Shuffler(400, 300, 6);
    createBoxes(6);
    createButtons();
    addChild(shuffler);
    }
    private function createBoxes(num:int):void{
    boxes = new Array();
    for (var i:int = 0; i < num; i++)
    {
    trace("created");
    var box:Sprite = drawBox(50, 50) as Sprite;

    boxes.push(box);

    shuffler.addItem(box);
    }
    }
    private function drawBox(w:Number, h:Number):DisplayObject{
    var box:Sprite = new Sprite();
    box.graphics.lineStyle(2, 0x000000);
    box.graphics.beginFill(Math.random() * 16000000);
    box.graphics.drawRect(0, 0, 100, 100);
    box.graphics.endFill();

    return box;
    }
    private function createButtons():void
    {
    // I've left out the drawing of the buttons
    square.addEventListener(MouseEvent.CLICK, shuffleHandler);
    square2.addEventListener(MouseEvent.CLICK, stackHandler);
    square3.addEventListener(MouseEvent.CLICK, addHandler);
    }
    private function shuffleHandler(event:MouseEvent):void{
    shuffler.shuffle();
    }
    private function stackHandler(event:MouseEvent):void{
    shuffler.stack();
    }
    private function addHandler(event:MouseEvent):void{
    var newBox:Sprite = drawBox(50, 50) as Sprite;
    shuffler.addItem(newBox);
    }
    }
    }
    [/sourcecode]

    Download source

    Just save it in your classpath, under com/mindfock/ui

    You need TweenLite for the tweening animations… If you don’t know what it is, you should look into tweening engines. They will save you a lot of hard work.

    Now that I’ve got the main bulk of my site done, I hope I can finish it before classes start. :D


    May 14

    It’s been a while since my last post. My connection has been down for a few days, so I haven’t got the chance to post. But during this downtime, I found some time to create some experiments in Flash/AS3.0 (maybe I’ll post it soon). I needed to call a method at timed intervals in this one experiment, and I thought I was in trouble. I never got around to getting how AS2.0 handled timers, if I did manage to do timers, they end up dirty.

    AS3.0 has a much much better Timer class to handle just such events. Now, I’m not going to bother comparing the AS3 Timer class with AS2’s timer handling, I’m just going to give a quick intro to the class.

    First, you need to create a new Timer object. The constructor has 2 parameters, delay and repeatCount. delay is the time in milliseconds the intervals will be. repeatCount is the number of times the Timer will run, assigning it 0 will set it to run infinitely.

    [sourcecode language='jscript']
    var myTimer:Timer = new Timer(1000, 5);
    [/sourcecode]

    Now, we want to write a function that will get called when an interval is passed (every 1 second), and when the whole timer finishes counting (after 5 seconds). The Timer class dispatches two events, TimerEvent.TIMER is dispatched when an interval is passed, TimerEvent.TIMER_COMPLETE is dispatched when the timer is finished (I love how simple that is).

    [sourcecode language='jscript']
    stage.addEventListener(TimerEvent.TIMER, everySecond);
    stage.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);

    function everySecond(e:TimerEvent):void{
    trace(”tick tock!”);
    }
    function onComplete(e:TimerEvent):void{
    trace(”Timer finished!”);
    }
    [/sourcecode]

    Now, we just need to start the timer. The Timer class has 3 methods, start, stop, and reset. Those are fairly self-explanatory. We could now add the following lines:

    [sourcecode language='jscript']
    myTimer.start();
    //modify the onComplete function
    function onComplete(e:TimerEvent):void{
    trace(”Timer finished!”);
    myTimer.reset();
    myTimer.start();
    }
    [/sourcecode]

    So now, when our timer finishes, it will automatically start all over again. This will trace
    [sourcecode language='js']
    tick tock!
    tick tock!
    tick tock!
    tick tock!
    tick tock!
    Timer finished!
    tick tock!
    tick tock!

    [/sourcecode]

    This was just a really quick intro to the Timer class, I just felt like sharing this because I was so relieved at how easy it was to handle timed events now.