Flex Builder to Flash Builder? Scandalous!

by Josh Tynjala

Much discussion ensued in the Flash and Flex world today as Adobe announced to the community that they’re rebranding Flex Builder as Flash Builder. It’s a good change, in my opinion. Though I consider myself a Flex developer at least half the time, I think I’ve actually worked on more pure AS3 projects in Flex Builder than Flex projects. It’s clearly not a Flex-only development environment, and the new name is far more accurate and widens the audience, in my opinion. It may cause some initial confusion (as all rebranding does), but I think that any problems will clear up quickly.

I’ve noticed a few people wonder out loud if explicitly declaring that Flex is a part of the Flash brand in the product name will turn off developers who are considering Flex. We all know that a certain subset of the developer community has a lasting grudge against Flash due to its occasional misuse on the web, so this almost seems possible. However, I suggest thinking critically about that concern for a moment. Don’t you think it’s rather obvious that Flex runs in Flash Player? Is it really conceivable that a developer would never realize that Flex is really Flash-based with even the smallest amount of research? If someone is so anti-Flash that simply seeing the name of the development tool would turn them away, I would expect them to have the same reaction after a quick visit to their favorite search engine or Wikipedia to learn a little more about Flex.

Also, can we stop with the irrational fear that Flash Builder will replace the Flash authoring tool? Do you really think Adobe would decide to start ignoring the massive number of Flash content creators who draw things by hand, work with animation on the timeline, and understand symbols in the library much better than code in classes? Flash Builder is a code-centric development tool that advanced developers find more comfortable and productive. It would need years and years of development time to implement all the features needed to replace the Flash authoring tool. Not to mention the massive amounts of training Adobe would have to commit to in order to move developers and designers from one to the other. These two tools, Flash CS and Flash Builder, have many of their own unique use-cases, but they can also co-exist for the same user. I create art for my games and applications in Flash CS, while I write all my code in the current version of Flex Builder. They’re separate tools, though, and both must exist for Adobe to have any chance of making their target audiences that don’t overlap happy. You need only look at the incredible differences between the layouts of each tool to see that. For some of us, that means we need to purchase both, which may be a little expensive. Personally, I’d say that each falls under “one tool that does one thing, but does it well”, so they’re worth the price.

Changing the name of the development environment you use shouldn’t mean that you must change your job title, the experience you list on your resume (one word only, if you happen to list the tools you know), or what you write in job descriptions when you want to hire a developer. A Senior Flex Developer is still a Senior Flex Developer, regardless of whether he or she uses Flash Builder, FDT, FlashDevelop, or a simple text editor like TextMate with a command line compiler from the Flex SDK. A Flash Developer is still a Flash Developer in the exact same way. If you build Flex applications, then market your technical knowledge by only talking about Flex, Flex, Flex(!), if you feel that’s important. You don’t need to tell your clients what IDE you use, if you’re worried that the word “Flash” will cause them undue stress. Personally, I think you’re probably causing yourself too much stress by wondering how the name change will affect others.

As I’ve probably made clear, I don’t believe that the name change from Flex Builder to Flash Builder will be bad for either brand. What’s strange to me is that I’ve seen the strongest pushback coming from the Flex developers in the community. What’s up with that, guys? I consider myself one of you, but sometimes I don’t understand you. The name Flex will become much clearer because it will always be a Rich Internet Application framework that runs on Flash Player. No more IDE that’s called Flex (but does more than Flex), no more expensive server requirements. Those parts of the old Flex brand are surviving separately on their own merits now, as they should, and the framework can now be Flex without interference. The ubiquitous Flash Platform will solidify a bit more with another “Flash” branded product, and maybe the Flash name will even a little more respect from those developers who think Flash is all about animation and banner ads. I doubt that Flex will lose any respect, though. It gained ground with developers outside the Flash community because it’s a great open source framework for building RIAs, not because it somehow separated itself from Flash. Sometimes, good libraries and frameworks can change the minds of developers by being just that, good. Look at how JavaScript went from being a web toy to becoming a serious language in the last several years. I think Flex will continue to gain mindshare in a similar way, and I think it can only benefit the Flash Platform as a whole.

