Jan 12, 2012
Posted on Jan 12, 2012 in Hints and Tips | 10 comments
Stop using static menus! Most players immediately base their initial impression of a Flash game on the menu that they see when they load it. Stand out from the crowd with an active menu!
This tutorial was first posted in December 2011, but has since been updated with extra steps that explain how to make the code more flexible!
Final Result Preview
Introduction: Static vs Active
The word “static” essentially means lacking in change. The majority of menus we see throughout web games are lacking in change, you simply press Play and the game starts. Menus like that are overused and show little creativity or innovation.
To make a menu “active” we must continuously cause change. So in this tutorial that is exactly what we are going to accomplish: a menu that continuously changes.
Step 1: Setting Up
The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 650px, its height to 350px, and the frames per second to 30. The background color can be left as white.
Now save the file; you can name it whatever you please, but I named mine menuSlides.fla.
In the next section we will create the nine MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial:
- White – #FFFFFF
- Gold – #E8A317
- Light Gold – #FBB917
- Blue – #1569C7
- Light Blue – #1389FF
- Green – #347235
- Light Green – #3E8F1B
- Red – #990000
- Light Red – #C10202
- Matte Grey – #222222
Step 2: Creating the Slide MovieClips
To start with we will create the slides used in the transitions, but before we begin let’s turn on some very useful Flash features.
Right-Click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid.
Now we can begin drawing! Select the Rectangle Tool and draw a Light Gold rectangle, 650px wide and 350px tall (you can Alt-click on the stage to make this easier). Now change the color to Gold and draw groups of three squares, each 20x20px, to form the shape of an L in each corner,:
Select the whole stage, right-click and choose Convert to Symbol. Name the MovieClip goldSlide and make sure that the type is MovieClip and the registration is top-left.
To save time and make things a whole lot easier, right-click the goldSlide MovieClip in the Library and select Duplicate Symbol three times to make three more copies. Change the colors in the new MovieClips to blue, green and red, then rename the MovieClips to blueSlide, greenSlide and redSlide.
Before we continue we should add some text to each slide. On goldSlide write PLAY, on blueSlide write INSTRUCTIONS, on greenSlide write OPTIONS and on redSlide write CREDITS.
Now that we have the text in place we can break it apart by right-clicking on it and selecting Break Apart twice; this will break the text down to a fill which will transition more smoothly. Plus as a bonus there will be no need to embed a font if you are just using it for the menu!
The Buttons
Now that we have drawn the 4 slides we can focus on the sideButton MovieClip that is used to move the slides either left or right.
First, draw a rectangle 30x60px with only a stroke (no fill), then draw diagonal lines 45 degrees from the top-right and bottom-right corners until they snap together in the middle of the opposite side. Now apply a Matte Grey fill to the triangle:
Next, delete the lines, then right-click the triangle and select Convert to Symbol. Name it sideButton, set the type to Button and make sure the registration is in the top-left corner.
Now insert 3 keyframes in the timeline by right-clicking the timeline and selecting Insert Keyframe. On the Up frame, select the fill of the triangle, go to the Windows tab and select Color. Change the Alpha to 50%. On the Over Frame repeat the same process, but this time set the alpha to 75%.
Now we can begin on the four numbered circle buttons, for jumping directly to a particular slide.
To start draw a white 30px circle with no stroke. Convert it to a symbol, name it circleOne, and set its type to Button and its registration point to the center. Insert three keyframes like we did before and then go to the Up frame.
Draw a black 25px circle with no stroke and center it to the middle through the coordinates or by using the Align menu. Next deselect the black circle, then reselect it and delete it. You should now have a white ring remaining. Now grab the text tool and put a white “1″ in the center of the ring. Then break this number apart until it is a fill.
Go to the Over frame and draw a black “1″. Center it and break it apart until it becomes a fill. Now deselect and reselect the fill, then delete it. Select everything on the frame and copy it, then go to the Down frame, select everything on it and hit delete. Paste in what we have copied.
Now create three more circle MovieClips, following the same process, for the numbers 2, 3 and 4.
Step 3: Positioning the MovieClips
Okay, we’re almost half-way done! First drag all of the slides onto the stage and position them with the following coordinates:
- goldSlide: (0, 0)
- blueSlide: (650, 0)
- greenSlide: (1300, 0)
- redSlide: (1950, 0)
Now drag and drop two copies of the sideButton. The first copy should be positioned at (10,145); before we can position the second copy we must first flip it!
Select the second copy and press Ctrl-T. Change the left-right to -100% and leave the up-down at 100%. Now move the second copy to (640,145).
Finally drag and drop the four circle MovieClips and position them as so:
- circleOne: (30, 320)
- circleTwo: (70, 320)
- circleThree: (110, 320)
- circleFour: (150, 320)
Your stage should now look like this:
The blue, green and red slides are hidden just off to the right of the stage. Now select everything on the stage and convert to a symbol. Name it menuSlidesMC, set the type to MovieClip and the registration to the top-left corner, and export it for ActionScript as MenuSlidesMC.
Before we finish we must give each of the MovieClips inside menuSlidesMC an instance name. Select each slide in the order they appear from the left and name them slide1, slide2, slide3 and slide4 respectively. Name the circle buttons one, two, three and four, and finally name the side buttons left and right.
Step 4: Setting Up the Classes
Now that all of our MovieClips have been created we can start setting up the two classes we are going to use.
First go to your Flash file’s Properties and set its class to menuSlides; then, create a new ActionScript 3.0 file and save it as menuSlides.as.
Now copy the following code into it; I will explain it after:
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class menuSlides extends MovieClip{
public var menuSlidesMC:MenuSlidesMC = new MenuSlidesMC();
public function menuSlides(){
addChild(menuSlidesMC);
}
}
}
Pretty basic – it’s a document class, into which we imported the MovieClips and Events we will use. Then we created an instance of MenuSlidesMC, and added it to the stage.
Now create a new ActionScript 3.0 file for the menuSlidesMC instance. Save it as MenuSlidesMC.as and copy the following code into it:
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class MenuSlidesMC extends MovieClip{
public var speed:Number = new Number();
public var activeSlide:Number = new Number();
public function MenuSlidesMC(){
speed = 10;
activeSlide = 1;
addEventListener(MouseEvent.CLICK, slidesClick);
addEventListener(Event.ENTER_FRAME, slidesMove);
}
}
}
Just like last time, we imported what we are going to need, but we created two number variables. The first variable, speed, is actually how many pixels the slides are moved by each frame. (Note: this number has to evenly divide into your stage’s width to give a smooth transition). The second variable, activeSlide, tells us which slide is currently set to be on screen.
We also added two event listeners for functions we are going to create; one of them is called on a mouse click, and the other is called at the beginning of every frame.
Step 5: Creating the Event Handler Functions
To begin we will get the mouse click function out of the way. Start by creating a public function named slidesClick():
public function slidesClick(event:MouseEvent):void {
}
Next we will create some if-statements regarding the event.target.name. Basically, this property stores the name of the object that was targeted by the mouse click. We can use this to check which button is pressed:
if(event.target.name == "left"){
if(activeSlide>1){
activeSlide-=1;
}
}else if(event.target.name == "right"){
if(activeSlide<4){
activeSlide+=1;
}
}
if(event.target.name == "one"){
activeSlide=1;
}else if(event.target.name == "two"){
activeSlide=2;
}if(event.target.name == "three"){
activeSlide=3;
}else if(event.target.name == "four"){
activeSlide=4;
}
The code above goes in the slidesClick() function. The first set of if-statements are for the left and right side buttons; they increase or decrease the value of activeSlide, but never allow the value to become less than 1 or greater than 4 (since we only have four slides). The second set of if-statements are for the circle buttons; instead of just incrementing or decrementing the value of activeSlide they set it to the selected value.
Now let’s begin with the ENTER_FRAME handler function:
public function slidesMove(event:Event):void {
}
Add the slidesMove() function below your slidesClick() function and we’ll start adding some code to it. First, we’ll use a switch to check which slide should be on the screen, based on the value of activeSlide:
switch (activeSlide){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
Now in each case we will create an if/else block that will check that slide’s current x-position, and move all of the slides either left, right, or not at all, depending on where the desired slide currently sits.
The first case looks like this:
if(slide1.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide1.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
Now all we have to do is repeat the same process for the other cases! After you are done your swtich should look like this:
switch (activeSlide){
case 1:
if(slide1.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide1.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 2:
if(slide2.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide2.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 3:
if(slide3.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide3.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 4:
if(slide4.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide4.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
}
And that’s it! We are all finished with the code and the menu should be working great right now.
…But wait, what if we want to add more slides or take some away?
Step 6: Adding Slides to an Array
At the moment our code isn’t very flexible due to all of those hard-coded if statements. So let’s do something bold: delete all of the code in the slidesMove() function because we will no longer be needing it, and also delete the if-statements for the circle buttons as we are going to optimize those as well.
Now declare a new variable (underneath speed and activeSlides):
public var slidesArray:Array = new Array();
The first variable, slidesArray, will be an array that contains all of our slides, which will allow us to access them by referencing an item in the array (so we can use slidesArray[2] instead of slide3).
One thing to note is that the first item in an array is given an index of 0, so we will have to make some changes to our instance names.
Select each slide in the order they appear from the left and name them slide0, slide1, slide2 and slide3, respectively. And to help us cut down on the number of lines of code we use, select each circle button in the order they appear from the left and name them circle0, circle1, circle2 and circle3, respectively.
If you are going to add more slides and buttons, now is the time to do so. Just position the extra slides at the end of the row of slides, then give them instance names following the same order. Then do the same for the circle buttons.
Now that we have the instance names correct we must add the slides to the array. Do so by adding the following code to your constructor:
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
Now the slides are in the array and can be accessed by their index in the array. For example, slidesArray[0] is equivalent to slide0 because that is the first item in the list.
Next, inside the “right” else-if statement, change the condition to:
if(activeSlide < slidesArray.length-1){
The value of slidesArray.length is equal to the number of elements in the array, so this new condition will now allow us to press the button and shift the slides over as long as the active slide is not the final slide.
Step 7: Handling Circle Button Presses
Now, when a circle button is clicked, we need to figure out which one it is (and which slide it refers to).
Create an array to hold all the circle buttons. First, define it, beneath the slide array:
public var slidesArray:Array = new Array();
public var circlesArray:Array = new Array();
Then, add the circle buttons to the array in the constructor:
circlesArray = [circle0, circle1, circle2, circle3, circle4, circle5];
Now, move to the slidesClick() function, underneath the whole if-else block. We’re going to check whether the button clicked is in the circle buttons array:
if (circlesArray.indexOf(event.target) != -1) {
}
The array’s indexOf() function checks to see whether an object is in the array; if it’s not, it returns -1. So, we’re checking to see whether it’s not equal to -1, which will check to see whether it is in the array.
Assuming it is, then the indexOf() function will return the index of the button within the circle buttons array – so, if circle3 was clicked, circlesArray.indexOf(event.target) will be equal to 3. This means we can just set activeSlide to 3, and we’re done!
if (circlesArray.indexOf(event.target) != -1) {
activeSlide = circlesArray.indexOf(event.target);
}
Step 8: Moving the Slides
The only thing left to do is move all of the slides. Begin by adding the same loop as we had before, in the slidesMove() function:
for(var i:int = 0; i < slidesArray.length; i++){
}
An if-else statement needs to be added now; this will use the variable activeSlide to select a slide out of the array and check where its x-position is, just like before.
if(slidesArray[activeSlide].x<0){
}else if(slidesArray[activeSlide].x>0){
}
Since activeSlide is a number, slidesArray[activeSlide] refers to one specific slide, so slidesArray[activeSlide].x is equal to that slide’s x-position.
In the first case we will add a for loop to move all of the movie clips to the right, and in the second case we will add a for loop to move all of the movie clips to the left.
Right:
for(var j:int = 0; j < slidesArray.length; j++){
slidesArray[j].x+=speed;
}
Left:
for(var k:int = 0; k < slidesArray.length; k++){
slidesArray[k].x-=speed;
}
If you test this now, you will notice that our optimised code has lead to a much zippier interface!
Step 9: Taking It Further
If you wanted to take this even further, you could use a for loop to position the slides and the circles, rather than needing to drag and drop them in the Flash IDE. For example, to position the slides, we’d first position slide0 in the constructor:
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
slidesArray[0].x = 0;
slidesArray[0].y = 0;
Then, we’d loop through all the other slides, starting at slide1:
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
slidesArray[0].x = 0;
slidesArray[0].y = 0;
for (var i:int = 1; i < slidesArray.length; i++) {
}
We can give all the slides an y-position of 0:
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
slidesArray[0].x = 0;
slidesArray[0].y = 0;
for (var i:int = 1; i < slidesArray.length; i++) {
slidesArray[i].y = 0;
}
…and then we can set each slide’s x-position to be 620px to the right of the slide before it:
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
slidesArray[0].x = 0;
slidesArray[0].y = 0;
for (var i:int = 1; i < slidesArray.length; i++) {
slidesArray[i].x = slidesArray[i-1].x + 620;
slidesArray[i].y = 0;
}
If your slides aren’t 620px wide, you can even detect their width automatically!
slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
slidesArray[0].x = 0;
slidesArray[0].y = 0;
for (var i:int = 1; i < slidesArray.length; i++) {
slidesArray[i].x = slidesArray[i-1].x + slidesArray[i-1].width;
slidesArray[i].y = 0;
}
You can do the same thing with the circle buttons, but I’ll leave that up to you to experiment with.
The great thing about this is, you can add as many slides as you want to the menu; all you have to do is add them to the array, and they’ll be dealt with by this code.
(You can remove slides from the array, too, but they won’t be affected by any of the code, so you’ll probably need to reposition them in the Flash IDE.)
Conclusion
Thank you for taking the time to read through the tutorial, I hope it was helpful and that you learned a little something about active game menus.



View full post on Activetuts+
Dec 21, 2011
Posted on Dec 21, 2011 in Hints and Tips | 10 comments
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:
- White –
#FFFFFF
- Gold –
#E8A317
- Light Gold –
#FBB917
- Blue –
#1569C7
- Light Blue –
#1389FF
- Green –
#347235
- Light Green –
#3E8F1B
- Red –
#990000
- Light Red –
#C10202
- Matte Grey –
#222222
Step 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:
- goldBar
- blueBar
- greenBar
- redBar
- goldBackground
- blueBackground
- greenBackground
- redBackground
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:
- The backgrounds are the size of the stage minus the total width of all the bars – which in turn is the number of bars that there are multiplied by the width of one bar.
- Each clause of the switch case either moves all the bars and their backgrounds that are on the selected bar’s right to the right, or moves the selected bar left with the bars to its left and their backgrounds, revealing its own background
Thank you for taking the time to read this article, I hoped you enjoyed it!



View full post on Activetuts+
Dec 9, 2011
Posted on Dec 9, 2011 in Hints and Tips | 10 comments
Stop using static menus! Most players immediately base their initial impression of a Flash game on the menu that they see when they load it. Stand out from the crowd with a dynamic menu!
Final Result Preview
Introduction: Static to Dynamic
The word “static” essentially means lacking in change. The majority of menus we see throughout web games are lacking in change, you simply press Play and the game starts. Menus like that are overused and show little creativity or innovation.
To make a menu “dynamic” we must continuously cause change. So in this tutorial that is exactly what we are going to accomplish: a menu that continuously changes.
Step 1: Setting Up
The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 650px, its height to 350px, and the frames per second to 60. The background color can be left as white.
Now save the file; you can name it whatever you please, but I named mine menuSlides.fla.
In the next section we will create the nine MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial:
- White – #FFFFFF
- Gold – #E8A317
- Light Gold – #FBB917
- Blue – #1569C7
- Light Blue – #1389FF
- Green – #347235
- Light Green – #3E8F1B
- Red – #990000
- Light Red – #C10202
- Matte Grey – #222222
Step 2: Creating the Slide MovieClips
To start with we will create the slides used in the transitions, but before we begin let’s turn on some very useful Flash features.
Right-Click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid.
Now we can begin drawing! Select the Rectangle Tool and draw a Light Gold rectangle, 650px wide and 350px tall (you can Alt-click on the stage to make this easier). Now change the color to Gold and draw groups of three squares, each 20x20px, to form the shape of an L in each corner,:
Select the whole stage, right-click and choose Convert to Symbol. Name the MovieClip goldSlide and make sure that the type is MovieClip and the registration is top-left.
To save time and make things a whole lot easier, right-click the goldSlide MovieClip in the Library and select Duplicate Symbol three times to make three more copies. Change the colors in the new MovieClips to blue, green and red, then rename the MovieClips to blueSlide, greenSlide and redSlide.
Before we continue we should add some text to each slide. On goldSlide write PLAY, on blueSlide write INSTRUCTIONS, on greenSlide write OPTIONS and on redSlide write CREDITS.
Now that we have the text in place we can break it apart by right-clicking on it and selecting Break Apart twice; this will break the text down to a fill which will transition more smoothly. Plus as a bonus there will be no need to embed a font if you are just using it for the menu!
The Buttons
Now that we have drawn the 4 slides we can focus on the sideButton MovieClip that is used to move the slides either left or right.
First, draw a rectangle 30x60px with only a stroke (no fill), then draw diagonal lines 45 degrees from the top-right and bottom-right corners until they snap together in the middle of the opposite side. Now apply a Matte Grey fill to the triangle:
Next, delete the lines, then right-click the triangle and select Convert to Symbol. Name it sideButton, set the type to Button and make sure the registration is in the top-left corner.
Now insert 3 keyframes in the timeline by right-clicking the timeline and selecting Insert Keyframe. On the Up frame, select the fill of the triangle, go to the Windows tab and select Color. Change the Alpha to 50%. On the Over Frame repeat the same process, but this time set the alpha to 75%.
Now we can begin on the four numbered circle buttons, for jumping directly to a particular slide.
To start draw a white 30px circle with no stroke. Convert it to a symbol, name it circleOne, and set its type to Button and its registration point to the center. Insert three keyframes like we did before and then go to the Up frame.
Draw a black 25px circle with no stroke and center it to the middle through the coordinates or by using the Align menu. Next deselect the black circle, then reselect it and delete it. You should now have a white ring remaining. Now grab the text tool and put a white “1″ in the center of the ring. Then break this number apart until it is a fill.
Go to the Over frame and draw a black “1″. Center it and break it apart until it becomes a fill. Now deselect and reselect the fill, then delete it. Select everything on the frame and copy it, then go to the Down frame, select everything on it and hit delete. Paste in what we have copied.
Now create three more circle MovieClips, following the same process, for the numbers 2, 3 and 4.
Step 3: Positioning the MovieClips
Okay, we’re almost half-way done! First drag all of the slides onto the stage and position them with the following coordinates:
- goldSlide: (0, 0)
- blueSlide: (650, 0)
- greenSlide: (1300, 0)
- redSlide: (1950, 0)
Now drag and drop two copies of the sideButton. The first copy should be positioned at (10,145); before we can position the second copy we must first flip it!
Select the second copy and press Ctrl-T. Change the left-right to -100% and leave the up-down at 100%. Now move the second copy to (640,145).
Finally drag and drop the four circle MovieClips and position them as so:
- circleOne: (30, 320)
- circleTwo: (70, 320)
- circleThree: (110, 320)
- circleFour: (150, 320)
Your stage should now look like this:
The blue, green and red slides are hidden just off to the right of the stage. Now select everything on the stage and convert to a symbol. Name it menuSlidesMC, set the type to MovieClip and the registration to the top-left corner, and export it for ActionScript as MenuSlidesMC.
Before we finish we must give each of the MovieClips inside menuSlidesMC an instance name. Select each slide in the order they appear from the left and name them slide1, slide2, slide3 and slide4 respectively. Name the circle buttons one, two, three and four, and finally name the side buttons left and right.
Step 4: Setting Up the Classes
Now that all of our MovieClips have been created we can start setting up the two classes we are going to use.
First go to your Flash file’s Properties and set its class to menuSlides; then, create a new ActionScript 3.0 file and save it as menuSlides.as.
Now copy the following code into it; I will explain it after:
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class menuSlides extends MovieClip{
public var menuSlidesMC:MenuSlidesMC = new MenuSlidesMC();
public function menuSlides(){
addChild(menuSlidesMC);
}
}
}
Pretty basic – it’s a document class, into which we imported the MovieClips and Events we will use. Then we created an instance of MenuSlidesMC, and added it to the stage.
Now create a new ActionScript 3.0 file for the menuSlidesMC instance. Save it as MenuSlidesMC.as and copy the following code into it:
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class MenuSlidesMC extends MovieClip{
public var speed:Number = new Number();
public var activeSlide:Number = new Number();
public function MenuSlidesMC(){
speed = 10;
activeSlide = 1;
addEventListener(MouseEvent.CLICK, slidesClick);
addEventListener(Event.ENTER_FRAME, slidesMove);
}
}
}
Just like last time, we imported what we are going to need, but we created two number variables. The first variable, speed, is actually how many pixels the slides are moved by each frame. (Note: this number has to evenly divide into your stage’s width to give a smooth transition). The second variable, activeSlide, tells us which slide is currently set to be on screen.
We also added two event listeners for functions we are going to create; one of them is called on a mouse click, and the other is called at the beginning of every frame.
Step 5: Creating the Event Handler Functions
To begin we will get the mouse click function out of the way. Start by creating a public function named slidesClick():
public function slidesClick(event:MouseEvent):void {
}
Next we will create some if-statements regarding the event.target.name. Basically, this property stores the name of the object that was targeted by the mouse click. We can use this to check which button is pressed:
if(event.target.name == "left"){
if(activeSlide>1){
activeSlide-=1;
}
}else if(event.target.name == "right"){
if(activeSlide<4){
activeSlide+=1;
}
}
if(event.target.name == "one"){
activeSlide=1;
}else if(event.target.name == "two"){
activeSlide=2;
}if(event.target.name == "three"){
activeSlide=3;
}else if(event.target.name == "four"){
activeSlide=4;
}
The code above goes in the slidesClick() function. The first set of if-statements are for the left and right side buttons; they increase or decrease the value of activeSlide, but never allow the value to become less than 1 or greater than 4 (since we only have four slides). The second set of if-statements are for the circle buttons; instead of just incrementing or decrementing the value of activeSlide they set it to the selected value.
Now let’s begin with the ENTER_FRAME handler function:
public function slidesMove(event:Event):void {
}
Add the slidesMove() function below your slidesClick() function and we’ll start adding some code to it. First, we’ll use a switch to check which slide should be on the screen, based on the value of activeSlide:
switch (activeSlide){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
Now in each case we will create an if/else block that will check that slide’s current x-position, and move all of the slides either left, right, or not at all, depending on where the desired slide currently sits.
The first case looks like this:
if(slide1.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide1.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
Now all we have to do is repeat the same process for the other cases! After you are done your swtich should look like this:
switch (activeSlide){
case 1:
if(slide1.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide1.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 2:
if(slide2.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide2.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 3:
if(slide3.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide3.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
case 4:
if(slide4.x<0){
slide1.x+=speed;
slide2.x+=speed;
slide3.x+=speed;
slide4.x+=speed;
}else if(slide4.x>0){
slide1.x-=speed;
slide2.x-=speed;
slide3.x-=speed;
slide4.x-=speed;
}
break;
}
And that’s it! We are all finished with the code and the menu should be working great right now.
Conclusion
Thank you for taking the time to read through the tutorial, I hope it was helpful and that you learned a little something about dynamic menus.



View full post on Activetuts+
Sep 24, 2011
Posted on Sep 24, 2011 in Hints and Tips | 10 comments
In this tutorial I will walk you through some of the uses of the Twitter REST API, and how you can use it to create a game that not only displays real-time Tweets, but uses them to generate objects the player can interact with.
Before you read this tutorial, I recommend that you read the AS3 101 sessions by Dru Kepple, Understanding JSON, Understanding the Game Loop – Basix, Greensock Tweening Platform sessions and maybe some design and animation tutorials.
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: Let’s Get the Assets Ready
Before we get started we will need to set up some assets; we are building a game, so you might want to make it look pretty
. We will need buttons for New Game, Instructions, Menu and Tweet (for the player’s score); we will also need a background, some birds, the golden egg and the cracked egg. Besides all that we will need some misc assets such as the loading message, the Tweet message, a “follow me” button, the instructions window and the bar where you will display your Tweets.
Step 2: Let’s Create Some Classes
For this tutorial we will be working with some classes, if you are not familiar with classes you should take a look at the How to Use a Document Class in Flash tutorial.
We will need a Main class which will be our main brain, that’s the one you will link to your FLA file. Besides that one, we will need a Game class which will handle the game logic of the game and do most of the work. Since games have events that you need to listen to we will create a class named GameEvent which we will use to communicate with our main class. We will also need an Egg class which will hold the data of the Tweet, the kind of egg that it will be, and some other things that we will need later on. And we will need a TweetHolder class which we will link to a movie clip on the library so we can autosize and add some properties to the Tweet that we will show. All of those classes will go to our com folder which needs to be right next to our FLA file.
Main.as
package com {
import flash.display.*;
// Extends MovieClip cause this will be linked our FLA file
public class Main extends MovieClip {
public function Main()
{
// Here we will add our code
}
}
}
Game.as
package com {
import flash.display.*;
public class Game extends Sprite {
public function Game()
{
// Here we will add the logics for our game
}
}
}
GameEvent.as
package com {
import flash.events.*;
// This will be our custom event so it will extend Event
public class GameEvent extends Event {
// Here we will store the parameters that we will receive, so that we can use them later on, that's why it's public
public var parameters:String;
// Here we add the params since we will use it later on to share information between classes
public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false)
{
// We need to initialize our super so we get all its properties
super(type, bubbles, cancelable);
}
}
}
Egg.as
package com {
import flash.display.*;
// This will be our custom event so it will extend Event
public class Egg extends Event {
public function Egg()
{
// Here we will add the logics for our eggs
}
}
}
TweetHolder.as
package com {
import flash.display.*;
// This will be our custom event so it will extend Event
public class TweetHolder extends Event {
public function TweetHolder()
{
// Here we will add the logics for our TweetHolder
}
}
}
Step 3: Arrange the Menu
It’s time to start the fun! Place all our menu assets, place your new game button on stage, create the title for your game, add the instructions as well as the instructions button. Once you have all that on stage assign an instance name to each of them since we will need to refer to them in our Main class.
Step 4: Prepare TweenLite
For this tutorial we will be using TweenLite from GreenSock which you can download HERE (click AS3, download the ZIP file containing it, then unzip it and copy the file named greensock.swc to the folder where you have your FLA file).
When you have the SWC file right next to your FLA we will need to link it to our FLA so click Edit on the Properties panel of your file:
Then click Settings right next to ActionScript 3.0, then the +, and enter “./greensock.swc”
After that we are ready to start working in our Main class.
Step 5: Showing the Instructions
To show the instructions of the game we will need to have already created a movie clip which will contain the instructions with the instance name of instructions_content and the button that will summon it with the instance name of instructions_btn. Besides that we will take the time to make everything act as a button.
We will use just one function to make the instructions show and hide so we will need a variable that will tell us whether the instructions are already being displayed; we will call that variable showingInstructions.
package com {
// import what we need to animate the objects
import com.greensock.TweenLite;
import com.greensock.easing.*;
import flash.display.*;
import flash.events.*;
public class Main extends MovieClip {
// variable that we will use to know if the instructions are being displayed
// set to false since the first position of the instructions will be out of frame
private var showingInstructions:Boolean = false;
public function Main() {
this.addEventListener(Event.ADDED, init);
}
private function init(e:Event):void
{
this.removeEventListener(Event.ADDED, init);
// set objects to act like button and get the pointer hand
instructions_btn.buttonMode = true;
instructions_content.close_btn.buttonMode = true;
// we will call the function instructionsHandler when the
instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
}
private function instructionsHandler(e:MouseEvent):void
{
// we ask if the instructions are being showed
if(showingInstructions)
{
// if they are we will want to send them out of frame and tell the game that is not being showed
TweenLite.to(instructions_content, .4,{y:600, ease:Cubic.easeIn});
showingInstructions = false;
} else {
// if it's not then we will animate it into stage and tell that it's being showed
TweenLite.to(instructions_content, .4,{y:364, ease:Cubic.easeOut});
showingInstructions = true;
}
}
}
}
Step 6: Follow Me Button
Since you are a developer and you might want users to get in touch with you a “follow me” button sounds like a good idea – so let’s make your button send the users to your twitter profile; we will do this by like so:
private function init(e:Event):void
{
this.removeEventListener(Event.ADDED, init);
// set objects to act like button and get the pointer hand
instructions_btn.buttonMode = true;
followMe_btn.buttonMode = true;
instructions_content.close_btn.buttonMode = true;
// we will call the function instructionsHandler when the
instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler);
}
The we will need to create our handler which will be called followMeHandler as we wrote when we declared the listener:
// this function will receive a MouseEvent object which we will call "e"
private function followMeHandler(e:MouseEvent):void
{
// You will need to change jscamposcr for your username, twitter will take care of the rest
navigateToURL(new URLRequest("http://www.twitter.com/jscamposcr"), "_blank");
}
Step 7: Prepare the Stage for a New Game
When you have your menu, the instructions and the “follow me” button working it’s time to get your hands dirty and start the hard work – but first we will need to prepare the area with the right objects to start the game. This we will do it by moving out all the objects of the menu, including the instructions.
First let’s add a click listener to the New Game button that we have in our stage, and then let’s create a function that will clean up the stage.
private function init(e:Event):void
{
this.removeEventListener(Event.ADDED, init);
// set up listeners, positions, visibility, etc
newGame_btn.buttonMode = true;
instructions_btn.buttonMode = true;
followMe_btn.buttonMode = true;
menu_btn.buttonMode = true;
instructions_content.close_btn.buttonMode = true;
newGame_btn.addEventListener(MouseEvent.CLICK, startGame);
instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler);
}
Next we will take all our objects out of the stage in the function startGame
private function startGame(e:* = null):void
{
TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
// we will need to hide the instructions if they are being desplayed
if(showingInstructions)
{
TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
showingInstructions = false;
}
}
Now we need to add a menu button and a score text field, we will call the menu button menu_btn and the score will be called score_text and it will be a dynamic text field. Don’t forget to embed the font; for this I will embed Verdana Bold by clicking on Embed and adding the characters we will need.
Then add both objects at the top of the stage but out of it since we wont need them in our first frame, then we will add two lines that will animate both of them on our startGame function:
private function startGame(e:* = null):void
{
TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
if(showingInstructions)
{
TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
showingInstructions = false;
}
}
Now let’s give the user the chance to go back to the menu by adding a function to the menu button that we just added; we will call this one goToMenu and we will call it when the user clicks on the menu_btn. For that, we will add an event listener in our start game function:
private function startGame(e:* = null):void
{
TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
menu_btn.buttonMode = true;
menu_btn.addEventListener(MouseEvent.CLICK, goToMenu);
TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
if(showingInstructions)
{
TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
showingInstructions = false;
}
}
Now the function that will make things come back:
private function goToMenu(e:MouseEvent):void
{
// we disable the event listener
menu_btn.removeEventListener(MouseEvent.CLICK, goToMenu);
// we move back all our assets
TweenLite.to(title, .3, {y:91, delay:.2, ease:Quad.easeOut});
TweenLite.to(newGame_btn, .3, {x:162, delay:.2, ease:Quad.easeOut});
TweenLite.to(instructions_btn, .3, {x:162, delay:.2, ease:Quad.easeOut});
TweenLite.to(followMe_btn, .3, {y:500, delay:.2, ease:Quad.easeOut});
TweenLite.to(menu_btn, .3,{y:-35, ease:Quad.easeIn});
TweenLite.to(score_text, .3,{y:-30, ease:Quad.easeIn});
}
So far the project should look like this:
We didn’t actually remove the title; we will leave it there while we show a message that says that the Tweets are being loaded.
Step 8: Create the Needed Events
We are almost ready to start our game engine, but as part of it we need to be able to communicate with our Main class. We will do this with events, so let’s take our GameEvent and add the type of events that we want to listen to:
- When the game has ended:
GAME_ENDED.
- When the score has changed:
SCORE_CHANGE.
- When the Tweets that we load are ready to use:
TWEETS_READY.
- When the Tweets couldn’t be loaded:
TWEETS_ERROR.
So with all that sorted now we need to edit our GameEvent class
package com {
import flash.events.*;
public class GameEvent extends Event {
public static const GAME_ENDED:String = "Game Ended";
public static const SCORE_CHANGE:String = "Score Change";
public static const TWEETS_READY:String = "Tweets Ready";
public static const TWEETS_ERROR:String = "Tweets Error";
public var parameters:String;
public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
parameters = params;
}
}
}
With our menu and events created we are finally ready to start our game engine
Step 9: Setting Up a Game Instance
To get our game working properly we need to instantiate it, add the event listeners, and destroy them when no longer needed; for that we will add some code to the startGame function, the goToMenu function, and a new function we will created called endGame (this one will kill our game instance and remove the event listeners).
First let’s edit our “start game” function; we will add the next lines to the end of the end of the startGame function.
game = new Game();
game.addEventListener(GameEvent.GAME_ENDED, endGame);
game.addEventListener(GameEvent.SCORE_CHANGE, changeScore);
game.addEventListener(GameEvent.TWEETS_READY, addGame);
game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler);
Since we are using a var called game we will need to declare it at the begining of our class as a private var:
private var game:Game;
In our goToMenu function we will add a call to our endGame function which we will create and add the following code:
private function endGame(e:GameEvent = null):void
{
// This will reset the score in case the user starts a new game
score_text.text = "Score: 0";
// This will kill our game with the function killGame that we will create inside our game class
game.killGame();
// We will remove all our listeners from our game instance
game.removeEventListener(GameEvent.GAME_ENDED, endGame);
game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore);
game.removeEventListener(GameEvent.TWEETS_READY, addGame);
game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler);
// If the game has been added then we will fade it out and then we will remove it from stage and memory
if (game.addedToStage)
{
TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})});
}
// If not then we will just kill it
else
{
game = null;
}
}
With this we will be good to go and work on our Game class
Step 10: Loading Tweets
First we will need to declare some variables that we will use later on:
// This will hold the information of our Tweets after they are loaded
private var goldenEggsData:Object;
private var crackedEggsData:Object;
// This will hold our eggs
private var goldenEggsArray:Array = new Array();
private var crackedEggsArray:Array = new Array();
// The count of eggs that have been used
private var goldenEggsCount:int = 0;
private var crackedEggsCount:int = 0;
// The speed of the eggs while they fall
private var speed:int = 4;
// This is the nest that we will use to catch the eggs
private var nest:Nest = new Nest();
// This will hold the eggs that are on stage
private var eggs:Array = new Array();
// This will hold the tweets that are being displayed
private var tweetsOnScreen:Array = new Array();
// This ones are self-explained
private var score:Number = 0;
private var difficulty:Number = 3;
private var ended:Boolean = false;
// This will tell if the key are being holded
private var rightKey:Boolean = false;
private var leftKey:Boolean = false;
// MovieClip from the library
private var tweetsBar:TweetsBar = new TweetsBar();
// This says if the game has been added to the stage
public var addedToStage:Boolean = false;
Then we need to tell the user what is going on so we will add a movie clip to the stage and name it loadingTweets; this says that the Tweets are being loaded. We will fade it in within our startGame from our Main class

