Archive for the ‘Flex’ Category

Flash/Flex Integration: SWFLibrary v1.5

Tuesday, August 19th, 2008

Usually I like to post glamorous stuff, like 3D swirly things and experiments. Occasionally, however, I feel the need to release a little code in the interest of helping a few people out. This code is a review of sorts, since I already posted a similar utility back in June. However, since then I have been expanding my code library and I thought I’d share the latest and much improved version. It’s really a simple concept, but having this in my toolbox has lightened my workload as an ActionScripter considerably.

Advantages

This utility allows you to publish any symbol from Flash and access it at runtime from an ActionScript-only project, such as in Flex Builder. This has a few advantages:

  • Easy storage of many assets in one file
  • Ability to change graphics without recompiling the main application
  • Faster load times with only one HTTP request (as opposed to many separate images and sounds)
  • Ability to import vector graphics and animations at runtime
  • Smaller main SWF size

The one disadvantage that I can think of is that you’ll need to recompile your library SWF every time you make a change. However, I think the advantages above outweigh this.

Differences in v1.5

Here are the main differences from the last version:

  • The class is no longer static. This allows for more than one instance of SWFLibrary at a time.
  • The class can now return instances of Sprites, MovieClips, and Sounds from a library SWF.

Usage

1 - In Flash, select “Export for ActionScript” in the symbol’s Linkage settings in the Library (ex. ‘Character’).
2 - Publish the Flash file as a SWF.
3 - Load the SWF into an instance of SWFLibrary
4 - Access the symbol through SWFLibrary, using the class name chosen in Step 1.

A SWFLibrary can be used with four lines of code. Here’s what you’ll need:

// creates an instance of SWFLibrary, adds a listener, and loads a SWF
var gameAssets:SWFLibrary = new SWFLibrary
gameAssets.addEventListener( Event.COMPLETE, handleAssetsLoaded );
gameAssets.load( "myCustomGameAssets.swf" );
 
// accesses the asset (assumes there is a symbol exported as 'Character' in the loaded SWF, as seen in step 1 above)
// this code should run after the Event above has fired
var mySprite:Sprite = gameAssets.getSprite( "Character" );
addChild( mySprite );
 
// gets the asset as a MovieClip (assuming, of course, that it actually is a movieclip)
var myMC:MovieClip = gameAssets.getSprite( "Character" );
addChild( myMC );
 
// getting a sound
var mySound:Sound = gameAssets.getSound( "SoundLinkageNameHere" );
mySound.play();
// === ===

After a symbol has been retrieved from SWFLibrary, it may be treated like any other object.

Download

DOWNLOAD SOURCE

So have fun with this. Hopefully it saves you as much time as it saves me.

Compiling Astro with Flex 3

Thursday, June 5th, 2008

Flash Player 10

Nothing revolutionary today, folks, on account of the ridiculous amount of time I spent today trying to get Flex 3 to compile Flash 10 SWFs. I had to use a combination of information from several sources, including the below:

Flash 10 / Astro Installation Guides

Adobe’s official page This is probably the place to start.
Ryan Taylor / Boostworthy There are some interesting notes here.
FLEX{er} This is a rather terse (but illustrated!) guide.

It would be pointless for me to go through it again, since I think they’ve pretty much got it covered. However, there are a couple valuable things I learned:

Setup Tips

1- I couldn’t get things to work with the last “stable” build (May 16- v3.0.1.1732), so my advice would be to go with one of the more recent ones. I’m using v3.0.1.1954, myself.

2- There is in fact a debug player, and it is here. I’m not sure why this isn’t mentioned in the documentation.

3- The debug player is standalone, so you won’t be able to debug in your browser. Instead, in your launch configuration (Project > Properties > Run/Debug Settings > New (or Edit)), point the Debug URL to the actual SWF you’re producing, not the generated HTML page. Then you can tell your OS to run SWFs with the standalone debug player, and then you’ll be able to actually see what you’re doing.

4- From my experience, I estimate that actually reading Adobe’s instructions before trying this will save you approximately four and a half hours.