Packages are actually namespaces in ActionScript 3

by Josh Tynjala

Have you ever looked at the returned value of the function flash.utils.getQualifiedClassName() and wondered why it includes :: between the package and the class name? For example, if you pass in a MouseEvent instance, you'll get the string value "flash.events::MouseEvent". The first time I tried it, I expected to receive "flash.events.MouseEvent" with a . because that's how you reference a packaged class in an import statement. I always thought the difference was a little strange, but I just shrugged and went about my business. Today, though, my mind must have been feeling a little extra clever than ususal because it suddenly dawned on me: you use :: as an operator in ActionScript 3 to access a namespace.

With one simple test, it became unquestionably clear that packages in ActionScript 3 are really an abstraction built on top of namespaces. Try running the following code using the Flex SDK or the Flash authoring tool:

namespace flash_events = "flash.events";
trace( flash_events::MouseEvent ); //output: [class MouseEvent]

No import needed!

I imagine this has ECMAScript 4 roots. In general, many of the OOP features of AS3, like class and package syntax, are considered syntactic sugar. How can AS3 developers benefit from this knowledge? I have no idea, but it's one of those discoveries that whispers, "someday, you may need me".

Get the class used to create an object instance in AS3

by Josh Tynjala

Sometimes, you want to know the datatype of an object at runtime. The most common thing to do in ActionScript 3 is use the is keyword to see if an object is an instance of a specific class. For example, you use exampleObject is Sprite to see if something is a Sprite (or any subclass of Sprite). However, there are times when you want to use the actual class in your code to create a new instance, or to do something a little more arcane. There are a couple simple ways to access the datatype of an object and place it in a variable.

Method 1: Combine a couple flash.utils functions

The first way to get an object’s class at runtime takes requires calls to a couple useful functions that live in the flash.utils package:

import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;

var example:Sprite = new Sprite();
var exampleName:String = getQualifiedClassName( example );
var exampleType:Class = getDefinitionByName( exampleName ) as Class;
trace( exampleType == Sprite ); //output: true

Start by calling the function flash.utils.getQualifiedClassName(), and pass in the object. It will return a string that includes the full class name, including the package. For example, passing in a Sprite object will return the String value "flash.display::Sprite". Next, call the function flash.utils.getDefinitionByName(), and pass in the String value that you just received. It will return a reference to the object’s class. An equality check is included in the code above to demonstrate that exampleType is actually the Sprite class.

Are you curious about that :: part of the fully-qualified class name? Shouldn’t it be . instead? Check out my post Packages are actually namespaces in ActionScript 3 to learn more.

Mainly, I’ve included this first method of extracting a class from an instance because the two utility functions used in the example above are quite useful in other contexts. However, the second method is much simpler, if a little more obscure.

Method 2: The constructor property

Every object in ActionScript 3 has a property named constructor. According to the documentation, it is a reference to the datatype used to instantiate the object. In other words, every object can tell you the Class (or Function, since AS3 still supports ECMAScript function prototypes) used to create it with one simple property lookup. How simple!

var example:Sprite = new Sprite();
var exampleType:Class = Object( example ).constructor;
trace( exampleType == Sprite); //output: true

What’s interesting, and not immediately obvious (unless you read the documentation thoroughly), is that if you try to access the constructor property in the strict mode (which is on by default in the AS3 compiler), you’ll get a compiler error. However, the documentation notes that dynamic objects don’t cause this error. We can use that fact to create an easy workaround because everything is an Object, and Object happens to be a dynamic class. As you can see in the code above, a simple cast makes the error go away.

Personally, I prefer the second method because it takes only a simple property lookup, and it requires no calls to functions with long names. Again, though, those functions can be quite useful in other contexts, so it’s worth making note of them.

Combine buttonMode = true and a mouse click to leak memory

by Josh Tynjala

