"tutorials" Posts

Tip of the Day – Getting a SWF’s background color

Recently at ZaaLabs, I’ve been working on a really cool tooling platform called Eden. One of the features that Eden has is a Screen Capture plugin. Eden can send a request to a remote SWF to return a bitmap of the stage.

For example, here is Eden pulling a screen capture from HanClinto’s Platformer Starter Kit.

Really cool! However, I quickly ran into an issue when I tried to take a screen capture of a more basic game.

On the right is the game running in Flash, and on the left is the screen capture.

As you can see, my screen capture doesn’t include the green background. So what happened?

Well it turns out the background color of a SWF isn’t actually part of the stage. The background color that you set using the SWF Metadata tag, or set in Flash Professional is drawn directly by Flash Player.

package
{	
	import flash.display.Sprite;
 
	[SWF(backgroundColor="0x00FF00")] // <--- How can I get this programmatically?
	public class SwfBackgroundExample extends Sprite
	{
		public function SwfBackgroundExample()
		{
		}
	}
}

So I had a dilemma… how could I access the backgroundColor of the SWF? I scoured the API docs, I asked the Twitter-sphere, but no luck. All I learned was that the backgroundColor was hard coded into the bytes of the SWF. So I decided that’s where I needed to look for it.

SwfData to the rescue.

I read up on the Adobe SWF specification, and consulted with my good friend James Ward. He pointed me in the direction of loaderInfo.bytes, which gives us access to the bytes of the currently running SWF.

After a few hours, I had a fun little class I like to call SwfData, which parsed the background color out of the currently running SWF’s bytes… as well as some other fun things. Here’s how you use it:

package
{
	import com.zaalabs.utils.SwfData;
 
	import flash.display.Sprite;
 
	[SWF(backgroundColor="0x969696")]
	public class SwfDataExample extends Sprite
	{
		public function SwfDataExample()
		{
			var data:SwfData = new SwfData(loaderInfo.bytes);
 
			trace("version \t"+data.version);
			trace("frameRate \t"+data.frameRate);
			trace("frameCount \t"+data.frameCount);
			trace("fileLength \t"+data.fileLength);
			trace("bgColor \t0x"+data.backgroundColor.toString(16));
		}
	}
}

Using SwfData, I could now use the background color as the fill color of my BitmapData class.

Get It Here

SwfData is MIT licensed under ZaaUtils (do with it what you will). It is available on GitHub

Questions, comments, complaints are all welcome below.

== UPDATE ==

So I just found out that Claus Wahlers has an awesome, more feature complete version of an AS3 SWF parser. It’s also available on GitHub. I’m still going to keep SwfData up since it’s much more specific to getting the background color of the swf. If you need more features, use as3swf by Claus, it’s very well done.

Developing games with PushButton Engine – Using the Console

One really cool feature that we have built into the PushButton Flash Game Engine is a console.

Using the Console

The only thing you need to do to include the Console into your project is call PBE.startup().

package
{
	import flash.display.Sprite;
	import com.pblabs.engine.PBE;
 
	public class HelloConsole extends Sprite
	{
		public function HelloConsole()
		{
			PBE.startup(this);
		}
	}
}

