Posts Tagged ‘as3’

Optimizing Animations

Posted in Actionscript 3, Animation, Article, Experiments, Flex on December 11th, 2010 by Ian Ford – Be the first to comment

I was working recently on a project that called for a certain special effect. Perhaps you’re all familiar with the classic page curl?

There’s an excellent tutorial available for free online at O’Reilly. I followed it in a misguided attempt to create my own page curl in AS3. Unfortunately, AS3 seems to have some trouble rendering complex masking effects correctly, and I was unwilling to drop the project to AS2 to accommodate one pushy art director so we needed another option.

The art director suggested we do the animation manually in InDesign and export a series of still frames that we could use in Flash. It sounded simple enough, so we produced a 50 frame sequence to use for our page curl.

Looks nice, right? Well, we can do better. How? We don’t need to use every frame! We certainly can’t expect visitors to this site to download all 50 frames, especially since there are 4 images total that will need to page flip. But how many frames should we use, and which ones?

Because the art director on this was picky, and because I have no interest in the publish->phone call->debate->repeat cycle, I decided to dump responsibility in his hands in the most explicit way possible: I wrote an app that would let him pick all the parameters for the animation.

What the application does is present every frame available to the animation in the left column. When an item in the list is selected, a preview loads in the top left frame.

The right column shows every frame currently being used in the animation. Users can drag frames from the left column to the right column and back, and a preview animation is updated and played in the top right frame. The speed of the animation can be adjusted by a multiplier of the frame rate of the anticipated swf using a numeric stepper below the animation.

Every frame is numbered and automatically sorted based on its index so that the user doesn’t accidentally produce something worthless.

As I write this I’m waiting to be told which frames to use and how long to display them. I’m not sure how long it will take to get a response, but I know in the time between now and then what I won’t be working on. :)

Try out the Animation Optimizer or Download the Project File

What is an API?

Posted in API, Article on October 28th, 2010 by Ian Ford – Be the first to comment

A while back I sent a video around the office (this one about Molehill) and received a confused response from a coworker:

You might think I’m completely stupid, but what is an API?  I was at the Flash in the Can Conference a few months ago and have been hearing that term ever since.  I assume it’s an AS3 thing?

I explained it as follows:

API means Application Programming Interface. It basically refers to a set of procedures and protocols for getting things done. For example, you could say that things like waving hello, handshakes, speech, and meetings are part of a human communication API. When we talk about new APIs, we mean that either the set of things we can do in a specific sphere has expanded or become more powerful. If you can imagine people who are only able to do things like wave and shake hands, an API upgrade might then allow them to truly speak, or maybe shake hands more vigorously.

It’s often challenging to explain things like this to non-programmers, but this seemed like a very useful metaphor to me. Would you agree?

YouTube AS3 Updated

Posted in Announcements, API, Article, Documentation, Flash, YouTube on October 3rd, 2010 by Ian Ford – Be the first to comment

I’ve updated the YouTube AS3 wrapper classes to include full ASDoc style documentation. Check out the project page for the latest files.

What I’ve been studying

Posted in Article, MultiCore, Pipes, PureMVC on September 28th, 2010 by Ian Ford – Be the first to comment

Lately I’ve been familiarizing myself with the MultiCore edition of PureMVC in the hopes of doing some larger, more modular applications. I decided my first MultiCore project (my learning project, as it were) would be a very large application I was tasked with developing at work. Furthermore, I decided that the best way to handle communication among the various cores of my application would be to use the heavily promoted pipes utility available alongside the MultiCore class files.

The application is largely built (I’ll let you know when it goes live), and I have some comments to make regarding the use of both the MultiCore edition of PureMVC and the pipes utility.

  • The MultiCore edition of PureMVC is very easy to use in place of the Standard edition. In fact, whether you intend to have multiple cores or not, you may as well just use the MultiCore edition. It contains all the functionality of the Standard edition.
  • Attention to naming conventions is key when working with multiple cores. Your file system in a medium sized application will become intimidating and unnavigable faster than you think if you don’t make especially sure to distinguish one module from another.
  • It is equally important to pay attention to the values of your notification/message constants.
  • Though the pipes utility touts its ability to easily be added on top of an existing project, this is only half true.