Here’s a troublesome Flash Player bug I discovered when I couldn’t understand why my SWF wouldn’t unload properly from a parent SWF. Everything seemed to unload fine unless I clicked on any buttons in my game’s menus. How strange. I loaded my SWF up in the Flex Builder profiler and watched what stuck around. Sure enough, in addition to the main document class and anything referenced there, some button instances that should be gone seemed to be sticking around. The reason they were stuck in memory? I set buttonMode to true.

Sounds weird, right? At first, following my own recent advice on how to cleanup an unloading SWF, I started commenting out certain mouse events used by the buttons. My thinking was that maybe these event listeners were causing the stage to keep a reference to the button. Unfortunately, that didn’t seem to help. In frustration, I started commenting out large portions of the button class. With almost no code left to run, I got the SWF to unload properly. No instances of any class in my SWF were left this time, so it was clear that this button class was the culprit. I began slowly adding bits of functionality back in. I eventually discovered two functions that would cause the button to stay in memory, and both had one thing in common: they modified buttonMode. I re-enabled all my code in that class, except for the lines that set buttonMode, and the SWF began unloading perfectly.

That’s a pretty complex case that involves multiple SWFs, and it certainly wasn’t easy to debug. For my bug report to Adobe, I built a very simple test case that you can look at below. I simply creates two Sprite instances that are clickable, one with buttonMode set to true, and one without:

package
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.system.System;

	public class ButtonModeBug extends Sprite
	{
		public function ButtonModeBug()
		{
			var button1:Sprite = new Sprite();
			button1.graphics.beginFill(0x009900);
			button1.graphics.drawRect(0, 0, 120, 20);
			button1.graphics.endFill();
			button1.x = 10;
			button1.y = 50;
			button1.addEventListener(MouseEvent.CLICK, regularSpriteClickHandler);
			this.addChild(button1);

			var button2:Sprite = new Sprite();
			button2.graphics.beginFill(0x990000);
			button2.graphics.drawRect(0, 0, 120, 20);
			button2.graphics.endFill();
			button2.x = 150;
			button2.y = 50;
			button2.buttonMode = true;
			button2.addEventListener(MouseEvent.CLICK, buttonModeSpriteClickHandler);
			this.addChild(button2);
		}

		private function regularSpriteClickHandler(event:MouseEvent):void
		{
			var button1:Sprite = Sprite(event.currentTarget);
			button1.removeEventListener(MouseEvent.CLICK, regularSpriteClickHandler);
			this.removeChild(button1);
			button1 = null;
			System.gc();
		}

		private function buttonModeSpriteClickHandler(event:MouseEvent):void
		{
			var button2:Sprite = Sprite(event.currentTarget);
			button2.removeEventListener(MouseEvent.CLICK, buttonModeSpriteClickHandler);
			this.removeChild(button2);
			button2 = null;
			System.gc();
		}
	}
}

Notice that when you click either button, it is removed from the display list, the event handler is removed, the variable is set to null, and then System.gc() is called to force the garbage collector to run.

To see the bug in action, you should run that class in the profiler with live memory data displayed (you may need to unfilter the flash.* classes too). When you click button1 (the green one), you can see the number of Sprite instances decrease by one. When you click button2 (the red one), the number of Sprite instances stays the same.

As a control case, comment out the line that says button2.buttonMode = true;, and run again. Both buttons will be removed from memory, and the number of Sprite instances will decrease to zero.

The description of this bug can be summarized like this:

If you set buttonMode to true on a Sprite, and that Sprite gets clicked by the user, it will not be removed from memory after all references have been removed in ActionScript.

It appears, although I cannot be certain, that Flash Player’s internal code isn’t properly releasing its own reference to the Sprite. Maybe related to the hand cursor? Whatever the case may be, I recommend being wary of buttonMode (and the related useHandCursor) until this gets fixed, especially if you have a SWFs that are loaded and unloaded inside other SWFs. I say that because your buttons will hold many more objects in memory when the SWF can’t unload properly. If you’ve encountered the same bug, please vote for it in my report, “buttonMode = true + mouse click keeps Sprite in memory” filed in the public Adobe bug system.

Be a good SWF citizen, listen for Event.UNLOAD

by Josh Tynjala