private function startGame(e:MouseEvent):void
{
loadingTweets.x = 130;
loadingTweets.y = 230;
loadingTweets.alpha = 0;
TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
TweenLite.to(loadingTweets, .3, {alpha:1, delay: .2});
menu_btn.buttonMode = true;
menu_btn.addEventListener(MouseEvent.CLICK, goToMenu);
TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
if (showingInstructions)
{
TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
showingInstructions = false;
}
game = new Game();
game.addEventListener(GameEvent.GAME_ENDED, endGame);
game.addEventListener(GameEvent.SCORE_CHANGE, changeScore);
game.addEventListener(GameEvent.TWEETS_READY, addGame);
game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler);
}
And we will fade it out in our endGame function:
private function endGame(e:GameEvent = null):void
{
score_text.text = "Score: 0";
game.killGame();
game.removeEventListener(GameEvent.GAME_ENDED, endGame);
game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore);
game.removeEventListener(GameEvent.TWEETS_READY, addGame);
game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler);
if (game.addedToStage)
{
TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})});
}
else
{
game = null;
loadingTweets.alpha = 0;
loadingTweets.x = 800;
loadingTweets.y = 2300;
}
}
It’s now time to start the fun and create the actual game! For that we will need Tweets. The main idea of this tutorial is to load Tweets, and we will use the search API from Twitter to do this.
I recommend you to go and check it out, but for this game we will just use a few of the possible options; we will make two requests and then add the game to the stage, that’s why we didnt add it when it was created, we will first load the Tweets for the golden eggs in our Game function and we will add an event listener when it’s added, where we start the game:
public function Game()
{
// tweets loader
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, loadCrackedEggs);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
// construct the URL q = what we are looking for rpp = the amount of tweets that we want
// If you are going to use complex string in your URL make sure to use the function encodeURI("Your String") and then add it to the URL
var url:String = "http://search.twitter.com/search.json?lang=en&q=golden%20eggs&rpp=50";
loader.load(new URLRequest(url));
this.addEventListener(Event.ADDED, init);
}
For this request we used just lang which is the language for the Tweets that we want to receive given in a ISO 639-1 code; q which is the main word (can be a phrase as well – just make sure to encode the URL) we are looking for; and rpp which is the number of Tweets that we want to receive. If you want to search for more than one thing you can use OR, it still works just fine but isn’t in the new documentation page so I can’t tell if or they are going to stop supporting it (the same for NOT which becomes handy when you are getting too many spam Tweets).
For even more information about this go to the “using search” page from Twitter.
When our Tweets for golden eggs are loaded we will load the Tweets for “cracked eggs” in the function loadCrackedEggs and then we will dispatch an event saying that everything is ready for the game to start:
private function loadCrackedEggs(e:Event):void
{
// We will declare this variable as a private variable so we can store the data here
goldenEggsData = JSON.decode(e.currentTarget.data);
// tweets loader
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, startGame);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
// construct the URL ors = what we are looking for rpp = the amount of tweets that we want
var url:String = "http://search.twitter.com/search.json?q=cracked%20eggs&lang=en&rpp=50";
loader.load(new URLRequest(url));
}
Once we load the JSON we will convert it into a object variable that we will declare at the begining of our code – to understand a JSON I recommend you read Understanding JSON – to convert it to an Object we will use the as3corelib from Mike Chambers and its function JSON.decode, which will return an object with all the contents of the JSON file.
Step 11: Starting Our Game
To start we will create two arrays which will contain the eggs information and for that we will need our class Egg which we created in Step 2; in that class we will store some data and add the graphics for our eggs. To add the graphics we will need to export the graphics for the eggs from the library to use them in our code like this:
Then we will need to work in our class:
package com {
import flash.display.*;
import flash.events.*;
public class Egg extends Sprite {
// Here we will store what type of egg this one is so the right graphic is used
public var type:String;
// Stores the string text
public var tweet:String;
// Stores the username of the autor of the tweet
public var user:String;
// Stores the URL of the avatar of the user
public var userImg:String;
public function Egg() {
this.addEventListener(Event.ADDED, init);
}
private function init(e:Event):void
{
this.removeEventListener(Event.ADDED, init);
// Here we add the graphic corresponding the the type of egg
// We use the MovieClips that we exported in our library
if(type == "Golden Egg")
{
var goldenEgg:GoldenEgg = new GoldenEgg();
addChild(goldenEgg);
} else {
var crackedEgg:CrackedEgg = new CrackedEgg();
addChild(crackedEgg);
}
}
}
}
This is all that we will do to our Egg class.
Now we will work in our startGame function. Here we will go through the object that contains the information of our Tweets, then for each Tweet that we loaded we will create an egg, give it the required information, and then add it to an array so we can use it later on.
private function startGame(e:Event):void
{
crackedEggsData = JSON.decode(e.currentTarget.data);
for (var i:int = 0; i < goldenEggsData.results.length; i++)
{
var goldenEgg:Egg = new Egg();
goldenEgg.tweet = goldenEggsData.results[i].text;
goldenEgg.user = goldenEggsData.results[i].from_user;
goldenEgg.userImg = goldenEggsData.results[i].profile_image_url;
goldenEgg.type = "Golden Egg";
goldenEggsArray.push(goldenEgg);
}
for (var x:int = 0; x < crackedEggsData.results.length; x++)
{
var crackedEgg:Egg = new Egg();
crackedEgg.tweet = crackedEggsData.results[x].text;
crackedEgg.user = crackedEggsData.results[x].from_user;
crackedEgg.userImg = crackedEggsData.results[x].profile_image_url;
crackedEgg.type = "Cracked Egg";
crackedEggsArray.push(crackedEgg);
}
dispatchEvent(new GameEvent(GameEvent.TWEETS_READY));
}
Step 12: Error Handling
It can happen that the Tweets can’t be loaded so it’s a good practice to do something about and not just let it happen, that’s why every time we loaded Tweets we added an IOErrorEvent listener, set to call a function named errorHandler. This function will just dispatch an error event so our Main class can handle it:
private function errorHandler(e:IOErrorEvent):void
{
dispatchEvent(new GameEvent(GameEvent.TWEETS_ERROR));
}
Then in our FLA we will add a new frame to our loadingTweets movie clip, there you can add your message for the user to know that something went wrong and move to a different frame so that it doesn’t show what it isn’t supposed to. We will display that in the errorHandler class that we set up as listener for TWEET_ERRORs.
private function errorHandler(e:GameEvent):void
{
loadingTweets.gotoAndStop(2);
}
Step 13: Initializing Our Game
Once the Tweets are ready we can initialize it; for this we will create our addGame function in our Main class, and in this function we will add our game to the stage so the init function on our Game class gets triggered, we will animate out our title, and we will move away the animation we had for the user to know that the Tweets were being loaded.
private function addGame(e:Event):void
{
addChild(game);
TweenLite.to(title, .3, {y:-200, ease:Quad.easeIn});
loadingTweets.alpha = 0;
loadingTweets.x = 800;
loadingTweets.y = 2300;
}
Then in our init function for the Game class we will create our first bird, and add a nest (which the player will use to catch the eggs) and a black bar (which will hold the Tweets that the user has catched) – so let’s create those movie clips.
Our nest needs to have graphics and a invisible movie clip that we will use to test collisions with the eggs; the black bar needs just a basic title. We will need to export both of them for AS use.