I should elaborate on the final bullet above. While it was relatively easy to allow the core of my application to send messages to modules, it was not quite as simple getting modules to correctly communicate back to the core. I encountered Pipe errors for which, as far as I could tell at the time, there was no obvious reference.

If you find yourself working with PureMVC MultiCore and the pipes utility, you might consider some of the following references, which I found useful while developing my application:

  1. Understanding PureMVC Pipes by Joshua Ostrom: This tutorial is referenced everywhere as a good starting point for understanding the pipes utility with regards to PureMVC MultiCore. There are some good conceptual diagrams here and a few meager code samples.
  2. A basic PureMVC MultiCore AS3 example using Pipes Utility and Modules by Jens Krause: The “HelloPipes” project files provided here were essential to helping me understand where to place my pipes code and how to structure it. This was really instrumental.
  3. Unit Tests – AS3/Pipes at PureMVC.org: The unit tests were recommended in most forums I visited. There are plenty of real-use code samples here to get you started.
  4. Pipes API Documentation: Anytime I work with new code I always start with the API Docs. There’s no better way to familiarize yourself with the code you’ll be using as you try to learn something new.

Hopefully these resources will help you as well. I look forward to showing off the finished project once it’s ready to go live.

Tutorial: Dynamic Superscripts

Posted in Actionscript 3, Article, Best Practices, Tutorial, Typography on April 28th, 2010 by Ian Ford – 3 Comments

EDIT: Apparently the site that was hosting the GG Fonts is down. I’m not sure when it’s coming back. Until then, you’ll have to find the appropriate fonts for this tutorial elsewhere.

Yesterday, as has happened many times before, I ran into a serious problem working with text in Flash: correctly rendering superscripted characters in a dynamic text field. This has been a problem in Flash for some time. Adobe seems to have no interest in fixing it, so the community has come up with a solution of its own. I repeat that solution for you here in as much detail as I have patience for.

Step 1: Download Special Fonts

The preferred method for addressing this problem involves html text, font tags, and a couple of special fonts designed to resemble superscripted characters without actually being superscripts. Personally, I have always used GG Superscript and GG Subscript, provided by the wonderful author of GG’s Flash Blog, who also wrote the first tutorial I ever saw on this issue. Apparently GG has offered up several other fonts that expand on the capabilities of the originals, and those can be found here. I can’t comment on this second set as I haven’t used them personally, but I see no reason to assume they don’t work just the same as the original set. For the purposes of this tutorial, I’ll be assuming you proceeded with GG Superscript.

Step 2: Embed Your Fonts

In order for this method to work, you have to make sure that your superscripted font is embedded. This is easy enough to do. Start by creating a new text field, and set the font for this text field to your superscripted font of choice.

Then, click on the “Character Embedding…” button, and embed the elements of the font that you’ll be using. You can either broadly embed a large range of characters…


…or you can cut it to the specific characters you’ll be needing (better idea). I typically find myself embedding the registered symbol, the copyright symbol, and the trademark symbol.

Finally, since you won’t actually be rendering text here, just move this text field off stage. We’re just using it to guarantee that our fonts are embedded and available.

Step 3: Create Your Text Field

For the sake of argument we’ll be doing this in Flash. The code for doing so looks like this…


var field:TextField = new TextField();
addChild(field);

field.multiline = true;
field.htmlText = "This copy is registered®, copyrighted©, and trademarked™";
field.width = field.textWidth+5;
field.height = field.textHeight+5;

field.x = (stage.stageWidth-field.width)/2;
field.y = (stage.stageHeight-field.height)/2;

…and the result looks like this:

The trademark symbol even looks alright without getting into the next steps, but we’ll carry through all the same so you can see the difference.

Step 4: Add Font Tags

There are two ways you can proceed from here, depending on the scope of your project and how complicated your needs are.

If you’re not working with a large amount of copy, or if you need to be very precise about how text is rendered, it may be in your best interests to hard code all of your font tags.