If you have a SWF that you know will be loaded into a parent SWF, then it’s your responsibility as a developer to properly clean up after yourself when your child SWF is unloaded. Certain activities will keep your SWF in memory long after the unload() method is called on the Loader object that holds your child SWF, and there’s a good chance that you’ll have created a memory leak if you don’t take care of things properly.

It’s important to note that in Flash Player 10, Loader has a new unloadAndStop() method that does some of this work for you (see Grant Skinner’s blog post about unloadAndStop() for detailed information). While that’s helpful for SWFs that you don’t control, I think it’s still very important to clean up your own SWFs as best you can manually. Obviously, you have no other choice if you’re still targeting Flash Player 9.

What sorts of things could cause problems when you’re trying to unload a SWF? Running Timer instances, enterFrame events, audio or video that’s still playing or streaming, MovieClip instances that are playing, and content loaders that have not completed yet are all good examples (see Grant’s post above for a longer list). Some of these activities don’t actually keep your SWF in memory, but it’s important to remember that your SWF may not be garbage collected immediately. Code that’s still running for no good reason is simply a waste of resources.

How to clean up after yourself

A SWF can discover when it has been unloaded by listening for Event.UNLOAD on its loaderInfo object. This event handler is the perfect place to do your cleanup. I’ve put together a couple of very simple classes to illustrate how this process works.

First, we have the aptly-named ParentSWF document class for the SWF that loads our second SWF as a child. It’s very simple. It instantiates a Loader to load ChildSWF.swf. When that Loader has completed, it has some code to unload ChildSWF.swf right away:

package
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;

	/**
	 * This is the document class for a parent SWF that loads, then unloads, a
	 * child SWF. It is part of a demonstration of how child SWFs can clean
	 * up after themselves up when they are unloaded.
	 *
	 * @author Josh Tynjala (joshblog.net)
	 */
	public class ParentSWF extends Sprite
	{
		public function ParentSWF()
		{
			super();

			//this loader will load the child SWF. Upon completion, it will
			//immediately unload the child SWF.
			this._loader = new Loader();
			this._loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
			this._loader.load(new URLRequest("ChildSWF.swf"));
			this.addChild(this._loader);
		}

		private var _loader:Loader;

		private function loaderCompleteHandler(event:Event):void
		{
			this._loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderCompleteHandler);
			this.removeChild(this._loader);

			//this is where we unload the child SWF
			this._loader.unload();
			this._loader = null;

			//at this point, the child SWF should be ready to be garbage
			//collected. only the child SWF can keep itself in memory now.
			//it had better clean up after itself!
		}
	}
}

Next, let’s take a look at ChildSWF, the document class for our second SWF that is loaded into the first SWF. It includes a running Timer that should be stopped when the child SWF is unloaded. We listen for Event.UNLOAD on loaderInfo to know when the parent SWF has unloaded the child SWF:

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * This is the document class for a child SWF is loaded in a parent SWF, and
	 * then unloaded. It is part of a demonstration of how child SWFs can clean
	 * up after themselves up when they are unloaded.
	 *
	 * @author Josh Tynjala (joshblog.net)
	 */
	public class ChildSWF extends Sprite
	{
		public function ChildSWF()
		{
			super();

			//we want to listen to Event.UNLOAD so that we know when the Loader
			//in the parent SWF has unloaded this SWF
			this.loaderInfo.addEventListener(Event.UNLOAD, unloadHandler);

			//this timer, if still running, will keep this SWF in memory after
			//ths SWF is unloaded.
			this._timer = new Timer(1000);
			this._timer.start();
		}

		private var _timer:Timer;

		private function unloadHandler(event:Event):void
		{
			//stop the Timer or this SWF won't be garbage collected
			this._timer.stop();

			//of course, make sure to remove this event listener too!
			this.loaderInfo.removeEventListener(Event.UNLOAD, unloadHandler);
		}
	}
}

To be perfectly clear, the most important parts of the child SWF code above can be summarized in the snippet below:

//listen for the unload event to know when all activities in this SWF should be stopped
this.loaderInfo.addEventListener(Event.UNLOAD, unloadHandler);

