Happy Holidays from Tuts+!
The holidays are upon us, and we’re feeling festive at Tuts+ this weekend! We’d like to take this opportunity to say a huge Christmas thank you to all our readers, and wish you a very Happy Holiday. Read on for a video message from the HQ team, and a few freebies from around the Tuts+ and Envato network!
A Message from Envato HQ

Although the Tuts+ team is spread over the globe, Envato HQ is where much of the Tuts+ magic happens! It isn’t looking traditionally Christmassy in Melbourne at the moment, but we have a special holiday message from everyone at head office:
From everyone at Envato we want to wish you a Happy Holidays and look forward to seeing you all refreshed and ready for another big year in 2012! From Envato HQ to the community, we’ve created a little video to share the holiday cheer. Enjoy!
Music is Kids Holiday Theme by AudioJungle Author CraigHall
Gift Guides & Freebies!
Wondering what to buy your fellow geek this Christmas? Never fear! You may have left it it a little late, but our holiday gift guides can still come in handy. Here are a few great places to start:
- The Official 2011 Nettuts+ Holiday Gift Guide
- 30+ Gift Ideas for Browser App and Browser Game Developers
- 10 Last-minute Gift Suggestions for the Musician in Your Life
- 36 Great Holiday Gift Ideas For The Cg Artist!
- The Official 2011 Phototuts+ Holiday Gift Guide
- 20+ Great Gift Ideas for Any WordPress Developer
We also have a couple of exclusive freebies and discounts, just in time for the holidays:
- Get $6 Off Our New Rockable Book: “How to Record Great Music”
- Exclusive Freebie: 50 Crisp Web UI Icons
The Christmas Freelance Freedom Comic
The “holiday jingle” comic encapsulates everything that we love and hate about freelancing. Don’t forget to sing along to the “Jungle Bells” theme music as you read it…!
You can also enjoy the whole back catalog of Freelance Freedom comics over at FreelanceSwitch.
AppStorm Giveaways

We have two fantastic competitions running over at the AppStorm network over the holiday period, and there’s still time to get your entry in to stand a chance of winning:
- Business Productivity Bundle Giveaway —Each bundle includes a license to Daylite and Billings Pro – it’s the perfect combination for getting your business organised and making money!
- The AppStorm Holiday ’11 Video Game Giveaway — In the spirit of this season we’ve hand picked a few critically acclaimed, and award-winning, games released over this year to give away to our readers!
Merry Christmas, and Happy New Year!
All that’s left is to wish you a very happy holiday on behalf of everyone at Tuts+! We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.
Here’s to another exciting year at Tuts+, and thank you for joining us on the journey!
View full post on Activetuts+


