Ternary / Conditional Operator in Actionscript 3

Like in many programming languages, Actionscript 3 allows for use of the ternary operator ?:

Let’s take a normal if statement as an example:

if( score == 10)
{
    win = true;
}
else
{
    win = false;   
}

This could be written in a different way using the ternary operator:

win = (score == 10) ? true : false;

So the syntax is: Expression ? statement : statement

If the expression is true, the value of the first statement is returned. Otherwise the value of the 2nd statement is returned.

Use the ternary operator judiciously. I’d recommend using it only with simple expressions and avoid nesting. This can make code very difficult to read!

Although I don’t like nesting, I think that chaining is not too bad if used to make the code easier to read. Here is an example of how the ternary operator can be used to make the code less noisy and more compact:

x = (height < 100) ? "Short" :
    (height < 200) ? "Average" :
    (height < 300) ? "Tall" :
    (height < 400) ? "Giant";
   
// The above is equivalent to the following if/else chain

if (height < 100)
{
    x = "Short";
}
else if (height < 200)
{
    x = "Average";
}
else if (height < 300)
{
    x = "Tall";
}
else
{
    x = "Giant";
}

To be fair, I could have written each of those if/else statements on one line each, but I still feel like the ternary version is cleaner. Of course, it is completely up to you where and when you use it. Enjoy!

Bring to Front Function

This one has been covered a million times on other sites but I thought I’d include it here anyway.

To move a MovieClip or other DisplayObject to the front of the stack, you can use the following function:

public function front(asset:DisplayObject):void
{
    asset.parent.setChildIndex(asset,asset.parent.numChildren - 1);
}

// usage:
front(myMovieClip);
front(someTextField);

DisplayObject is used since anything that would be added to the display list (added to the stage) is a DisplayObject at its core. I’ve seen this function all over the web in different forms; quite often they only accept MovieClips or even use the * wildcard. This function will universally work with MovieClips, Textfields or any other display object you want to throw at it.

Add Mask to Display List when using StageScaleMode.SHOW_ALL

I spent a few hours going nuts with this one today, so save yourself some time by reading this post. Suppose that you have some content that you want to scale when the flash player is re-sized. Suppose also that you have added this line in order to accomplish it:

stage.scaleMode = StageScaleMode.SHOW_ALL;

Now imagine that you test that program and are stretching the window around. Everything seems to be working great, except that there are some items that you have used masks on and the mask is floating around all over the place!

There is a VERY simple fix for this. In AS3 projects you MUST add the mask itself to the display list, or it will NOT scale with your project.

So, for example:

var myMask:Sprite = new Sprite();
myMask.graphics.beginFill(0x0000FF);
myMask.graphics.drawRect(0,0,100,200);
myMask.graphics.endFill();

// YOU MUST FIRST ADD IT TO THE DISPLAY LIST OR IT WILL NOT SCALE WITH THE CONTENT!!!
addChild(myMask);
myContent.mask = myMask

I figured this out by just trying it on a hunch. I’m guessing that by adding it to the display list it has something to reference for what size it is ‘supposed’ to be. When you simple add a mask to a display object’s mask property, it does not make it a child of that object automatically; therefore it does not scale with it. Weird if you ask me, but there it is. I hope this helps!

How to Remove Spaces from a String

Removing spaces from a string is really easy in Actionscript 3. One method is to simply convert the string to an array using the String.split() function using a space as the delimiter. Then you can use the Array.join function to put it all back together again without the spaces.

Here is a simple function that will do the trick:

public function removeSpaces(input:String):String
{
    var split:Array = input.split(" ");
    var output:String = split.join("");
    return output;
}

That’s it!

example:

trace(removeSpaces("ABCD EFG HI    JKLMNOP QRSTU      VWXYZ"));
// outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ

A Simple Pause Function in Actionscript 3

Just a quick function that you can use in your library of tricks to simulate pausing in Actionscript 3.

public static function pause(timeInSeconds:int, functionToCall:Function):void {
    var timer:Timer = new Timer(timeInSeconds * 1000);
    timer.addEventListener(TimerEvent.TIMER, callFunction, false, 0, true);
    timer.start();
    function callFunction(event:TimerEvent):void {
        timer.stop();
        timer.removeEventListener(TimerEvent.TIMER, callFunction);
        timer = null;
        functionToCall();              
    }
}

The function takes 2 arguments:

timeInSeconds – how many seconds to wait before calling the function
functionToCall – the function to call after the given time has passed

example usage (assuming that you drop this function into a class called Utilities:

private function gameWinTriggered():void{
 
     // player just dropped the last piece on the game board,
     // but we want to wait a second before showing the win screen
   
    Utilities.pause(1,showWinScreen);
}

private function showWinScreen):void{
     trace('You Win!');
}

That’s all there is to it. Really handy for instances like these when you want to wait before a transition as to not jar the player with instant changes.