Archive for the ‘Flash’ Category

Multi-Treading Oriented ActionScript

Thursday, November 16th, 2006

I am currently working on a Flash animation that must deal with simultaneous management of dynamically created, autonomous MovieClips and the management of data obtained from various XML feeds from the Internet. It’s basically a RSS Aggregator in which RSS items are represented by a graphical symbol. All must be generated using ActionScript, meaning the actual .swf file only consists of a call to the constructor of my main class.
Having learned how to program mainly with Java and VB.Net, the approach I wanted to take was to have two threads running in my flash movie : one that fetches and treats the XML data, the second that handles events, collisions and movements of the MovieClips. However, to put it bluntly, there is no such thing as multi-treading in Flash 9.
The approach I chose to solve this problem was to generate calls to key function of my main class using the setInterval function. Of course, on a much larger scale, one would probably notice a lag when using an interval technique compared to real simultaneous treading. However, with the usual Flash applications this kind of performance goes rather unnoticed.

Here’s an example similar to what I am doing:

class Feed {
public function Feed():Void {
setInterval(this.refreshFeedData, 500);
setInterval(this.moveFeedMovieClips, 500);
}
public function refreshFeedData():Void {
// load the xml
}
public function moveFeedMovieClips():Void {
// run through my MovieClip objects
}
}

By keeping a frequent and similar interval (in this example 0.5 seconds), you can mimic the threading effect. Note that you can lose the reference to the class using “this.” in the function being called by setInterval . I have yet to understand and explain this problem, but you can go around it by supplying a reference to the current class in the call :

setInterval(this.moveFeedMovieClips, 500, this);

Rise Of The Espers: The Making of

Wednesday, June 14th, 2006

Introduction

For about 2 years now, I wanted to make a full blown flash game. Ive done a few unfinished sketches, have tried to build an adventure game engine, then I tried doing an RPG engine, then followed a simulation, and then I tried making an RPG again. Hell, I even tried to make a hockey game.

Do I even need to say making a real flash game its hard as hell?

That’s without mentioning the common clich of Real Life catching up and forcing me to put my projects on the side for a while. Also, just like any project you do without thinking thoroughly before beginning, after a while you start noticing how the programming sucks, how the same thing could be done in a much simpler way and all that depressing crap.

Well! Now I feel like going at it again. Though I dont know how much time itll take me, I have decided on continuing Rise of the Espers (read: start it over again). This RPG is meant to be similar than those of the SNES and should be a mix between Final Fantasy 3 and Secret Of Mana. We’ll see how that will go!

Of course, you cant quite tackle a task like that without help. Even if Ill probably end up making everything myself, I will need the help of those with more mathematical minds that mine. It was by asking Evilmax help on how I could generate an isographic map dynamically that he came up with the idea of having me publish the games progress. Without further ado, heres the first post in a long series in the Rise Of The Espers: The Making of.

Let there be light

Flash Project FileHere is a screenshot of the game’s architechture at the moment. The Game.as file is where I will be handling the game’s interface (new game menu, options menu, save, etc). The Map.as class will generate the map using data from an XML file and by creating a Tile.as object per each texture tile.

Utils.as is a file I’ve been using for a while in many of my projects. I store usefull static functions in there like the event handlers.

XML file of the map called 0001.xmlgame.fla is an empty file with only a call to the Game.as’ constructor in the actions layer of the first frame.

The map itself is created from an xml file that contains arrays of numbers which are each associated with a image in the game.fla texture pack. For performance issues, the texture images are likely to be pixel images and not drawn in Flash.

library of the game.fla fileThe game.fla file does more than it is supposed to be doing at the moment. As the project grows in maturity, game.fla will handle game menus, pauses, server connections and whatnot. To continue loading the maps, I will create another placeholder movie where only Map instances are created. This map movie loader will be loaded from game.fla using the loadMovie() command.

Extensive use of the Progress bar control warns of data transfers delays but is also used with each heavy loops, like the one that creates the tiles. While you don’t even see them when I start the game from my desktop, they will be much appreciated on the web. I also use the alert component to raise error messages.

the beginning of a gameAnd that’s where I stand at the moment, the movie loads a simple map of two textures dynamically. The next step will be to draw the main textures and build a quick interface in flash through which I will be able to save my arrays automatically, and not have to learn all the texture codes by heart.

Eureka Follow up

Tuesday, February 7th, 2006

As I mentioned in my last post, the Delegate class is quite useful even if I couldn’t pass parameters as easily as I would have wanted. While looking around today, I stumbled on this method which makes things much easier. I don’t like how it’s written because of the in-line functions, but it really does solve the problem. Here’s the code, which I took the liberty to customize a little bit:

class Utils {
// Desc		:	Usually, when you attach a functio nto an event, you can't pass
//			parameters, using this function instead of the Delegate class
//			will allow you to do the same thing but with unlimitted parameters
// 			Window: General Information.
// 			http://www.person13.com/articles/proxy/Proxy.htm
public static function delegateEvent(oTarget:Object, fFunction:Function):Function {
// Create an array of the extra parameters passed to the method. Loop
// through every element of the arguments array starting with index 2,
// and add the element to the aParameters array.
var aParameters:Array = new Array();
for(var i:Number = 2; i < arguments.length; i++) {
aParameters[i - 2] = arguments[i];
}
// Create a new function that will be the proxy function.
var fProxy:Function = function():Void {
var aActualParameters:Array = arguments.concat(aParameters);
fFunction.apply(oTarget, aActualParameters);
};
return fProxy; 	}
}