Once your game is running, to access the console press the default hot key, which is the Tilde (~) / Grave (`) key.

HelloConsole

As of this post, the latest revision of the PushButton Engine is revision 702. In this version there are some commands registered by default:

  • help – List known commands.
  • clear – Clears the console history.
  • listDisplayObjects – Outputs the display list.
  • showFps – Show an FPS/Memory usage indicator.
  • verbose – Set verbosity level of console output.
  • version – Echo PushButton Engine version information.

Quick Tricks

The console supports a few shortcuts to make your life easier:

  • The console is not case-sensitive, so don’t worry if you put showFps or shOwFPS, the same command will execute.
  • You can use the up and down arrows to move through your command history.
  • By pressing enter on an empty command line, you can add new lines. This is helpful for adding space between commands to make it easier to read.
  • You can use the “name” property on a DisplayObject to make meaningful names show up in the listDisplayObjects command.
  • Different Log Levels are colored by default, to change the colors edit com.pblabs.engine.debug.LogColor.

Creating custom commands for the console

The PBE console also supports the ability for the developer to add their own commands.

package
{
	import com.pblabs.engine.PBE;
	import com.pblabs.engine.debug.Console;
	import com.pblabs.engine.debug.Logger;
 
	import flash.display.Sprite;
 
	public class ConsoleCommand extends Sprite
	{
		public function ConsoleCommand()
		{
			PBE.startup(this);
			Console.registerCommand("test", onTestCommand, "This is a test command.");
			Console.registerCommand("testStrict", onTestStrict, "Test strict parameters.");
		}
 
		protected function onTestCommand(... args):void
		{
			Logger.print(this, "onTestCommand: "+args);
		}
 
		protected function onTestStrict(str:String, num:Number):void
		{
			Logger.print(this, "You passed in the string: "+str);
			Logger.print(this, "You passed in the number: "+num);
		}
	}
}

Parameters are passed in sequence using spaces. So to run the test command, I would open the console, and then type “test a b c 1 2 3″. This would then call the onTestCommand method and pass in an array with 6 elements.

Below is an example of what using custom commands in the console looks like.

ConsoleCommand

Changing the Console HotKey

Some of our good friends over in the Netherlands use different keyboard layouts, so they requested the ability to change the hot key binding to another key.

package
{
	import com.pblabs.engine.PBE;
	import com.pblabs.engine.core.InputKey;
	import com.pblabs.engine.debug.Console;
	import com.pblabs.engine.debug.Logger;
	import com.pblabs.engine.debug.UIAppender;
 
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
 
	public class TestConsole extends Sprite
	{
		public function TestConsole()
		{
			PBE.startup(this);
 
			UIAppender.hotKey = InputKey.C.keyCode;
			Console.registerCommand("test", onTestCommand, "My test command");
		}
 
		protected function onTestCommand(... args):void
		{
			Logger.print(this, "onTestCommand: "+args);
		}
	}
}

WARNING!!! When changing the hot key to another key, the input textfield doesn’t escape the new key binding. So you must remove focus from the input field to use the hot key to close the console.

More information on this can be found in issue 98.

What’s coming?

I do have plans on adding either tab-complete or a drop-down auto complete list into the console which will match avaliable commands.

Another thing that I’m currently working on is code-named Tumbler. It’s and Adobe AIR version of the console which has additional features to assist in debugging and troubleshooting your games.

It’s a proof-of-concept at the moment… but if there is enough interest in it… I may spend more time on it.

Tip of the Day – Quick and inexpensive design work

Using Amazon’s Mechanical Turk in combination with outsourcing your design task to Elance, you can get great designs and user feedback very quickly, easily and for very little money.

Step 1: Post your job “design a logo” on Elance (elance.com). Be sure to include instructions including other designs that inspire you and a description of your product vision and intended audience.

Step 2: After selecting a designer, ask them to create 3 to 5 draft design mocks

Step 3: Using mechanical turk (mturk.com), submit each design option to mechanical turk as a survey (e.g. “which design do you like best”). You can choose any number of people to answer your survey. Estimated cost: 100 people at $0.10 each = $10

Step 4: Review results.

I’ve found that using this technique that for about $10 I can get around 100 people to tell me which design they prefer and offer suggestions. Also, I usually ask for the age, country and background of the participant so I can filter down to an audience that matches my purposes.


This tip was provided by Joe H. Excellent tip Joe!

Tip of the Day – Using interactive assets from Flash in Flex

So for the most part… up to this point I haven’t really needed to use extensive Flash animations within Flex. I mean like most people, I’ve embedded swf assets into my Flex application by using the [Embed] metadata tag. However, using the Embed metadata tag, in my opinion, is for static assets or simple animations… you know… images, animation only swfs, fonts, etc…

Today I found a cool button that I wanted to use in my Flex application.

The button (roll your mouse over me):

Get Adobe Flash player

The thing about this button is that it has complex roll over and roll out animations. Of course we could create the same thing within Flex using an ActionScript tween class… but some things are better left to the Flash timeline.

So how do we get our button into Flex, with all of its animation and interactivity intact? The answer, my friends, is to use Adobe’s Flex Component Kit.

Doing some research online, it’s not really clear where to get it, or how to use it. According to labs, it’s released within Flex 3… but I don’t have a clue where. So we’re going to do this my way…

Step 1 : Install Adobe Extension Manager 2.1

Obviously, you can skip this step if you already have Extension Manager 2.1 installed.

If you didn’t install the Adobe Extension Manager when you installed your copy of CS4, you can download it here —> Download Adobe Extension Manager

If you already had Adobe Extension Manager installed… just be sure it has been updated to version 2.1.

Download and open up Setup.app
installfck_01

Click Next
installfck_02

Let it run
installfck_03

You’re welcome Adobe
installfck_05

Extension Manager > About Extension Manager
installfck_06

Says 2.1… cool, we’re ready to move on to step 2.

Step 2 : Install the Flex Component Kit

Now we need to go download the extension —> Download the Flex Component Kit (you need an adobe.com account)

All the way at the bottom you’ll find the extension we’re looking for… Flex Component Kit for Flash CS3 Professional (I know it says CS3 and we’re working in CS4, don’t worry)
installfck_07

Once downloaded, unzip and double-click FlexComponentKit.mxp
installfck_08

Read this whole agreement and only if you agree the terms click “Accept”
installfck_09
…how many of you read that?

Okay, you should see this now.
installfck_10

Documentation for this component can be found here —> FCK Docs

Onward!

Step 3 : The Flash Side

Let’s take our button and load it into Flash. We’re going to name it “MyButton”.
fck_part2_01

Create an AS3 class to handle all of the button interactions we need
fck_part2_02

package {
	// MyButton
	import mx.flash.UIMovieClip;
	import flash.events.MouseEvent;
 
	public class MyButton extends UIMovieClip
	{
		public function MyButton()
		{
			super();
 
			buttonMode = true;
			useHandCursor = true;
 
			addEventListener(MouseEvent.MOUSE_OVER, onOver);
			addEventListener(MouseEvent.MOUSE_OUT, onOut);
		}
 
		public function onOver(event:MouseEvent):void
		{
			gotoAndPlay(1);
		}
 
		public function onOut(event:MouseEvent):void
		{
			gotoAndPlay("end");
		}
 
	}
}

Make sure you have MyButton selected in the Library, and then use Commands > Convert Symbol to Flex Component.
fck_part2_03

Your output panel will let you know the command worked properly.
fck_part2_04

Test the movie by pressing ⌘ + enter (ctrl + enter on the PC).
fck_part2_05

Publish the movie, which creates both a SWF and a SWC file.
fck_part2_06

Now that we have our SWC file, we’re ready to move into Flex Builder.

Step 4 : The Flex Side

Copy our newly create SWC file into our libs directory.
fck_part2_07

With the SWC in our libs directory, it will automatically be included in the classpath of our Flex application (see this tip for more information on the libs directory).

The SWC file includes the MyButton class, so we can now write our code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
	xmlns:local="*" 
	layout="absolute" backgroundColor="0x000000" backgroundGradientAlphas="[0,0]" 
	creationComplete="onReady()">
	<mx:Script>
		<![CDATA[
			private function onReady():void
			{
				// How to use the custom button in ActionScript 
				/*
				var button:MyButton = new MyButton();
				button.x = 35;
				button.y = -10;
 
				addChild(button);
				*/
 
				// And just for fun				
				makeGrid();
			}
 
			private function makeGrid():void
			{
				var pad:int = 35;
				var gridWidth:int = 10;
				var gridHeight:int = 10;
				var yOffset:int = -45;
				var xOffset:int = -25;
 
				for(var h:int=1; h<=gridHeight; h++) {
					for(var w:int=1; w<=gridWidth; w++) {
						var button:MyButton = new MyButton();
						button.x = w*pad+xOffset;
						button.y = h*pad+yOffset;
						myPanel.addChild(button);
					}
				}
 
			}
		]]>
	</mx:Script>
	<mx:Panel id="myPanel"
		layout="absolute" left="10" right="10" top="10" bottom="10" 
		backgroundColor="#1D1D1D" title="Hey look, I'm a Flex Panel"/>
 
	<!-- How to use the custom button in MXML -->
	<!--<local:MyButton x="-5" y="-10" />-->
</mx:Application>

And here’s what it looks like:

Get Adobe Flash player

Weeeeee…. that’s fun, you can download the source here.

The source there is an Archived Flex project, all you need to do is Import it into Flex Builder and you’re good to go.

That was a long tip, any questions please post them.