The holidays are upon us, and we’re feeling festive at Tuts+ this weekend! We’d like to take this opportunity to say a huge Christmas thank you to all our readers, and wish you a very Happy Holiday. Read on for a video message from the HQ team, and a few freebies from around the Tuts+ and Envato network!
A Message from Envato HQ
Although the Tuts+ team is spread over the globe, Envato HQ is where much of the Tuts+ magic happens! It isn’t looking traditionally Christmassy in Melbourne at the moment, but we have a special holiday message from everyone at head office:
Music is Kids Holiday Theme by AudioJungle Author CraigHall
Gift Guides & Freebies!
We also have a couple of exclusive freebies and discounts, just in time for the holidays:
The Christmas Freelance Freedom Comic
The “holiday jingle” comic encapsulates everything that we love and hate about freelancing. Don’t forget to sing along to the “Jungle Bells” theme music as you read it…!
You can also enjoy the whole back catalog of Freelance Freedom comics over at FreelanceSwitch.
AppStorm Giveaways
We have two fantastic competitions running over at the AppStorm network over the holiday period, and there’s still time to get your entry in to stand a chance of winning:
Merry Christmas, and Happy New Year!
All that’s left is to wish you a very happy holiday on behalf of everyone at Tuts+! We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.
Here’s to another exciting year at Tuts+, and thank you for joining us on the journey!
Twice a month, we revisit some of readers’ favorite posts from throughout the history of Activetuts+. Please enjoy this festive tutorial from Christmas past!
Ever wanted give your Flash design an extra dimension? Using Electric Rain’s brilliant 3D software, this basic tutorial will give you an introduction in using Flash and Swift 3D together to create some fantastic graphics and animations.
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: New Flash File
Create a new Flash file, it doesn’t matter what version of ActionScript you use; we’re only using Flash at the moment to create the graphics to export to Swift 3d.
Step 2: Creating the Graphics
Using whatever tools you feel comfortable with, create the basic shapes of the Santa and his Skidoo. I used the pen and pencil tool to create the basic shapes, the fewer anchor points and detail you use the better. This will speed up the time it takes for Swift 3d to import the objects you have created in Flash, and also make the 3d models easier to modify and render in Swift 3d.
An important thing to know is that Swift doesn’t like gradient fills or strokes created in Flash. So just use single color fills and make sure you delete any strokes/outlines.
Step 3: Exporting Your Graphics
File > Export > Export Image > Adobe Illustrator… I’ve saved my file as “father_xmas.ai”.
Step 4: The Swift 3d Interface
I could produce a whole tutorial on the in’s and out’s of Swift 3d, but just to give you an idea of what Swift 3d is like and how easy it is to use I’ve included an image of the interface. The interface is made up of these main elements …
As this is only a simple beginner’s tutorial we’ll be using most of these tool and functions, but nothing too complicated…
Step 5: Importing Your Graphics
It will take a minute for Swift to import all the graphics and data.
Step 6: Our Imported Graphics
As you can see, our graphics have come in pretty much as we created them in Flash. Swift is good at creating these extrusions on its own using the "Extrusion Editor", but I find it easier to draw in Flash, so I use Flash to create all my Extrusions.
Step 7: Adjusting Our Layout in Swift 3d
First thing we want to do is adjust the size of our layout. In the "Property Tools" change the following settings:
Step 8: Viewing Imported Graphics
The first thing to do is change our first viewport to a "Default Target Camera" View, this allows us to rotate and view our Santa freely in any direction.
These cmd/Ctrl/right-click techniques do take a bit of getting used to, but stick with it and it will soon become second nature to you.
As you can see they are all pretty much the same depth at the moment, we can easily change that, but the first thing to do is name all our objects so we know our arms from our legs!
Step 9: Viewing Objects
I thought it might be worth pointing out how to move your focus point in the "Default Target Camera". This red circle with a green vertical line through it is your camera focus/target point. If you click in the middle of this shape and drag, it will move the target position of your camera.
Step 10: Un-Grouping Imported Graphics
Swift 3d has grouped all our objects and I have 24 objects in my "Hierarchy Menu". First thing to do is "Ungroup" these objects/extrusions. To do this select "Arrange", then "Ungroup". Click anywhere in a viewport and your objects will appear in a list called Extrusion, Extrusion 1, 2, 3 etc…
Step 11: Re-naming Imported Graphics
I know it’s a bit tedious but it will help you later on!
Step 12: Creating Parent and Child Relationships
To parent the foot to the leg for example is easy. Simply drag the RightFoot onto the RightLeg to create the parent child relationship, do the same for the arms, hands and cuffs and the same for the rest of the objects as I’ve done here.
Step 13: Improving the Quality of our Model
This bit is optional but I like to improve the quality of my models. This can increase the file size of the final image or animation, but as ours is relatively simple it shouldn’t matter too much. To do this got to the "Property Tools"
Step 14: Moving and Positioning Objects
You can move your objects into position a number of ways:
Step 15: The Finished 3d Model
This is what I ended up with as my final model in Swift 3D. Father Xmas sitting on a skidoo! I used a couple of the ski supports as handle bars and colored them red. We’re nearly there now, just a few more steps and we’re done.
Step 16: Re-coloring our Model
The files coloring should look pretty much the same as the graphics you created in Flash. However, I tend to re-color them in Swift as I find that they are a bit too glossy for my liking. To change the color of an object..
Do this for all or none of your objects, it’s up to you.
Step 17: Adding a Floor
To add a floor to place your model on you need to create a plane, this will allow the shadows to be cast onto a surface/floor.
Step 18: Lighting
First we want to remove Swift’s default lighting, or if you want you can keep it as is… I just prefer to add my own lighting setup.
Step 19: Adjusting the Lighting
Now we’re ready to create our own lighting. Still in the "Top View":
Step 20: Adding More Lights
OK, we need to create more lights by doing exactly the same as "Step 19". The new light will appear over the top of the light you have just created, so we need to move it to another position.
Make sure the "Lock Spin" button is toggled to "On" This will rotate around a fixed axis.- Make sure you have "Rotation Increment" set to 90 degrees.
- Then simply click drag the second light you’ve created around the trackball.
- Do this 3 times so that you have 4 equal lights around the trackball (Name your lights if you wish …Front, Left, Right, Back).
- Create 1 more light. This will be our top light and will cast the shadows in the scene.
- Make sure the "Lock Vertical" toggle is active and drag it up to the top of the scene.
- With this light you want the "Shadows" to be active.
Step 21: Rendering Santa
If you’re using the trial version you won’t be able to export any of your renderings, but you can screen grab what you have done and save it out as a bitmap and crop it in Photoshop. If you have the full working version, Swift 3d comes with a built in Smart Layer rendering function, which separates our graphics/animations into layers. This means that things like shadows, moving objects and transparency layers are separated onto their own layer to help reduce file sizes and makes editing in Flash easier.
Swift can render to both Vector and Bitmap formats, can export to all the standard .swf, .AI and the .SWFT (Smart Layer) for vector formats and render to .png, .jpeg etc in the bitmap formats.
OK here we go…
Make sure the "Default Target View" is active in the "Scene Editor" (swift will render the active viewport by default).
Step 22: Rendering Santa Continued..
Step 23: Importing Santa into Flash
All done!
Conclusion
In this tutorial I’ve shown you the basics of using Flash and Swift 3d together to add an extra dimension to your Flash design work. There’s certainly a lot to cover with Swift 3D and I hope this gives you an idea of what you can achieve using these two pieces of software together. Once you’ve explored the capabilities of Swift 3D I’m sure, like me, you’ll find you use it all the time.
I hope you liked this tutorial, thanks for reading and have avery merry Christmas!
Sometimes you may find yourself needing to modify the behavior of a component for a user input event. This article will explain how to do so by modifying the event object in-flight, before it’s processed by the component. That’s right, you can lie and cheat. In code.
Example
Suppose we have a List component for the user to select multiple items from. We have set its
allowMultipleSelectionproperty totrue, which would allow it to have more than one selected items (hence the name). However, this still requires that the user holds down the Ctrl key, while clicking, to select multiple items. When a single selected item is the exception, not the rule, it would be better if we didn’t make the user hold the Ctrl key every time!The component determines whether the user is holding the Ctrl key by examining the
ctrlKeyproperty of the MouseEvent event object. In the above example, we’re tricking the component, by making it appear that the Ctrl key is pressed.Let’s look at how this is done…
Step 1: Set Up the Flash Document
If you already know how to create Flash applications (you probably do) you can skip reading this step, but keep in mind that the existence of an instance of a List component is assumed in next steps. Just in case, let’s briefly explain the creation of the project.
Create a new FLA (here named htefExample.fla) and a new document class ActionScript file (here named htefExample.as).
Set the properties of the FLA file and link the document class.
The width of the FLA is set to 300, the height to 200 and the ‘Class’ input field is set to ‘htefExample’”.
Drag a List component from the Components panel to the Library.
In the Library the List symbol and its assets are contained.
Write the document class (htefExample.as).
package{ import flash.display.Sprite; import flash.events.MouseEvent; import fl.controls.List; import fl.data.DataProvider; public class htefExample extends Sprite{ private var list:List; function htefExample(){ // create an instance list = new List(); // and set some properties list.width = 200; list.x = 50; list.y = (200-list.height)/2; // set allowMultipleSelection list.allowMultipleSelection = true; // add data list.dataProvider = new DataProvider([{label:"One", data:1}, {label:"Two", data:2}, {label:"Three", data:3}, {label:"Four", data:4}, {label:"Five", data:5}]); // add to display list this.addChild(list); } } }Step 2: Add an Event Listener to the Capturing Phase
The signature of the addEventListener method is:
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):voidTo add a listener to the capturing phase, set the third parameter (useCapture) to true.
Step 3: Define the Contents of the Listener Function
In the body of the function, set the
ctrlKeyproperty totrue.private function hackMouseListener(e:MouseEvent):void{ // set ctrlKey property e.ctrlKey = true; }How It Works
Flash Player has a model for dispatching events and calling event listeners called the event flow. For display-related events, the Player doesn’t dispatch the event directly to the target object, but instead injects it at the top-level display object: the stage.
We can visualize the event traveling from the stage down the hierarchy to the target object. This is called the capture phase.
At the target, the event is in the target phase.
Then, the event ‘bubbles up’ back to the stage. This is the bubbling phase.
The Flash Player event flow.
This imaginary trip determines the order in which the listener functions are called. The
useCaptureparameter in theaddEventListenermethod states our desire about which direction we want our function to be activated: on the capturing way down (value:true) or bubbling way up (value:false– the default).What is interesting is the fact that the event object that is passed as an argument to the listener functions is the same one. So, if we change some of its properties, the listeners further down the event flow will get the same object, now modified!
In the example above, when we registered the
hackMouseListenerfunction to use the capture phase, we made sure that we’ll get the event on its “way down”, so to speak. That function will be called before the list’s listeners which are registered to the target/bubbling phase on the component itself. When the list’s code inspects thectrlKeyproperty it will find that it is set totrue, indicating that the user pressed the Ctrl key.Or did he?
Conclusion
You now know how to make a List component multi-select with just a simple event listener. You can use this on other list-based components like DataGrid. Don’t forget to set the
allowMultipleSlectionproperty.More importantly, however, is that (hopefully) you’ve learned something new about the Flash event flow, about the
useCaptureparameter, event phases and how to use this marvelous (and a bit unconventional) method to bend events to your needs.Hope you enjoyed it. Thank you for reading!
When a user first opens up a Flash game, their initial impression is based upon the menu that they see. Unfortunately, many games’ menus are dull, plain and static. This is terrible news! A lot of players will just close the game before even playing it, and move on to another. Don’t let this happen to you!
Final Result Preview
Take a look at the menu we’ll be building:
Obviously, in a full game, the different menu screens would contain different buttons, text, and submenu items!
Introduction: What is a Dynamic Menu?
Before we learn what a dynamic menu is we must first learn what a static menu is.
A static menu can be described by the definitions of the two words it is made up of: “static”, meaning lacking in change, and “menu”, meaning a list of available options or choices. Therefore a static menu has an interface of options or choices that is lacking in change.
Conversely, the word “dynamic” means to continuously cause change within a system or process. So in the simplest terms a dynamic menu continuously updates the interface of given options or choices.
Step 1: Setting Up
The first thing that we are going to need to create is a new Flash File(ActionScript 3.0), set its width to 650px and height to 350px, and set the frames per second to 60. Instead of changing the background color leave it as white; later on in the tutorial we will create a background.
Now that we have the basic Flash File set up we can save it; you can name yours whatever you please. I just named mine MenuAccordion.fla.
In the next section we will create the eight MovieClips required for the menu; here is a list of all the colors and their hexidecimal codes that will be used throughout the tutorial:
#FFFFFF#E8A317#FBB917#1569C7#1389FF#347235#3E8F1B#990000#C10202#222222Step 2: Creating the MovieClips
To start off we need to create one main background color, four “bar” MovieClips (these are the ones that will be clicked on) and four background MovieClips (these will slide out after a bar is clicked).
First, right-click the stage and choose Grid, then select Show Grid – by default it will create a 10px by 10px square grid accross the stage. To make your life easier right-click again and select Snapping > Snap to Grid. Now we are ready to start drawing!
Select the Rectangle tool and draw a Matte Grey background over the whole stage. Name the layer Background and lock it. Next, create a new layer and name it Menu. Your timeline and stage should look something similar to this now:
Next we will create one bar MovieClip; to make things easier we will just duplicate it to form four MovieClips and change the color of each.
Select the rectangle tool once again, and draw a 30px by 350px rectangle with no stroke. Right-click the fill and select Convert to Symbol…. Name it goldBar, make sure the type is MovieClip and the registration point is in the top-left corner. Double-click the MovieClip on the stage to edit it.
Right-click the first keyframe in the timeline and go to actions, type in a simple
stop();command to prevent the MovieClip from cycling through frames. Next, right-click the second frame and select Insert Keyframe. It is up to you what you would like to write in each fill; only thing to remember is that if your are writing on a 90 degree angle the text may appear invisible if you have the text set to dynamic. Personally I just broke apart the text until it became a fill, and I drew an arrow that was pointing opposite directions on each frame:Now that we have one bar completed we can right-click it in the library and select Duplicate Symbol…. Make three copies of it and name them blueBar, greenBar and redBar, respectively. Then just edit their fill colors and change the text. Voila! We have four bar MovieClips.
Now we can begin on the background MovieClips which we will create and duplicate in the same way. Select the rectangle tool again and draw a rectangle of 560x350px. Convert it to a symbol, name it goldBackground, and make sure that the type is a MovieClip and the registration is in the top-left corner. Then just duplicate it three times and name the new MovieClips blueBackground, greenBackground and redBackground respectively.
Your rectangles should look very simple, like this:
There is only one more MovieClip to create, I promise! Go to the Insert menu and select New Symbol; name it menuAccordionMC, set the type to MovieClip and put the registration point in the top-left corner (because our last MovieClips had this too). Next, check the box that says Export for ActionScript: the class name should be MenuAccordionMC with the capital at the beginning.
Step 3: Positioning the MovieClips
In the previous section we created all the MovieClips required, and now we need to position them!
Delete any MovieClips on the stage if they are on still there. Open your menuAccordionMC from the Library, and create seven more layers in its timeline. Now name them in the following order from top to bottom:
Now drag and drop each MovieClip from the library to its corresponding layer. The easiest way to position all of these will be to lock all of the layers besides the one with the MovieClip you are currently positioning.
Start with the goldBar and set its x and y coordinates to (0,0). Next the blueBar with the coordinates (30,0), then the greenBar with (60,0), and finally the redBar with (90,0).
Time for the backgrounds: the goldBackground‘s coordinates are (-530,0), the blueBackground‘s coordinates are (-500,0), the greenBackground‘s coordinates are (-470,0) and the redBackground‘s coordinates are (-440,0).
Your MovieClip should look like this now, and the (0,0) coordinate should be in the top-left corner of the goldBar MovieClip where the white plus is in the image:
Step 4: Identifying the MovieClips
Before we can begin coding there is one more thing we have to do: give the eight inner MovieClips instance names.
Open up the the menuAccordionMC for the final time then select each MovieClip and make its instance name the same as its MovieClip name. So goldBar’s instance name would be goldBar, greenBackground’s instance name would be greenBackground, and so on. After this is done we can begin the coding, which is fairly easy to understand!
Step 5: Setting Up the Classes
Go to your Flash file’s properties and name the document class MenuAccordion. Now create a new ActionScript 3.0 file and put the following code in it and save the file as MenuAccordion:
package { import flash.display.MovieClip; import flash.events.Event; public class MenuAccordion extends MovieClip { public var menuAccordionMC:MenuAccordionMC = new MenuAccordionMC(); public function MenuAccordion() { addChild(menuAccordionMC); } } }Here, we first import what we will need (in this case just the MovieClip and Event classes). Next we add the variable for our menuAccordionMC, then in the constructor we attach the MovieClip to the stage at (0,0).
That is all the code we will need for the document class; now let’s create a new ActionScript 3.0 file for the MovieClip and save it as MenuAccordionMC.as.
To set up the MenuAccordionMC class, input the following code – I will explain the variables and event listeners shortly:
package{ import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; public class MenuAccordionMC extends MovieClip{ public var activeColor:String = new String(); public var speed:Number = new Number(); public function MenuAccordionMC(){ activeColor = "none"; speed = 10; addEventListener(MouseEvent.CLICK, accordionClick); addEventListener(Event.ENTER_FRAME, accordionMove); } } }First thing to notice is that we have imported the MouseEvent: this is very important because without it our mouse click will have no effect. As for the two new variables: activeColor is just a simple string to tell us which color is currently in use, and speed is how many pixels the backgrounds shift every frame.
The first event listener is for a MouseEvent.CLICK and will call the function accordionClick when our menu is clicked anywhere. The second event listener adds the function accordionMove and will be called every frame.
Now we will create the two functions for the event listeners. Place the following code right after the closing curly brace for the constructor.
public function accordionClick(event:MouseEvent):void { } public function accordionMove(event:Event):void { }The two classes are now set up, so it’s time to start putting code in these functions!
Step 6: The accordionClick Function
This function is relatively easy and only has an if, else statement in it. Begin by writing the following in the function:
if(event.target.currentFrame==1){ }else{ }Many people are unfamiliar with event.target, so I will briefly explain it. In a nutshell, it just directs the code to the target of the the event – so if the blueBar is clicked, event.target is equal to blueBar.
This means that the if statement checks to see whether the bar’s currentFrame is equal to 1, and if so it executes that code; if not, it will execute the code in the second curly brackets. We can continue now and change the if, else statement to the following:
if(event.target.currentFrame==1){ event.target.gotoAndStop(2); activeColor = event.target.name; }else{ event.target.gotoAndStop(1); activeColor = "none"; }The new lines are very basic: the target’s currentFrame is changed to the second or first frame and the activeColor variable is set to the target’s name or it is set to “none”. That is all the code needed for the accordionClick function.
Step 7: The accordionMove Function
Alright, this is where all the magic happens! This is the endgame and its a long stretch to the finish, but if you follow the final instructions correctly you will have a working accordion menu!
First thing we need to add to the function is a switch case, which will eventually include all of the if statements required for this to run smoothly:
switch (activeColor){ case "none": break; case "goldBar": break; case "blueBar": break; case "greenBar": break; case "redBar": break; }This switch case corresponds to the variable activeColor that is set during the accordionClick function. Now let’s start with the easiest part of this case statement, case: none:
if(this.goldBackground.x>=-530){ this.goldBackground.x-=speed; } if(this.blueBackground.x>=-500){ this.blueBackground.x-=speed; } if(this.greenBackground.x>=-470){ this.greenBackground.x-=speed; } if(this.redBackground.x>=-440){ this.redBackground.x-=speed; } if(this.blueBar.x>30){ this.blueBar.x-=speed; } if(this.greenBar.x>60){ this.greenBar.x-=speed; } if(this.redBar.x>90){ this.redBar.x-=speed; }(Editor’s Note: You may argue that this code is not neat enough for practical use. See the comments of the other tutorial in this series for a discussion about this!)
All that the none case does is check whether any of the MovieClips’ x-positions are greater than their original ones, if they are it moves them left until they no longer are greater than their original x positions.
The next case, goldBar, does something similar. It moves all the other bars that are on the right side of it to the right side of the stage and the backgrounds to the bars’ previous x-positions. Then it just switches all the other bars’ currentFrame properties to 1 (so that the arrows point in the opposite direction):
if(this.goldBackground.x<0){ //Moves The Bars & Backgrounds this.goldBackground.x+=speed; if(this.blueBar.x<560){ this.blueBar.x+=speed; } if(this.blueBackground.x<30){ this.blueBackground.x+=speed; } if(this.greenBar.x<590){ this.greenBar.x+=speed; } if(this.greenBackground.x<60){ this.greenBackground.x+=speed; } if(this.redBar.x<620){ this.redBar.x+=speed; } if(this.redBackground.x<90){ this.redBackground.x+=speed; } //Checks if any other bar's currentFrame is 2, if it is it switches it to 1 if(this.blueBar.currentFrame==2){ this.blueBar.gotoAndStop(1); }else if(this.greenBar.currentFrame==2){ this.greenBar.gotoAndStop(1); }else if(this.redBar.currentFrame==2){ this.redBar.gotoAndStop(1); } }All right, we have two out of the five cases complete. The next three cases work the same as the goldBar – with one exception. They move any backgrounds that are open to the left of them back to their original position and shift themselves back to their original position.
Here is the blueBar case:
if(this.blueBackground.x<30){ this.blueBackground.x+=speed; if(this.greenBar.x<590){ this.greenBar.x+=speed; } if(this.greenBackground.x<60){ this.greenBackground.x+=speed; } if(this.redBar.x<620){ this.redBar.x+=speed; } if(this.redBackground.x<90){ this.redBackground.x+=speed; } if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.greenBar.currentFrame==2){ this.greenBar.gotoAndStop(1); }else if(this.redBar.currentFrame==2){ this.redBar.gotoAndStop(1); } } if(this.blueBar.x>30){ this.blueBar.x-=speed; if(this.goldBackground.x>-530){ this.goldBackground.x-=speed; } if(this.greenBar.x<590){ this.greenBar.x+=speed; } if(this.greenBackground.x<60){ this.greenBackground.x+=speed; } if(this.redBar.x<620){ this.redBar.x+=speed; } if(this.redBackground.x<90){ this.redBackground.x+=speed; } if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.greenBar.currentFrame==2){ this.greenBar.gotoAndStop(1); }else if(this.redBar.currentFrame==2){ this.redBar.gotoAndStop(1); } }The only thing new about this case is the second main if statement; this is for when another background was already open, it performs a check to see which one and then it moves it back just like the “none” case, then it changes the frames on the other bar MovieClips.
The final two cases work in exactly the same way; the only difference between the three of these is the positions where each bar is being moved to and where its background is being moved to.
Here are the final two cases:
if(this.greenBackground.x<60){ this.greenBackground.x+=speed; if(this.redBar.x<620){ this.redBar.x+=speed; } if(this.redBackground.x<90){ this.redBackground.x+=speed; } if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.blueBar.currentFrame==2){ this.blueBar.gotoAndStop(1); }else if(this.redBar.currentFrame==2){ this.redBar.gotoAndStop(1); } } if(this.greenBar.x>60){ this.greenBar.x-=speed; if(this.goldBackground.x>-530){ this.goldBackground.x-=speed; } if(this.blueBar.x>30){ this.blueBar.x-=speed; } if(this.blueBackground.x>=-500){ this.blueBackground.x-=speed; } if(this.redBar.x<620){ this.redBar.x+=speed; } if(this.redBackground.x<90){ this.redBackground.x+=speed; } if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.blueBar.currentFrame==2){ this.blueBar.gotoAndStop(1); }else if(this.redBar.currentFrame==2){ this.redBar.gotoAndStop(1); } }if(this.redBackground.x<90){ this.redBackground.x+=speed; if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.blueBar.currentFrame==2){ this.blueBar.gotoAndStop(1); }else if(this.greenBar.currentFrame==2){ this.greenBar.gotoAndStop(1); } } if(this.redBar.x>90){ this.redBar.x-=speed; if(this.goldBackground.x>-530){ this.goldBackground.x-=speed; } if(this.blueBar.x>30){ this.blueBar.x-=speed; } if(this.blueBackground.x>=-500){ this.blueBackground.x-=speed; } if(this.greenBar.x>60){ this.greenBar.x-=speed; } if(this.greenBackground.x>=-470){ this.greenBackground.x-=speed; } if(this.goldBar.currentFrame==2){ this.goldBar.gotoAndStop(1); }else if(this.blueBar.currentFrame==2){ this.blueBar.gotoAndStop(1); }else if(this.greenBar.currentFrame==2){ this.greenBar.gotoAndStop(1); } }And with that all of the coding is complete for the accordion!
Conclusion
Right now you should be admiring your hard work and its magnificent result, but if you are wondering how to take the accordion to the next level and add more bars, then just remember the following:
Thank you for taking the time to read this article, I hoped you enjoyed it!
Here’s an present for our Facebook fans: a new Facebook Fan Bonus tutorial! In this month’s beginner-level tutorial, you’ll learn how to use the Input.as class to create smooth keyboard-driven movement.
Final Result Preview
Here’s a look at the type of keyboard movement you’ll learn to create in the tutorial:
As Cristian Bote, the author, describes it:
Download This Fan Bonus Now!
All you have to do is Like us…
Not On Facebook?
Don’t worry, the tutorial will be posted on Activetuts+ in a month’s time!
It’s time for another Premium tutorial! In this mammoth post, James Tyner will introduce you to Standing Wave 3, an excellent AS3 library for dynamically generating or manipulating sounds in Flash.
Premium Preview
Let’s take a look at what you’ll be building in this tutorial:
You’ll add each section of the above SWF step by step, learning the main features of Standing Wave 3 as you go. Quoting from the tutorial:
If you’re not yet a Premium member, you can still read the first few steps of the tutorial. Members can, of course, access the full thing right away!
Active Premium Membership
We run a Premium membership system which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium, Photo Premium, and the new Mobile Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!
Also, don’t forget to follow @envatoactive on twitter and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.
In this tutorial I’ll walk you through the steps required to install and use the TextArea component as an alternative to Flash’s native TextField class, and show you how to detect mouse roll over/out events on hyperlinks. I’ll also talk about how you can call custom functions and pass different data types as arguments.
Background
The native TextField class was the first to support text scripts in Flash projects. With TextField, you could support dynamic and static text, as well as the input type to allow user interactivity. It also supported a (very limited) selection of HTML tags for styling your scripts – but when comparing this narrow availability of HTML support in TextField to what is possible with regular HTML files being used within browsers, Flash developers felt the extreme lack of flexibility when dealing with text.
In 2009 when TLFTextField was introduced, developers were hoping to see some solutions – but these didn’t appear. Today, with the TextArea class, you can do what you always wanted with your text blocks. Functionalities like detecting roll over/out on href links, calling custom functions from text blocks, creating anchor links, loading custom created tags like video players, slideshow, and buttons: these are all now possible with TextArea.
Final Result Preview
The following simple no-frills demo will present how custom functions are called on hyperlinks. This is what you’ll build in the next 30 minutes:
Step 1: Set Up the Environment
TextArea can be used in any IDE that compiles AS3 – like Flash Builder, CS pro versions and FlashDevelop – which means it’ll work across Flash platform (in Flex, AIR and AS3-only web projects). Different IDEs each have a somehow similar but unique approach to how you compile your project, and due to this diversity it’s sometimes frustrating, especially for beginners, to work with AS3 tutorials because the author may prefer Flash Builder while the learner is accustomed to work with the CS IDE.
To solve this problem, I will try to explain the usage of TextArea independent of the IDE. So, the first step is to set up your environment. No matter which IDE you’re using, just open it and create a new AS3 project, then save it somewhere on your computer.
Create a document class, name it Main.as, and add a trace call to output Hello World.
package { import flash.display.MovieClip public class Main extends MovieClip { public function Main():void { trace("Hello World") } } }Step 2: Download TextArea
TextArea is free to download and to use but be sure to read the license agreements here. Head to doitflash.com and find the download button at the bottom of the home page to download TextArea classes.
Extract the zip file you downloaded, TextArea.zip, to your computer, go to the folder TextArea/Src, and copy the com folder then to the same directory as your document class, Main.as.
By copying the com folder to where you have your project document class, you are letting the IDE find TextArea classes only in this specific project. Alternatively, you could copy the classes to your global class path so that it will always be available to all your projects – to find out more, read How To Use an External Library in Your Flash Projects.
Step 3: Initializing TextArea
After downloading and installing the TextArea, it’s time to initialize it. First you need to import the required classes to the Main class.
Then remove the hello world trace function and enter the following instead.
Test your movie and this time instead of outputting hello world, you’ll see a text field (but not a
TextField!) created for you:As you can see, TextArea works exactly like the native TextField class. All the different settings that you could apply to TextField are true for TextArea also; it’s basically an extension to TextField so it will do everything TextField does, plus more. I’ll talk about these extra features in the next sections.
Step 4: Feeding TextArea With an XML File
To make this tutorial as informative as possible and to make it useable for real world practices, let’s try to feed the TextArea instance with data from an external XML file.
This procress will again be similar to how you load XML data into TextField. First, create your XML file and place it where you have the published SWF file from the previous steps. Make the XML look like the below and save it as “data.xml”:
(So that XML contains HTML in a CDATA section.)
Now get back to your Main.as, which should look like the following:
package { import flash.display.MovieClip import com.doitflash.text.TextArea; public class Main extends MovieClip { public function Main():void { var _textArea:TextArea = new TextArea(); _textArea.wordWrap = true; _textArea.multiline = true; _textArea.htmlText = "Initialize TextArea just like you used to initialize TextField."; this.addChild(_textArea); } } }Add the required imports for xml loading process.
Then replace the whole Main() function with this.
public function Main():void { var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onXmlLoaded); loader.load(new URLRequest("data.xml")); function onXmlLoaded(e:Event):void { var xml:XML = new XML(e.currentTarget.data); var _textArea:TextArea = new TextArea(); _textArea.wordWrap = true; _textArea.multiline = true; _textArea.width = 400; _textArea.height = 200; _textArea.condenseWhite = true; _textArea.htmlText = xml.text(); addChild(_textArea); } }The above code loads data.xml – there’s no difference from how you would have done it with a TextField so far.
Step 5: Detecting Mouse Rollover/Rollout
To use the specific features of TextArea, you need to specify a few extra settings when initializing it.
The first and the most important thing to remember about using TextArea is that you should use the
fmlTextmethod for sending text scripts into the instance rather than using the classichtmlText. ThefmlTextmethod will parse scripts using a different approach thanhtmlText; it stands for Flash Markup Language Text.So, in your test project, replace
htmlTextwithfmlTextlike below.The next thing to do is create two custom functions in your document class,
Main.as, which will be called when you rollover or rollout a hyperlink (which we will build later in data.xml). For the sake of this tutorial, these two functions will just trace some outputs, but in the real world, you could do anything you want with these functions – like, say, opening a tooltip window.public function funcOnOver():void { trace("rollOver"); } public function funcOnOut():void { trace("rollOut"); }You should also set some settings while initializing the TextArea instance. Add these lines just after you initialize TextArea.
Also add the following line to the beginning of the Main() function.
To make sure you have written the code in Main.as correctly, below is how your file should look up to now.
package { import flash.display.MovieClip import com.doitflash.text.TextArea; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; public class Main extends MovieClip { public function Main():void { var refToThis:Object = this; var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onXmlLoaded); loader.load(new URLRequest("data.xml")); function onXmlLoaded(e:Event):void { var xml:XML = new XML(e.currentTarget.data); var _textArea:TextArea = new TextArea(); _textArea.holder = refToThis; // indicates the location where you are adding TextArea to stage _textArea.client = refToThis; // must be the location where you have your "allowedFunctions" saved _textArea.mouseRollOverEnabled = true; // enables mouse rollover detection _textArea.funcSecurity = true; // makes sure only function names in "allowedFunctions" are accessible _textArea.allowedFunctions(funcOnOver, funcOnOut); _textArea.wordWrap = true; _textArea.multiline = true; _textArea.width = 400; _textArea.height = 200; _textArea.condenseWhite = true; _textArea.fmlText = xml.text(); addChild(_textArea); } } public function funcOnOver():void { trace("rollOver"); } public function funcOnOut():void { trace("rollOut"); } } }That’s pretty much everything you need to do in your .as file; and the rest will be done in the XML but before we go to XML and create a hyperlink, let’s talk a bit about the above settings.
First we have the holder property which is something that you won’t use in this article but when you go deeper into TextArea to create custom html tags you will need this a lot; for the sake of this tutorial, it’s sufficient for you to know that this property saves the location where you are adding the TextArea instance into the stage.
Then we have the client property. This is the location of – or better to say, this is a reference to – a class where you save all your allowed functions. In this example we use Main.as as the client, but if you have a long list of functions that want to give them the permission to be called from your text scripts, you may prefer creating a separate class for that purpose.
We also have the mouseRollOverEnabled property which is set to
falseby default for performance reasons. If you want to detect mouse roll over/out on your hyperlinks, you must make sure you enable this property.Then we have two security properties: allowedFunctions and funcSecurity. These properties will let you restrict the called functions to the specific ones mentioned in the allowedFunctions method.
Okay, to see the magic, get back to data.xml and and add the following line somewhere inside the CDATA section:
As you see you have created two function calls (one on mouse rollover, one on mouse rollout) and you can do whatever you like with these functions inside your AS3 project.
But this is not all! In the next section I’ll talk about how you can call custom functions and pass different types of data as arguments.
Step 6: Pass Arguments to Functions
Up to now, you have learned how to set the TextArea instance ready for accepting function calls from HTML content which can be placed in external sources like XML. Now we’re going to send different types of arguments along with the calls.
We can send array, object and simple string types. Try adding the following hyperlink somewhere inside the CDATA tag in your XML file:
<u><a href='event:func1()'>SIMPLE CALL</a></u>.<br /> <u><a href='event:func2(some string)'>SEND STRING</a></u>.<br /> <u><a href='event:func3([0,1,2,3,4])'>SEND ARRAY</a></u>.<br /> <u><a href='event:func4({var1:val1;var2:val2})'>SEND OBJECT</a></u>.<br /> <u><a href='event:func5(string,[0,1,2],{var1:val1;var2:val2})'>SEND MIXED ARGUMENTS</a></u>.<br />This will create five function calls in your AS3 project; each function demonstrates how you can send different types of arguments. But remember that this will not work until you actually create these functions inside your AS3 project. To do that, simply add these functions along with the
funcOnOver()andfuncOnOut()functions that you had previously:public function func1():void { trace("no arguments sent"); } public function func2($str:String):void { trace("arguments >> " + $str); } public function func3($arr:Array):void { trace("arguments >> " + $arr); } public function func4($obj:Object):void { trace("arguments >> " + $obj); } public function func5($str:String, $arr:Array, $obj:Object):void { trace("arguments >> " + $str); trace("arguments >> " + $arr); trace("arguments >> " + $obj); }Now you have the calls in XML and the functions are also available in the AS3 project; all that’s left is to give the usage permission to the TextArea instance. Modify the allowedFunctions method of TextArea as so:
Now publish and test your project and try clicking the hyperlinks you created.
Congratulations, you have now learned how to enable mouse rollover and rollout in your text fields, and you know how to create custom functions and call them from within your text blocks.
Conclusion
TextArea extends TextField, adds only 6kb to your project, and can be used as an alternative to TextField. In this tutorial you learned how to initialize TextArea to create simple hyperlinks which can call custom functions inside your AS3 project, and you also learned how to enable mouse rollover and rollout detection on hyperlinks that can call custom functions.
There are many things you can do with these features, like open a tooltip when rolling over a certain hyperlink or create links which call a custom function in your project to navigate through your application pages easier.
I hope you find this tutorial (and TextArea itself) useful!
In the first part of this series, I introduced a class to handle single mouse stroke detection:
MGesture. This tutorial takes it a step further, by detecting a sequence of strokes.We’ll be using the class
GManagerfor this, in tandem withMGesture. After briefing throughGManagerfunctionality, an application demonstrating its use will be developed.Final Result Preview
Let’s take a look at the final result we will be working towards. To use the Flash presentation below, use your mouse to perform the gesture as indicated by the arrow in the top left corner. Gesture by pressing the left mouse button, moving the mouse while holding the button, and then releasing it.
Step 1: Recap Direction Numbering
First step, a revision on integers used to represent different directions from Part 1. Hopefully, you can form a mental picture of the diagram above as we shall refer to it heavily throughout this tutorial.
Step 2: Strokes Detected
As user makes a gesture by any pointing devices (mouse, tablet pen, etc), the vectors successfully detected over time actually form a series of integers. Refer to diagram below.
Notice the unique integers in the sequence are 0, 4, 1. However, I shall say unique integers are 0, 1. Lets face it: it’s difficult to make an accurate stroke on my Bamboo tablet, and even more so with a mouse. Errors are inevitable. Our algorithm should then be based upon the high repetition of integers in a continuous string. They are 0, 1 here – 4 is probably due to inaccurate stroke. Therefore, this gesture can be uniquely identified as a sequence of 0, then 1.
I’ve included another few gestures with their accompanying unique sequences below.
Step 3: Introducing
GManagerThe purpose of this class is simple:
Developer has to define a set of stroke sequences to detect initially. Once done, event listeners to capture user gesture at runtime can be programmed. If the current gesture’s sequence successfully matches any one sequence in the predefined set, different operations can then be carried out.
Step 4: Variables
GManagerhas the following variables:gestSeqVector.<Vector.<int>>gestNameVector.<String>strokesVector.<int>gestCurrent‘s strokes when compared with stroke sequence.gestCurrentVector.<int>_orderBooleangestSeqshould be detected in order.orderCurrentint_orderis turned on; starts at 0.Step 5: Methods
Methods in
GManagerare as below:GManagergestSeqandgestName,strokesinitialisedregisterVector.<int>, String, intremoveintremoveAllstartgestCurrentpopulateintgestCurrentwith detected strokes (singular)tracerVector.<int>gestCurrentfor debugging purposes.dropStrokesVector.<int>, intVector.<int>gestCurrent. Keep mains and diagonals (0), keep only mains (1), keep only diagonals (2). (Part 3 will further explain its use.)dropDuplicatesVector.<int>, intVector.<int>duplicates. Input minimum duplicates (apart from self) to be considered valid stroke
checkMatchintintgestSeqmatches withgestCurrentendArrayArraywith index of matchedsequence in
gestSeqand its name ingestNameProperties of
GManagerare as below:useOrdergestSeqis to be detected in orderlengthgestSeqStep 6: Register Predefined Stroke Sequences
As mentioned, the first step is to register unique stroke sequences that the entered gesture can be compared against. The constructor initates variables needed (highlighted) and methods that follow registers into and removes from predefined stroke sequences.
/** * Constructor to initiate gestSeq, stokes, gestName */ public function GManager(){ gestSeq = new Vector.<Vector.<int>>; gestName = new Vector.<String>; strokes = new Vector.<int>; } /** * Method to register a set/ sequence of gesture * @param sequence Numerical representation of gesture sequence * @param identifier Name representation of gesture * @param allowed Stokes allowed: Both (0), main four (1), diagonals (2) */ public function register(sequence:Vector.<int>, name:String, onlyStrokes:int = 0):void { gestSeq.push(sequence); gestName.push(name); strokes.push(onlyStrokes); } /** * Method to remove a specific set of gesture * @param selectSet Selected sequence to remove */ public function remove(selectSet:int):void { gestSeq.splice(selectSet, 1); gestName.splice(selectSet, 1); strokes.splice(selectSet, 1); } /** * Method to remove all predefined gestures. */ public function removeAll():void { gestSeq = new Vector.<Vector.<int>>; gestName = new Vector.<String>; strokes = new Vector.<int>; }Step 7: Properties
Below are the properties specifically for set holding stroke seqeunces,
gestSeq:/** * Property to get total sets of predefined gestures */ public function get length ():int { return gestSeq.length; } /** * Property to get current setting on sequential gesture detection */ public function get useOrder():Boolean { return _order; } /** * Property to determine whether sets of predefined gestures should be detected sequentially */ public function set useOrder(value:Boolean):void { _order = value; }Step 8: Record Current Stroke Sequence
After registering stroke sequences to detect against, we can prepare
gestCurrentand record consequtive valid singular strokes into it. Methods below will provision for it.Traceris a method to trace the current gesture’s sequence./** * Method to start recording current set of gesture made */ public function start():void { gestCurrent = new Vector.<int>; } /** * Method to populate gesture into current set of gesture * @param gestureCode Gesture detected from MGesture */ public function populate (gestureCode:int):void { //Accept only valid singular gesture (0~8) into current sequence if(gestureCode > -1) gestCurrent.push(gestureCode); } /** * Method used for debugging. Traces gestCurrent */ public function tracer():Vector.<int> { return gestCurrent; trace(gestCurrent); }Step 9: Looking into
gestCurrentBy now, we can already write a program to check out current gesture’s sequence as mentioned in Step 2. You may download the source and look at the class
CheckOut2. Turn on your Output panel in FlashDevelop to view the sequence of integers committed by your current gesture.I’ve also included a demo of it below and placed a
TextFieldto display the sequence instead of the Output panel in FlashDevelop.Step 10: Implementation of
CheckOut2I have included source code of
checkOut2as below. Its not tough to understand the logic provided you have understood how event handlers are assigned. (Read this tutorial to find out more about event handlers.) I’ve also highlighted important points whereGManager‘s methods are being used.public class CheckOut2 extends Sprite { private var ges:MGesture; //instance of singular gesture detection private var gesMan:GManager; //instance of sequence gesture detectio private var t:TextField; public function CheckOut2() { //initiating MGesture to allow singular gesture detection ges = new MGesture(stage); //initiating GManager to allow sequential gesture detection gesMan = new GManager(); t = new TextField() t.x = 50; t.y = 50; t.autoSize = TextFieldAutoSize.LEFT; addChild(t); stage.addEventListener(MouseEvent.MOUSE_DOWN, start); stage.addEventListener(MouseEvent.MOUSE_UP, end); } private function start(e:MouseEvent):void { //Start detecting singular and sequential gesture ges.start(); gesMan.start(); stage.addEventListener(MouseEvent.MOUSE_MOVE, check); //Start drawing gesture graphics.clear(); graphics.lineStyle(3); graphics.moveTo(mouseX, mouseY); } private function check(e:MouseEvent):void { gesMan.populate(ges.evalDirections()); //Feed singular gesture into a sequence graphics.lineTo(mouseX, mouseY) //Drawing gesture } private function end(e:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE, check); t.text = gesMan.tracer().toString() } }Step 11: Clean Up
gestCurrentof Unnecessary StrokesCleaning up strokes in current gesture is important, as there are:
I have divided the clean-up job into two phases, specifically
dropStrokesanddropDuplicates.dropStrokeseliminates strokes that made it difficult to detect of gestures. (This feature will be explained in detail in Part 3 when we detect alphabetical letters.)dropDuplicateseliminates duplicates and invalid strokes.dropStrokeswill only keep strokes ingestCurrentaccording to the third paramenter,onlyStrokes, inregister. It is defined when we register the gesture sequences initially. For further understanding, again, watch out for Part 3. But for now, just keep it at the back of your head. In fact, this tutorial does not make use of this feature just yet./** * Method to rid irrelevant strokes based upon condition * @param strokesCondition * @return Vector of */ private function dropStrokes(inputArray:Vector.<int>, strokesCondition:int):Vector.<int> { var xDiagonals:Vector.<int> = inputArray.slice(0,inputArray.length); //Keep mains only if (strokesCondition == 1) { for (var i:int = 0; i < xDiagonals.length; i++) { if (xDiagonals[i] > 3) { xDiagonals.splice(i, 1); i-- } } } else if (strokesCondition == 2) { for (var j:int = 0; j < xDiagonals.length; j++) { if (xDiagonals[j] <4) { xDiagonals.splice(j, 1); j-- } } } return xDiagonals }Step 12: Clean Up
gestCurrentSwipe left-to-right to go to the next frame.
The second phase of clean up is to rid the duplicate and invalid strokes as mentioned in Step 2. The implementation is written below.
I’ve placed a Flash presentation above to ease your understanding of the algorithm. Make a right gesture using mouse to go to next frame, make a left to go back to previous frame. Up gesture brings you to the final frame, down gesture brings you to the first frame.
/** * Method to rid duplicates and possible mistaken gestures * @param minDuplicates Repetition to be considered high repetition * @return Vector array w/o duplicates and possible mistaken gestures */ private function dropDuplicates (inputArray:Vector.<int>, minDuplicates:int = 1):Vector.<int> { //Append end of line indicator to integer array var xDuplicates:Vector.<int> = inputArray.slice(0,inputArray.length); xDuplicates.push( -1); //Initiate variables var count:int = 1; var keepIndex:int = 0; //Ripping duplicates and invalid moves for (var i:int = 0; i < xDuplicates.length - 1; i++) { if (xDuplicates[i] == xDuplicates[i + 1]) count ++ else{ if (count > minDuplicates) { xDuplicates.splice(keepIndex, count - 1) keepIndex++ i = keepIndex count = 1 } else xDuplicates.splice(keepIndex, minDuplicates) i-- } } xDuplicates.splice(xDuplicates.length - 1, 1); return xDuplicates; }Step 13: Check for a Match
After trimming down
gesCurrent, our next task is to find a proper match in the set of predefined gesture sequences. We can verify match between current gesture and a member of predefined gestures usingcheckMatch. Input the index ofgestSeqyou would like to check match withgestCurrent. A return value of-1indicates no match; the index ofgestSeqis matched otherwise./** * Method to check if gestCurrent matches with gestSeq * @param index Member of gestSeq * @return Match (1) or fail (-1) */ private function checkMatch(index:int):int { //Pessimistic search, assumes not found initially var matched:int = -1; //clean input first var cleaned:Vector.<int> = dropStrokes(gestCurrent, strokes[index]); trace(cleaned, " xstrokes"); cleaned = dropDuplicates(cleaned);trace(cleaned," xduplicates") //Check only those of same length if (cleaned.length == gestSeq[index].length) { var counter:int = cleaned.length; //Scroll through each integer of selected predefined gesture for (var member:int = 0; member < cleaned.length; member++) { if (cleaned[member] == gestSeq[index][member]) counter--; else break; } //if all integers matched, current index of gestSeq matches gestCurrent if (counter == 0 ) matched = index; } return matched; }Step 14: Output the Result
Finally, we can output the result. The result will be based upon whether
_orderis turned on or not. We check match betweengestCurrentwith currentgestSeqonly if_orderis turned on, otherwise we will need to search for match with any member ingestSeq.Regardless of the search outcome, we need to output the result. Search result will be
-1if there’s no successful match; if there’s a match, an array of stroke index coupled with its name will be returned. The result is-2ifgestSeqis empty./** * Method to evaluate gesture according to preferred approach (in sequential order or not) * @return No predefined gestures (-2), No match of gesture (-1), array with index of match and its description */ public function end():Array { //Pessimistic search, -2 indicates that there are no predefined gesture var result:Array = [ -2, "No predefined gestures"]; //If there are predefined gestures if (gestSeq.length > 0) { //Find the match in order if (_order) { if (checkMatch(orderCurrent) > -1) { result = [orderCurrent, gestName[orderCurrent]]; orderCurrent++; } } //Find a match in no specific order else if (!_order) { //Scroll through all gestures for (var i:int = 0; i < gestSeq.length; i++) { if (checkMatch(i) > -1) { result = [i, gestName[i]]; } } } //Handle when cant find else { result = [ -1, "Gesture is invalid."] } } return result }Step 15: Prepare Graphical Assets in Flash
With Step 14 we completed
GManager. We need to create graphical assets next. I have created the graphical assets in Flash Pro and will export them in .swc format. Press Ctrl + Shift + F12 to pop the Publish Setting window out in Flash and check “Export SWC” under Flash tab. I’ve made my assets available for download but feel free to develop your own.Step 16: Importing Assets Into FlashDevelop
Bring your SWC into FlashDevelop’s
libfolder as shown above. Create a class named “Main2″ in FlashDevelop and instantiate the MovieClip that holds the graphics. I’ve highlighted the relevant ActionScript below.private var ges:MGesture; private var gesMan:GManager; private var a:Arrows; private var seq:Boolean = false; public function Main2() { //Importing graphics in form of movieclip a = new Arrows(); a.stop(); a.x = 50; a.y = 50; addChild(a);Step 17: Register Corresponding Gestures
We shall register our gesture sequences in the order that graphics are arranged in our published MovieClip. We do so to make easy scrolling of frames once the result has been attained. Note as well that I have highlighted line 33 of the implementation; you may uncomment this to in my source file to see matching done in order.
public function Main2() { //Importing graphics in form of movieclip a = new Arrows(); a.stop(); a.x = 50; a.y = 50; addChild(a); //initiating MGesture to allow singular gesture detection ges = new MGesture(stage); //initiating GManager to allow sequential gesture detection gesMan = new GManager(); //this.seq = true; //Detecting gestures in sequence if (seq) { a.gotoAndStop(2); gesMan.useSeq = true; } //Register gesture sequences in line with frames //Register gesture sequences in line with frames gesMan.register(new < int > [2, 1], "2 Stroke Down, CCW"); gesMan.register(new < int > [1, 0], "2 Stroke Right, CCW"); gesMan.register(new < int > [0, 3], "2 Stroke Up, CCW"); gesMan.register(new < int > [3, 2], "2 Stroke Left, CCW"); gesMan.register(new < int > [3, 2, 1], "3 Stroke Down, CCW"); gesMan.register(new < int > [2, 1, 0], "3 Stroke Right, CCW"); gesMan.register(new < int > [1, 0, 3], "3 Stroke Up, CCW"); gesMan.register(new < int > [0, 3, 2], "3 Stroke Left, CCW"); gesMan.register(new < int > [3, 0], "2 Stroke Right, CW"); gesMan.register(new < int > [0, 1], "2 Stroke Down, CW"); gesMan.register(new < int > [1, 2], "2 Stroke Left, CW"); gesMan.register(new < int > [2, 3], "2 Stroke Up, CW"); gesMan.register(new < int > [2, 3, 0], "3 Stroke Right, CW"); gesMan.register(new < int > [3, 0, 1], "3 Stroke Down, CW"); gesMan.register(new < int > [0, 1, 2], "3 Stroke Left, CW"); gesMan.register(new < int > [1, 2, 3], "3 Stroke Up, CW"); gesMan.register(new < int > [0, 3, 0, 3, 0],"Step Up"); gesMan.register(new < int > [0, 1, 0, 1, 0], "Step Down"); gesMan.register(new < int > [4], "South East"); gesMan.register(new < int > [5], "South West"); gesMan.register(new < int > [6], "North West"); gesMan.register(new < int > [7], "North East"); gesMan.register(new < int > [4, 5, 4, 5], "Zigzag"); stage.addEventListener(MouseEvent.MOUSE_DOWN, start); stage.addEventListener(MouseEvent.MOUSE_UP, end); }Step 18: Handling Results
Recording of gesture sequence follows the same approach as
CheckOut2. I assume readers have gone through Step 10. So finally, we shall output the result. Upon successful match (> -1), we shall scroll to the appropriate frame. Again, this is subject to whether you have enabled the use of sequence by turning onseqor not.private function end(e:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE, check); //evaluate gesture and output result var output:Array = gesMan.end() if (output[0] > -1) { if (seq)a.nextFrame(); else a.gotoAndStop(output[0] + 2); //offset needed as first frame is empty. } }Step 19: Publish Your Project
Press Ctrl + Enter to publish your project. Gesture with your mouse and what was detected. I’ve included both projects (one requests you to match a given gesture; the other displays the gesture you drew, if it matches one it knows). Have fun.
Step 20: Application Development
Inaccuracies in user gestures are common, and any application that incorporates gestures should consider this. In the next part of this tutorial, I shall attempt to use
MGestureandGManagerto develop an alphabet recognition application. I shall point out several details to tweak accordingly to improve gesture detection.Conclusion
You should now find it easy to develop applications that detect gesture sequences of any combination. Hope this tutorial has helped you in some ways. Let me know of your comments, queries and bugs encountered. Terima kasih.
A couple of months ago, Carlos showed Premium members how to create a Whack-a-Mole game using Flash and AS3. Now, following on from Monday’s introduction to EaselJS, he’ll explain how to use that library to create the same game with the HTML5 canvas and JavaScript.
Preview
Let’s take a look at the final result we will be working towards:
Click to try it out!
You can read the first five steps of the tutorial over on Tuts+ Premium, or join Premium to read the whole thing.
Active Premium Membership
We run a Premium membership system which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium, Photo Premium, and the new Mobile Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!
Also, don’t forget to follow @envatoactive on twitter and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.
In this series finale I’m excited to introduce you to the features that make TimelineMax so special. I’m also going to touch on some special tricks you can do with TimelineLite so that you can apply wild ease effects to the total play back speed of a timeline that includes hundreds of tweens and nested timelines. You have to see it to believe it.
TimelineMax in Action
The swf below contains a single TimelineMax with a repeat value of 1 and yoyo of true. The
totalTimeandtotalProgressvalues reflect the amount of time it takes for the entire sequence to run twice. TimelineMax’saddCallback()method is used to call a function that handles swapping the depths of the blob and the bush so that the blob can jump behind the bush. This swapping happens instantly when the blob finishes his upward movement regardless of whether or not the timeline is playing backwards or forwards.You can find all the files used to create the SWF above in the source files for this tutorial.
Watch the Screencast
Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!
TimelineMax Special Properties
TimelineMax’s most popular feature is that you can easily tell it how many times to repeat. There are a number of special properties that can be passed into the TimelineMax constructor’s
varsobject that help you fine tune exactly how the repeat works:tl = new TimelineMax( {repeat: 2, repeatDelay: 1, onRepeat: doSomethingCool, yoyo: true } );The code above will create a timeline that does the following:
doSomethingCool()will fire and the timeline will play backwards instantaneously.doSomethingCool()will fire and the timeline will play forwards instantaneously.Duration, Time and Progress
Once a timeline is told to repeat it is helpful to be able to access a number of properties that take into consideration the duration of all the iterations and delays:
It’s worthwhile to note that TimelineLite does have
totalDurationandtotalTimeproperties but since TimelineLite doesn’t repeat, they offer the most value when used with TimelineMax.Calling a Function From TimelineMax
TimelineMax makes it easy to call functions from any point in time. You may be familiar with the process of adding an
onComplete()callback to an individual tween in a timeline, butaddCallback()offers two advantages:addCallback()functions will be fired when the timeline is playing forwards AND in reverse.addCallback()doesn’t need to be locked to a particular tween endingaddCallback() Method signature:
tl = new TimelineMax(); tl.append( TweenLite.to( mc, 5, {x:500} ) ); tl.addCallback ( doSomethingCool, tl.duration-1, ["Steve"]) ); function doSomethingCool(someValue:String):void{ trace("Hi " + someValue); }The code above will cause the phrase “Hi Steve” to appear in the output panel one second before the previous tween ends.
Calling a Function From TimelineLite
TimelineLite offers similar functionality by way of appending or inserting a TweenLite.delayedCall() method but the code is a bit more verbose.
someTimelineLite.append( TweenLite.to( mc, 5, {x:500} ) ); someTimelineLite.append( TweenLite.delayedCall( 0, doSomethingCool, ["Steve"] ), -1 );Tweening the Playback of a Timeline
One of the best kept secrets of the GreenSock Tweening Platform is that you can tween a TweenLite, TweenMax, TimelineLite and TimelineMax. In the video I focus on tweening the playback of the “timeline brothers”. The benefit of tweening a tween or timeline is that you can adjust the speed at which it plays back and also apply easing.
Tween the timeScale of a TimelineLite/Max
This method is great for getting an animation to slowly come to stop at any point in time or resume playing with a nice ease-in. Notice the nice ease that is applied when entering or leaving a paused state.
Combine TimelineMax’s tweenTo() With an Ease
This method works well for applying an ease to the playback speed of an entire timeline or just a segment. Notice the radical change in playback of the timeline when the Circ In Out and Bounce Out buttons are pressed.
Hopefully the SWF above will entice you find out more by watching the video and downloading the source files.
Conclusion
There are more things that TimelineMax can do but I chose to focus on the most commonly used features. I gave you a look at TimelineMax’s
currentLabelproperty andgetLabelAfter()method in Part 4: Working with Labels. As always I recommend reading and bookmarking the TimelineMax documentation to be sure you are getting the most out the tools you choose to use. I still learn something new every time I poke around in there.It has been an amazing experience for me to share with you nearly three hours of TimelineLite/Max training. I am confident that if you take the time to watch through each video and experiment with the source files you will have an incredibly strong foundation to start building upon. The potential for what you can achieve with TimelineLite/Max is virtually limitless. I truly hope you are as excited as I am about what can be done with these amazing tools.
For those of you who want to continue your TimelineLite/Max education I am sure you will find the following tutorials very useful:
I have to give special thanks to Jack Doyle of GreenSock for creating these amazing tools and also offering his support throughout the creation of these videos. Never in my life have I come across a business or product creator that goes to the lengths that Jack does to keep his customers and legions of enthusiasts so darn happy.
Thanks so much for watching this series and providing feedback. If you would like to contact me with any questions related to TimelineLite/Max please comment below or send an email. You can find my email address at the end of the video.
-Carl