Monday, August 31, 2009

AS3: Creating a timer event for delay/sleep

There is no sleep() method in AS3, so one cannot do:

some code;
sleep(); // Delay for x amount of time
some more code;

So one needs to use the timer class to achieve delays and such, which means that if you come from a multi thread background and are accustomed to putting in a sleep(), you would have to rethink your approach.

The timer usage is simple enough:

import flash.events.TimerEvent;
import flash.utils.Timer;

// Create the timer, generate a tick every 500 millisec, Timer ends after 2 seconds.
var new_timer:Timer = new Timer(500, 2);

// function on_tick() will be called every 500 millisec
new_timer.addEventListener(TimerEvent.TIMER, on_tick);
// function timer_complete will be called once the timer expires, 2 secs in this case
new_timer.addEventListener(TimerEvent.TIMER_COMPLETE, timer_complete);
// Start the timer
new_timer.start();

function on_tick(event:TimerEvent):void {
// some code
}

function timer_complete(event:TimerEvent):void {
// some code
}

Note the parameters, event:TimerEvent in the functions on_tick and timer_complete, those are needed else the implementation will not work.

Tuesday, August 25, 2009

AS3: Extending Bitmap class

To extend the Bitmap class and get it to display stuff properly, we need to call the constructor of the Bitmap class in our custom class using super(). When we call Super we need to pass a BitmapData var that contains the image we want to display. This has to happen before you do addChild(your_extended_bitmap_class)

So the custom class which would need to reside in a custom_class.as file would look like this:

package {
import flash.display.Bitmap;
import flash.display.BitmapData;

public class custom_class extends Bitmap {
public var our_new_property:String = "Blah";

// We will call super in our constructor.
public function custom_class(image:BitmapData = null) {
super(image);
}
}
}

To use this class, the code would look like this:

// Embed a image to use
[Embed(source="my_image.png")]
[Bindable]
private var image:Class;

private var tmp_image:Bitmap = new image();

private var custom_image:custom_class =
new custom_class(tmp_image.bitmapData);

// Now our custom properties and all
// the Bitmap properties are accessible

custom_image.our_new_property = "some string value";
custom_image.x = some x value;
stage.addChild(custom_image); // Will now get displayed on the stage.

Multidimensional arrays in AS3

To declare a multidimensional array in AS3, we would have to create a loop, so to create for example a 2 dimensional bitmap array the code would be like so:
private var my_array:Array = new Array();

var i:int;
for (i=0; i < 20; i++) {
my_array[i] = new Array();

var j:int;
for (j=0; j < 20; j++) {
my_array[i][j] = new Bitmap();

}
}



Now we have a 20 x 20 bitmap array initialised and you can access the properties and methods of the bitmap like so:
my_array[some value][some value].x = some x value;