Archive for the ‘AS3’ Category

The OR ( || ) operator in AS3

Tuesday, September 21st, 2010

Here’s a quick tip: the OR operator ( || ) in AS3 does not return true if either condition evaluates to true; it returns the actual value of the first condition to evaluate to true.

What does that mean? Lets try an example:
This statement:

trace ( "foo" || "bar" );

will trace out the string “foo”, not “true” (in an if statement “foo” will evaluate to true).

This statement:

trace ( undefined || false || "bar" );

will trace out the string “bar”.

If no condition evaluates to true, it will return the last condition.

trace ( false || undefined || 0 || "" || NaN || null );

will trace out “null”.

This can be really handy when making sure variables are not uninitialized before using them.
Check out this example:

function doSomething(arr:Array, data:Object, path:String):void {
    this.args = arr || [];
    this.dataObject = data || {};
    this.dataUrl = path || "http://default.url";
}

And even sexier (thanks MonkeyMagiic):

this.args ||= [];

Re-dispatch an event

Monday, July 19th, 2010

I just stumbled upon a sexy and simple way to forward an Event that I wanted to share with you:

myEventDispatcher.addEventListener("someEvent", dispatchEvent);

AS3 “with” keyword and casting

Monday, July 12th, 2010

I’ve rarely (if ever) used the “with” keyword in as3, but I recently found a neat trick to use it with.

When I quickly need to cast an object to access a few methods/properties I don’t always want to
create a new casted variable:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	var childAsMc:MovieClip = child as MovieClip;
	trace(childAsMc.numChildren);
	trace(childAsMc.currentFrame);
}

or cast it every single time:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	trace((child as MovieClip).numChildren);
	trace((child as MovieClip).currentFrame);
}

Using the “with” keyword, we can temporarily cast it without creating a temporary casted variable or casting it again and again:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	with (child as MovieClip) {
		trace(numChildren);
		trace(currentFrame);
	}
}

Elegant =)

Global error handling with Flash Player 10.1

Wednesday, June 23rd, 2010

Since the official release of Flash Player 10.1 is out, now might be a good time to start implementing the global error handler.

When this is written, flash builder 4 doesn’t have a native way that lets you use it, so we have to do a little mix. (Update: The update is out.)
The global error handler works by adding an event to the uncaughtErrorEvents property of the loaderInfo of the application.
There are currently two methods of getting it to work.

Method 1 – The backwards compatible one:

Here the code doesn’t crash in flash player 9/10, but the error handling will only work in 10.1.

if(loaderInfo.hasOwnProperty("uncaughtErrorEvents")){
	IEventDispatcher(loaderInfo["uncaughtErrorEvents"]) .addEventListener("uncaughtError", uncaughtErrorHandler);
}
private function uncaughtErrorHandler(e:Event):void {
	trace("Global error:", e);
}

Method 2 – The type safe one:

Get the Flex 4.1 SDK if you haven’t already and choose that one as your project’s SDK.

Now you can use the new global error handling like it was meant to be used:

import flash.events.UncaughtErrorEvent;

loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);

private function uncaughtErrorHandler( e:UncaughtErrorEvent):void {
	trace("Global error:", e);
}

Color.setTint() alternative (AS3)

Monday, February 1st, 2010

I once discovered a really cool feature of the color class that lets you set the tint of an object via its color transform object using the setTint function.
The bad news though is that the Color class is in the fl namespace, so if you’re developing outside of the Flash IDE you have no access to that class natively, so here is how to replicate that functionality without the Color class:

Tinting with the color class:

import fl.motion.Color;
// Tint the movie clip 50% with the color 0xFF9933
var c:Color = new Color();
c.setTint(0xFF9933, 0.5);
myMovieClip.transform.colorTransform = c;

Tinting without the color class:

import flash.geom.ColorTransform;

// Tint the movie clip 50% with the color 0xFF9933
var tintColor:uint = 0xFF9933;
var tintMultiplier:Number = 0.5;
setTint(myMovieClip, tintColor, tintMultiplier);

function setTint(displayObject:DisplayObject, tintColor:uint, tintMultiplier:Number):void {
	var colTransform:ColorTransform = new ColorTransform();
	colTransform.redMultiplier = colTransform.greenMultiplier = colTransform.blueMultiplier = 1-tintMultiplier;
	colTransform.redOffset = Math.round(((tintColor & 0xFF0000) >> 16) * tintMultiplier);
	colTransform.greenOffset = Math.round(((tintColor & 0x00FF00) >> 8) * tintMultiplier);
	colTransform.blueOffset = Math.round(((tintColor & 0x0000FF)) * tintMultiplier);
	displayObject.transform.colorTransform = colTransform;
}

Pie mask in AS3

Friday, November 13th, 2009

Sometimes I have the need for a rotational progress bar that acts like a pie growing bigger (or smaller if that strikes your fancy). As usual, I made my own =)
The function drawPieMask takes first the graphics object of the displayObject instance and draws a part of pie on it, percentage set’s how big the part is.
If you want to offset the rotation of the pie (it starts to the right by default) you can set the rotation parameter. Note that rotation is in radians, not degrees, but you can multiply your degrees by (Math.PI/180) to convert to radians.
Lastly, the sides property determines how many sides the circle drawn in the mask has. You can see an example of different pie masks after the code.

To make the code as customizable as possible, it does not make a call to beginFill in case you want to set your own fill (or gradientfill even?).
If you just want to use it as a basic mask, just call beginFill(0) before and endFill() after the call to drawPieMask.