private function init(e:Event):void
{
this.removeEventListener(Event.ADDED, init);
// We set our varible to true so our Main class knows if it has been added or not
addedToStage = true;
// Set up the position, alpha and animation for our nest object
nest.x = 10;
nest.y = 497;
nest.alpha = 0;
TweenLite.to(nest, .5,{alpha:1});
addChild(nest);
// Add, position and anomation for the Tweets bar
tweetsBar.x = 350;
tweetsBar.alpha = 0;
TweenLite.to(tweetsBar, .6,{alpha:1});
addChild(tweetsBar);
// This is our main loop which will take care of our game and tell whats going on
stage.addEventListener(Event.ENTER_FRAME, updateGame);
// We will move our nest via keys so we will need to listen to keyboards events
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
// We will create our first bird which is the begining of the actual game
createBird();
// To make this game a bit interesting we will change the dificulty of our game as the user plays it
TweenLite.delayedCall(10, changeDifficulty);
}
With this ready we will now need to work on our birds, our eggs, our Tweets and the main loop for this game.
Step 14: Creating Our Birds
Our birds will drop our eggs so they are kind of important! So let’s create them and animate them. In our createBird function we will create a bird, animate it, and decide when the next bird will be created; besides that we will set up the speed of the bird (to give some variety in the difficulty level they will move faster as the game goes on).
private function createBird():void
{
// Create a new Bird instance from out library
var bird:Bird = new Bird();
// This is the time that will pass before the egg is released
var time:Number = (Math.random()*1.3)+.5;
// We will position out bird out of stage and in random Y position so they look a bit more real
bird.x = -100;
bird.y = (Math.random()*60) + 50;
// Animates the bird and destroys it after it's done animating
TweenLite.to(bird, 5, {x: 600, onComplete:killObject, onCompleteParams:[bird]});
addChild(bird);
if (! ended)
{
// We need to tell our bird to release our eggs after a certian time which will be random
TweenLite.delayedCall(time, releaseEgg, [bird]);
// If the game has no ended we need to create a new bird and depending on the difficulty it will come faster
TweenLite.delayedCall(Math.random()*difficulty, createBird);
}
else
{
// Since the game has ended we wont need any updates
stage.removeEventListener(Event.ENTER_FRAME, updateGame);
// If the game has ended we won't want any eggs to be released so we call any calls to that function
TweenLite.killTweensOf(releaseEgg);
// Besides not letting any eggs come we will delete all the eggs
if (eggs.length > 0)
{
for (var i:int = 0; i < eggs.length; i)
{
killObject(eggs[i]);
eggs.shift();
}
}
// We will animate out our nest since no more eggs will be catched
TweenLite.to(nest, .6,{y:700});
// We will show the score and give the user the option to Tweet it
showTweetScore();
}
}
Step 15: Releasing Eggs
Now that we have birds flying around we need them to drop eggs, so in our releaseEgg function we will do that:
private function releaseEgg(b:Bird):void
{
var r:Number = Math.random();
var egg:Egg;
// Here we choose if our egg will be a golden eggs or a cracked egg, giving a bit more chance to get a golden egg
if (r > 0.45)
{
// If the user gets a golden egg then we need to assign one egg form our array of golden eggs and refresh the count
egg = goldenEggsArray[goldenEggsCount];
goldenEggsCount++;
}
else
{
// If the user gets a cracked egg then we need to assign one egg form our array of cracked eggs and refresh the count
egg = crackedEggsArray[crackedEggsCount];
crackedEggsCount++;
}
// Then we will assign the position of the bird that is going to release it
egg.x = b.x;
egg.y = b.y;
// Then we add it to stage and push it to our eggs array so it gets updated
addChild(egg);
eggs.push(egg);
}
Step 16: Change Difficulty
Over time the difficulty will change; we already made a call for that to happen in our init function, so now we will make that happen:
private function changeDifficulty():void
{
// The first difficulty is set to 3 so if this function is called we will change it so more birds come together and speed up the eggs
if (difficulty == 3)
{
difficulty = 2;
speed = 5;
// We call this function again so the difficulty chages again
TweenLite.delayedCall(10, changeDifficulty);
return;
}
if (difficulty == 2)
{
difficulty = 1.5;
speed = 7;
TweenLite.delayedCall(5, changeDifficulty);
return;
}
if (difficulty == 1.5)
{
difficulty = 1;
speed = 8;
TweenLite.delayedCall(5, changeDifficulty);
return;
}
// If the difficulty is set to 1 it means that this function has been called some times and that the 30 seconds of this game are gone so it's time to end this game
if (difficulty == 1)
{
ended = true;
return;
}
}
Step 17: Getting Things Ready to Move
To move our nest we will use our keyboard and our update loop, so we need to tell our game which key is being pressed, for that we already created a couple of variables but now we will add the functionality that will make our nest move. We already set up a couple of event listeners – one for when a key is down and another for when it is released – in our init function, so now let’s handle those calls. We will need to use keycodes for this, for more information about those you can visit the Quick Tip about the usage of keycodes
private function keyDownHandler(e:KeyboardEvent):void
{
// When the left or right key is holded we need to set it's value to true
// 37 = left
// 39 = right
if (e.keyCode == 37)
{
leftKey = true;
}
if (e.keyCode == 39)
{
rightKey = true;
}
}
private function keyUpHandler(e:KeyboardEvent):void
{
// When the left or right key is released we need to set it's value to false
// 37 = left
// 39 = right
if (e.keyCode == 37)
{
leftKey = false;
}
if (e.keyCode == 39)
{
rightKey = false;
}
}
Step 18: Showing Score
When the time is gone we will give our user the option to see and share their score, for that we will create a movie clip that states the score and gives the option to share it:
Dont forget to assign an instance name to your dynamic text field and to embed the font that you want to use. When your graphic is ready we are good to go and code it; for this we will create a function named showTweetScore in which we will create a new instance of that movie clip, position it, add a message with the score, and give the option to Tweet the score.
private function showTweetScore():void
{
var tweetMessage:TweetMessage = new TweetMessage();
tweetMessage.x = 10;
tweetMessage.y = 270;
tweetMessage.message_text.text = "You just scored "+score.toString()+" point on Golden Eggs!";
tweetMessage.embedFonts = true;
addChild(tweetMessage);
TweenLite.from(tweetMessage, .6, {alpha:0});
tweetMessage.tweet_btn.buttonMode = true;
tweetMessage.tweet_btn.addEventListener(MouseEvent.CLICK, shareScore);
}
Step 19: Share Score
Once the user clicks on the tweet_btn of our message he or shee will be redirected to a page on Twitter with a prewritten message so they can share their score. To do this we will use another call form the Twitter API – the Tweet button API – for more information about it please visit Twitter’s page.
For this tutorial we will use just three variables: the text; the URL that we want to share; and “via”, which is kind of the bridge that we are using, in this case Activetuts+.
The URL that we need to send our user to is https://twitter.com/share, there the user will be able to log in and Tweet about our game. To that URL we must append variables like this:
private function shareScore(e:MouseEvent):void
{
// We need to encode the string
var url:String = encodeURI("https://twitter.com/share?text=I just scored "+score.toString()+" points in Golden Eggs!, try to beat me!&url=http://www.jsCampos.com/GoldenEggs&via=envatoactive");
// We use _blank so the user can come back and keep playing the game without having to load again the game
navigateToURL(new URLRequest(url), "_blank");
}
There are some other variables that you can add to your URL, such as recommended accounts and language, but we won’t use those because those are for the Tweet button so are useless for this tutorial. But I recommend you to go check them out, as they might come in handy some day.
Step 20: Destroy Objects
Some times when you create too many variables and objects your application might become slow, so we make use of the garbage collector and tell it what to pick up and what to leave for us to use. Once the eggs get out of stage it means that we don’t need them any more (the same is true for our birds) so it’s a good practice to get rid of them. We will do this with a function called killObject which we have called already a few times and we will call later on. This function will clear that object and get rid of it; it will take a sprite since we are just going to kill display objects.
private function killObject(ob:Sprite):void
{
// We will remove them from stage and then set them to null so the garbage collector takes care of it
ob.parent.removeChild(ob);
ob = null;
}
Besides those objects we might need to get rid of our game instance; in those cases we will kill all the listeners so we dont waste memory on anything.
public function killGame():void
{
if(addedToStage)
{
stage.removeEventListener(Event.ENTER_FRAME, updateGame);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
}
}
Step 21: Our Game Cycle
Our cycle will be one of the most important functions; this will take care of everything that is on stage and keep track of everything. The first thing this function will do is move our nest when the user is pressing the right or left key – keeping in mind that there should be limits for it, so the nest doesn’t go out of stage.
private function updateGame(e:Event):void
{
if (nest.x < 250 && rightKey)
{
nest.x += 5;
}
if (nest.x > 9 && leftKey)
{
nest.x -= 5;
}
}
Then we need to take care of our eggs, check whether any have been caught or have moved out of the stage. For that we will need to add the following code to our function:
// First we need to check if there are any eggs on stage
if (eggs.length > 0)
{
for (var i:int = 0; i < eggs.length; i++)
{
// if there are we need to move them so they fall
eggs[i].y += speed;
// Then we need to check if any of those has been catched by using hitTestObject with the invisible object inside our nest
if (eggs[i].hitTestObject(nest.hit))
{
// If one egg has been catched then we need to add or substract points
if (eggs[i].type == "Golden Egg")
{
score += 100;
}
else
{
score -= 80;
}
// Then we need to let our Main class know so the score text is changed
// We send the score as a parameter of the GameEvent
var gameEvent:GameEvent = new GameEvent(GameEvent.SCORE_CHANGE,score.toString());
dispatchEvent(gameEvent);
// Then we will show out Tweet in out bar using a class that we will create
// We will assign the values to this Tweet from out egg, that's why that class has those properties
var tweet:TweetHolder = new TweetHolder();
tweet.user_text.text = eggs[i].user;
tweet.tweet_text.text = eggs[i].tweet;
tweet.userImg = eggs[i].userImg;
tweet.x = 5;
tweetsBar.addChild(tweet);
// If there are too many Tweets being showed we will need to hide some
if (tweetsOnScreen.length > 0)
{
// first we need to make room for out new tweet
for (var a:int = 0; a < tweetsOnScreen.length; a++)
{
tweetsOnScreen[a].y = tweetsOnScreen[a].y - tweet.height;
}
// if our first tweet is going to high then we need to fade it out
if (tweetsOnScreen[0].y < 100)
{
// We fade it and them we remove it from stage and from our array of Tweets
TweenLite.to(tweetsOnScreen[0], .5,{alpha:0, y:"-100", onComplete:tweetsOnScreen[0].parent.removeChild, onCompleteParams:[tweetsOnScreen[0]]});
tweetsOnScreen.shift();
}
// If the new tweet is too long the next one might be too high as well so we need to check and apply the same process
if (tweetsOnScreen[0].y < 100)
{
tweetsOnScreen[0].parent.removeChild(tweetsOnScreen[0]);
tweetsOnScreen.shift();
}
}
// After everything is ready we need to add our new Tweet to our array of tweets
tweetsOnScreen.push(tweet);
tweet.alpha = 1;
tweet.y = 600 - tweet.height - 10;
// after we are done it's time to kill that egg
killObject(eggs[i]);
eggs.splice(i, 1);
}
// If the Tweet wasn't catched and is out of frame then we should destroy it as well
else if (eggs[i].y > 600)
{
killObject(eggs[i]);
eggs.splice(i, 1);
}
}
}
Step 22: Creating Tweet Objects
For our Tweet objects we will first need an object from our library, which we will export, and to which we will assign a new class to handle the data that is pushed. This movie clip will have a backup image in case the user image can’t be loaded, a space for the name of the user who Tweeted it, and a space for the Tweet content.
When you create your graphics don’t forget to embed the font that you are using.
The class that we are going to create will fill the data, resize the text fields, load the publisher’s avatar and give the user the posibility to click on the tweet and go to the publisher’s profile:
package com {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class TweetHolder extends MovieClip {
// This will hold the URL of the image so it can be loaded
public var userImg:String;
public function TweetHolder() {
this.addEventListener(Event.ADDED, init);
}
private function init(e:Event):void
{
// As we did in our Game class we first added the data and then added this to the stage
this.removeEventListener(Event.ADDED, init);
// When it's added it resizes the text fields so no space is wasted
tweet_text.autoSize = "left";
hit.height = tweet_text.height + tweet_text.y;
// Then we load the image and call a function if the image is loaded or is we get an error
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addImage);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.load(new URLRequest(userImg));
// We finally make this Tweet clickable and add a function to handle the clicks
this.buttonMode = true;
this.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(e:MouseEvent):void
{
// To go to the user's profile we just need to add the username to Twitter's URL
navigateToURL(new URLRequest("http://www.twitter.com/"+user_text.text), "_blank");
}
private function addImage(e:Event):void
{
// When the image is added we need to make it look smooth
Bitmap(e.currentTarget.content).smoothing = true;
// Resize it
e.currentTarget.content.height = 40;
e.currentTarget.content.width = 40;
// And add it to our Tweet holder
addChild(e.currentTarget.content);
}
private function onError(e:Event):void
{
// If there is an error we just need to catch it
// Since we already have a backup image we don't need to do anything if the image is not loaded
trace("Image couldnt be loaded");
}
}
}
When we are done with this class everything should be ready to go.
Conclusion
I hope you guys find this tutorial helpful and find great ways to apply what has been taught! For another example of the usage of this you can visit my site home page at JsCampos.com, or check out some other nice games that use Twitter, such as Tweet Land and Tweet Hunt.
Thanks for your time and I hope you liked it, any feedback is well received.



View full post on Activetuts+