Using the sample from above, your new code would look like this:


var field:TextField = new TextField();
addChild(field);

field.multiline = true;
field.htmlText = "This copy is registered<font face='GG Superscript'>®</font>, copyrighted<font face='GG Superscript'>©</font>, and trademarked<font face='GG Superscript'>™</font>";
field.width = field.textWidth+5;
field.height = field.textHeight+5;

field.x = (stage.stageWidth-field.width)/2;
field.y = (stage.stageHeight-field.height)/2;

This isn’t very glamorous, but it works. The downside to this is that if you have a large number of special characters that need the super treatment, you’ll have to pick through all of your text and wrap every symbol in a font tag.There is another way that’s quite a bit more fun.

If you have a larger quantity of text you need to take care of and you’re less concerned about small level details, you can do something like this…


var reSuper:RegExp = /(\®|\©|\™)/g;
var str:String = "This copy is registered®, copyrighted©, and trademarked™";

var field:TextField = new TextField();
addChild(field);

field.multiline = true;
field.htmlText = str.replace(reSuper, "<font face='GG Superscript'>$1</font>");
field.width = field.textWidth+5;
field.height = field.textHeight+5;

field.x = (stage.stageWidth-field.width)/2;
field.y = (stage.stageHeight-field.height)/2;

I prefer this method, mostly because I love any excuse to use Regular Expressions. The benefit to using this method is that you don’t have to worry about adding, removing, or maintaining font tags in the copy you’re putting in. You could also theoretically apply this method to other characters (numbered references anyone?), or use it to apply other styles to your text rather than just changing fonts (italics, bold, etc.). Pretty sweet huh?

Regardless of which method you use, you’ll get the following when you compile:

In case the difference isn’t obvious, check out the comparison below. The first line of text is the original text. The second line is the text after our pseudo-superscript has been applied.

Step 5: Celebrate

Your superscripts now work. Why not have a beer? Something good.

Gesture Recognition

Posted in Article, Gesture Recognition, Links, Tips, User Experience on March 11th, 2010 by Ian Ford – Be the first to comment

Gesture Recognition

I’ve spent the last day or two reacquainting myself with what’s been done to achieve reliable gesture recognition in AS3. I have reviews of two different packages I tried, one of which is relatively new and one of which has been around for some time.

One note about all of the gesture recognition classes I’ve looked at is that they are direction-dependent. That is to say that if you’re attempting to capture the gesture corresponding to a vertical line, a stroke from top to bottom is not the same thing as a stroke from bottom to top. Furthermore, neither of those will necessarily be captured in a stroke from top to bottom to top. This all has to do with the algorithms being employed to detect gestures and attempts to make them run as efficiently as possible.

The first package I looked at was offered up by a Mr. Felix at bertiesbraum.de. Felix’s gesture recognizer consists of AS3 implementations of the “$1 Gesture Recognizer” and “ShortStraw Corner Finder” algorithms, which he has the decency to cite and link to (unlike me).

His post does a much better job of explaining basic usage of the classes than I care to at the moment, but what I will say is that I was unable to get the classes to function without false positives. This is likely because, as Felix notes, “The gestures are also rotation, position and scale invariant,” which is to say that a single stroke probably ends up being a single stroke, regardless of which direction it points. With more complex figures I was able, in the sample application Felix provides, to demonstrate direction dependence. In my case I’m trying to detect single strokes in distinct directions, and so it may be that these algorithms are over-engineered for my purposes.

The second package I looked into was posted in a short article at ByteArray.org by Didier Brun. I caught this post when it first came out (almost three years ago) and was very impressed with the concept but didn’t have any real use for it at the time. I toyed with it today and have been pleased with the results.

Initially Mr. Brun’s classes posed the same problem that most gesture recognition algorithms do: it was unable to recognize identical patterns if they proceeded in different directions. Additionally, all of the packages I’ve seen presume that the user will begin their gesture by pressing the mouse button down, and end the gesture by releasing it. I’m trying to detect whether or  not a user is shaking an object they’ve picked up in an up-and-down fashion, so it’s important to me to recognize sub-gestures within a larger “gesture.” If I depend solely on button presses and releases, the gesture that ends up being analyzed consists of tens of motions at the least.