And you can call it like this:

private function someFunction():Void {
this._xml.onLoad = Utils.delegateEvent(this, xml_onLoad, "GeneralInformation");
}
private function xml_onLoad(success:Boolean, nextStep:String):Void {
if(success)
// Get the contents of xml
switch (nextStep) {
case "GeneralInformation" :
this.open_GeneralInformation();
break;
//etc...
}
}

It really saved me time.

Eureka!

Wednesday, February 1st, 2006

Ive been having a lot of trouble having Event (clicks, loads, whatever) in Flash for as long as Ive been doing Object oriented ActionScript. I barely managed to call inline functions and having to use the absolute path to the property. Example:

class Foo {
	public var _someProperty:String
	public function Foo() {
		// Lets skip how I actually make the button,
		// but I usually use .attach() and I make
		// exportable the object in the Library. I
		// think I should use createClassComponent however.
		var but:MovieClip = new MovieClip();
		but.onPress = function () {
		_root.MyFooObject._someProperty = Clicked;
		}
	}
}

To access my attribute, I must leave my class and follow the absolute, pratically hard-coded path to my value. It’s really not a good thing to do. I found you can use the Delegate class to forward events to a function inside the parent class. Like this:

class Foo {
	private var _someProperty:String
	public function Foo() {
		// Lets skip how I actually make the button here too.
		var but:MovieClip = new movieclip();
		but.onPress = mx.utils.Delegate.create(this, button_onClick);
	}
	private function button_onClick():Void {
		this._someProperty = Clicked;
	}
}

Where “this” means the class you are in (could be another one), and “button_onClick” is the name of the function you will be calling after the event is triggered.

There you go! Its a lot more powerful, much more logical in a semantic point of view and it makes the code a lot clearer. Notice how I can protect my call properties now using the private attribute.

Speaking of being semantic, you always should call you call properties with “getters and setters” instead of calling it directly like I did in my example. It should look like this instead:

private var _someProperty:String
public function get someProperty():String { return this._someProperty;}
public function set someProperty(val:String):Void { // validation if needed; this._someProperty = val;}

What still needs to be clarified however is how I can pass the object that raised the event and called the function.

mx.transitions.Tween

Thursday, December 8th, 2005

One of my current assignments at work is to make something similar to Google Maps for my employers Oil website. I must build a map browser that is completely dynamic thatll need to generate 3 dynamic layers for 3 different types of maps of Oil Wells.

I decided on making this using Flash, just like Yahoo Maps have. From the start, the most important feature was how I had to permit a click event somewhere on the map and to center the map on these X and Y coordinates. At first, I approached the project by planning on incrementing a value to the _x and _y properties for some period of time to mimic movement until the map was re-centered, but Ive had no success doing so.

Thats when I had a revelation. Once you start trying to build Object-Oriented applications in Flash, you tend to forget all the design tools built in Flash. Why didnt I call the Tween function from within ActionScript? And so I did.

Heres the relatively simple function call to move a MovieClip object using the Tween class:

new mx.transitions.Tween(MovieClip, "_x", easeType, begin, end, speed of execution, time unit boolean);

You pass on a MovieClip, the property you wish to edit (in Flash, the properties all start with _), the effect you wish to use for the transition, the starting value (for the _x property, MovieClip ._x for instance), the end value (passing MovieClip ._x + 50 would create a motion tween that would move the MovieClip 50 pixels to the right from its original location), and the speed of execution which is either counted in seconds or in frames depending on the last Boolean parameter (true being in seconds).

Its really incredible because the transition allow you to apply built-in elastic or bouncing effects to the MovieClip. Now all of the bouncing menus we see all over the Internet seem much simpler.

You can also pause, rewind and do other operations on the Tween process because it generates events as the animation plays.

It opens a lot of doors to OOP in Flash. You no longer need to bother with sketchy animations when forcing movement on your MovieClips from within a Class.

Read more on this undocumented function

On a different and more disappointing note, I also completely gave up on trying to have a logical OOP approach on Events handling. Doing the following discusses me because I find it rather illogical to have an inline function call from within another one, but its one of the only things that work:


class Foo {
function Foo() {
// create a button with the path _root.button
// now tell him what to do when hes clicked
_root.button.onPress = function {
// some code
}
}
}

Love/hate relationship with Flashs components

Saturday, November 12th, 2005

Macromedia have brought a lot more depth into Flash by adding pre-compiled components (or movie clips) to the softwares library. Mostly in the professional edition these components make building application faster and easier.

One of the components Ive played with it the Window object. Its simple to understand and its possible to create one on the fly using ActionScript only. Let me put some emphasis on that. Within a few lines, I was able to program my way into a graphic application. We can all agree thats the direction Macromedia is taking and to a certain extent they are succeeding in doing so.

However, other components are much harder to instantiate or create/call straight from ActionScript. The documentation on Live Docs is also somewhat deficient. Ive tried a gazillion times to have the XML connector work when created dynamically but couldnt make it work yet. The media playback was a bit easier to build with dynamic values, but as I write this, the Mp3 player on The Music Tank still has trouble opening .mp3 files consistently.

What I hate about components is how I never know if its my fault if its not working. If it is (which is probably the case) there are two questions I can rarely find answers for:

Am I supplying invalid values which failed validation once the control is speaking with my website and
Is the control not working because I instantiated its properties with wrong values?

I hope Flex will make it easier for graphic artists who are able to do real Object-Oriented programming. Right now, I feel pretty dumb having to use illogical code just to make up for Flash’s almost-there programming language.