function unloadHandler(event:Event):void
{
	this.loaderInfo.removeEventListener(Event.UNLOAD, unloadHandler);

	//DO YOUR CLEANUP HERE!
}

Again, let me cover some of the most common things that should be cleaned up. Be sure to stop audio and video that is playing, MovieClip instances that no longer need to be playing, Timer instances, tweens (they’re probably run by Timer instances or enterFrame events), active listeners for any type of Event.ENTER_FRAME, listeners for events coming from the stage (also a good place to use a weak reference), and be sure to stop any data that may be loading from external sources using URLLoader, Socket, Loader, and other classes of that type. If your child SWF has it’s own child SWFs, be sure to unload those too!

That’s a lot of stuff to remember! Yes, it is, and it’s your responsibility as the developer to ensure that nothing in your SWF causes a memory leak, just like it’s your responsibility to do the same for your individual classes. If you’ve designed the rest of your application with good memory management, then it might not be as bad as you think. Often, you only need to take care of objects that are referenced in the document class. Those objects should already be doing their own work to cleanup any references and event listeners that aren’t needed anymore. For more information on that subject, check out the excellent series of blog posts about AS3 memory management by (once again) the very knowledgeable Grant Skinner.

A quick glance at my game development workflow

by Josh Tynjala

My recent excursion into Flash game development has been fun, to say the least. Certainly, I’ve finally been able to dive into more creative areas of Flash that I haven’t touched as much as I would have liked. It’s also enjoyable to be in charge of all aspects of a project from concept to conclusion. As much for self-exploration as for passing on knowledge, I want to share a little bit about certain aspects of my recent workflow. It won’t be a full inside-out dissection, but more a peek at some highlights that I think might be particularly interesting.

The Whiteboard

No matter what stage of game development in which I’m currently working, I keep a small hand-held whiteboard around. Most of the time, it just sits on my desk or the closest table, but it stays nearby for good reason. Firstly, it helps me immediately visualize current tasks that might be hard to fully imagine in my head. If I’m in the zone, I don’t want to run off searching for something to write on. I want to stay focused, draw on something that’s nearby, and instantly produce results. If something doesn’t look right, all it takes is a quick swipe to erase, and I can try something new.

I’ve found the whiteboard to be most useful when I get the very first idea for a new game. I’m not yet ready to code up a quick semi-playable prototype. I just want to physically see what has vaguely formed in my head. It’s very much a creative task where a simple drawing (that doesn’t even necessarily show interaction in any way) can make the idea more solid. It’s also the first line of defense for deciding if an idea is actually worth pursuing further.

As I mentioned, I’ve been using a small whiteboard. It’s common for software developers to have larger ones on cubicle or office walls nearby. Those are great too, especially if you’re visualizing complex UML architectures. The games I’ve been building are generally quite simple, so I haven’t focused much on code architecture. For that reason, a smaller whiteboard gets the job done. The biggest advantage of a small whiteboard comes from the fact that I’ve been working from different locations almost every day. It’s nice to have a whiteboard that is portable.

Prototypes

Early in development, new ideas need to be tested. This process can go anywhere from a simple drawings on a whiteboard (as mentioned earlier), to semi-interactive proof-of-concepts, to fully-featured demos that only need refactoring and better art before turning into production code. Which of these prototyping choices is needed should be determined on a case-by-case basis. Generally, the more likely it is that a feature will be very time-consuming or difficult to implement, the more complex your prototype should be.

Later in development, features that didn’t need prototypes to ensure that they weren’t blockers may still benefit from quick prototypes outside the game’s main codebase. When one of these features comes up as my next task, I’ll often create a new project in my IDE and play around with some ideas. This not only ensures that I don’t mess up any of my existing code (obviously, this can also be handled through version control rollbacks instead), but it also helps me focus on the single task at hand without all that other code to distract me. One possible benefit from this separate project is a cleaner API, in terms of reusability, because I’ll have a harder time tightly coupling this new code to the existing code in the main project.