I came up with a solution using Mr. Brun’s classes that allowed me to achieve my ends. Brun’s gesture recognition class offers a custom event that fires when capture begins and ends, when a match is made or not made, and while capture is taking place. The last of those was most important to me. I added a public property to his existing GestureEvent class. The modified class looks like this:

package com.foxaweb.ui.gesture {

	import flash.events.Event;

	public class GestureEvent extends Event {

		// ------------------------------------------------
		//
		// ---o static
		//
		// ------------------------------------------------

		public static const START_CAPTURE:String="startCapture";
		public static const STOP_CAPTURE:String="stopCapture";
		public static const CAPTURING:String="capturing";
		public static const GESTURE_MATCH:String="gestureMatch";
		public static const NO_MATCH:String="noMatch";

		// ------------------------------------------------
		//
		// ---o properties
		//
		// ------------------------------------------------

		public var datas:*;
		public var fiability:uint;
		public var moves:String;

		// ------------------------------------------------
		//
		// ---o constructor
		//
		// ------------------------------------------------

		public function GestureEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false){
			super (type,bubbles,cancelable);
		}

		// ------------------------------------------------
		//
		// ---o methods
		//
		// ------------------------------------------------

		public override function clone():Event{
			return new GestureEvent(type, bubbles, cancelable) as Event;
		}

	}
}

I also made a change to the MouseGesture class to make sure that “moves” were being attached to GestureEvents dispatched during the “CAPTURING” phase. The modified function looks like this:

protected function captureHandler(e:TimerEvent):void{

	// calcul dif
	var msx:int=mouseZone.mouseX;
	var msy:int=mouseZone.mouseY;

	var difx:int=msx-lastPoint.x;
	var dify:int=msy-lastPoint.y;
	var sqDist:Number=difx*difx+dify*dify;
	var sqPrec:Number=DEFAULT_PRECISION*DEFAULT_PRECISION;

	if (sqDist>sqPrec){
		points.push(new Point(msx,msy));
		addMove(difx,dify);
		lastPoint.x=msx;
		lastPoint.y=msy;

		if (msx<rect.minx)rect.minx=msx;
		if (msx>rect.maxx)rect.maxx=msx;
		if (msy<rect.miny)rect.miny=msy;
		if (msy>rect.maxy)rect.maxy=msy;
	}
	// event
	var evt:GestureEvent = new GestureEvent(GestureEvent.CAPTURING);
	evt.moves = moves.join("");
	dispatchEvent(evt);

	//dispatchEvent (new GestureEvent(GestureEvent.CAPTURING));

}

The final step was to deal with the entire set of move data in my application. I configured my instance of the MouseGesture class to handle GestureEvent.CAPTURING events and created the following function to deal with them.

private function _captureHandler(e:GestureEvent):void {
	var reShake:RegExp = /(62|26)/g;
	var shakes:int = e.moves.match(reShake).length;
	field_shakes.text = "Number of Shakes: " + shakes;
	if (shakes >= 12) {
		stage.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
		field_shakes.text = "Congratulations!";
	}
	trace(e.moves);
}

The important thing to note here is the regular expression being used. The strings “62″ and “26″ correspond to the output that would be expected from a vertical shake gesture in the MouseGesture class (respectively “up->down” and “down->up”). What the function does is scan the entire list of movements and look for instances in which the patterns I’m trying to match have occurred in sequence. For each occurrence of either pairing, we know that the user has successfully “shaken” the can. A single call fired to the “_captureHandler” function might have a “moves” list that looks like this…

0666662255222666666222566222266222266672226666122561

…in which each digit corresponds to one of 8 possible directions the user moved his mouse. If you count carefully, you’ll find 8 instances of either the sequence “62″ or the sequence “26.”

Ultimately Mr. Brun’s class ended up being more useful for the project that I’m working on, but I hope to see other implementations in the future that will allow for more complex gestures to be recognized.

AS3 Developer? Android User?