function drawPieMask(graphics:Graphics, percentage:Number, radius:Number = 50, x:Number = 0, y:Number = 0, rotation:Number = 0, sides:int = 6):void {
	// graphics should have its beginFill function already called by now
	graphics.moveTo(x, y);
	if (sides < 3) sides = 3; // 3 sides minimum
	// Increase the length of the radius to cover the whole target
	radius /= Math.cos(1/sides * Math.PI);
	// Shortcut function
	var lineToRadians:Function = function(rads:Number):void {
		graphics.lineTo(Math.cos(rads) * radius + x, Math.sin(rads) * radius + y);
	};
	// Find how many sides we have to draw
	var sidesToDraw:int = Math.floor(percentage * sides);
	for (var i:int = 0; i <= sidesToDraw; i++)
		lineToRadians((i / sides) * (Math.PI * 2) + rotation);
	// Draw the last fractioned side
	if (percentage * sides != sidesToDraw)
		lineToRadians(percentage * (Math.PI * 2) + rotation);
}

Example of different sides values. The last circle has a pie with 3 sides as a mask.

Get Adobe Flash player

You can get the example fla here.

Profiling AS3/Flex applications

Tuesday, October 6th, 2009

I’m working on a big project and was having some problems with memory leaks. After some google-ing around I found this great video on AdobeTV by Jun Heider where he shows you how to profile both the memory and performance of your AS3 or Flex application.
It’s pretty thorough and it is little over one hour in length.

Number Format – Thousand Separator in AS3

Wednesday, August 12th, 2009

Here’s a short number format function I wrote to easily paste in your code when needed. It’s really handy for currency formatting.
The first parameter (number:*) can be a Number, int, uint or a String class instance.
The last parameter (siStyle:Boolean) specifies whether to use the International System of Units or not. SI units have points between the thousands and a comma for the seperator (123.456.789,01). Putting siStyle as false reverses that behaviour (123,456,789.01).

It’s really ugly by design since I wanted it to be a single, tiny function. There’s loads of prettier/faster code samples out there.

function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = false):String {
    var i:int = 0, inc:Number = Math.pow(10, maxDecimals), str:String = String(Math.round(inc * Number(number))/inc);
    var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    if (forceDecimals) for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
    while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    return str.substr(0, sep - i) + ret;
}

Load font dynamically on runtime

Wednesday, May 6th, 2009

Sometimes you want to be able to keep your fonts in a seperate swf file, a “font library” if you will, that you can load dynamically on runtime. Here’s how to do that in AS3:

The first thing you have to do is create a new flash file to store the font(s). Then, right click the library and select “New Font…”.
newfont

Choose the font you want to embed and give it a name. Any name will do here, as this is only the library name and will not affect our code in any way. I prefer to name the font with the same name as the linkage name I plan to give it.
myfont

Click ok, and then right click the font in the library and select “Linkage…”. Check the “Export for ActionScript” and “Export in first frame” options, give your font the linkage name of your own liking and click OK.
linkage

And now you’re ready. Export the file to swf and there’s your font resource file.

If you want to use that font, you first have to load it into the application domain, and then register it on the global font list using the Font.registerFont function. The textfield can’t display it until it has the embedFonts property set to true and the font name in its textformat.
You can see an example in the following code, ready to be pasted into your frame:

var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
l.load(new URLRequest("MyFont.swf"), new LoaderContext(false, ApplicationDomain.currentDomain));

function onLoaded(e:Event):void {
	// Register the font to the global font list
	Font.registerFont( Class( ApplicationDomain.currentDomain.getDefinition("MyFont")));
	
	myTextField.embedFonts = true;
	// instantiate the font just to get the real font name, or if you know the name before hand you can just hard-code it in here
	var fontName:String = new (ApplicationDomain.currentDomain.getDefinition("MyFont"))().fontName;
	var tf:TextFormat = new TextFormat(fontName);
	// Set the text format for the text already in the text field
	myTextField.setTextFormat(tf);
	// and for future changes
	myTextField.defaultTextFormat = tf;
}

Line-Line Intersection in AS3

Tuesday, April 28th, 2009

Line line intersection function explanation

I found a bug in my old Line-Line Intersection in C++ post, and after I fixed it I thought it would be a good idea to port it to AS3:

function intersection(p1:Point, p2:Point, p3:Point, p4:Point):Point {
    var x1:Number = p1.x, x2:Number = p2.x, x3:Number = p3.x, x4:Number = p4.x;
    var y1:Number = p1.y, y2:Number = p2.y, y3:Number = p3.y, y4:Number = p4.y;
	var z1:Number= (x1 -x2), z2:Number = (x3 - x4), z3:Number = (y1 - y2), z4:Number = (y3 - y4);
    var d:Number = z1 * z4 - z3 * z2;
	
    // If d is zero, there is no intersection
    if (d == 0) return null;

	// Get the x and y
    var pre:Number = (x1*y2 - y1*x2), post:Number = (x3*y4 - y3*x4);
    var x:Number = ( pre * z2 - z1 * post ) / d;
    var y:Number = ( pre * z4 - z3 * post ) / d;
    
    // Check if the x and y coordinates are within both lines
    if ( x < Math.min(x1, x2) || x > Math.max(x1, x2) ||
        x < Math.min(x3, x4) || x > Math.max(x3, x4) ) return null;
    if ( y < Math.min(y1, y2) || y > Math.max(y1, y2) ||
        y < Math.min(y3, y4) || y > Math.max(y3, y4) ) return null;
 
    // Return the point of intersection
    return new Point(x, y);
}

You can try it here:

Get Adobe Flash player