Broadcasting Events from Custom MXML Components - The [Event] Tag

Thursday, April 17th, 2008

Okay, this was hard for me to wrap my brain around, so let me summarize, in case anyone else is stuck on this. When developing in Flex, all the standard components let you specify a listener when you create them in MXML, like this:

<mx:Button id="someButton" click="handleClick( event );"/>

Now when someone clicks on someButton, it calls the function handleClick(). Although not strictly best practice, it really is a nice little shorthand for adding an event listener to a Flex component. And since the Adobe components contain this functionality, people are used to it. If you have any plans of releasing your component into the wild, people will expect it to act like the components they already know and love.

Well, here’s how you do it: with the [Event] metadata tag.

1- First of all, the tag goes before the class declaration because it applies to the entire class. You can actually have more than one of these tags, for different events that you might broadcast. In my example, I have two, and they both broadcast ModelEvents.

// create the [Event] tags
[Event(name="onLoad", type="com.pixelwelders.events.ModelEvent")]
[Event(name="onLoadError", type="com.pixelwelders.events.ModelEvent")]
 
// declare your class
public class DataModel extends EventDispatcher implements IModel { ...

2- The type attribute refers to the actual type of event that this class broadcasts, package and all.

3- The name attribute refers to the string you use when you create a new Event of this type. You have to use an actual literal here; you can’t use a variable like ModelEvent.LOADED. So if you are dispatching an event like either of these:

dispatchEvent( new ModelEvent( ModelEvent.LOADED ) );
dispatchEvent( new ModelEvent( ModelEvent.LOAD_ERROR ) );

…you’ll need to check in your Event class to see what the actual value of LOADED or LOAD_ERROR is. In my ModelEvent class, I have:

public static const LOADED				: String = "onLoad";
public static const LOAD_ERROR			: String = "onLoadError";

Thus, my complete Event metadata tags are:

[Event(name="onLoad", type="com.pixelwelders.events.ModelEvent")]
[Event(name="onLoadError", type="com.pixelwelders.events.ModelEvent")]

Of course, that’s only the first part of the equation. The second part is listening for the event, which thanks to our [Embed] tags, is now a piece of figurative cake. Here’s my Flex tag:

<model:DataModel
		id="dataModel"
		xmlURL="fileName.xml" 
		onLoad="handleModelLoaded( event );"
		onLoadError=”handleModelError( event );”/>

That onLoad and onLoadError attributes have the same value as your name attributes that you specified in step 3 above. Now put your two handlers in your Script tag, and they will be called any time those events are fired. Voilà.

MXML Singletons in Flex 3

Thursday, April 10th, 2008

If you’re not clear on what a Singleton is, try glancing through my brief yet poignant article here: The Art and Beauty of Singletons.

Creating a Singleton through MXML

Okay, so I’ve been putting together a little image-viewer component in Flex, and I wanted it to load one data model that all other components would share. Sounds like a job for a Singleton, right? However, I also wanted to instantiate said model from MXML, which adds some kinks. In fact, I’ve heard it said that it’s not possible at all. And after some trial and error, I found that apparently it is possible- you just have to hack around a little bit.

If you instantiate your class (or “component”) through MXML, Flex will automatically call its constructor. Typically, this is a bad thing because you don’t call constructors directly in Singletons- instead of calling a method that returns a new object (i.e. a constructor), you call a method that returns a reference to an already-created object (getInstance() or instance()). Flex won’t do that for you. However, this is not a deal-breaker. To make that class a Singleton, you just need to make sure that the constructor is only called once.

So, set up your Singleton like normal:

private static var _instance: DataModel = null;
public static function get instance(): DataModel
{
	return _instance;
}

Then, in the constructor of said Singleton, add the following:

if ( !_instance )
{
	_instance = this;
} else {
	throw new Error( "DataModel is a Singleton: only one instance allowed." );
}

All I’ve done here is move the creation of the Singleton from the get instance() method to the constructor. And if the constructor is called more than once, it throws an error. Now you can instantiate the class through MXML, just like any other component.

<model:DataModel
		id="dataModel"
		xmlURL="fileName.xml" />

Meanwhile in Actionscriptland, you can refer to this instance of your class just like it was a normal Singleton:

