logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Apr 28, 2012 Posted on Apr 28, 2012 in Hints and Tips | 10 comments

An ImpactJS Overview: Optimization

In this video I will discus some tips and tricks for optimizing your Impact games and how to get the best performance possible across desktop to mobile. I will cover ways to reduce draw calls, how to set up setting properties for your levels and other important things I have learned through trial and error while building games with Impact.


Watch the Screencast

You can also download the video to watch later.


More Info and Links

To learn more about Impact visit http://ImpactJS.com and check out a copy of my book on Impact called Introducing HTML5 Game Development, published by O’Reilly.



View full post on Activetuts+

banner ad

10 Responses to “An ImpactJS Overview: Optimization”

  1. Jesse Freeman says:
    April 28, 2012 at 5:44 pm

    In this video I will discus some tips and tricks for optimizing your Impact games and how to get the best performance possible across desktop to mobile. I will cover ways to reduce draw calls, how to set up setting properties for your levels and other important things I have learned through trial and error while building games with Impact.


    Watch the Screencast

    You can also download the video to watch later.


    More Info and Links

    To learn more about Impact visit http://ImpactJS.com and check out a copy of my book on Impact called Introducing HTML5 Game Development, published by O’Reilly.


  2. Dru Kepple says:
    April 28, 2012 at 6:34 pm

    Sublime Text 2 is a powerful text editor, popular due to its cross-platform availability and its knack for leveraging pre-existing TextMate capabilities. Combine Sublime Text 2 with Google’s new Dart language, and power coders can be very happy.


    Prerequisites

    In order for this to go quickly, I’ll assume that you have some foundational knowledge. You should be familiar with the following for this tip:

    • A working knowledge of Sublime Text 2 packages. Most of this tip centers on the steps required to build our own Dart package, but if you’ve never used a snippet before you might want to back up for a second and go learn more about Sublime Text first.
    • A working knowledge of Dart will also help. We won’t really be coding any Dart in this tip, but having a few Dart files around with which to test things will help greatly.
    • We’ll be checking code out of a Subversion repository, and while I’ll feed you the command to use, hopefully this isn’t your first time using Subversion.
    • Finally, a general knowledge of your particular OS is in order. We’ll need to do a small amount of configuration and if you’re comfortable, say, modifying a .bash_profile file via the Terminal, then you’ll be fine.

    If you need some prior reading material, I refer you to the following:

    • Sublime Text 2 documentation (however unofficial) is kept at sublimetext.info/docs. The pages on Packages, Syntax Definitions, and Snippets were particularly useful in the writing of this tip.
    • Dart information can be found at the official site, or by following along Activetuts’ Introduction to Dart tutorial
    • Much has been written about Subversion, not to mention a complete online book. That’s a bit more than you need, as you simply need to have Subversion installed and to checkout a single folder
    • Google will be your friend when it comes to learning more about configuring your system.

    Step 1: Install Dart Editor

    We won’t really be using the Dart Editor (the point of this tutorial is to use Sublime Text for Dart development, after al), but the download includes the Dart SDK, which is really what we’re after. Even if you’re a hardcore Sublime Text 2 fanatic, it’s still not a terrible idea to have the “official” Dart Editor installed and handy.

    On the official Dart site, you can download the Dart Editor from the following link:

    http://www.dartlang.org/docs/getting-started/editor/

    Under “Step 1″ of that page, you’ll find a link to a ZIP file containing the Dart Editors. It’s around 70-100 MB, depending on your OS, so it’s not a terribly heavy download. But get it started!

    The Dart Editor is based on Eclipse, so if you’ve used that you’ll be right at home with the Dart Editor. I won’t be getting into details on using it in this tutorial, but feel free to play around with it. The Activetuts+ introductory Dart tutorial (currently exclusively available through Facebook) takes you through the basic usage of the Dart Editor.

    Note that if you don’t want to install the Dart Editor, you can download just the Dark SDK for your OS at this URL (it’s only 2 or 3 MB):

    http://www.dartlang.org/docs/getting-started/sdk/index.html


    Step 2: If You Have 64-Bit Linux

    If you don’t have a 64-bit Linux installation, you can skip this step. (Yep, that includes you, Windows and Mac users; scroll down for your instructions.)

    If you are on a 64-bit Linux installation, you’ll need to install a 32-bit library in order to run the Dart compiler, even if you’ve downloaded the 64-bit Dart Editor. I’m not a Linux guru by any stretch, but this worked for me, on my Ubuntu 11 installation.

    Go to the Software Center and search for “lib32stdc++6″ or “GNU Standard C++ Library 32 bit”. Install it. You can continue on with the next few steps while it installs – just be sure this library has successfully installed before attempting to run the build system.

    Install this library if you're running 64-bit Linux

    Step 3: Download Google’s Dart TextMate Language File

    The TextMate language file is hosted on Google Code here (web-based view into the repository):

    http://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tools/utils/textmate/Dart.tmbundle/Syntaxes/Dart.tmLanguage

    This is actually part of a larger TextMate bundle (but not that much larger), but we’re only interested in the language grammar.

    Before we grab that file, create a location for it to live on your system. You’ll need to create a folder named Dart in the following location, depending on your OS:

    • Mac OS: ~/Library/Application Support/Sublime Text 2/Packages/Dart
    • Windows 7: C:\Users\Administrator\AppData\Roaming\Sublime Text 2\Packages\Dart
    • Linux: ~/.config/sublime-text-2/Packages/Dart

    Then open up your command line interface and navigate to inside of that newly-created Dart folder.

    Subversion doesn’t make it easy to checkout a single file, but we can export a single file. Enter this command:

    
    
    svn export http://dart.googlecode.com/svn/branches/bleeding_edge/dart/tools/utils/textmate/Dart.tmbundle/Syntaxes/Dart.tmLanguage
    

    After a moment you should have the Dart.tmLanguage file in your Dart folder.

    Go ahead and try it out (you may need to restart Sublime Text). Open up a Dart file and check out the colorful syntax:

    A simple Dart file in Sublime Text 2, showing off syntax highlighting
    A simple Dart file in Sublime Text 2, showing off syntax highlighting

    Step 4: Locate your frogc Executable

    frogc is the Dart-to-JavaScript compiler. It’s a command line tool, but it’s thankfully easy to use. We’ll be using it in a Sublime Build System later to turn our Dart file(s) into JavaScript, so we don’t even need to use it on the command line anyway.

    To make the Build System, we need the path to our frogc executable. This was downloaded with the Dart SDK (which you either downloaded with the Dart Editor or by itself). It will be located at dart-sdk/bin/frogc. “dart-sdk” will either be where you downloaded and unzipped the SDK by itself, or nested just inside the dart folder which also contains the Dart Editor application, which will be where you placed it.

    We need a command-line-compatible path to frogc. On Mac OS, you can do this:

    Open up a Terminal window and drag frogc into it. The window will contain the text of the path of the file you dropped.

    For Windows:

    Click in the address bar of the window. It should turn into a plain text path for the folder, which you can then copy. You’ll need to add “\frogc.bat” at the end to get the path to frogc, not just the bin folder.

    If you’re on Linux, you probably already know how to do this.

    Make sure the path is absolute, and readily available. Place it on your clipboard or in a scratch text file for the next step.


    Step 5: Create a Dart Build System to Compile JavaScript

    To make this language package really useful, we should set up a Build System, which lets us run files through a shell build command.

    In Sublime Text, choose the Tools > Build System > New Build System… menu. You’ll be presented with a new file with the following default contents:

    
    
    {
        "cmd": ["make"]
    }
    

    This is just a JSON object that describes a very basic build command. We’ll add much more to this to make it useful for Dart development.

    With that path you determined in the last step readily available, we can edit our sublime-build file.

    If you’re on Mac or Linux, change the contents of the file to:

    
    
    {
        "cmd": ["/Applications/dart/dart-sdk/bin/frogc", "$file"],
        "file_regex": "^(.+\\.dart):(\\d+):(\\d+):.+\\[0m(.+)$",
        "selector": "source.dart"
    }
    

    The above is what I have on my Mac system. Where it says /Applications/dart/dart-sdk/bin/frogc, add in your own frogc path.

    If you're on Windows, the file will look rather similar, but you should change the "cmd" line to:

    
    
    {
        "cmd": ["cmd", "/C", "C:\\insert path here\\frogc.bat", "$file"],
        "file_regex": "^(.+\\.dart):(\\d+):(\\d+):.+\\[0m(.+)$",
        "selector": "source.dart"
    }
    

    To briefly explain what this does, the cmd property is basically just what to run on the command line. frogc is simple to use: just invoke the command and feed it a file. The $file part of that line is a variable that gets expanded automatically to the page of the current file.

    On Windows, things are a little funkier by default (at least in this scenario; that's not a dig at Microsoft, I swear!). What we have will run the Windows command line (cmd) with the "don't keep the terminal window up" parameter (/C, though even the "keep the terminal window up" /K parameter doesn't show it either), and run frogc.bat, passing it the full file path. This is the quick way to get it working, but does seem to produce errors in the current build. This is probably a temporary problem, as at the time of this writing these errors are produced with the standard SDK and not the latest SDK. See the next step for an alternate route.

    The file_regex line is for error reporting purposes. If a line in the output of the command matches this regular expression pattern, it's recognized as an error and pressing F4 will highlight them for you in the output panel.

    Unfortunately frogc uses text-styling codes to make parts of the error message a different color and/or bold. When piped into Sublime Text, these style codes are presented as regular text, so the output can be a little hard to read, with [0m and similar codes peppered amongst the human-readable text. I'm not aware of any way around this, sadly.

    The final line, selector, specifies the scope in which this Build System should take place. With this set to source.dart, Dart files should automatically choose this Build System. Sublime Text 2 knows that a ".dart" file is a, well, a Dart file thanks to the language grammar we installed.

    Save this file as Dart-frogc.sublime-build in [Sublime Data]/Packages/User/Dart/


    Optional Power-User Step for Windows

    To avoid the aforementioned errors on Windows, and also make your build system fit more in line with the Mac and Linux versions, we can add the dart-sdk bin folder to the Windows environment, so that Sublime Text knows to look there for frogc.

    To add the path, click Start, then right-click Computer, and select Properties. (Alternatively: Control Panel > System and Security > System.) Click "Advanced system settings", then on "Environment Variables."

    Now, find the "path" variable, in either User Variables or System Variables (it works with either). If it doesn't exist, you can click New to create it, but if it does exist, then clicking New will overwrite it, so be careful.

    Append the correct path to the end of what's already there, using a semicolon to separate it from everything else. No need to escape slashes or replace spaces with underscores or anything like that. Mine looks like:

    
    
    C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Users\Administrator\Downloads\dart-win32-latest\dart-sdk\bin
    

    (Scroll the above box to the right.)

    That'll let you run frogc c:\whatever\source.dart from the command window, but it still won't work within Sublime Text 2. For some reason, ST2 on Windows requires you to specify the file extension in your build system file, like so:

    
    
    "cmd": ["frogc.bat", "$file"]
    

    At this point, you should have a usable build system on Windows that's less likely to break.


    Step 6: Using the Build System

    Go ahead and try our new Build System out. Open up a Dart file, and press F7 or Control-B (on the Mac, Command-B). "B" for Build.

    You should see the output panel open up at the bottom, and if the Dart is error-free, you'll just see [Finished].

    The Build System is successful

    If you have errors, you'll get much more complex output. For example:

    The Build System showing errors

    When this happens, press F4 to move forward through the various lines of error, and Shift-F4 to move backward. The error line will highlight in the output panel, and your cursor will be placed at the line and column identified by the error.

    The Build System highlighting an error

    Step 7: Start Building Snippets

    There are potentially many useful snippets to be added to a Dart bundle. Let me get you started by adding a snippet that creates a new method.

    From the Sublime Text menu, choose Tools > New Snippet... You'll again be presented with a default file, this one in XML format. Change its contents to:

    
    
    <snippet>
        <content><![CDATA[
    ${1:void} ${2:methodName}(${3:arguments}) {
        $0${1/void|(.+)/(?1:\n\treturn null;)/}
    }
    ]]></content>
        <tabTrigger>method</tabTrigger>
        <scope>source.dart</scope>
    </snippet>
    

    Feel free to change the contents of the <tabTrigger> node from method to something else that you'll find more useful. This is what you type before pressing Tab in order to get the snippet.

    Save the file as method.sublime-snippet (the extension is crucial; the base name is what your snippet will show up as in the menus), in the following location relative to your Sublime Text 2 Packages folder:

    
    
    /Dart/method.sublime-snippet
    

    You should already have the "Dart" folder from the installation of the language grammar file.

    Now try out your new snippet (you may need to restart Sublime Text, but I think this is no longer an issue).

    In a Dart file, type "method" (or whatever you specified, if you forged your own tab trigger), press Tab, and watch it expand. You can tab through the various stops, starting at the return type, then to the method name, and finally in between the parentheses if you want to add arguments. The last tab will drop you at the first line of the method.

    The cool part is that if you change the return type from void, you get an automatic return null statement at the end of your method body. Naturally you'll want to adapt this to your needs, but hopefully it's a feature that saves a little typing. The magic happens in the unwieldy second line of the snippet; if you've never seen this before, then it's somewhat difficult to explain concisely, but it looks at the contents of the first tab stop (the return type) and if it's anything other than "void", it adds the return null. It might make sense if you've ever used Regular Expressions, particularly with the substitution syntax of /pattern/substitute/ found in Perl.

    The field's wide open for the creation of time-saving Dart snippets. Feel free to post your snippets in the comments.


    That's All

    And there you have it; those of use who prefer a certain text editor over anything else can continue to do so, even with this new Dart language. Thanks for reading, and I hope you learned something about Sublime Text 2's extensibility along the way.


  3. Jesse Freeman says:
    April 28, 2012 at 6:58 pm
    This entry is part 3 of 3 in the series An ImpactJS Overview

    Impact is an incredibly powerful HTML5 game framework and one of it’s key advantages is its ability to run on many different platforms such as desktop browsers, mobile browser, as a native iOS or Win 8 Metro app, and on Chrome Market. In this video I will go over how I use Ant to automate building out versions of my game to each of these platforms and some things to keep in mind when you are looking into distributing your own game.


    Watch the Screencast

    You can also download the video to watch later.


    More Info and Links

    This video is based on a more detailed article I wrote called Automating Impact Builds With Ant. To learn more about Impact visit http://ImpactJS.com and check out a copy of my book on Impact called Introducing HTML5 Game Development, published by O’Reilly.


  4. Abel Toy says:
    April 28, 2012 at 7:24 pm

    It’s not easy to create the UI side of your game with FlashPunk, as it doesn’t include any UI components like buttons or text fields by default. This isn’t a restriction, though; it just means you’re completely free to create the UI exactly as you like. But you need to know how to do it first! This tutorial will teach you how to build some custom UI components, and show you the different ways you can customize them to exactly fit the style of your game.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:


    Step 1: Introduction

    Many FlashPunk users tend to have problems with the UI side of their games. There’s no ‘easy’ way of making buttons and other interactible-elements like text fields or checkboxes, for example, in FlashPunk. No Button class.

    That may seem of a restriction, yes, and many newcomers find it a little bit confusing at first… but there’s a reason behind that. Games, each one of them, tend to have a custom user interface unique to themselves, which design is related to the mechanics or theme of the game itself. You won’t see any good game (generally speaking) that has the default window buttons for its controls!

    We could argue that, in this case, there could be some classes providen with the bare-bones of the functionality, the minimum required for some buttons to work, and leave the graphic side to the user… yes, that is true… but the generalization we would have to use in those classes would be either too big and confusing or too specific and not costumizable enough. (believe me, I was in charge of the semi-failed semi-working Punk.UI project.) We will learn how to code our own components instead!

    So what this tutorial is going to show you is how to build your own UI elements for your game in FlashPunk, give them behaviour, and show some tricks to make their graphic part with the most used techniques… but remember that each of your games will need a different UI graphically-wise!

    As the tutorial is really lengthy, it’s been divided into multiple parts. This first part will teach you how to build each component, without the eye-candy and costumization. We will introduce these later.

    To code the example SWF with our UI, we are going to use FlashPunk, as this is a FlashPunk tutorial, and FlashDevelop for the IDE. If you feel more comfortable with another IDE, like FlashBuilder, you are free to use that, just adapt the specific parts of this tutorial.

    Previous knowledge on FlashPunk is needed to follow this tutorial. This is not a general FlashPunk tutorial, this is a UI tutorial using FlashPunk. If you don’t know FlashPunk, you can take a look at the Introductory FlashPunk tutorials on Activetuts+ and also check out the official FlashPunk tutorials.


    Step 2: Create a New Project

    Open FlashDevelop and click Project > New Project to open the New Project window.

    FlashDevelop New Project Window

    Choose ActionScript 3 > AS3 Project. For the name of the project, put in “FlashPunk UI”. For the location, click and navigate to the folder you would like to save it into. Leave the “create directory for project” checkbox selected and click OK.


    Step 3: Download the Latest FlashPunk

    The Downloads page of FlashPunk

    Go to the official FlashPunk webpage, FlashPunk.net, and click the Download button on the navigation bar. Then click the “Download FlashPunk” link on the top of the page. It should take you to the GitHub download webpage. Click the “Download .zip” button (or “Download .tar.gz” if you prefer that format) and save the file somewhere you know.


    Step 4: Add FlashPunk to Our Project

    Added FlashPunk to our project

    Now that we have downloaded FlashPunk, we have to add it to our project. To do so, we will simply copy the “net” folder from the FlashPunk zip to our “src” folder in our project, like usual.


    Step 5: Starting the Engine

    We have to initialize FlashPunk in our document class now, so it takes control of our game, like on every FlashPunk project. We do so by making our document class extend the Engine class, and calling super with the required parameters. We will give our application a size of 550×400 pixels. Don’t forget to right-click on our project, go to Properties and configure the dimensions to 550×400 pixels as well.

    
    
    package
    {
    	import net.flashpunk.Engine;
    
    	public class Main extends Engine
    	{
    		public function Main():void
    		{
    			super(550, 400);
    		}
    	}
    }
    
    Setting our project's dimensions

    Step 6: Creating Our World

    Now, we have to create a FlashPunk World to hold our entities. We will place every UI component we create there, so we can test them. In a real-world case, each of our Menu States would be a different World, as well as the Game itself. So we will create a new class which will extend World, called TestWorld, in our “src” folder.

    
    
    package
    {
    	import net.flashpunk.World;
    
    	public class TestWorld extends World
    	{
    
    		public function TestWorld()
    		{
    			super();
    		}
    
    	}
    }
    

    Then we’ll tell our Engine class to go to our TestWorld on startup by overriding the init function. Don’t forget to import the class FP from net.flashpunk!

    
    
    		override public function init():void
    		{
    			super.init();
    
    			FP.world = new TestWorld;
    		}
    

    Step 7: The Button Entity

    The first thing we are going to build is our Button component. Every component we’re going to make will be an Entity, as it’s the most logical step for making something in FlashPunk which will live in a World.

    First of all, we will create a new folder inside the “src” folder, to keep things a bit organized. We will name this folder “ui”, and will hold all of our components.

    Then we create a class there named Button, which will extend Entity. The package will be ui, as it’s inside the ui folder.

    
    
    package ui
    {
    	import net.flashpunk.Entity;
    
    	public class Button extends Entity
    	{
    		public function Button(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    		}
    	}
    }
    

    Now we will add a new instance of this Button class in our World, so we can see it working… when we finish it, as at the moment it’s an invisible Entity. So, add this in our TestWorld class, and don’t forget to import the Button class using import ui.Button;

    
    
    		override public function begin():void
    		{
    			super.begin();
    
    			add(new Button(10, 10));
    		}
    

    Step 8: Graphic for Our Button

    To make our button visible, it will need a graphic. I have created an image for our Button, which you can use freely, but you can also create your own graphic if you want:

    Button graphic

    Save this as “button.png” without the commas in a new folder named “gfx”, situated inside an assets folder which will be in the root of your project (at the same level of your src folder).

    Now we need to insert this button graphic in our game. To do so, we will embed the image and then tell FlashPunk to use it as our graphic. To keep things a bit organized, we will embed everything we need in a new class called Assets. This is what I tend to do on all my projects, and it works like a charm! So we will proceed to create a new Assets class, and embed the graphic as a public static constant, so we can access it from outside:

    
    
    package
    {
    	public class Assets
    	{
    		[Embed(source = "../assets/gfx/button.png")] public static const BUTTON:Class;
    	}
    }
    

    Finally, we will tell FlashPunk to use this as the graphic of our Button. We can use it as an Image or as a Stamp. The difference is, Image will consume more memory but will allow us to transform the graphic, and the Stamp will consume less memory but won’t allow any transformation at all, unless they are applied manually directly to the BitmapData. We will currently use a Stamp, as we don’t need to transform the button yet. Add this to our Button class, and don’t forget to import Stamp.

    
    
    		public function Button(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    			graphic = new Stamp(Assets.BUTTON);
    		}
    

    If you test the project now, you will see our graphic on the World, but clicking on it won’t do anything. We will add some behaviour now!


    Step 9: Adding Interactivity

    To make an Entity respond to mouse clicks on FlashPunk, we just need to: check the mouse is over the entity and check if the mouse was released this frame. The second step is really easy, we just have to check the value of the mouseReleased variable in the Input class, but for the other, we must do a collision test between a point (mouse coordinates) and the entity, and to do so, we will need to define the entity collision. At the moment we will use a hitbox, as it’s the simplest option.

    So here’s the code achieving all of what we just said, with an explanation below:

    
    
    package ui
    {
    	import net.flashpunk.Entity;
    	import net.flashpunk.FP;
    	import net.flashpunk.graphics.Stamp;
    	import net.flashpunk.utils.Input;
    
    	public class Button extends Entity
    	{
    		public function Button(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    			graphic = new Stamp(Assets.BUTTON);
    			setHitboxTo(graphic);
    		}
    
    		override public function update():void
    		{
    			super.update();
    
    			if (collidePoint(x, y, world.mouseX, world.mouseY))
    			{
    				if (Input.mouseReleased) click();
    			}
    		}
    
    		protected function click():void
    		{
    			FP.screen.color = Math.random() * 0xFFFFFF;
    			trace("click!");
    		}
    	}
    }
    
    • Line 15: We set the Entity’s hitbox to our graphic, so it will have the same Width and Height of the Stamp.
    • Line 22: We check if the mouse position in the world we are collides with the entity.
    • Line 24: If the mouse was released this frame, we call the click function.
    • Lines 28-32: This code will be executed when the button is clicked. It will trace a click message and change the background colour, so we notice the button has been pressed.

    Some of you may notice this class would perform better if we checked the mouse state first and then check the collision, but as we will have to add the hover graphics, we would have to change it back to this, so we’ll leave it this way.

    If you test the game now, it should look like this, but with your button graphic:


    Step 10: Hover and Down Graphics

    Right now, our Button is really boring, and it does not show ANY sign of interactivity, apart from its callback. It’s the time to add some graphics to show the different states: normal, hover, and down.

    First of all, we need to make different graphics for each, so let’s get working! You can grab these two I made or simply make your own. Put them in the gfx folder with the names button_hover.png and button_down.png.

    Button Hover Graphic
    button_hover.png
    Button Hover Graphic
    button_down.png

    Then, we will add them in our Assets class.

    
    
    		[Embed(source = "../assets/gfx/button.png")] public static const BUTTON:Class;
    		[Embed(source = "../assets/gfx/button_down.png")] public static const BUTTON_DOWN:Class;
    		[Embed(source="../assets/gfx/button_hover.png")]  public static const BUTTON_HOVER:Class;
    

    Now we have to hold those graphics somewhere in our button, and switch to the correct one when it’s needed. So we will create three variables to hold the normal, the down, and the hover graphics respectively, and switch the graphic properties to each of the three as appropriate.

    
    
    		protected var normal:Graphic;
    		protected var hover:Graphic;
    		protected var down:Graphic;
    
    		public function Button(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    			normal = new Stamp(Assets.BUTTON);
    			hover = new Stamp(Assets.BUTTON_HOVER);
    			down = new Stamp(Assets.BUTTON_DOWN);
    
    			graphic = normal;
    
    			setHitboxTo(graphic);
    		}
    

    Step 11: Fix a Little Bug

    Before making the graphic behaviour, we want do something else. We need to keep track of some data which will also solve a little issue: if I press the mouse outside the button, then go to the button and release the mouse, it will detect as a mouse click. We don’t want that. So we will create a new protected boolean called clicked, which will simply tell us if the mouse was first pressed over the button or not.

    
    
    		protected var normal:Graphic;
    		protected var hover:Graphic;
    		protected var down:Graphic;
    
    		protected var clicked:Boolean = false;
    

    Then we will apply the following changes on the update function: first, inside the collision check, if the mouse was pressed this frame (Input.mousePressed) we will set the clicked boolean to true. Then, on the check for the released mouse button, we will also check for the clicked variable, so we will only detect a button click if the mouse was pressed while over it before. Finally, outside of the collision check, we set clicked to false when the mouse is released.

    
    
    override public function update():void
    {
    	super.update();
    
    	if (collidePoint(x, y, world.mouseX, world.mouseY))
    	{
    		if (Input.mousePressed) clicked = true;
    
    		if (clicked && Input.mouseReleased) click();
    	}
    
    	if (Input.mouseReleased) clicked = false;
    }
    

    Step 12: Assigning the Hover and Down Graphics

    For the graphics itself, we must first plan the behavior we have in mind. When the mouse is over the graphic and it’s not pressed, we will display the hover state. If the mouse is over the graphic and it’s pressed, we will display the pressed state. If the user presses the button and, while keeping the mouse button down, moves the mouse out of the button collision, we will display the hover state, imitating AS3′s SimpleButton behavior. In all the other cases, we will display the normal state.

    
    
    		override public function update():void
    		{
    			super.update();
    
    			if (collidePoint(x, y, world.mouseX, world.mouseY))
    			{
    				if (Input.mousePressed) clicked = true;
    
    				if (clicked) graphic = down;
    				else graphic = hover;
    
    				if (clicked && Input.mouseReleased) click();
    			}
    			else
    			{
    				if (clicked) graphic = hover;
    				else graphic = normal;
    			}
    
    			if (Input.mouseReleased) clicked = false;
    		}
    

    Inside the button collision check we also check if the mouse button is being pressed at the moment. We will check that using the clicked variable, and not the Input.mouseDown variable, because we want to be sure we show the pressed graphic the mouse has been clicked while over the button, not when clicked outside of the button and then dragged on top of it. In case the mouse is being pressed, we will display the down state, if not, the hover state, because the mouse will be over the button but it won’t be pressed.

    In the other pair of checks, when the mouse isn’t over the button, we check first if the mouse has been clicked. If it has, we will display the hover state as we said before. If not, the normal state will be shown.

    Here you can see how it should look at the moment, but with your own graphics instead:


    Step 13: Checkboxes

    If you think about it, a checkbox isn’t really that different from a button. The only difference, apart from the graphic, is they also have a state which determines whether they are checked or not. In fact, a checkbox and a push button – which is a button that remains pressed until you click on it again – are the same.

    For that reason, creating a checkbox is really easy if we know how to create a button. All we need to add is an extra variable that is toggled on each click, and with a few extra checks on the graphic changes, where we determine which version of the graphic to show: the checked or the unchecked one.

    I would also like to teach you something extra as we do the checkbox. For the button, we created the graphics in different files, but what if we want all of the states in the same graphic? That’s pretty simple, we just need to use the clipRect property of the Image class, as we will show when assigning our checkbox graphics.

    So, as checkboxes and buttons share so many features, it’s logical that we want our checkbox class to extend the button class. But, if we did that with the current code, we would have to replace the full update function to considerate our checkbox checked state on the graphics changes. Thus, before creating our Checkbox class, we will refactor our Button class a bit before, so things are easier and cleaner for us.


    Step 14: Refactoring Our Button

    To be able to insert the checked consideration when our graphics change, all we need to do is abstract the graphic change. So, instead of setting the graphic directly in the update function, we will call another function telling what state we want, and that function will do the actual graphic switch.

    The function we will create will be called changeState, and will accept one argument as an integer, the state. 0 will mean normal, 1 will mean hover and 2 will mean down. As we could get a bit confused and forget the meaning of those numbers easily (well, not in THIS case, but this technique may be useful to you in other, more complicated cases), we will create some constants that will hold this values instead.

    First, we create those constants on our Button class:

    
    
    		protected const NORMAL:int = 0;
    		protected const HOVER:int = 1;
    		protected const DOWN:int = 2;
    

    Then we substitute all the graphic changes to call our yet-to-be-created function:

    
    
    		override public function update():void
    		{
    			super.update();
    
    			if (collidePoint(x, y, world.mouseX, world.mouseY))
    			{
    				if (Input.mousePressed) clicked = true;
    
    				if (clicked) changeState(DOWN);
    				else changeState(HOVER);
    
    				if (clicked && Input.mouseReleased) click();
    			}
    			else
    			{
    				if (clicked) changeState(HOVER);
    				else changeState(NORMAL);
    			}
    
    			if (Input.mouseReleased) clicked = false;
    		}
    

    Finally we create the function, using a switch statement with three cases:

    
    
    		protected function changeState(state:int = 0):void
    		{
    			switch(state)
    			{
    				case NORMAL:
    					graphic = normal;
    					break;
    				case HOVER:
    					graphic = hover;
    					break;
    				case DOWN:
    					graphic = down;
    					break;
    			}
    		}
    

    Now we’re ready to easily code our checkbox! But first…


    Step 15: Checkbox Graphics

    As we explained before, we will place all the checkbox graphics in a single file, so you can see both techniques (separate files or same files) and choose whichever you prefer.

    The order of the file will be as follows: normal – hover – down; the top row will be the unchecked states and the bottom one will be the checked states. You can use your own graphics or download this one we provide. Don’t forget to save the graphic as checkbox.png inside the gfx folder.

    Checkbox Graphic

    Now we’ll add it to our Assets class so we can use it.

    
    
    		[Embed(source = "../assets/gfx/button.png")] public static const BUTTON:Class;
    		[Embed(source = "../assets/gfx/button_down.png")] public static const BUTTON_DOWN:Class;
    		[Embed(source = "../assets/gfx/button_hover.png")]  public static const BUTTON_HOVER:Class;
    		[Embed(source = "../assets/gfx/checkbox.png")] public static const CHECKBOX:Class;
    

    Finally, we will create our Checkbox class and setup the variables containing the graphics. So, first we will create the Checkbox class in the ui folder, and make it extend our Button.

    
    
    package ui
    {
    	public class Checkbox extends Button
    	{
    		public function Checkbox(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    		}
    	}
    }
    

    Then, we will add three more variables containing the checked graphics. The unchecked graphics will be at the normal, hover and down variables we already have.

    
    
    		protected var normalChecked:Graphic;
    		protected var hoverChecked:Graphic;
    		protected var downChecked:Graphic;
    
    		public function Checkbox(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    		}
    

    And now, we will populate them, as Images so we can clip them using the clipRect variable. This variable accepts a flash Rectangle, which is a Class with x, y, width and height properties. So, when Image sees we provide a clipRect, it will crop itself using that information. That’s how it will look like in my case. You might have to adapt the values, so they fit your own graphics dimensions:

    
    
    		public function Checkbox(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    			normal = new Image(Assets.CHECKBOX, new Rectangle(0, 0, 38, 34));
    			hover = new Image(Assets.CHECKBOX, new Rectangle(38, 0, 38, 34));
    			down = new Image(Assets.CHECKBOX, new Rectangle(76, 0, 38, 34));
    
    			normalChecked = new Image(Assets.CHECKBOX, new Rectangle(0, 34, 38, 34));
    			hoverChecked = new Image(Assets.CHECKBOX, new Rectangle(38, 34, 38, 34));
    			downChecked = new Image(Assets.CHECKBOX, new Rectangle(76, 34, 38, 34));
    
    			graphic = normal;
    			setHitboxTo(normal);
    		}
    

    If you take a look at the code, you can see that in the end we are also assigning our graphic to the normal state, and resizing our hitbox to match the Checkbox graphics.


    Step 16: Adding Our Checkbox

    Now we will add the checkbox into our World and see how it looks! Add this in our TestWorld class:

    
    
    		override public function begin():void
    		{
    			super.begin();
    
    			add(new Button(10, 10));
    			add(new Checkbox(20, 140));
    		}
    

    Now test the project… hey, wait! Our checkbox acts just like a normal button, it doesn’t check and uncheck itself! We haven’t added the behavior yet, that’s what we’re going to do now.


    Step 17: Checking and Unchecking the Checkbox

    First of all, we need to create a public boolean which will hold the checked state of our Button. It will be called… oh, surprise! checked. So…

    
    
    		protected var normalChecked:Graphic;
    		protected var hoverChecked:Graphic;
    		protected var downChecked:Graphic;
    
    		public var checked:Boolean = false;
    

    Now, we will need to toggle this variable each time we click the checkbox. The easiest way to do so is to override the click function, and toggle it, so add this in our Checkbox:

    
    
    		override protected function click():void
    		{
    			checked = !checked;
    
    			super.click();
    		}
    

    But, if we test the project, the checkbox won’t change yet. We need to make one last change: make a check when setting each graphic to change it to the checked or unchecked version. To do that, we just need to override the changeState function we refactored before:

    
    
    		override protected function changeState(state:int = 0):void
    		{
    			if (checked)
    			{
    				switch(state)
    				{
    					case NORMAL:
    						graphic = normalChecked;
    						break;
    					case HOVER:
    						graphic = hoverChecked;
    						break;
    					case DOWN:
    						graphic = downChecked;
    						break;
    				}
    			}
    			else
    			{
    				super.changeState(state);
    			}
    		}
    

    So first we check the checked property. If it’s true, we check the state we just changed to, and set it to our corresponding checked graphic. Otherwise, if the checkbox is not checked, we call our Button version of the changeState, which simply sets the graphic to the unchecked state. By using the super there, we need to write less code to do the same behavior! Yay!

    If we test the project, we can see the checkbox working now. It should look like this, but with your own graphics:


    Step 18: Radio Buttons

    If we think about it, a radio button is practically the same as a Checkbox. The only difference is, while the Checkbox is totally independent from the other checkboxes, a RadioButton is part of a group, and in that group, only ONE member can be checked at the same time, so we will have to handle that.

    So, instead of making the RadioButton open and close itself, it will tell the group it needs to be checked, and the group will uncheck all of the other radio buttons, and check ours… and what’s the group?

    Basically, the RadioButton Group will be a special class with an Array (well, in our case an AS3 Vector) containing all the RadioButtons belonging to the group. It will also contain methods to add and remove buttons from the group.

    First of all, though, we will make the graphics for our RadioButtons…


    Step 19: RadioButton Graphics

    We will make the graphics for the RadioButton the same way we did it for the Checkbox. You can make your own costumized graphic if you want to, but if not, you can use this. Save your graphic as “radiobutton.png” in the gfx folder.

    RadioButton Graphic

    Now we’ll add it to our Assets class so we can use it.

    
    
    		[Embed(source = "../assets/gfx/button.png")] public static const BUTTON:Class;
    		[Embed(source = "../assets/gfx/button_down.png")] public static const BUTTON_DOWN:Class;
    		[Embed(source = "../assets/gfx/button_hover.png")]  public static const BUTTON_HOVER:Class;
    		[Embed(source = "../assets/gfx/checkbox.png")] public static const CHECKBOX:Class;
    		[Embed(source = "../assets/gfx/radiobutton.png")] public static const RADIOBUTTON:Class;
    

    After that, we create our RadioButton class which will extend RadioButton, and we’ll set up the graphics the same way we did it before.

    
    
    package ui
    {
    	import flash.geom.Rectangle;
    	import net.flashpunk.graphics.Image;
    
    	public class RadioButton extends Checkbox
    	{
    		public function RadioButton(x:Number=0, y:Number=0)
    		{
    			super(x, y);
    
    			normal = new Image(Assets.RADIOBUTTON, new Rectangle(0, 0, 39, 44));
    			hover = new Image(Assets.RADIOBUTTON, new Rectangle(39, 0, 39, 44));
    			down = new Image(Assets.RADIOBUTTON, new Rectangle(78, 0, 39, 44));
    
    			normalChecked = new Image(Assets.RADIOBUTTON, new Rectangle(0, 44, 39, 44));
    			hoverChecked = new Image(Assets.RADIOBUTTON, new Rectangle(39, 44, 39, 44));
    			downChecked = new Image(Assets.RADIOBUTTON, new Rectangle(78, 44, 39, 44));
    
    			graphic = normal;
    			setHitboxTo(normal);
    		}
    	}
    }
    

    Step 20: RadioButton Group

    It’s time to make the radiobutton group itself now. The class will hold all the radiobuttons in a Vector of RadioButtons. It will also have the following methods: add(), for adding a new radio button, addList(), to add multiple radio buttons in a single step, remove(), to remove a radio button, removeList(), the equivalent of addList() but for removing, and removeAll(), to remove all the radio buttons from the group at once. It will also have a getAt() method, to get a radio button by the index, and a getIndex(), to get the index of a button. We won’t spend much time explaining those methods, as they are basic operations for arrays.

    Then, when creating a RadioButton, it will ask for a radio button group as the parameter, and it will be added automatically there if provided. Also, when removing the RadioButton from the world, it will also be removed from its group. Finally, when clicked, it won’t do anything by itself but call an internal method of the group, which will be called click(). This method will uncheck all the radio buttons and check the one which called the method.

    First of all, we create the group. I have provided some comments to explain a few things, but as it’s only basic operations with an array, I won’t explain it all:

    
    
    package ui
    {
    	public class RadioButtonGroup
    	{
    		public var buttons:Vector.<RadioButton> = new Vector.<RadioButton>;
    
    		public function RadioButtonGroup(...buttons)
    		{
    			//we add the buttons provided to the constructor, if any
    			if (buttons) addList(buttons);
    		}
    
    		public function add(button:RadioButton):void
    		{
    			buttons.push(button);
    		}
    
    		public function addList(...buttons):void
    		{
    			if (!buttons) return;
    			if (buttons[0] is Array || buttons[0] is Vector.<RadioButton>)
    			{
    				//if the parameter is an array or vector of radio buttons, we add the buttons in the vector / array
    				for each(var b:RadioButton in buttons[0]) add(b);
    			}
    			else
    			{
    				//if the parameters are simply a comma separated list of buttons, we add those instead
    				for each(var r:RadioButton in buttons) add(r);
    			}
    		}
    
    		public function remove(button:RadioButton):void
    		{
    			buttons.splice(getIndex(button), 1);
    		}
    
    		public function removeList(...buttons):void
    		{
    			if (!buttons) return;
    			if (buttons[0] is Array || buttons[0] is Vector.<RadioButton>)
    			{
    				//if the parameter is an array or vector of radio buttons, we remove the buttons in the vector / array
    				for each(var b:RadioButton in buttons[0]) remove(b);
    			}
    			else
    			{
    				//if the parameters are simply a comma separated list of buttons, we remove those instead
    				for each(var r:RadioButton in buttons) remove(r);
    			}
    		}
    
    		public function removeAll():void
    		{
    			//fastest way to clear a vector
    			buttons.length = 0;
    		}
    
    		public function getAt(index:int):RadioButton
    		{
    			return buttons[index];
    		}
    
    		public function getIndex(button:RadioButton):int
    		{
    			return buttons.indexOf(button);
    		}
    	}
    }
    

    Now, we will make our RadioButtons ask for a group on the constructor, and add themselves on it when provided:

    
    
    		public function RadioButton(x:Number=0, y:Number=0, group:RadioButtonGroup = null)
    		{
    			super(x, y);
    
    			if (group) group.add(this);
    
    			normal = new Image(Assets.RADIOBUTTON, new Rectangle(0, 0, 39, 44));
    			hover = new Image(Assets.RADIOBUTTON, new Rectangle(39, 0, 39, 44));
    			down = new Image(Assets.RADIOBUTTON, new Rectangle(78, 0, 39, 44));
    
    			normalChecked = new Image(Assets.RADIOBUTTON, new Rectangle(0, 44, 39, 44));
    			hoverChecked = new Image(Assets.RADIOBUTTON, new Rectangle(39, 44, 39, 44));
    			downChecked = new Image(Assets.RADIOBUTTON, new Rectangle(78, 44, 39, 44));
    
    			graphic = normal;
    			setHitboxTo(normal);
    		}
    

    Finally, we’ll add the buttons on the world, so we can test them. We will add 3 buttons in a group, and 2 in a different one.

    
    
    		override public function begin():void
    		{
    			super.begin();
    
    			add(new Button(10, 10));
    			add(new Checkbox(20, 140));
    
    			var group1:RadioButtonGroup = new RadioButtonGroup();
    			add(new RadioButton(20, 200, group1));
    			add(new RadioButton(20, 250, group1));
    			add(new RadioButton(20, 300, group1));
    
    			var group2:RadioButtonGroup = new RadioButtonGroup();
    			add(new RadioButton(200, 200, group2));
    			add(new RadioButton(200, 250, group2));
    		}
    

    If you test it now, the radio buttons will still behave as normal checkboxes. It’s time to change that now.


    Step 21: RadioButton Click Behavior

    First of all, we need to override the click function of the RadioButton, and instead of calling the code there is on the checkbox using super, we will call the still-to-be-created click function of our RadioButton group… oops! How are we going to call this function, if we haven’t got a reference to the group? A simple solution would be to set a reference from the group provided on the constructor but… then we won’t be able to change groups, and all of the methods we can see in the group will be useless.

    What we are going to do instead is, first add a variable on the RadioButton which will reference its group, and we will set this on the added method of the group. We will also set it to null when removing the button:

    
    
    	public class RadioButton extends Checkbox
    	{
    		internal var group:RadioButtonGroup;
    
    		// [...] all the methods in the RadioButton class were omitted for brevety.
    	}
    

    Now we add this on the following methods of the RadioButton group:

    
    
    		public function add(button:RadioButton):void
    		{
    			button.group = this;
    			buttons.push(button);
    		}
    
    
    
    		public function remove(button:RadioButton):void
    		{
    			button.group = null;
    			buttons.splice(getIndex(button), 1);
    		}
    

    And we will also set all the group references to null on the removeAll function:

    
    
    		public function removeAll():void
    		{
    			for each(var b:RadioButton in buttons) b.group = null;
    			//fastest way to clear a vector
    			buttons.length = 0;
    		}
    

    Now we are ready to call the click function on the RadioButton!

    
    
    		override protected function click():void
    		{
    			group.click(this);
    		}
    

    And finally we will build the click function. This function will uncheck all the RadioButtons in the group, and then check the button provided.

    
    
    		internal function click(target:RadioButton):void
    		{
    			for each(var b:RadioButton in buttons) b.checked = false;
    			target.checked = true;
    		}
    

    Now, just before testing, we will also make our button remove itself from the group when removed from the world.

    
    
    		override public function removed():void
    		{
    			super.removed();
    
    			group.remove(this);
    		}
    

    This is how it will look like, but with your own graphics!


    Step 22: Custom Parameters: Text

    What if we want our buttons to contain some text? For example, in the menu of our game, we may want to have a Play button, a Help button, etc. and we want those buttons to have some text on them, which tells which of them is the play and which of them is the help. Currently, the only way we can do it is create a new image for each of them, create a new class as well and change the image in the class…

    So what we can do is accept an extra parameter in our components: the text. This will be a string we will send to our components, and then they will display it as text. Super easy!

    Let’s implement it in our Button now. First, we will add the parametrer text as a string, and also a label variable with type of Text, which is a FlashPunk graphic:

    
    
    		protected var label:Text;
    
    		public function Button(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			normal = new Stamp(Assets.BUTTON);
    			hover = new Stamp(Assets.BUTTON_HOVER);
    			down = new Stamp(Assets.BUTTON_DOWN);
    
    			graphic = normal;
    
    			setHitboxTo(graphic);
    		}
    

    Then we will instantiate this text, with a size of 16 pixels and black color, with the width of the button (minus the borders), wordWrap activated and aligned to the center.

    
    
    		public function Button(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			var normalStamp:Stamp  = new Stamp(Assets.BUTTON);
    
    			label = new Text(text, 10, 0, { size: 16, color: 0x000000, width: normalStamp.width - 30, wordWrap: true, align: "center" } );
    
    			normal = normalStamp;
    			hover = new Stamp(Assets.BUTTON_HOVER);
    			down = new Stamp(Assets.BUTTON_DOWN);
    
    			graphic = normal;
    
    			setHitboxTo(normalStamp);
    		}
    

    We also created an extra variable, a Stamp, which will hold the stamp of the normal graphic, so we can reference its width. We set normal graphic to the normalStamp.

    Now we need to display this text somewhere. To do this, we need to include it in the graphic of our button. In FlashPunk, to display more than a single graphic at once, we need to put all of them in a graphiclist, and use this as the graphic instead. So we will do something similar, to make all of our graphics contain the text:

    
    
    		public function Button(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			var normalStamp:Stamp  = new Stamp(Assets.BUTTON);
    
    			label = new Text(text, 10, 0, { size: 16, color: 0x000000, width: normalStamp.width - 30, wordWrap: true, align: "center" } );
    
    			normal = new Graphiclist(normalStamp, label);
    			hover = new Graphiclist(new Stamp(Assets.BUTTON_HOVER), label);
    			down = new Graphiclist(new Stamp(Assets.BUTTON_DOWN), label);
    
    			graphic = normal;
    
    			setHitboxTo(normalStamp);
    		}
    

    Finally, we will center our text vertically:

    
    
    		public function Button(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			var normalStamp:Stamp  = new Stamp(Assets.BUTTON);
    
    			label = new Text(text, 10, 0, { size: 16, color: 0x000000, width: normalStamp.width - 30, wordWrap: true, align: "center" } );
    			label.y = (normalStamp.height - label.textHeight) * 0.5;
    
    			normal = new Graphiclist(normalStamp, label);
    			hover = new Graphiclist(new Stamp(Assets.BUTTON_HOVER), label);
    			down = new Graphiclist(new Stamp(Assets.BUTTON_DOWN), label);
    
    			graphic = normal;
    
    			setHitboxTo(normalStamp);
    		}
    

    So if we add some text in the button we created in our TestWorld, we will see something like this:


    Step 23: The Problem With the Text

    There is a little problem with the way we are doing Text at the moment: we need to create a new Graphiclist for each graphic. This means we have to write more code for EACH graphic we have, and we can’t have text on classes that extends us unless we also change that. A bit inconvenient.

    So here’s my solution: instead of inserting the text in our graphics, we’ll just render it manually by overriding the render function.

    Here’s a renderGraphic function I created, which mimics the rendering of the Entity class, but accepts the graphic as a parameter. We will add this to our button:

    
    
    		protected function renderGraphic(graphic:Graphic):void
    		{
    			if (graphic && graphic.visible)
    			{
    				if (graphic.relative)
    				{
    					_point.x = x;
    					_point.y = y;
    				}
    				else _point.x = _point.y = 0;
    				_camera.x = world ? world.camera.x : FP.camera.x;
    				_camera.y = world ? world.camera.y : FP.camera.y;
    				graphic.render(renderTarget ? renderTarget : FP.buffer, _point, _camera);
    			}
    		}
    		protected var _point:Point = FP.point;
    		protected var _camera:Point = FP.point2;
    

    Now we will set the graphics as they were before:

    
    
    		public function Button(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			var normalStamp:Stamp  = new Stamp(Assets.BUTTON);
    
    			label = new Text(text, 10, 0, { size: 16, color: 0x000000, width: normalStamp.width - 30, wordWrap: true, align: "center" } );
    			label.y = (normalStamp.height - label.textHeight) * 0.5;
    
    			normal = normalStamp;
    			hover = new Stamp(Assets.BUTTON_HOVER);
    			down = new Stamp(Assets.BUTTON_DOWN);
    
    			graphic = normal;
    
    			setHitboxTo(normalStamp);
    		}
    

    And finally we will override the render function, to render the text as well as the button graphic:

    
    
    		override public function render():void
    		{
    			super.render();
    
    			renderGraphic(label);
    		}
    

    It’s time to add text to our Checkbox as well! First of all, we must accept the text as a string. Then, as we want it completely different (width / height and color), we will replace the label, as following:

    
    
    		public function Checkbox(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y, text);
    
    			normal = new Image(Assets.CHECKBOX, new Rectangle(0, 0, 38, 34));
    			hover = new Image(Assets.CHECKBOX, new Rectangle(38, 0, 38, 34));
    			down = new Image(Assets.CHECKBOX, new Rectangle(76, 0, 38, 34));
    
    			normalChecked = new Image(Assets.CHECKBOX, new Rectangle(0, 34, 38, 34));
    			hoverChecked = new Image(Assets.CHECKBOX, new Rectangle(38, 34, 38, 34));
    			downChecked = new Image(Assets.CHECKBOX, new Rectangle(76, 34, 38, 34));
    
    			label = new Text(text, 40, 0, { color: 0xFFFFFF, size: 16 } );
    			label.y = (Image(normal).height - label.textHeight) * 0.5;
    
    			graphic = normal;
    			setHitboxTo(normal);
    		}
    

    And, thanks to the power of extending, to have text in our RadioButtons, we only have to accept the text parameter and send it to super (and center it vertically)!

    
    
    		public function RadioButton(x:Number=0, y:Number=0, group:RadioButtonGroup = null, text:String = "")
    		{
    			super(x, y, text);
    
    			if (group) group.add(this);
    
    			normal = new Image(Assets.RADIOBUTTON, new Rectangle(0, 0, 39, 44));
    			hover = new Image(Assets.RADIOBUTTON, new Rectangle(39, 0, 39, 44));
    			down = new Image(Assets.RADIOBUTTON, new Rectangle(78, 0, 39, 44));
    
    			normalChecked = new Image(Assets.RADIOBUTTON, new Rectangle(0, 44, 39, 44));
    			hoverChecked = new Image(Assets.RADIOBUTTON, new Rectangle(39, 44, 39, 44));
    			downChecked = new Image(Assets.RADIOBUTTON, new Rectangle(78, 44, 39, 44));
    
    			label.y = (Image(normal).height - label.textHeight) * 0.5;
    
    			graphic = normal;
    			setHitboxTo(normal);
    		}
    

    In some applications and UIs, the “hitbox” of the checkbox / radiobutton also includes its text, so we can include that with a simple line in the Checkbox class, at the end of the constructor (and in RadioButton as well):

    
    
    			width = label.x + label.textWidth;
    

    If we add the text in our TestWorld, and test the project, we will have something like this:


    Step 25: Custom Parameters: Callbacks

    So now we can create different buttons with different text easily, to differentiate them… but at the moment, all our buttons do is change the background color. There’s no use in having zillions of buttons if all of them… well, just change the background color. If we wanted to have different functionalities, with the current code, what we’d have to do is create a Button class for each functionality a button will do… that’s a no-no!

    What we’re going to do instead is use a really similar approach to the text problem: we’ll add a parameter for the functionality. This parameter will be simply a function. We’ll send a function name to it, and when the button is clicked, the function will be called. This way we can have in our World three functions: gotoGame, gotoOptions and gotoCredits. Then, we can link each of them to the Play button, the Options button and the Credits button.

    Doing this is extremely easy. We just need to accept the callback parameter, store it in our Button variables, and call it on the click function. Yay! We’ll also remove the background color code.

    Part of the button class variables and part of its constructor:

    
    
    		//[...]
    		protected var label:Text;
    		public var callback:Function;
    
    		public function Button(x:Number=0, y:Number=0, text:String = "", callback:Function = null)
    		{
    			super(x, y);
    
    			this.callback = callback;
    			//[...]
    		}
    

    And the click function, only calling the callback if a callback was provided:

    
    
    		protected function click():void
    		{
    			if (callback != null) callback();
    		}
    

    That’s it… but I want to add an extra feature for the checkboxes. The whole point of creating a checkbox is being able to determine if it’s checked or unchecked. The current way to do it is keep a reference of the checkbox in the World class, and then check its clicked property on the callback… but it’s a bit tedious having to mantain references to each checkbox in our world, if we have many of them. So what we’re going to do is: send a boolean parameter to the callback, with the value of the checked property. So, for the checkbox callback, we’ll have to accept a boolean, the value of which will be the checked value of the checkbox. Nice!

    Here’s the new checkbox click function:

    
    
    		override protected function click():void
    		{
    			checked = !checked;
    
    			if (callback != null) callback(checked);
    		}
    

    Remember to also ask for the callback parameter, and send it to super, as we show in this fragment of the Checkbox constructor:

    
    
    		public function Checkbox(x:Number=0, y:Number=0, text:String = "", callback:Function = null)
    		{
    			super(x, y, text, callback);
    			//[...]
    		}
    

    And in case of the radiobuttons, I think we need a different approach. Usually, with a radiobutton, you don’t want to determine the click of each individual radiobutton… what you want to do is determine which is the new clicked button in the group. That’s why I think the callback shouldn’t be on the button itself, but on the RadioButton group. Moreover, we also want this callback to provide information to determine which radiobutton was clicked. This can be sorted easily by demanding an extra parameter on the RadioButton: an ID, and sending that to the callback.

    So, first of all, we add the id parameter on the radiobuttons, as shown in this fragment of the RadioButton constructor.

    
    
    		public var id:String = "";
    
    		public function RadioButton(x:Number=0, y:Number=0, group:RadioButtonGroup = null, text:String = "", id:String = "")
    		{
    			super(x, y, text);
    
    			this.id = id;
    			//[...]
    		}
    

    Then, we send it to the group in the click function.

    
    
    		override protected function click():void
    		{
    			group.click(this, id);
    		}
    

    Now it’s the turn of the RadioButtonGroup. First, we add the callback parameter:

    
    
    		public var callback:Function = null
    
    		public function RadioButtonGroup(callback:Function = null, ...buttons)
    		{
    			this.callback = callback;
    
    			//we add the buttons provided to the constructor, if any
    			if (buttons) addList(buttons);
    		}
    

    Then, we call it with the id provided when a RadioButton from the group is clicked:

    
    
    		internal function click(target:RadioButton, id:String):void
    		{
    			if (callback != null) callback(id);
    
    			for each(var b:RadioButton in buttons) b.checked = false;
    			target.checked = true;
    		}
    

    That’s it!


    Step 26: Custom Parameters: Custom Parameters

    Custom parameterception! Basically, let’s say we have a game with 30 levels. We want to create a Level Screen, where the user can select the level they want to play. If we had to create a function to go to each level, it would be a pain… really simpler if we were able to pass the level number to the callback! This way, we assign the level number when creating the button from, possibly, a loop, and then the callback reads the number and shows us the correspondant level.

    If we asked for an extra argument called level number, though, this solution wouldn’t work for any other case where we need extra parameters. What we are going to do instead is, ask for an optional parameter Object. As it will be an object, it can be an int, a String, a custom class, even an array to contain multiple params… or an Object itself, in this syntax: {param: "value", param2: 1, param3: false}. This way, we can have multiple parameters which can be retrieved like this: object.param, object.param2, etc.

    To implement this is really simple. We just need to ask for an extra param, called params, and send it to the callback. You should be able to do it on your own, but just in case, here’s the code for Button and Checkbox:

    
    
    		protected var label:Text;
    		public var callback:Function;
    		public var params:Object;
    
    		public function Button(x:Number=0, y:Number=0, text:String = "", callback:Function = null, params:Object = null)
    		{
    			super(x, y);
    
    			this.callback = callback;
    			this.params = params;
    			//[...]
    		}
    
    		//[...]
    
    		protected function click():void
    		{
    			if (callback != null)
    			{
    				if (params != null) callback(params);
    				else callback();
    			}
    		}
    

    And now the checkbox:

    
    
    		public function Checkbox(x:Number=0, y:Number=0, text:String = "", callback:Function = null, params:Object = null)
    		{
    			super(x, y, text, callback, params);
    
    			//[...]
    		}
    
    		override protected function click():void
    		{
    			checked = !checked;
    
    			if (callback != null)
    			{
    				if (params != null) callback(checked, params);
    				else callback(checked);
    			}
    		}
    

    Now, for the RadioButton, we want the params to be in the button, but they will be transfered to the group and sent using the group callback… wait a minute! We already have something which does just like that! But it’s called ID and it is a String. I think we can safely say we can change ID to params and set it to object, and we will be able to use it for the same reason as ID and as extra params as well.

    Basically, we need to remove the id variable on the RadioButton and rename the param in the constructor:

    
    
    		public function RadioButton(x:Number=0, y:Number=0, group:RadioButtonGroup = null, text:String = "", params:Object = null)
    		{
    			super(x, y, text, null, params);
    
    			//[...]
    		}
    

    Then we send the params on the click function instead of the id:

    
    
    		override protected function click():void
    		{
    			group.click(this, params);
    		}
    

    And we change the click function on the group reflecting these changes as well:

    
    
    		internal function click(target:RadioButton, params:Object):void
    		{
    			if (callback != null) callback(params);
    
    			for each(var b:RadioButton in buttons) b.checked = false;
    			target.checked = true;
    		}
    

    Step 27: Arcade Text Input

    Text Inputs (text fields) are commonly used in games. Most games need at least one text input from the user: to set their name for the score. Depending on the game, there might be other uses for text inputs. Now we’re going to learn how to make them in FlashPunk, without using the AS3 TextField.

    Note that, by implementing the TextInput directly in FlashPunk, there are some kind of characters, like accents (àáèéìíòóùú) which can’t be typed. If you need those, you may want to add AS3 TextFields to FlashPunk directly by adding them on the stage (FP.stage.addChild) or to the engine MovieClip (FP.engine.addChild). Those won’t really be necessary if you are using English text, but other languages have them so keep that in mind.

    First of all, we’ll build the TextInput component. The class will extend Entity, and will have two custom properties: text, as a String, and textGraphic, of the type Text. text will contain the text inputted in the TextInput, and textGraphic will be the visual representation of it. We will implement text as a getter/setter, because when we change it through code, we also want to update the visual representation.

    
    
    package ui
    {
    	import net.flashpunk.Entity;
    	import net.flashpunk.graphics.Text;
    
    	public class TextInput extends Entity
    	{
    		protected var _text:String = "";
    		protected var textGraphic:Text;
    
    		public function TextInput(x:Number=0, y:Number=0, text:String = "")
    		{
    			super(x, y);
    
    			textGraphic = new Text("", 0, 0, { size: 16, color: 0xFFFFFF } );
    			this.text = text;
    			graphic = textGraphic;
    		}
    
    		public function get text():String
    		{
    			return _text;
    		}
    
    		public function set text(value:String):void
    		{
    			_text = value;
    			textGraphic.text = value;
    		}
    	}
    }
    

    Now we need to check for each key and write them on the text string… or use a really helpful variable provided in the Input class! The variable is called keyString, and registers the last 100 keys that were written by the user. This way, we can retrieve the string to know what the user typed. The simplest way is to add an update function to our textField, add all the keys in the variable to our text, and clear the variable so we don’t duplicate the keys we already retrieved.

    
    
    		override public function update():void
    		{
    			super.update();
    
    			if (Input.keyString != "")
    			{
    				text += Input.keyString;
    				Input.keyString = "";
    			}
    		}
    

    Step 28: Erasing Text and Multiline Text

    One thing the Input keyString variable doesn’t support is erasing text. We must add the functionality by hand. But it’s really easy, we just check if the backspace key was pressed, and if it was, delete a character from the string.

    
    
    		override public function update():void
    		{
    			super.update();
    
    			if (Input.keyString != "")
    			{
    				text += Input.keyString;
    				Input.keyString = "";
    			}
    
    			if (Input.pressed(Key.BACKSPACE)) text = _text.substr(0, _text.length - 1);
    		}
    

    The problem is that this method won’t erase if the user keeps the backspace key pressed. To do so, we will use a KeyboardEvent, which we will add to the stage. We will also remove the event when the text input is removed, and it won’t do anything if it detects the current world is not the world the text is in.

    
    
    		override public function added():void
    		{
    			super.added();
    
    			FP.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    		}
    
    		protected function onKeyDown(e:KeyboardEvent):void
    		{
    			if (world != FP.world) return;
    			if (e.keyCode != Key.BACKSPACE) return;
    
    			text = _text.substr(0, _text.length - 1);
    		}
    
    		override public function removed():void
    		{
    			super.removed();
    
    			FP.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    		}
    

    From here, adding multiline is really simple. We just need to check for the Enter key on the onKeyDown function, and insert the "\n" character to the string:

    
    
    		protected function onKeyDown(e:KeyboardEvent):void
    		{
    			if (world != FP.world) return;
    
    			if (e.keyCode == Key.BACKSPACE) text = _text.substr(0, _text.length - 1);
    			else if (e.keyCode == Key.ENTER) text += "\n";
    		}
    

    We could even add a boolean to allow or not multiline. This way we can have the “textfields” and the “textareas”. First, we add it to our variables and ask it as an optional parameter for the constructor:

    
    
    		protected var multiline:Boolean = false;
    
    		public function TextInput(x:Number=0, y:Number=0, text:String = "", multiline:Boolean = false)
    		{
    			super(x, y);
    
    			this.multiline = multiline;
    
    			textGraphic = new Text("", 0, 0, { size: 16, color: 0xFFFFFF } );
    			this.text = text;
    			graphic = textGraphic;
    		}
    

    Then, we just add the check to the onKeyDown function.

    
    
    		protected function onKeyDown(e:KeyboardEvent):void
    		{
    			if (world != FP.world) return;
    
    			if (e.keyCode == Key.BACKSPACE) text = _text.substr(0, _text.length - 1);
    			else if (e.keyCode == Key.ENTER && multiline) text += "\n";
    		}
    

    Now, if you add a multiline textfield to your world, this is approximately what you will see:


    Step 29: Multiple Text Operations

    If you try adding two TextI

  5. Michael James Williams says:
    April 28, 2012 at 7:36 pm

    The newest Adobe Creative Suite has been announced. It’ll be available to purchase on May 7th; let’s take a look at what’s new for Flash app and game developers.


    What’s New in Flash Professional CS6?

    Most of the big new features in the flagship Flash software do not involve Flash Player at all; the one exception seems to be integration with Starling, the Stage3D library for 2D assets which we’ve covered before. Other than that, the emphasis is on mobile and HTML5 development.

    A new mobile simulator lets you emulate tilting and rotating a phone (affecting the acceleromoter and the screen orientation), as well as touch gestures such as pinch-to-zoom. There are also new debugging features. I’ll let Mobiletuts+ go into more detail on these additions!

    Flash Pro CS6 also has the ability to export to the HTML5 library CreateJS, which we’ve also covered before under the name EaselJS. No, this doesn’t mean you can take an existing Flash app or game and create an HTML5 canvas version, but you can export animations, images, and sounds, both from the stage and from the library, into clean JavaScript format.

    Along similar lines, movie clips can also be exported to sprite sheets, which will be useful for game development in both HTML5 and Flash Player (as well as pretty much any other platform, for that matter).


    What About Flash Builder and Flash Catalyst?

    Flash Builder is not a “Creative Suite” product – it doesn’t have the CS name – so it runs on a different upgrade schedule. This means it’s not going to be updated to coincide with the CS6 launch. It has been dropped from the Web Premium suite, however, since the Web Premium suite no longer exists (it’s been combined with Design Premium to form Web and Design Premium), but it’s still available in the Master Collection.

    Flash Catalyst, on the other hand, has been dropped; there will not be a Flash Catalyst CS6.


    Creative Cloud

    CS6 in general also sees the launch of the Adobe Creative Cloud; in brief, this allows you to pay an ongoing subscription fee to get every single CS6 app. For some people, this will be a much more attractive or convenient option than buying the entire Suite as a set of software – especially as there’s no additional fee to get future updates.


    What Do You Think?

    Personally, I think it’s interesting (but not at all surprising) that CS6 does not have much to offer programmers. I feel that’s been the case with Flash Professional for a while now; the Flash Platform and AS3 are not constrained to the 18- or 12-month Creative Suite release schedule, and FlashDevelop, Flash Builder and FDT are far better tools for coding anyway. (With that in mind, I am surprised that Flash Builder is not included in the Design and Web Premium bundle.)

    The new sprite sheet and CreateJS export features will be useful for developers that want to port old Flash projects to Stage3D, mobile, HTML5, or other platforms, as well as for designers that work with non-Flash developers but want to keep their familiar Flash workflow. This isn’t something that interests me enough to upgrade, personally, but I don’t think it’s a bad idea.

    What about you?



  6. Jesse Freeman says:
    April 28, 2012 at 8:06 pm
    This entry is part 2 of 3 in the series An ImpactJS Overview

    In this video I will briefly go over one of my Impact games, how I set up some of the core logic and discuss how Impact’s level editor works. Creating games with Impact is incredibly straight forward but with the tips from this video you will get a sense of what a final game looks like, how it’s organized as well as some helpful tricks when it comes to working with the level editor.


    Watch the Screencast

    You can also download the video to watch later.


    More Info and Links


    Click here to play Resident Raver

    To learn more about Impact visit http://ImpactJS.com and check out a copy of my book on Impact called Introducing HTML5 Game Development, published by O’Reilly.

    You can also play the Resident Raver game at http://gamecook.com/games/resident-raver/.


  7. Jesse Freeman says:
    April 28, 2012 at 8:23 pm
    This entry is part 1 of 3 in the series An ImpactJS Overview

    Impact is an incredibly powerful HTML5 game framework which takes advantage of modern browser’s canvas element and can also run on mobile or be compile into a native iOS app. In this video I will go over the framework, how to set up a project, some background into how to create classes in it and finally go over the core classes that make up the framework. This is a high level overview which will give you a general sense for how things work.


    Watch the Screencast

    You can also download the video to watch later.


    More Info and Links

    To learn more about Impact visit http://ImpactJS.com and check out a copy of my book on Impact called Introducing HTML5 Game Development, published by O’Reilly.

    • Conner Petzol’s nodejs module for Impact: https://github.com/cpetzold/node-impact
    • Mike Hamtilon’s ImpactJS-IIS-.NET-API project: http://code.google.com/p/impactjs-iis-backend/
    • Chris Darroch’s Sinatra backend for Impact: https://github.com/chrisdarroch/impactrb
    • John Resig’s Simple JavaScript Inheritance: http://ejohn.org/blog/simple-javascript-inheritance/
    • There are three more videos in this mini-series, and we’ll be posting them all this week, so come back later for more!


  8. Collis says:
    April 28, 2012 at 9:03 pm

    It’s a month of new beginnings over at our design and inspiration gallery Creattica. April has seen the site undergo a complete redesign with a whole new streamlined grid-style layout for its over 50 different categories. On top of that, Creattica now has better navigation, a new UI Elements section and a growing Freebies area of now over 700 items. All this and over 14,000 featured works from some 100,000 members. It’s quite the site!

    But that’s not all, let’s first take a look at some of Creattica’s top Flash website work – and then stay tuned for some exciting news at the conclusion!

    1. Interactive agency portfolio

    2. Oblique FX

    3. THE INCREDIBLE POLO

    4. Taua Design

    5. Ben Fragau Photography

    6. Offices in Greenford

    7. iLussori Multimedia

    8. Joe Dowdle

    9. Karim Balaa – Fresh Contrast

    10. Puppetbrain

    11. The wishes greenhouse

    12. Portfolio: Joonas Paloheimo

    13. The Italian Experience 2010 – First Edition

    14. Interni Design Studio

    15. Flash site for wedding photographer


    The Future of Creattica

    When we started Creattica (originally Faveup) back in 2007, we wanted it to be one on the top inspiration galleries on the web. And as the site has grown and changed over the years, we find ourselves with what has become one of the biggest, broadest and most in-depth galleries of design out there. So I guess we can say – mission accomplished!

    Over these past few months, Envato has really started working on focusing on our core products of Marketplaces and Tuts+ sites. So while we love Creattica, we find ourselves in the regrettable position of having to put the site up for sale soon. We really want it to go to an awesome home, so if anyone would like to express interest in the sale or get more details, please contact us here.

    I’m certain we’ll find some new owners who can keep Creattica growing and evolving on into the future. And in the meantime I hope you enjoy the new design and all the gorgeous work as much as I do!


  9. Cadin Batrack says:
    April 28, 2012 at 9:33 pm

    In this tutorial we’ll make a reusable countdown timer with a dynamic target date that can be set via XML. We’ll animate the numbers flipping down in the style of an old airport or train station status board. We’ll cover code, graphics creation and animation.

    May of 2010


    Step 1: Set Up Your Flash File

    Create a new Flash file (Actionscript 3) with these settings: 500×300, black background, and 30 fps.

    Flash file setup

    Step 2: Create the digit_bottom MovieClip

    Create a new MovieClip called ‘digit_bottom’ and draw a rounded rectangle inside it approximately 36px wide by 50px tall. (A quick way to draw a rectangle with precise dimensions is to select the rectangle tool and Alt-click on the stage.)

    Give the rectangle a gradient fill from #111111 (top) to #333333 (bottom) and a 2 px outline colored #333333.

    Background image or animation

    Step 3: Position the Rectangle

    Position the rectangle so that the registration point of the MovieClip (the little ‘+’) is exactly halfway between the top and bottom and the left edge. If you made your rectangle 50px tall, then the y value should be -25.

    Rectangle Properties

    Step 4: Add the Number

    Create a new layer and add a dynamic text field called ‘t_num’. Choose a font that has an airport or train station feel to it (like Helvetica, DIN, or Interstate). I’m using Helvetica Bold.

    Set the Paragraph Format to centered, and remember to embed the fonts for the numbers 0–9.

    Position the text field so it’s centered on the background rectangle.

    Number text field

    We’re going to be using this MovieClip as the base for another graphic, so take a moment to make sure it looks good.


    Step 5: Add a Mask

    Create a new layer on the timeline of the digit_bottom MovieClip and call it ‘mask’. Copy the rounded rectangle and Paste in Place on the mask layer (Edit > Paste in Place, or Command-Shift-V).

    Select the top half of the mask rectangle and delete it.

    Right-click the mask layer, choose Mask and make sure that it is masking all of the layers below it.

    Create the Mask

    Step 6: Create the digit_top MovieClip

    Go into the Library, duplicate the digit_bottom MovieClip and name the new copy ‘digit_top’.

    This MovieClip will be virtually identical to the digit_bottom clip, except the mask will be showing the top half of the graphics instead of the bottom.

    Delete the graphics currently on the mask layer. Copy the rounded rectangle and again Paste in Place on the mask layer. This time select the bottom half and delete it.

    The only other adjustment you might want to make here is to adjust the color of the text and the shading of the background rounded rectangle. I made the graphics in my digit_top clip a bit darker to simulate light coming from the top.

    digit_top and digit_bottom clips

    Step 7: Create the Digit MovieClip

    Create a new MovieClip named ‘Digit’. Drag in the digit_top and digit_bottom MovieClips and position them both at 0,0. Give them the instance names ‘top1′ and ‘bottom1′.

    Now copy both of the MovieClips (digit_top and digit_bottom), create a new layer, and Paste in Place a copy of each. Name the new copies ‘top2′ and ‘bottom2′.

    You should now have 4 MovieClips inside your Digit MovieClip: 2 copies of digit_top and 2 copies of digit_bottom. I’ll explain why we’re setting it up like this in the next step.


    Step 8: Animation Strategy

    We have to do a bit of animation trickery to get the flipping numbers effect we want. Take a look at the diagram below of our Digit MovieClip (I’m rendering it in 3D just so you can see the layering more easily):

    Digit Animation Diagram

    Animation Step 1:

    We start out with the bottom2 clip flipped upside down (using the scaleY property) and placed behind the top2 clip. At this point the 2 clips that are visible are top2 and bottom1. The numbers on these two clips correspond to each other, so they form a complete digit.

    Animation Step 2:

    Now we flip down the top2 clip to the center of the digit. At this point scaleY will be zero, so the clip won’t be visible. At the same time, we’re also flipping down the bottom2 clip, but this one we’ll flip all the way to the bottom. Since it’s behind top2, it won’t show until it flips past the halfway point. Now the 2 visible clips are top1 and bottom1. The numbers on these two clips don’t match, but that’s okay because this step only lasts for a brief moment.

    Animation Step 3:

    The top2 clip stays in the center as bottom2 continues to fall all the way down to the bottom. Once it’s in place the numbers on the visible clips (top1 and bottom2) again match to form a complete digit.

    Animation Step 4:

    At this point we’ll relayer and reset the positions of the 2 hidden clips to get ready for the next flip. Notice how the clips are in the same positions as Step 1, only reversed.


    Step 9: Create the Clock MovieClip

    Now that we have the individual Digit MovieClip set up, let’s build the clock.

    Create a new MovieClip on the stage called ‘Clock’ with the instance name ‘clock’. Inside the new MovieClip place 9 copies of your Digit MovieClip; 2 for seconds, 2 for minutes, 2 for hours, and 3 for days. Give each digit an instance name. From left to right name them ‘digit0′, ‘digit1′, ‘digit2′, and so on.

    Add some colons to separate the MovieClips and labels for each section. The design is up to you. I added a dark rounded rectangle as a background for my clock.

    Lastly, add a dynamic text field called ‘t_date’. This is where we’ll show the target date the clock is counting down to. Remember to embed the font for this text field if you’re not using a system font.

    Clock MovieClip

    Step 10: Create the Digit Class

    Create a new Actionscript file called ‘Digit.as’ and add this code to create the empty shell for the class:

    package {
    
    	import flash.display.MovieClip;
    
    	public class Digit extends MovieClip {
    		private const TOP:int = 0;
    		private const BOTTOM:int = 1;
    
    		private var _currentDigit:Array;
    		private var _nextDigit:Array;
    		private var _number:String = "0";
    
    		// CONSTRUCTOR
    		public function Digit() {
    			_currentDigit = new Array( top1, bottom1 );
    			_nextDigit = new Array( top2, bottom2 );
    
    		}
    
    	}
    
    }
    

    This doesn’t do much yet. We’ve got a couple of arrays to hold the 2 sets of digit_top and digit_bottom MovieClips. I’ve set up 2 constants, TOP and BOTTOM to help keep track of the top and bottom clips within those arrays. The _number variable will hold the digit that’s on display at any given time.

    (Note: I’m using the underscore in my variable names to indicate private variables.)

    Find your Digit MovieClip in the Library and assign this class to it in the Linkage settings.

    Digit Class Linkage Settings

    Step 11: Import the TweenLite Library

    We’re going to be using the TweenLite library to animate our Digit MovieClip.

    Download the AS3 version of the TweenLite library here.

    Place the ‘com’ folder in the same directory as your main Flash file (or in your source path, if you’ve set up a different class path).

    Add these two lines at the top of your Digit class, just below the MovieClip import:

    import com.greensock.*
    import com.greensock.easing.*
    

    We’re barely going to scratch the surface of what TweenLite can do in this tutorial. For more information check out the TweenLite Documentation.


    Step 12: Program the flipTo Animation

    Add this function to your Digit class:

    public function flipTo(num:String):void {
    	_number = num;
    	_nextDigit[TOP].t_num.text = num;
    	_nextDigit[BOTTOM].t_num.text = num;
    
    	// flip down the top of the digit to the halfway point
    	TweenLite.to(_currentDigit[TOP], .15, {scaleY: 0, ease: Linear.easeNone});
    	// flip the next digit bottom down
    	TweenLite.to(_nextDigit[BOTTOM], .3, {scaleY:1, onComplete: flipComplete,  ease: Bounce.easeOut});
    }
    

    Here’s what’s happening, line by line:

    • This function accepts a String that will hold the digit we’ll be flipping to. The first line just sets our _number variable to hold that digit.
    • Next we set the text fields in the TOP and BOTTOM MovieClips in our _nextDigit array to display that same digit.
    • Then we use TweenLite to tween the scaleY property of the TOP MovieClip of the _currentDigit to 0. This gives the effect that it’s ‘falling’ toward the center of the digit.
    • The last line is another tween, this time animating the BOTTOM clip of the _nextDigit from the the top of the digit down to the bottom. Again we’re using the scaleY property to simulate this effect, but this time from -1 to 1. Since it’s tweening twice as far as the TOP clip, we give it twice the amount of time (.3 seconds instead of .15). When this tween finishes it will call a function called ‘flipComplete’. We’ll write that function in the next step.

    Take another look at the diagram in Step 8 if you’re confused about the animation here.


    Step 13: Add the flipComplete() Function

    Add this function to the Digit class just below the flipTo function:

    private function flipComplete():void {
    	// swap digits
    	var next:Array = _currentDigit;
    	_currentDigit = _nextDigit;
    	_nextDigit = next;
    
    	// reset layering
    	reset();
    }
    

    Once the flip animation completes we’ll run this function. It swaps the _currentDigit and _nextDigit arrays. After that’s done it calls a function named ‘reset’ to reset the clip layering and positions for the next flip. Let’s write that function now.


    Step 14: Add the reset() Function

    Add this function to the Digit class:

    private function reset():void {
    	addChild(_nextDigit[BOTTOM]);
    	addChild(_currentDigit[TOP]);
    
    	// flip up the next bottom to be behind the current top
    	_nextDigit[BOTTOM].scaleY = -1;
    	_nextDigit[TOP].scaleY = 1;
    }
    

    The first two lines in this function pop the _nextDigit BOTTOM and then the _currentDigit TOP to the top of the display list. I usually just use addChild() to do this because it requires less typing than using setChildIndex().

    After the clips are re-layered, we set the scaleY properties so they’ll be ready for the next flip. This means changing _nextDigit[BOTTOM] from 1 to -1 and _nextDigit[TOP] from 0 to 1.

    Again, check the diagram in Step 8 if you’re getting lost.


    Step 15: Add to the Constructor

    One thing we forgot to do is position the clips properly for the first flip animation. We can do that easily by adding a call to the reset function right in the Digit class constructor:

    // CONSTRUCTOR
    public function Digit() {
    	_currentDigit = new Array( top1, bottom1 );
    	_nextDigit = new Array ( top2, bottom2 );
    
    	reset();
    }
    

    Step 16: Add the number() Function

    One last thing we’ll need in our Digit class is a way to access the private _number variable from outside the class. We’ll add a simple accessor function:

    public function get number():String {
    	return _number;
    }
    

    Step 17: Create the Clock Class

    Create a new ActionScript file named ‘Clock.as’. Paste in this code:

    package {
    
    	import flash.display.MovieClip;
    	import flash.events.TimerEvent;
    	import flash.media.Sound;
    	import flash.utils.Timer;
    
    	public class Clock extends MovieClip {
    		private var _clockTimer:Timer;
    		private var _targetDate:Date;
    
    		// CONSTRUCTOR
    		public function Clock() {
    
    		}
    
    	}
    
    }
    

    Not much here yet. Just importing some of the classes we’ll need. I also have a couple of private variables. _clockTimer will count down the seconds for us, and _targetDate will hold the date that we’re counting down to.


    Step 18: Add the set() Function

    Add this function to the Clock class just below the constructor:

    // set the target date and start the countdown timer
    public function set(date:Date):void {
    	_targetDate = date;
    
    	_clockTimer = new Timer(1000) // tick every second (1000 milliseconds)
    	_clockTimer.addEventListener(TimerEvent.TIMER, update);
    	_clockTimer.start();
    
    	// display the target date above the clock
    	t_date.text = _targetDate.toLocaleString().toUpperCase();
    
    	// update the clock once here so it starts with the correct time
    	update();
    }
    

    This is the function that we’ll use to set the target date for the clock. It accepts a date (of course) and assigns that to the _targetDate variable. It then instantiates our _clockTimer. The _clockTimer will call the update function once per second to update the digits.

    After starting the timer, the function sets the t_date text with the target date. The toLocaleString() function ensures the date is displayed in the user’s local time zone.

    The last line of this function calls update once to set the clock to the proper time. Otherwise it would display “000 00:00:00″ for one second until the first timer event.


    Step 19: Add the update() Function

    This function is a bit long because it’s where most of the work gets done. Add it to your Clock class:

    private function update(e:TimerEvent = null):void {
    	var now:Date = new Date(); // get the current time
    
    	// find the difference (in ms) between the target and now
    	var diff:Number = _targetDate.valueOf() - now.valueOf();
    	if(diff <=0){
    		// TIME'S UP!
    		// do something cool here
    		_clockTimer.stop();
    		_clockTimer.removeEventListener(TimerEvent.TIMER, update);
    		diff = 0;
    	}
    
    	// convert to seconds
    	diff = Math.round(diff/1000);
    
    	// number of days
    	var days:int = Math.floor(diff/ (24 * 60 * 60));
    	diff -= days*(24 * 60 * 60 );
    
    	// number of hours
    	var hours:int = Math.floor(diff / (60 * 60))
    	diff -= hours*60 * 60;
    
    	// number of minutes
    	var min:int = Math.floor(diff/ 60);
    	diff -= min*60;
    
    	// seconds are all that remain
    	var sec:int = diff;
    
    	// create an array of strings to hold the number for each value
    	var diffArr:Array = new Array(String(days), String(hours), String(min), String(sec));
    	var diffString:String = ""
    	var len:int = 3; // the first value (days) has 3 digits. All the rest have 2
    	for each(var s:String in diffArr){
    		// pad the string with a leading zero if needed
    		while(s.length < len){
    			s = "0"+s;
    		}
    
    		len = 2; // all the other values are 2 digits in length
    		diffString += s; // add the padded string to the diffString
    	}
    
    	// go through each character in the diffString and set the corresponding digit
    	for(var i:int = 0; i< diffString.length; i++){
    		if(diffString.substr(i, 1) != this["digit"+i].number){
    			this["digit"+i].flipTo(diffString.substr(i, 1));
    		}
    	}
    
    }
    

    This function accepts a TimerEvent as its parameter. The default value for this parameter is null. This allows us to call the function without sending a parameter, as we’re doing in the set function.

    The first line of this function gets the current date and time as a Date object. Next, we find the difference between the current date and the target date (line 37). If the difference is 0 or less, then it’s past the target date, so we stop the _clockTimer (lines 38-44).

    Since the difference in time between now and the target is calculated in milliseconds, we need to convert that into a nice readable display of days, hours, minutes, and seconds (lines 46-62). The math here is pretty simple as long as you know that there are 1000 milliseconds in a second, 60 seconds in a minute, 60 minutes in an hour and 24 hours in a day.

    On line 65 we store all those values as elements in an array. Starting on line 68 we loop through each element and add it to a String of characters called ‘diffString’. While doing this we also add leading zeroes where necessary (line 71). So if our values for the clock were 30 days, 5 hours, 56 minutes, and 6 seconds the diffString would look like this: “030055606″.

    The last thing this function does is loop through the characters in the diffString (using the charAt() method). For each character in the string we check to see if it’s different from the number currently displayed on the corresponding digit. This is easy because of the way we named our digit instances. If the number is not the same as the one currently displayed we tell that digit to flip to the number in the diffString.


    Step 20: Add Sound

    Find (or create) a good ticking sound that will play every time the clock updates. Import it into the Library of your Flash file and set the class name to ‘TickSound’ in the Linkage settings.

    Tick Sound Linkage Settings

    Add the _tickSound variable to the top of your Clock class just below the two other variables:

    private var _clockTimer:Timer;
    private var _targetDate:Date;
    private var _tickSound:Sound = new TickSound();
    

    And play the sound inside the update function:

    _tickSound.play();
    

    Step 21: Add the Main Document Class

    Our countdown timer is complete, we just need some way to set the target date. Create a new Actionscript file called ‘Main.as’ with this code:

    package {
    
    	import flash.display.MovieClip;
    
    	public class Main extends MovieClip {
    
    		public function Main() {
    
    			// set the target date for the clock
    			var targetDate:Date = new Date();
    			targetDate.setTime( Date.UTC(2010, 4, 28, 20, 00) );
    			clock.set(targetDate);
    		}
    	}
    
    }
    

    All this does is set the target date for the Clock instance on the Stage. I’m using setTime() and Date.UTC() to convert the date to Universal Timecode. This way the date will be correct when it gets converted back to local time on the user’s computer. Also, remember that the months are zero-based. So, the month 4 is actually May, not April.

    In your Flash file set the Document class to ‘Main’.

    Set the Document Class

    If you need a refresher on using the Document Class check out this Quick Tip.


    Step 22: Test

    Test your movie now and everything should work. Try changing the target date in the Main class and see how the countdown changes.

    One potential downside to how we’ve set this up is that the target date is hard-coded in our SWF. That’s fine, but it would be cool if we could dynamically load the date so that we could reuse the countdown for different things.

    Let’s see what we can do about that…


    Step 23: Create the XML File

    Create a new XML file in the same folder as your Flash file called ‘targetDate.xml’ (an XML file is just a plain text file). Add this to the XML file:

    <targetDate>
    	<year>2011</year>
    	<month>3</month>
    	<day>25</day>
    	<hour>20</hour>
    	<minute>21</minute>
    </targetDate>
    

    Using this format for our target date is pretty bloated (there is more markup than there is actual data), but it will keep things very clear for the purposes of this tutorial.


    Step 24: Load the XML

    Now let’s make some changes to our Main document class. Replace everything in that file with this code:

    package {
    
    	import flash.display.MovieClip;
    	import flash.net.URLLoader;
    	import flash.net.URLRequest;
    	import flash.events.Event;
    
    	public class Main extends MovieClip {
    
    		// CONSTRUCTOR
    		public function Main() {
    			// load the XML
    			var xmlLoader:URLLoader = new URLLoader();
    			xmlLoader.addEventListener(Event.COMPLETE, onDataLoaded);
    			xmlLoader.load( new URLRequest("targetDate.xml") );
    
    		}
    
    	}
    
    }
    

    You’ll notice we’ve imported some additional classes to help us load the XML file. In the constructor function we’re creating a new URLLoader instance to load the file for us. We attach an event listener that will call a function named ‘onDataLoaded’ when the file is finished loading.


    Step 25: Add the onDataLoaded() Function

    Add this function to the Main class:

    private function onDataLoaded(e:Event):void {
    	var xml:XML = new XML(e.target.data);
    
    	var targetDate:Date = new Date();
    	targetDate.setTime(Date.UTC(int(xml.year), int(xml.month), int(xml.day), int(xml.hour), int(xml.minute) ));
    
    	clock.set(targetDate);
    }
    

    This function creates a new XML object from the file we loaded. We then create a new Date object from the values in the XML. We’re again using setTime() and Date.UTC() to convert the date to Universal Timecode. The final line is the same as before, it just sends the target date to our Clock instance.


    Step 26: Wrap Up

    That’s pretty much it for this one. There are a couple of enhancements you might like to make though:

    1. Depending on what you’re using the countdown for, you might want to do something special for the user when the countdown hits zero. You’d add this to the Clock class in the part of the update function that checks if the timer is at zero.
    2. As I mentioned, the format of our XML is pretty wasteful as it is. You might rather just pass in the date as a string via FlashVars, use a different data format (like JSON), or just reformat the XML to be a bit more compact.

    Good luck! As always, post a comment and let me know what you think.


  10. Jason Killian says:
    April 28, 2012 at 10:00 pm

    Bitwise operators are those strange looking operators that may look hard to understand… but not any more! This easy to follow article will help you understand what they are and how to use them, with a couple of practical examples as well to show you when and why you’d need them.


    Introduction

    Bitwise operators are operators (just like +, *, &&, etc.) that operate on ints and uints at the binary level. This means they look directly at the binary digits or bits of an integer. This all sounds scary, but in truth bitwise operators are quite easy to use and also quite useful!

    It is important, though, that you have an understanding of binary numbers and hexadecimal numbers. If you don’t, please check out this article – it will really help you! Below is a little application that will let you try out the different bitwise operators.

    Don’t worry if you don’t understand what is going on yet, it will all be clear soon…


    Recognizing the Bitwise Operators

    Let’s take a look at the bitwise operators that AS3 supplies. Many other languages are quite similar (for example, JavaScript and Java have practically identical operators):

    • & (bitwise AND)
    • | (bitwise OR)
    • ~ (bitwise NOT)
    • ^ (bitwise XOR)
    • << (bitwise left shift)
    • >> (bitwise right shift)
    • >>> (bitwise unsigned right shift)
    • &= (bitwise AND assignment)
    • |= (bitwise OR assignment)
    • ^= (bitwise XOR assignment)
    • <<= (bitwise left shift and assignment)
    • >>= (bitwise right shift and assignment)
    • >>>= (bitwise unsigned right shift and assignment)

    There are a couple of things you should take from this: First, some bitwise operators look similar to operators you’ve used before (& vs. &&, | vs. ||). This is because they are somewhat similar.

    Second, most bitwise operators come with a compound assignment form of themselves. This is the same as how you can use + and +=, – and -=, etc.


    The & Operator

    Up first: the bitwise AND operator, &. A quick heads-up though: normally, ints and uints take up 4 bytes or 32 bits of space. This means each int or uint is stored as 32 binary digits. For the sake of this tutorial, we’ll pretend sometimes that ints and uints only take up 1 byte and only have 8 binary digits.

    The & operator compares each binary digit of two integers and returns a new integer, with a 1 wherever both numbers had a 1 and a 0 anywhere else. A diagram is worth a thousand words, so here’s one to clear things up. It represents doing 37 & 23, which equals 5.

    Bitwise And operator example

    Notice how each binary digit of 37 and 23 are compared, and the result has a 1 wherever both 37 and 23 had a 1, and the result has a 0 otherwise.

    A common way of thinking about binary digits is as true or false. That is, 1 is equivalent to true and 0 is equivalent to false. This makes the & operator make more sense.

    When we compare two booleans, we normally do boolean1 && boolean2. That expression is only true if both boolean1 and boolean2 are true. In the same way, integer1 & integer2 is equivalent, as the & operator only outputs a 1 when both binary digits of our two integers are 1.

    Here’s a table that represents that idea:

    Bitwise AND table

    A neat little use of the & operator is to check whether a number is even or odd. For integers we can simply check the rightmost bit (also called the least significant bit) to determine if the integer is odd or even. This is because when converting to base 10, the rightmost bit represents 20 or 1. When the rightmost bit is 1, we know that our number is odd since we’re adding 1 to a bunch of powers of two which will always be even. When the rightmost bit is 0, we know our number will be even, since it simply consists of adding up a bunch of even numbers.

    Here’s an example:

    
    
    var randInt:int = int(Math.random()*1000);
    if(randInt & 1)
    {
    	trace("Odd number.");
    }
    else
    {
    	trace("Even number.");
    }
    

    On my computer, this method was about 66% faster than using randInt % 2 to check for even and odd numbers. That’s quite a performance boost!


    The | Operator

    Up next is the bitwise OR operator, |. As you may have guessed, the | operator is to the || operator as the & operator is to the && operator. The | operator compares each binary digit across two integers and gives back a 1 if either of them are 1. Again, this is similar to the || operator with booleans.

    Bitwise OR table

    Let’s take a look at the same example as before, except now using the | operator instead of the & operator. We’re now doing 37 | 23 which equals 55:

    Bitwise OR table

    Flags: A Use of the & and | Operators

    We can take advantage of the & and | operators to allow us to pass multiple options to a function in a single int.

    Let’s take a look at a possible situation. We’re building a pop-up window class. At the bottom of it, we can have a Yes, No, Okay, or Cancel button or any combination of those – how should we do this? Here’s the hard way:

    
    
    public class PopupWindow extends Sprite
    {
    	// Variables, Constructor, etc...
    
    	public static void showPopup(yesButton:Boolean, noButton:Boolean, okayButton:Boolean, cancelButton:Boolean)
    	{
    		if(yesButton)
    		{
    			// add YES button
    		}
    
    		if(noButton)
    		{
    			// add NO Button
    		}
    		// and so on for the rest of the buttons
    	}
    }
    

    Is this horrible? No. But it is bad, if you’re a programmer, to have to look up the order of arguments every time you call the function. It’s also annoying – for example, if you only want to show the Cancel button, you have to set all the other Booleans to false.

    Let’s use what we learned about & and | to make a better solution:

    
    
    public class PopupWindow extends Sprite
    {
    	public static const YES:int = 1;
    	public static const NO:int = 2;
    	public static const OKAY:int = 4;
    	public static const CANCEL:int = 8;
    
    	public static void showPopup(buttons:int)
    	{
    		if(buttons & YES)
    		{
    			// add YES button
    		}
    
    		if(buttons & NO)
    		{
    			// add NO button
    		}
    	}
    }
    

    How would a programmer call the function so the Yes button, No button, and Cancel button are showing? Like this:

    
    
    PopupWindow.show(PopupWindow.YES | PopupWindow.NO | PopupWindow.CANCEL);
    

    What’s going on? It’s important to note that our constants in the second example are all powers of two. So, if we look at their binary forms, we will notice they all have one digit equal to 1, and the rest equal to 0. In fact, they each have a different digit equal to 1. This means that no matter how we combine them with |, every combination will give us a unique number. Looking at it in a different way, out result of our | statement will be a binary number with a 1 wherever our options had a 1.

    For our current example we have PopupWindow.YES | PopupWindow.NO | PopupWindow.CANCEL which is equivalent to 1 | 2 | 8 which rewritten in binary is 00000001 | 00000010 | 00001000 which gives us a result of 00001011.

    Now, in our showPopup() function, we use & to check which options were passed in. For example, when we check buttons & YES, all the bits in YES are equal to 0 except the very rightmost one. So, we are essentially checking if the rightmost bit in buttons is a 1 or not. If it is, buttons & YES will not equal 0 and anything in the if statement will be executed. Conversely, if the rightmost bit in buttons is 0, buttons & YES will equal 0, and the if statement will not be executed.


    The ~ Operator

    The bitwise NOT operator is slightly different than the two we’ve looked at so far. Instead of taking an integer on each side of it, it takes an integer only after it. This is just like the ! operator, and, not surprisingly, it does a similar thing. In fact, just as ! flips a boolean from true to false or vice versa, the ~ operator reverses each binary digit in an integer: from 0 to 1 and 1 to 0:

    Bitwise OR table

    A quick example. Say we have the integer 37, or 00100101. ~37 is then 11011010. What’s the base 10 value of this? Well…


    Two’s Complement, uint vs. int, and More!

    Now the fun begins! We’re going to take a closer look at binary numbers on a computer. Let’s start with the uint. As mentioned before, a uint is typically 4 bytes or 32 bits long, meaning it has 32 binary digits. This is easy to understand: to get the base 10 value we simply convert the number to base 10 regularly. We’ll always get a positive number.

    But how about the int? It also uses 32 bits, but how does it store negative numbers? If you guessed that the first digit is used to store the sign, you’re on the right path. Let’s take a look at the two’s complement system for storing binary numbers. While we won’t go into all the details here, a two’s complement system is used because it makes binary arithmetic easy.

    To find the two’s complement of a binary number, we simply flip all the bits (i.e. do what the ~ operator does) and add one to the result. Let’s try this out once:

    Two's Complement of 37

    We then define our result as the value -37. Why do this complicated process and not just flip the very first bit and call that -37?

    Well, let’s take a simple expression 37 + -37. We all know this should equal 0, and when we add the 37 to its two’s complement, that’s what we get:

    37 + -37 in binary

    Notice that since our integers only hold eight binary digits, the 1 in our result is dropped, and we end up with 0, as we should.

    To recap, to find the negative of a number, we simply take its two’s complement. We can do this by inverting all the bits and adding one.

    Want to try this yourself? Add trace(~37+1); to an AS3 file, then compile and run it. You’ll see -37 is printed, as it should be.

    There is also a little shortcut to do this by hand: starting from the right, work to the left until you reach a 1. Flip all the bits to the left of this first 1.

    Two's Complement of 37 Shortcut

    When we’re looking at a signed binary number (in other words, one that can be negative, an int not a uint), we can look at the leftmost digit to tell whether it’s negative or positive. If it’s a 0, then the number is positive and we can convert to base 10 simply by calculating its base 10 value. If the leftmost bit is a 1, then the number is negative, so we take the two’s complement of the number to get its positive value and then simply add a negative sign.

    For example, if we have 11110010, we know it is a negative number. We can find it’s two’s complement by flipping all the digits to the left of the rightmost 1, giving us 00001110. This equals 13, so we know 11110010 equals -13.


    The ^ Operator

    We’re back to the bitwise operators, and up next is the bitwise XOR operator. There is no equivalent boolean operator to this one.

    The ^ operator is similar to the & and | operators in that it takes an int or uint on both sides. When it is calculating the resulting number, it again compares the binary digits of these numbers. If one or the other is a 1, it will insert a 1 in to the result, otherwise it will insert a 0. This is where the name XOR, or “exclusive or” comes from.

    Bitwise XOR table

    Let’s take a look at our usual example:

    Bitwise XOR example

    The ^ operator does have uses – it’s especially good for toggling binary digits – but we won’t cover any practical applications in this article.


    The << Operator

    We’re now on the bitshift operators, specifically the bitwise left shift operator here.

    These work a little differently than before. Instead of comparing two integers like &, |, and ^ did, these operators shift an integer. On the left side of the operator is the integer that is being shifted, and on the right is how much to shift by. So, for example, 37 << 3 is shifting the number 37 to the left by 3 places. Of course, we’re working with the binary representation of 37.

    Let’s take a look at this example (remember, we’re just going to pretend integers only have 8 bits instead of 32). Here we have the number 37 sitting on its nice block of memory 8 bits wide.

    Bitwise Left Shift example

    Alright, let’s slide all the digits over to the left by 3, as 37 << 3 would do:

    Bitwise Left Shift example

    But now we have a small problem – what do we do with the 3 open bits of memory where we moved the digits from?

    Bitwise Left Shift example

    Of course! Any empty spots are just replaced with 0s. We end up with 00101000 . And that’s all there is to the left bitshift. Keep in mind that Flash always thinks the result of a left bitshift is an int, not a uint. So if you need a uint for some reason, you’ll have to cast it to a uint like this: uint(37 << 3). This casting doesn’t actually change any of the binary information, just how Flash interprets it (the whole two’s complement thing).

    An interesting feature of the left bitshift is that it is the same as multiplying a number by two to the shiftAmount-th power. So, 37 << 3 == 37 * Math.pow(2,3) == 37 * 8. If you can use the left shift instead of Math.pow, you’ll see a huge performance increase.

    You may have noticed that the binary number we ended up with did not equal 37 * 8. This is just from our use of only 8 bits of memory for integers; if you try it in ActionScript, you’ll get the correct result. Or, try it with the demo at the top of the page!


    The >> Operator

    Now that we understand the left bitshift, the next one, the right bitshift, will be easy. Everything slides to the right the amount we specify. The only slight difference is what the empty bits get filled with.

    If we’re starting with a negative number (a binary number where the leftmost bit is a 1), all the empty spaces are filled with a 1. If we’re starting with a positive number (where the leftmost bit, or most significant bit, is a 0), then all the empty spaces are filled with a 0. Again, this all goes back to two’s complement.

    While this sounds complicated, it basically just preserves the sign of the number we start with. So -8 >> 2 == -2 while 8 >> 2 == 2. I’d recommend trying those out on paper yourself.

    Since >> is the opposite of <<, it’s not surprising that shifting a number to the right is the same as dividing it by 2 to the power of shiftAmount. You may have noticed this from the example above. Again, if you can use this to avoid calling Math.pow, you’ll get a significant performance boost.


    The >>> Operator

    Our final bitwise operator is the bitwise unsigned right shift. This is very similar to the regular bitwise right shift, except that all empty bits on the left are filled with 0s. This means the result of this operator is always a positive integer and it always treats the integer being shifted as an unsigned integer. We won’t run through an example of this in this section, but we’ll see a use for it very shortly.


    Using Bitwise Operators to Work With Colors

    One of the most practical uses of bitwise operators in Actionscript 3 is working with colors, which are stored typically as uints.

    The standard format for colors is to write them in hexadecimal: 0xAARRGGBB – each letter represents a hexadecimal digit. Here, the first two hexadecimal digits, which are equivalent to the first eight binary digits, represent our alpha, or transparency. The next eight bits represent the amount of red in our color (so an integer from 0 to 255), the next eight the amount of green, and the final eight represent the amount of blue in our color.

    Without bitwise operators, it’s extremely difficult to work with colors in this format – but with them it’s easy!

    Challenge 1: Find the amount of blue in a color: Using the & operator, try to find the amount of blue in an arbitrary color.

    
    
    public function findBlueComponent(color:uint):uint
    {
    	// Your code here!
    }
    

    We need a way to ‘erase’ or mask all the other data in color and just have the blue component left. This is easy, actually! If we take color & 0x000000FF – or, written more simply, color & 0xFF – we end up with only the blue component.

    Bitwise Left Shift example

    As you can see from above and you learned in the description of the & operator, any binary digit & 0 will always equal 0, while any binary digit & 1 will keep its value. So if we mask our color by 0xFF which only has 1s where the blue component of our color is located, we end up with just the blue component.

    Challenge 2: Find the amount of red in a color: Using two bitwise operators, try to find the amount of red in an arbitrary color.

    
    
    public function findRedComponent(color:uint):uint
    {
    	// Your code here!
    }
    

    We actually have two solutions to this problem. One would be return (color & 0xFF0000) >> 16; and the other would be return (color >> 16) & 0xFF;

    This is very similar to Challenge 1, except that we have to shift our answer at some point.

    Challenge 3: Find the transparency of a color: Using only one bitwise operator, try to find the alpha of a color (an integer from 0 to 255).

    
    
    public function findAlphaComponent(color:uint):uint
    {
    	// Your code here!
    }
    

    This one is a touch trickier. We have to be careful with which right shift operater we choose. Because we’re working with the leftmost digits of a uint, we want to use >>> operator. So, our answer simply is return color >>> 24;.

    Final Challenge: Create a color from its components: Using the << and | operators, take the components of a color and merge them in to one uint.

    
    
    public function createColor(a:uint, r:uint, g:uint, b:uint):uint
    {
    	// Your code here!
    }
    

    Here, we have to shift each component to its correct position, and then merge them. We want Flash to treat it as an unsigned integer, so we cast it to a uint: return uint((a << 24) | (r << 16) | (g << 8) | b);


    Compound Operators

    You may have noticed I have neglected to explain the compound bitwise operators. Imagine we have an integer x. Then, x = x & 0xFF is the same as x &= 0xFF, x = x | 256 is the same as x |= 256, and so on for the rest of the compound operators.


    Conclusion

    Thanks for reading this article! I hope you now understand bitwise operators and can utilize them in your AS3 code (or in many other languages!). As always, if you have any questions or comments, please leave them below.


Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Tuts+ Community Meetup in New York!
  • HTML5 Canvas Optimization: A Practical Example
  • Recreate the Cover Flow Effect Using Flash and AS3
  • Drawing Activetuts+ to a Close
  • Intro to Dart: Creating a Marquee
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Code Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2013
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
2728293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting