Archived entries for ActionScript 3.0

BasicFLAR.as
- FLARToolKit made easy

A while ago i posted my first fidlings with FLARToolkit, and promised to show more. Well since I was going to do a presentation at FUGN, I though I might as well write is down here.

FLARToolKit for me has been made possible from three sources. Saqoosha is the guy that ported the ARToolKit to ActionScript 3, and has a number of examples of his creative work at his site. Mikko Haapoja’s blog has been a fantastic resource, and Lee Brimelow’s tutorial was what kick-started me.

Here is an example of BasicFLAR.as in use, by yours truly:


The prerequisites for using my BasicFLAR class can be met by following the step called “Step 1: Download” written down by Mikko Haapoja here. Much of this post will be summarizing alot of what Mikko writes in his post, so if you have the time, you should read up on his post before continuing. Anyways, let’s get started.


The Marker

First of all, what we need to do is make a marker, for the FLAR to detect. You can either download mine here and print it out on thick paper, or build one yourself. To build it yourself you need to need to draw it first, using the guidelines Mikko Haapoja points out in his post, and print it out. When this is done you need to create a pattern file that we will later load into the FLARToolKit library. Saqoosha made an air app that creates this file for us. Simply download and install it from here. Start the app, hold your marker infront of the camera, and click “save pattern” when you see the read box forming round your pattern. Make sure you add the “.pat” extension when you save it.


The Camera Parameters

There is one more ting the FLAR is dependent on, and that is a camera parameters file. This file is a binary file that contains information that corrects lens distortion of your webcam. Mikko Explains this more in detail in his post. Just use the “camera_para.dat” file that comes with FLARToolKit, and you should be sorted.


The BasicFLAR.as

Now on to the code. Using my BasicFLAR class lets you just start doing the 3D stuff and let the FLAR stuff be taken care of by the class. Simply extend the class, and start coding, like this:



       // Import the class
       import com.perkstoveland.flar.BasicFLAR;

       public class FLARExample extends BasicFLAR
       {
              /**
              *    Constructor.
              **/
              public function FLARExample()
              {
                     // Feed the two files that FLARToolKit requires to work
                     super( "camera_para.dat", "perkmarker.pat" );
              }
       }


Now the first time you compile FLARToolKit and Papervision3D, you most likely will get an error. Mikko Haapoja, again, explains this very well here. Since the issue can result in a head-scratcher, i’ve quoted what he says about the issue:


The very first time you try to compile FlarToolkit after getting Papervision even the examples will not compile and you will get this error message:

Error: Attempted access of inaccessible property _projection through a reference with static type org.libspark.flartoolkit.pv3d:FLARCamera3D.

To fix this just go into the class-

org.papervision3d.cameras.Camera3D

And change the line-

private var _projection:Matrix3D;

to

protected var _projection:Matrix3D;

This will not break Papervision however it will just allow FlarToolkit’s FlarCamera3D to use the projection matrix of the Camera3d class.


Ok, so we go the FLARToolKit going, what we need to do now is start adding 3D objects to the stage. Since we need to load the files before BasicFLAR is ready to receive 3D objects, in our example here we override the BasicFLAR’s onInit() function, and feed the Papervision3D container with objects. Let’s create a cube that sits on the marker:

      

       import org.papervision3d.materials.ColorMaterial;
       import org.papervision3d.materials.utils.MaterialsList;
       import org.papervision3d.objects.primitives.Cube;

       //   We store the cube as a class variable,
       //   so we can manipulate it later.

       private var _cube:Cube;

       //   Next we override the onInit function, note that
       //   we  do not need to call the super's onInit() method
       //   as that method doesn't really do anything. It's
       //   there for you to override and implement.

       override protected function onInit():void
       {
              //   Create the cube materials
              var mat:ColorMaterial = new ColorMaterial();
              var matList:MaterialsList = new MaterialsList( { all: mat } );

              //   Create the cube.
              _cube = new Cube( matList, 30, 30, 30 );

              //   Since the cube's center point will be in the middle
              //   of the marker, we just want to lift it up half its
              //   height, so it is "standing" on the marker.
              _cube.z = 15;

              //   Finally we add it to BasicFLAR's container property.
              container.addChild( _cube );
       }