For one game I built, a match-3 puzzle game, I made several prototypes to validate the gameplay. They led to some very important changes that improved the game mechanics quite a bit over time. It started with a whiteboard drawing that seemed to validate what, in my head, I envisioned to be a very fast-paced and fun game. However, the first functional prototype with interaction showed me that matches happened too often, and that made the game extremely easy and quite boring. I simplified the controls a bit in the next prototype, but I added a timer-based game mechanic that still kept the matches paced as quickly as before while speeding up other aspects of the game to ensure that the player had some challenges that required him or her keep up.

These changes I made in each prototype helped to make the game a little more fun. As pieces started fitting into place, I could discover other parts of the game that needed tweaking for each successive prototype. In the end, the game mechanics got more and more basic, but they focused strongly on what actually made the game fun to play. So far, this process of simplification in the prototype stage has helped me improve every one of my games as they moved from conceptualization to actual development.

Content Creation Tools

I have a wide variety of tools that I use to develop my games. For my first game, Chroma Circuit, I did all of my development in Flex Builder, and almost all the graphics are programmatic (other than some assets used in the main menus). That game had certain strict geometric requirements that made it difficult to build some of the game’s elements visually. Ultimately, I chose to organize the final code (which has several branches, for reasons that I’ll talk more about later) in such a way that it’s easily built with a short Ant script.

For my second game, Gridshock (still in development at the time of this writing), almost all the graphical assets were created using the vector tools in Flash CS4. I still wrote my code in a Flex Builder ActionScript project, though, since it provides a much better code editor. It’s worth noting that I tried using Powerflasher FDT for a while, but it didn’t quite fit my style of development. Still, I mention it because can provide a similar workflow in place of Flex Builder. For this game, I chose to compile the SWF in the Flash authoring tool instead of with the Flex SDK, but I could have embedded the assets in code and stuck with Flex Builder for all development-centric tasks instead. Mainly, I went with the Flash authoring tool as the compiler because had the urge to try a workflow based around a FLA file rather than only a document class. I can’t say that I encountered many disadvantages, other than switching windows more often to go between Flex Builder and Flash CS4, so I may try this workflow again with other games.

For audio editing, I’ve been using a combination of Apple’s Garage Band and the open source tool, Audacity. It’s worth noting that when I was a Windows user in another life, I enjoyed working with Adobe Audition a bit more, but Audacity has been good enough for me on my Mac. All of my sound effects are derived from royalty free sounds that I purchase for a small fee online, but most of them receive some tweaks. In fact, I’ve often made collections of related sounds derived from the same original audio file as a way to offer some better aural continuity in a single game.

Version Control

Of course, using a version control system is software development common sense, but for many folks who use their free time to create casual games or do any other type of development, it might be a forgotten detail. Allow me to highlight a couple notable reasons for considering a version control system for games.

For me, one of the biggest advantages of using version control for Flash games is related to sponsorships. If your game is popular with sponsors, you might get a primary sponsorship and one or more non-exclusive, site-locked sponsorships. This means multiple versions of the same game, and if you’re using version control, you’ll be able to manage these separate versions with branches. Need to make a change for one particular sponsor? Just edit the files in that version’s branch, and it won’t affect other sponsored versions. Need to make a change to the core game? Do it in the main branch, and merge those changes into the sponsor-specific branches as needed.

For any type of development you do in your free time, it might be a good opportunity to check out one of the various free version control systems you possibly haven’t used yet. Distributed systems like Git and Mercurial have been gaining in popularity recently, and many prominent open source projects have switched to them from centralized systems like CVS or Subversion. This may be a sign that the business world will switch eventually too, so it’s a smart move to begin exploring DVCS now, if you haven’t already (I personally haven’t yet, actually, but it’s on my list of things to do).

It’s worth noting that if you compile games (or any other type of project) with the Flash authoring tool, the binary nature of a FLA file makes it potentially difficult to use with version control systems, try to keep as many assets externalized as you can. Obviously, that includes all source code that can be put into class files, but maybe even images and sound files if they change often enough. Basically, ensure that changes analyzed (diffed) by the version control system are focused to the specific asset files and not on one giant centralized FLA file. This should help to keep your repository history from taking up massive amounts of space, and you’ll find it easier to rollback changes to specific assets while keeping others in their current state.