Posted in API, Documentation, Flash, Flex, Mobile on January 27th, 2010 by Ian Ford – Be the first to comment

For those of you carrying Android phones that spend far too much time thinking about flash/flex development, I’ve found a very handy little app.

From the publisher’s website:

After seeing that someone wrote an ActionScript reference application for the iPhone called ActionScript 3 API Reference for iPhone, I decided to take matters into my own hands and make the same application for the Android platform which the t-mobile G1 works on.

Displaying YouTube Content in AS3

Posted in API, Downloads, Flash, Uncategorized on January 14th, 2010 by Ian Ford – 12 Comments

UPDATE: This content has been migrated to a permanent page of the blog. Please direct any comments or questions to the new page.

Recently, while working on my portfolio, I was presented with the problem of displaying YouTube content extracted from an RSS feed in Flash. On the one hand there was the difficulty of parsing embed and object tags and extracting relevant data from the mess I was given, and on the other hand there was the problem of displaying the content itself.

YouTube provides documentation for their api, but after digging around online I was surprised to find that nobody had gone through with packaging it in a format I was willing to work with. There is an ActionScript 3 YouTube Wrapper available online, but it presumes that the Chromeless YouTube Player (http://www.youtube.com/apiplayer?version=3) you download to play videos with will be accessed using a combination of the static ExternalInterface class and external JavaScripts.

This seems, to me, to be unnecessarily complicated.

I’ve gone through the trouble of picking through the API and creating a simple class that loads a chromeless player and exposes methods you can use to manipulate it and display content from YouTube, without requiring any external javascript.

The application above is written in Actionscript 3. Basic usage is as follows:

import com.agitcraft.youtube.YouTube;
import com.agitcraft.youtube.YouTubeEvent;
_tube = new YouTube();
_tube.cueURL("http://www.youtube.com/v/-CsA1CcA4Z8", 0);
addChildAt(_tube, 0);

Each of the methods made available in the official YouTube API is available in some form or another via this set of classes. When I have a little more time I’ll follow up with official documentation and availability via google code.

Download AS3 YouTube Classes

A Solution to the No-Design Cycle

Posted in API, Flash, Flex, Frameworks, Links, PureMVC on January 5th, 2010 by Ian Ford – Be the first to comment

For well over a year now, I’ve been engaged in the process of moving and redesigning my professional portfolio. The current (a term I use loosely…) version is over 3 years old, and it’s sitting at a domain I don’t really use anymore. I initially began work on a relaunch almost immediately after my portfolio landed me a permanent job, but over the years I’ve been indecisive, full of excuses, and just generally unable to commit to any planned redesign.

I’m sure you know the cycle: You come up with a great design concept, plan about 80% of it, and jump excitedly into development. You make rapid progress initially, but as you delve deeper into the project you come across roadblocks and development stalls. After hammering away for weeks at a time on bugs that seem to multiply faster than you can fix them, you eventually come to consider the project too flawed to complete and scrap it.

Where do these flaws come from? In my case the culprits are poor planning, over-ambitious development goals, and lack of a consistent process for developing large scale applications.

What I once considered the “Redesign Cycle,” I will now be calling the “No-Design Cycle,” as the use of the prefix “re-” vaguely implies that eventually some new design is produced and launched.

This post, however, is not just about my failure to produce a new portfolio in several years, or about my enthusiasm for the current draft I’m working on. It’s about what, thus far, is proving an effective solution to this terrible problem. It’s called PureMVC. Perhaps you’ve heard of it?

The claim made by proponents of PureMVC is that it allows you to program “at the speed of thought.” Outrageous, right? After picking the framework up several weeks ago and developing with it in the time since, I can mostly agree.

If you’d like to start working in PureMVC, you can download the AS3 port, check out the full API documentation, and follow the tutorial I used to get started learning the framework, courtesy of Ahmed Nuaman.

Marking Menus in AS3

Posted in Links on December 18th, 2009 by Ian Ford – Be the first to comment

I just read a great article explaining the use and implementation of marking menus in AS3. This may be just the kind of interface I’m looking for for my long overdue portfolio relaunch. Check it out!