	trace( DataModel.instance ); // traces "[object DataModel]"

Plus, if you try to create another instance, be it through MXML or through ActionScript, you’ll get a good ol’ runtime error. You’ll have to wait until runtime to see it, but that’s certainly better than nothing, right?

Flex 3 + Game Dev = Awesome

Monday, March 31st, 2008

<Synopsis!>
First of all, a synopsis of this entry so you don’t have to read the whole thing. First, I’m going to reminisce in a slightly condescending tone. Then, I’m going to suddenly switch tacks and turn my reminiscence into a rather awkward metaphor about how Flex rocks. Then I’ll say something like “download Adobe Flex 3 here and try it for game development.” So if that’s enough to convince you, you can stop reading here. If not, read on! There’s another link to download the Flex trial at the bottom of this post.
</Synopsis!>

A few years ago, before my brilliant web career, I lived a very different life. I worked in a small studio in downstate Illinois as a songwriter and producer. This was not quite as awesome as it sounds. Usually it meant dealing with clients who were pretty convinced of their own brilliance, who brought me lyrics scratched on stained and wrinkled napkins. “It goes like this,” they would say, and hum me a series of unrelated notes.

Emo kid

My job was to take this stained napkin and these notes and, through a sort of studio alchemy, synthesize an actual song. I acted as an amplifier for the natural talent of the client. If she thought she might want some drums, I was the drummer. If this called for some keyboard or guitar, then that was my job too. If there was a note a client didn’t like or a harmony that didn’t seem to work, it was my job to suggest a better one. I became an extension of the client- the whole point of my employment being to make each artist sound better than they actually were.

Okay, now let’s make the awkward jump to the other side of this too-obvious metaphor. The hapless client is now the Flash developer. The studio is now the Flash player and development environment. And the producer, the guy who amplifies your strengths and fills in for your weaknesses… that producer is Flex 3.

Yes, it’s an awkward metaphor. I realize this. But it’s very important to me that I evangelize Flex as much as possible, and this particular comparison makes a lot of sense in my head. Actionscript 3 dropped a ton of new functionality in our laps- the Flash Player 9 API is like five times the size of Flash Player 8’s. In many ways, the AS2 expert, the Java developer, and the AS newbie are all in the same boat (to mix metaphors) when it comes to starting AS3. It’s a room full of powerful equipment and there’s no one to ask for help.

Flex Assistance

So that’s why I am evangelizing Flex 3. If you’ve been using the Flash CS3 compiler, you’re going to freak when you start using the Flex 3 compiler. Seriously, it’s that awesome. And Flex itself provides a ridiculous amount of help in the form of auto-completion and code hints. It’s like that producer. You say “I’d like to make a call to that BadGuy class I made three weeks ago.” Flex 3 says, “Awesome! You’ll need to send it the following five parameters, of these five types, in this order.” As soon as you mistype a variable name Flex is there with a friendly reminder: “Ahem. The ScoreKeeper class only accepts Numbers. I suggest you change your approach.” No more thirty-second compiles in Flash only to find that you have errors in your code. It’s instant- Flex checks your syntax and compiles every time you save.

Flex Errors

Okay, I’m getting carried away here. I can’t help it- I’ve only recently started using Flex for game development, and it’s changed the way I code. I know you FlashDevelop and Eclipse folks have had these functions forever, but it’s new to me. I can get twice as much done in half the time, with a third of the frustration. Or something. So if you haven’t tried Flex for your game development, I suggest you give it a whirl. Adobe even gives you a 60-day trial here. Seriously, how can you lose?

Credits
The studio above is The Noisegate, in Pekin IL. It’s a beautiful studio, and Mike Layne (lead engineer) is a great guy. Tell ‘em I sent you.