Conclusion

Again, I’m not trying to cover every detail of my daily development workflow, and probably went into more specific details in some areas than I did others. The process of explaining some things certainly helped me to better understand some of my new processes. It even helped me compare how I’ve been building games a bit more critically to my previous workflow with reusable components. Thanks for reading.

Flash Player Bug: Removing an event listener in another listener for the same type fails

by Josh Tynjala

Update: My bug report has been marked Not a Bug by Adobe. As Joeri mentions in this post’s comments, and Charles Liss explains in the bug report comments, Flash Player makes a copy of the event listeners internally when dispatchEvent() is called. It’s by design that a call to removeEventListener() will affect the original list of listeners, but it will not affect the copied list. I followed up with a request to describe this behavior in the API documentation so that others who run into the same weird behavior might have a better chance of learning why Flash Player seems to be behaving incorrectly.

I’ve been struggling off and on for days trying to figure out why a certain display object that I’d been fading in and out sometimes got stuck with partial visibility. Even when I explicitly set the alpha value to 0.0 or 1.0 after removing the animation and all its listeners, there was still the occasional situation where it would clearly receive a different value. I finally tracked down the following bug in Flash Player. If two functions are subscribed to the same event type from the same event dispatcher, and the first listener removes the second listener, the second listener is still called by Flash Player.

The following class demonstrates the problem.

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class EventErrorTest extends Sprite
	{
		public static var dispatcher:EventDispatcher = new EventDispatcher();

		public function EventErrorTest()
		{
			dispatcher.addEventListener(Event.COMPLETE, dispatcherComplete1Handler);
			dispatcher.addEventListener(Event.COMPLETE, dispatcherComplete2Handler);
			dispatcher.dispatchEvent(new Event(Event.COMPLETE));
			dispatcher.dispatchEvent(new Event(Event.COMPLETE));
		}

		private function dispatcherComplete1Handler(event:Event):void
		{
			dispatcher.removeEventListener(Event.COMPLETE, dispatcherComplete2Handler);
			trace("1");
		}

		private function dispatcherComplete2Handler(event:Event):void
		{
			trace("2");
		}
	}
}

The expected output is as follows:

1
1

Instead, my output console displays this instead:

1
2
1

Clearly, the second listener is still called the first time the event is dispatched. If you move the call to removeEventListener() to the line before the first call to dispatchEvent(), the output appears as expected.

I discovered this bug while using Grant Skinner’s excellent GTween library for AS3 in the current game I’ve developing. In my game, certain animations may be paused following the completion of other animations. Since (internally) all GTween instances listen to a static timing object, pausing a GTween inside an event listener attached to another GTween causes the supposedly-paused GTween to update the target’s properties one last time.

If you happen to be using GTween, and you encounter this same issue, adding the following line at the beginning of handleTick() in GTween.as should fix the problem:

if (_paused) return;

This event bug has been filed in Adobe’s public Flash Player database. You’re welcome to vote for it.

A preview of my first Flash game: Chroma Circuit

by Josh Tynjala

For the last couple of months, I’ve been quietly (or not so quietly, if you follow me on Twitter) developing a Flash game. Like a lot of software developers, games were what made me want to start programming in the first place. Finally, after getting a little burnt out and needing a bit of a break, I decided to spend some time focusing on making writing code fun for me again. After about a month and a half of exploration, I finished my first Flash game, and it’s called Chroma Circuit.

Screenshot of Chroma Circuit Title Screen
Chroma Circuit’s Title Screen

The basic idea behind Chroma Circuit is that, in each level, you need to match up colors on neighboring elements. Generally, this is done by rotating them, but some other mechanics are introduced later on. The game works a lot like a jigsaw puzzle, in a way, if a bit faster paced. You need to align the colors for every element on-screen before you can advance to the next level. To rotate an element clockwise, you just click it with your mouse. Hold shift, and it will rotate in the other direction. Several of my testers independently called it “addicting”.

Screenshot of Chroma Circuit In Game 1
Three-Sided Rotating Elements