Finally, if we want, we can manipulate and animate the 3D objects that we just added. Again this is done by overriding an existing method in BasicFLAR, namely onFrameTick(). But this time we need to be sure to call the superclass’s method we are overriding. This method takes care of the 3D rendering and marker detecting. This is the way to do it:



       override protected function onFrameTick( $e:Event ):void
       {
              //   Roll the cube by 2 degrees each frame.
              _cube.roll( 2 );

              //   Call the super's method, and pass the event to it.
              super.onFrameTick( $e );
       }


Thats is, you should now be seeing an animated cube following the moves you make on the marker through you web cam. Below are downloads and source code for you to dig into. I’d love to see what you do with it. Enjoy!


The Downloads

  • BasicFLAR.as
    – This is the class i explain in this post, authored by me.
  • Papervision3D
    – There is loads of documentation on papervision out there, just google it :)
  • FLARToolKit
    – You can get a start-up guide here, as well as the FLARToolKit library.
  • MarkerGenerator
    – The AIR app built by saqoosha, generates a marker file.
  • Popularity: 20% [?]

    AS3 Sound Spectrum
    Analyzer

    A couple of weeks ago i wanted to try out working with sound. I done little more with sound other than loading mp3s and playing them. I wanted to make a sound visualizer…

    ..well I did! And id like to share it with you. Getting the actual snap shot data of the sound spectrum was the easy part. The tricky part was in fact making some cool graphics. Below you can see a screenshot of the visualizer, and here is the link to the actual visualizer.

    Download source files here.

    Popularity: 8% [?]

    Scrollbar class for AS3

    I have recently been working with a lot of display objects that needed scroll bars. Previously i have often used the scrollbar component in the Flash IDE, but i wanted a lightweight and slicker looking way to scroll through content. I made a class that is very simple to use, that i would like to share with you. This is the class in action:


    You can download the source files here.

    The class is very easy to use, below i will give two usage examples. One which is more of a Flash IDE approach where code is written in timeline, and the other where the object that is to be scrollable is created programatically. But first of all you need to add the Scroller class to you class path. In the Flash IDE, you can add the classes folder ( in the zip file ) to you list of classpaths in Preferences -> ActionScript -> ActionScript 3.0 Settings…



    Now the code. First off, the timeline version. Lets say you have a MovieClip you need a scrollbar on, where the viewable area should be 250 pixels high, and has a red color. The content of this MovieClip can be anything, an image, graphic, text etc. We place it onto the stage where you want the scrolling MovieClip to be, and give it an instance name of “myClip” in the properties panel. Finally we write this code on the timeline:

    
          // Import the class.
          import com.perkstoveland.utils.Scroller;
    
          // Create the scrollbar
          var scroller:Scroller = new Scroller( myClip,  250, 0xFF0000 );
    

    This will create a scrollbar and place it next to the MovieClip on the stage.



    This class can used without using the timeline too, lets create a TextField that uses the Scroller all programatically. Like this:

    
          // Import the class.
          import com.perkstoveland.utils.Scroller;
    
          // Create the TextField, asume we have stored the text to
          // show in a variable "theTextToShow", which is a string
          // with a few paragraphs of text.
          var txt:TextField = new TextField();
          txt.multiline = true;
          txt.wordWrap = true;
          txt.autoSize = TextFieldAutoSize.LEFT;
          txt.width = 300;
          txt.text = theTextToShow;
    
          // Lastly we create the scroller, position it, and add it
          // to the display stack.
          var scroller:Scroller = new Scroller( txt, 350, 0x333333 );
          scroller.x = 20;
          scroller.y = 20;
          addChild( scroller );
    

    Thats it, hope you use it, and like it. Enjoy!

    Popularity: 7% [?]

    Introduction to
    scripting and OOP
    in ActionScript

    It’s been a long time since my last post. But that means i have been busy, so I guess that would be a good thing. Anyways, last week i was asked to teach a well-versed timeline Flash designer some scripting, in AS3. My would-be “pupil” has some years under his belt of flash use, pre-dominantly AS2, and has only been using the Flash IDE to add basic actions like, stop(), gotoAndPlay(), and placing button actions directly on the movieclip. Now, my first thought when asked about this, was “where do I start?”. So, I write this post for him and any other who can benefit from from it.


    Variables & functions

    First off i want to explain some scripting basics. When you code you will de dealing with variables and functions is some form or way, 99% of the time spent. So ill start by explaining the concept of these two things first.



    A variable is a reference to an object. A variable can be anything, it could be a number, a string of text, a MovieClip, a text field, a list… you get the idea. But to be able to use a variable you must first declare it. The way to declare is by deciding a descriptive name of what the variable represents, and add the declaration syntax var in front of it. Like this:

    
           var address = "123 Anystreet, 01234 Cooltown";
    

    We have now created a reference to the a string of text, and can access that it by referencing to the address variable. Like this:

    
           trace( address );
    

    This will print “123 Anystreet, 01234 Cooltown” without the quotes, to the Flash IDE output panel. This is all neat ‘n’ cool, but you cant actually do anything with variables without using functions. So on to that.



    A function is an action. A function is a block of code that will be executed every time the function has been called. Lets first create a function that will trace a message to the output panel. Like variables you have to create ( declare ) a function much in the same way, you think of a descriptive name for the function ( usually a verb ). Lets say we want to greet the world, the function would look like this:

    
           function greet()
           {
                  trace( "Hello World, I'm alive!" );
           }
    

    First we write function then the name, add “()” and place the code implentation of the function between the two curly brackets ( “{” and “}” ). Now that we have declared a function, we can now call it:

    
           greet();
    

    This will run the code inside our function, and print “Hello World, I’m alive!” to the output panel.


    Arguments & data typing

    Now on to arguments. A function can have arguments sent to it when the function is called. This is useful since we then can process different objects through the same code block ( the function ). Lets make a function that tells me what time it is in the output panel. Imagine the code for determining the time is somewhere else, and we are going to write the function that does the actual tracing to to output panel. So each time the new time has been determined, it will call our function and pass the new time as an argument. Like this:

    
           function displayTime( time )
           {
                  trace( "The time now is: " + time );
           }
    

    Now let’s try this out:

    
           displayTime( "10:24" );
           displayTime( "14:51" );
    

    When the code is executed, you will get to lines printed to the output panel “The time now is: 10:24″, and “The time now is: 14: 51″. We have now centralized the code for displaying the time in one function, and can call that function with different time arguments.



    The last basic concept i want to discuss is data typing. I think the easiest way to explain this is by first giving an example of a function that take two numbers as arguments, add them together and trace them to the output panel:

    
           function add( firstNumber, secondNumber )
           {
                 var total = firstNumber + secondNumber;
                 trace( "The total is " + total );
           }
    
           add( 5, 4 );         // Will output "The total is 9"
           add( 2, 3 );         // Will output "The total is 5"
    

    Ok, so we have a function that adds to numbers together. The way this function is written can open up for some weird results since we have not data typed anything. Imagine this scenario:

    
           var num1 = 5;
           var num2 = "Two";
    
           add( num1, num2 );   // Will output "The total is 5Two"
    

    Now, since we are tracing the result we can catch the error quite quickly, but imagine that our add() function is being used in some other code as part of a bigger operation. Since we have not data typed it, finding the error in a larger block of code can start to be quite hard. This is where data typing comes in. When you data type a variable you make certain that the variable only references one sort of object. You data type a variable by adding “:” and the class name of the data type you want that variable to contain, to the variable name. Here are a few examples:

    
           var num:Number = 5;
           var text:String = "this is some text";
           var list:Array = new Array();
    

    All these are legal declarations, however the next block of code will generate some errors ( and thus making you aware that you have a fault in your code):

    
           // Error: Array is not a Number
           var num:Number = new Array();
    
           // This is legal
           var text:String = "some text";
           // But this isn't
           var list:Array = text;
    
    

    In the same way you data type a variable, you can also data type an agrument to a function like this:

    
           function add( firstNumber:Number, secondNumber:Number )
           {
                 var total:Number = firstNumber + secondNumber;
                 trace( "The total is " + total );
           }
    

    Now the above function is much less prone to silent errors. If you at anytime pass any other type of data than a Number as an argument to the function you will get an error and you will be informed exactly where the error is occuring. Makes you a happier coder, trust me…



    There is one more type of data typing, and that is data typing a functions return value. Some functions can me set to return some data. When you use the keyword return the function will end executing its code and deliver the value of the object you wish to return. You declare the data type of a functions return value, by adding “:” and the class name of the data type before the first curly bracket. Like this:

    
           function add( firstNumber:Number, secondNumber:Number ):Number
           {
                 var total:Number = firstNumber + secondNumber;
                 return total;
           }
    
           var sum:Number = add( 5, 4 );
           trace( sum );
    

    Very often you will have functions that are not supposed to return anything, in this case you can omit data typing it’s return value, but if you don’t data type it, a person reading your code won’t know right away if the function was meant to not have a return value, or you simply forgot to data type it. Therefore it is a good practice to data type a non-returning function with :Void (AS2) and :void (AS3). Like this:

    
           // ActionScript 2.0
           function greet():Void
           {
                  trace( "Hello World, I'm alive!" );
           }
    
           // ActionScript 3.0
           function greet():void
           {
                  trace( "Hello World, I'm alive!" );
           }
    

    Thats it for the basics, now on to OOP.


    Object Oriented Programming ( OOP )

    Now that the basics of programming in ActionScript has been discussed, i would like to introduce the basics of OOP. Instead of me writing an essay on OOP, i want to direct you to a site which I used to introduce myself into the concept. This site, which has been created by Colin Moock takes you through the concepts of classes, methods, accessors and more, in a very easy-to-understand way. This tutorial example code is in ActionScript 2.0 but the main concepts are the same in both AS2 and AS3

    Here is the link: www.moock.org

    Popularity: unranked [?]

    ActionScript 3.0 API’s

    Although i said my next post would be about Blogform’s new development path, i happened to stumble across a page containing list of 22 different ActionScript 3.0 API’s today. So since I often forget important links, and maybe someone out there would find this link helpful, here it is: List of 22 ActionScript 3.0 API’s. Basically this page lists up 22 useful API’s like the Adobe API’s, Away3d, Papervision3D, ebay API etc, enjoy!

    Popularity: unranked [?]

    Extending
    EventDispatcher in
    Flex Builder 3

    Ok, so was working on an AS project in Flex Builder 3, and wanted to write a class that extended EventDispatcher. My class was going to receive an XML and dispatch an event when it had transformed the XML into an array of value objects. Since this class wasn’t going to be on the display list, i thought that extending the EventDispatcher class was a good idea.

    I created a new actionScript class in Flex Builder and told it to extend the EventDispatcher. When I looked at the auto generated code in the file there, I scratched my head. This is what it looked like:

    
       package com.example {
    
          import flash.events.EventDispatcher;
          import flash.events.IEventDispatcher;
    
          public class Example extends EventDispatcher {
    
             public function Example(target:IEventDispatcher=null) {
                super(target);
             }
    
          }
       }
    

    I was wondering what the target in the constructor was. After some quick research i learned that you only use the EventDispatcher constructor when you have to implement the IEventDispatcher, because you are already extending another class. Therefore i changed my class to look like this instead:

    
       package com.example {
    
          import flash.events.EventDispatcher;
    
          public class Example extends EventDispatcher {
    
             public function Example() {
    
             }
    
          }
       }
    

    This wouldn’t have been an issue if i had just written it in TextMate, but because i used Flex Builders auto generating code, i had to investigate what was happening.

    Popularity: 4% [?]