As the game progresses, levels contain more and more elements, and new elements are introduced over time. Three- and four-sided elements that may be rotated are the most basic types that appear when the game first starts. Later, transfer elements change colors and pass colors to different parts of the level to test the player’s spacial memory. Finally, in the last several levels, a new “bomb” element is introduced. Bombs must always match the colors of their neighboring elements, or they will explode, and you’ll be forced to restart the level.

Screenshot of Chroma Circuit In Game 2
Watch out for The Gauntlet!

The game contains 18 hand-crafted levels that I spent a lot of time tweaking and play-testing. I had so much fun putting it all together (especially the number of mathematical challenges required to draw the elements programmatically!), and I’m excited to get started on my next game. Chroma Circuit can now be played on my Bowler Hat Games company site, and at various distribution partners across the web. If you think it’s fun, please share it with your friends!

Open Source Flex Component: PopUpInitializer

by Josh Tynjala

At Adobe MAX this year, I got an idea for an interesting little Flex component. It took me a while to get around to implementing it, but I finally found some time. At the time, I had been building several quick prototype applications with floating information windows that needed to be added to the PopUpManager immediately when the application was initialized. Seeing as these were prototypes, I wanted to be able to do this rapidly without making new class files for each window, and if possible, I’d like to skip calling any methods on PopUpManager from a Script block. Basically, I wanted to throw as much as possible into one MXML file, and then have some component that’s smart enough to add my components to the PopUpManager. With those requirements in mind, the PopUpInitializer was born.

Here’s some example code that adds a TitleWindow to the PopUpManager using PopUpInitializer:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:toolbox="http://www.flextoolbox.com/2006/mxml">

    <toolbox:PopUpInitializer>
        <mx:TitleWindow title="An Example Pop-Up"
            x="50" y="50" width="200" height="200"/>
    </toolbox:PopUpInitializer>

</mx:Application>

It’s a simple class that implements IMXMLObject and makes liberal use of compiler metadata to make itself act like a regular UI container. For example, it uses the [DefaultProperty] metadata to pass the UIComponents to a controls property without having to specify that property name, and the [ArrayElementType] metadata to specify that the controls (there may be more than one) must all be of type mx.core.IUIComponent. Once it receives the list of controls, it waits for the application to be created, and then tosses them all up on the PopUpManager. A cleanup() method is added for convenience to remove all the controls from the PopUpManager, if desired.

Download the component SWC, an example, and the full source code from my Google Code repository. API documentation for PopUpInitializer is available as part of the common documentation with my other “Flex Toolbox” controls like ZoomFrame and PopUpThumbnail. As with most of my other open source code, PopUpInitializer is available under the terms of an MIT-style license.

Mac Switchers: How to Enable Tabbing to Combo Boxes

by Josh Tynjala

One thing I could never understand about my Mac is why I couldn’t use the keyboard to switch to combo boxes in forms on the web. For example, when I buy something online, I generally need to enter my shipping address. First, I type in my name, street address, and city. I press the Tab key to switch between each field. Next, I need to enter my state, so I press Tab…. Oops! It went straight to ZIP code and skipped the State field. What the hell?

Coming from a Windows world, I’m used to keyboard tabbing that goes between every field in a webpage or application window. It turns out that Mac users do what they do best (think differently) in regards to this user interaction. By default, keyboard tabbing only moves between “text boxes and lists only”. How strange.

As I happily discovered today, there is a setting hidden deep in the System Preferences that allows you to change this behavior. Here’s what you need to do:

  1. Open up System Preferences.

  2. Choose Keyboard & Mouse under the Hardware group.

  3. Go to the Keyboard Shortcuts page.

  4. At the very bottom where it says “Full Keyboard Access” change the radio button from “Text boxes and lists only” to All controls.

Thankfully, that’s one of the last things about my Mac that I still had to work around. Now if only I didn’t have to work around all sorts of new things when I need to go back to Windows! I hope this post helps someone else who finds it strange that tabbing is so limited by default on Mac OS X.

Pages: Prev 1 2 3 4 5 6 7 8 9 10 ...18 19 20 Next