search

Build an Active Flash Game Menu: Slides

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,:

The basic Slide Design

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:

What your side Button Should Look Like

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.

circleOne Up Frame

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.

circleOne Over Frame

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:

What your stage Should Look Like

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+

Build a Dynamic Flash Game Menu: The Accordion

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:

first look at the timeline

first look at the stage

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:

A frame comparison of the gold bar

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:

The goldBackground

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:

What you should see in the menuAccordionMC

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+

Build a Dynamic Flash Game Menu: Slides

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,:

The basic Slide Design

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:

What your side Button Should Look Like

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.

circleOne Up Frame

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.

circleOne Over Frame

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:

What your stage Should Look Like

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+

Use the Flash Project Panel‏ to Build a Dynamic AS3 Menu

During this tutorial, we’ll use the Project Panel in Flash to create a vertical animated AS3 menu. The whole process will allow you to easily customize all aspects of the menu using the parameterized constructors. Read on to learn more!


Final Result Preview

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


Step 1: Create a New Project

Start by creating a new project. Open Flash and go to File > New, then select Flash Project. The Project panel will appear.

simple Flash menu tutorial

In the Projects dropdown select New Project. Type the project name “AnimatedMenu”. In the Root Folder, browse and choose where you want to save your project; you can select an already existing folder or create a new one. Make sure the ActionScript version is set to ActionScript 3.0 and click Create Project.

simple Flash menu tutorial

Step 2: Add the Classes Folder

Now that the project is created, we are going to add a new folder to group in it our classes. Still in the same panel “Project” press the “New Folder” icon in the bottom, name the new folder “Classes” and click Create Folder.

simple Flash menu tutorial

Step 3: Install TweenLite

During this tutorial we will use the TweenLite classes from GreenSock for tweening, so we need to add it to our project. Download it and extract it, place it in your project folder (so you will have AnimatedMenu/com/greensock/).

Now if you refresh the Project panel you should see this structure:

simple Flash menu tutorial

Step 4: Create a New Flash File

Click the “New File” icon in the Project panel to create a new file, name it “AnimatedMenu.fla” (make sure that the File Type is Flash File) and click Create File.

simple Flash menu tutorial

Set the stage size to 600x350px.

simple Flash menu tutorial

Step 5: Create a New ActionScript File

Select the Classes folder and click the “New File” icon, set the File Type to ActionScript, name it “Main”. This will be our document class, if you are not familiar with document classes this Quick Tip on using a document class will help you.

simple Flash menu tutorial

Step 6: Set a Relative Source Path

This will allow us to use any class located in our Classes folder without the need to change the package name. Go to File > ActionScript Settings and click the plus button “Add New Path” and write the relative path ‘./Classes’.

simple Flash menu tutorial

Step 7: Start Coding the Main.as File

Inside the package Classes, import the Sprite Class and use it to extand the class “Main”. Here is the code :

package Classes
{
	import flash.display.Sprite;

	public class Main extends Sprite
	{

Step 8: Declare the Variables

These are the variables we will use (MenuItem is an ActionScript class that we will create later)

private var item1:MenuItem;
private var item2:MenuItem;
private var item3:MenuItem;
private var item4:MenuItem;

Step 9: The Constructor

Now we are going to code the constructor, it contains the code that will be executed when this class is called.

public function Main():void
{

Step 10: Create Four Menu Items

Instantiate the MenuItem class to create four menu items with different colors, labels, functionalities and positions:

//Create four instances of the MenuItem class and spacify the parameters (x,y,color,label,URL).
item1 = new MenuItem(100,60,0x28D9E9,"Home page","http://active.tutsplus.com/");
item2 = new MenuItem(140,150,0xA8FA2D,"Services","http://psd.tutsplus.com/");
item3 = new MenuItem(120,240,0xFC30FC,"About me","http://net.tutsplus.com/");
item4 = new MenuItem(160,330,0xEE2B2B,"Contacts","http://vector.tutsplus.com/");

You can change the URLs to point to other sites.


Step 11: Add the Items to the Stage

This code simply adds the four items created earlier to the stage.

//Add the items to the stage.
addChild(item1);
addChild(item2);
addChild(item3);
addChild(item4);

Now we are done with the Main class, here is the full code of this class.

package Classes
{
	import flash.display.Sprite;

	public class Main extends Sprite
	{
		private var item1:MenuItem;
		private var item2:MenuItem;
		private var item3:MenuItem;
		private var item4:MenuItem;

		public function Main():void
		{
			//Create four instances of the MenuItem class and spacify the parameters (x,y,color,label,URL).
			item1 = new MenuItem(100,60,0x28D9E9,"Home page","http://active.tutsplus.com/");
			item2 = new MenuItem(140,150,0xA8FA2D,"Services","http://psd.tutsplus.com/");
			item3 = new MenuItem(120,240,0xFC30FC,"About me","http://net.tutsplus.com/");
			item4 = new MenuItem(160,330,0xEE2B2B,"Contacts","http://vector.tutsplus.com/");

			//Add the items to the stage.
			addChild(item1);
			addChild(item2);
			addChild(item3);
			addChild(item4);
		}
	}
}

This class is too short to do all the functions that our menu is supposed to do, so we will create the “MenuItem.as” class that contains the necessary functions for our menu.


Step 12: Create the MenuItem.as

Add a new ActionScript 3 file in the Classes folder exactly like you did for the Main.as. Name it “MenuItem.as”.

simple Flash menu tutorial

Step 13: Import Classes

These are the classes that we need to import for our new class. Don’t forget you can always look them up in the LiveDocs.

package Classes
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.*;
	import com.greensock.TweenLite;
	import com.greensock.easing.*;
	import com.greensock.plugins.*;
	import flash.text.TextField;
	import flash.media.Sound;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;

Step 14: Class and Variables

Declare the MenuItem class (should have the same name as its File name “MenuItem”) and extend the Sprite class.

public class MenuItem extends Sprite
{

These are the variables that we need at the moment, later we will add some others as we progress in this tutorial.

private var rect1:DynamicMovie = new DynamicMovie(); //Use the DynamicMovie class instead of Sprite class.
private var rect2:DynamicMovie = new DynamicMovie(); //This allow us to change the registration point.
private var rect3:DynamicMovie = new DynamicMovie(); //So we can rotate the rectangels around their centers.
private var X:Number;
private var Y:Number;
private var Color:uint;

DynamicMovie is an AS3 class based on an old AS2 class written by Darron Schall; this AS3 class extends MovieClip and adds a new set of properties (x2, y2, rotation2, scaleX2, scaleY2, mouseX2, mouseY2) that allow you to manipulate the sprite based on a contextual registration point that can be set using the setRegistration() method.

We need this class to rotate the rectangles around their centers. So let’s place it.


Step 15: Add the DynamicMovie Class

You find this class in the source folder of this tutorial or you can download it from oscartrelles.com, then just place it in the Classes Folder so that it can be recognized by our code.

simple Flash menu tutorial

Step 16: The Constructor

This is the constructor of the MenuItem.

public function MenuItem(posX:Number, posY:Number,color:uint,Title:String,URL:String)
{
	//Get the position and color parameters.
	X = posX;
	Y = posY;
	Color = color;

	// Call the addRect function to add 3 rectangles with the specified parameters.
	addRect(rect1,X-12,Y,360,62,Color,0.3,3);
	addRect(rect2,X-4,Y,360,62,Color,0.4,0);
	addRect(rect3,X,Y,360,62,Color,0.7,-2);
}

Step 17: addRect() Function

This function is responsible for drawing the rectangles according to the given parameters: position, width, height, color, alpha and rotation.

private function addRect(rect:DynamicMovie,X:Number, Y:Number, width:Number, height:Number,color:uint, alpha:Number, rotation:Number)
{
	rect.setRegistration(X+(width/2),Y+(height/2));
	rect.graphics.beginFill(color,alpha);
	rect.graphics.drawRect(X,Y,width,height);
	addChild(rect);
	rect.rotation2 = rotation;
}

Now you can test it and you will see this:

Sure, we can’t call it a menu if we don’t add some labels. We’ll deal with that in the next step.


Step 18: Add a Dynamic TextField

Head back to your AnimatedMenu.fla file and add a new symbol (Ctrl + F8); name it “Text_mc” and select “Export for ActionScript”.

simple Flash menu tutorial

Now inside this symbol add a 160x30px Dynamic TextField using the Text Tool (T). This is the font I used: Creampuff Regular, 24px, #FFFFFF. Name the instance “txtLabel”.

Select the TextField and go to Window > Align (Ctrl + K) and hit the buttons “Align left edge” and “Align top edge” (make sure that the checkbox “Align to stage” is selected)

simple Flash menu tutorial

Step 19: Embed the Font

After creating the text field with the specified font we should embed it to display the text properly.

So go to Text > Font Embedding, give it a name (for example “Font1″), select the Creampuff font from the Family combo box, in the Character ranges select all of the Uppercase and the Lowercase, then press the “plus” button located in the left section. See the image below:

simple Flash menu tutorial

Step 20: Add Labels

To add labels to the menu items we are going to instantiate the Text_mc MovieClip. Add this line of code to the variables in the MenuItem.as file.

private var txt:Text_mc = new Text_mc();

Now we should assign to the TextField the title given in the constructor’s parameters.

Add this code to the end of the constructor.

//Assign a title to the TextField and place it.
txt.txtLabel.text = Title;
txt.x = X + 70;
txt.y = Y + 16;
addChild(txt);

This is what you should get:

In the next steps we will add some functions to animate the menu.


Step 21: Menu Button

To turn our menu item into a button we should add a transparent rectangle over it and set the buttonMode to true. So add this variable to the variable list.

private var menuButton:DynamicMovie = new DynamicMovie();

In the end of the constructor add this code:

//Use the addRect function to draw a transparent rectangle over the menu item.
addRect(menuButton,X-10,Y-5,380,80,Color,0,0);
buttonMode = true;

Step 22: Add Event Listeners

Add the following event listeners to the menuButton at the end of the constructor.

menuButton.addEventListener(MouseEvent.MOUSE_OVER,mouseOver);
menuButton.addEventListener(MouseEvent.MOUSE_OUT,mouseOut);
menuButton.addEventListener(MouseEvent.CLICK,mouseClick);

Step 23: Mouse Over

This function will be called when the mouse is over the menuButton.

private function mouseOver(e:MouseEvent)
{
	var timeline:TimelineLite = new TimelineLite();

	//Rotate the rectangels.
	new TweenLite(rect1,.3,{rotation2:-4});
	new TweenLite(rect2,.3,{rotation2:0});
	new TweenLite(rect3,.3,{rotation2:5});

	//Tween the text.
	timeline.append(new TweenLite(txt,.3,{x:X+45,scaleX:1.1,scaleY:1.1}));
	timeline.append(new TweenLite(txt,.3,{x:X+70,alpha:1}));

	//Add a Glow Filter to the text.;
	new TweenMax(txt,.3,{glowFilter:{color:0xffffff,alpha:1,blurX:5,blurY:5,strength:1,quality:3}});
}

Here we are using the GreenSock classes TimelineLite and TweenMax to animate the button. Search the Activetuts+ site for more tutorials featuring GreenSock.


Step 24: Mouse Out

When the mouse is out this function will return the menu to its initial position.

private function mouseOut(e:MouseEvent)
{
	var timeline:TimelineLite = new TimelineLite();

	//Rotate the rectangles to their initial position.
	new TweenLite(rect1,.3,{rotation2:3});
	new TweenLite(rect2,.3,{rotation2:0});
	new TweenLite(rect3,.3,{rotation2:-2});

	//backward the text animation.
	timeline.append(new TweenLite(txt,.3,{x:X+65,alpha:.9}));
	timeline.append(new TweenLite(txt,.3,{x:X+70}));
	new TweenMax(txt,.3,{glowFilter:{color:0xffffff,alpha:0,blurX:0,blurY:0,strength:0,quality:3}});
}

Step 25: Mouse Click

This function will open the specified URL when the menu item is clicked.

private function mouseClick(e:MouseEvent)
{
	//Open the requested URL.
	navigateToURL(new URLRequest(myURL));
}

You should add this variable to the variables list.

private var myURL:String;

And add this instruction to the constructor.

myURL = URL;

This is what you should get. Roll over the menu to see the animation.

Now let’s add a cool bubbles effect.


Step 26: The Bubbles Effect

This function will create a number of bubbles with a random position, size and alpha in two directions. This is the code:

private function bubbles(position:Number,direction:Number)
{
	//Create 50 bubbles, you can modify the number to get more or less bubbles.
	for (var i=0; i<50; i++)
	{
		var bubble:DynamicMovie= new DynamicMovie();

		//Set the registration point for the current bubble.
		bubble.setRegistration(X+position,Y);

		//Give the bubble the same color as the menu item and a random alpha (but greater than 0.2).
		bubble.graphics.beginFill(Color,Math.random()+0.2);

		//draw a circle with a random position and radius.
		bubble.graphics.drawCircle(X + position + Math.random() * i,Y + 55  - Math.random() * i,Math.random()*5);

		//add the bubble at the third index so that it is under the menuButton.
		addChildAt(bubble,3);

		//Tween the Bubble randomly according to the direction.
		new TweenLite(bubble,Math.random() + 1,{x2:X - 80 * direction + position - Math.random() * i,y2:Y - Math.random() * i,alpha:0,ease:Circ.easeOut});
	}
}

Step 27: Call the Bubbles Function

We need to call the bubbles() function when the mouse rolls over the menu item. So add this code to the mouseOver() function:

//Left bubbles.
bubbles(70,1);

//Right bubbles
bubbles(270,-1);

This is what we get:


Step 28: Import the Sound Effect

We are going to finish by adding a sound effect to the menu when it is rolled over by the mouse. To do so, download the sound from here (download the mp3 file). Then import it to the library, File > Import > Import to Library. Rename it to “MySound.mp3″.

simple Flash menu tutorial

Open its properties and click Advanced; the window will display extra content, select “Export for ActionScript” and name the Class “MySound”.

simple Flash menu tutorial

Step 29: Add the Sound Effect to the Menu

To add the sound effect instantiate the sound imported earlier to the library and play it. Place this code in the mouseOver() function.

var mySound:MySound = new MySound();
mySound.play();

We are done with our menu! Here is the full code of the MenuItem.as :

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.*;
	import com.greensock.TweenLite;
	import com.greensock.easing.*;
	import com.greensock.plugins.*;
	import flash.text.TextField;
	import flash.media.Sound;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;

	public class MenuItem extends Sprite
	{
		private var rect1:DynamicMovie = new DynamicMovie();//Use the DynamicMovie class instead of Sprite class.
		private var rect2:DynamicMovie = new DynamicMovie();//This allow us to change the registration point.
		private var rect3:DynamicMovie = new DynamicMovie();//So we can rotate the rectangels around their centers.
		private var menuButton:DynamicMovie = new DynamicMovie();
		private var X:Number;
		private var Y:Number;
		private var Color:uint;
		private var txt:Text_mc = new Text_mc();
		private var myURL:String;

		public function MenuItem(posX:Number, posY:Number,color:uint,Title:String,URL:String)
		{
			//Get the position and color parameters.
			X = posX;
			Y = posY;
			Color = color;
			myURL = URL;

			// Call the addRect function to add 3 rectangles with the specified parameters.
			addRect(rect1,X-12,Y,360,62,Color,0.3,3);
			addRect(rect2,X-4,Y,360,62,Color,0.4,0);
			addRect(rect3,X,Y,360,62,Color,0.7,-2);

			//Assign a title to the TextField and place it.
			txt.txtLabel.text = Title;
			txt.x = X + 70;
			txt.y = Y + 16;
			addChild(txt);

			//Use the addRect function to draw a transparent rectangle over the menu item.
			addRect(menuButton,X-10,Y-5,380,80,Color,0,0);
			buttonMode = true;

			menuButton.addEventListener(MouseEvent.MOUSE_OVER,mouseOver);
			menuButton.addEventListener(MouseEvent.MOUSE_OUT,mouseOut);
			menuButton.addEventListener(MouseEvent.CLICK,mouseClick);
		}

		private function addRect(rect:DynamicMovie,X:Number, Y:Number, width:Number, height:Number,color:uint, alpha:Number, rotation:Number)
		{
			rect.setRegistration(X+(width/2),Y+(height/2));
			rect.graphics.beginFill(color,alpha);
			rect.graphics.drawRect(X,Y,width,height);
			addChild(rect);
			rect.rotation2 = rotation;
		}

		private function mouseOver(e:MouseEvent)
		{
			var timeline:TimelineLite = new TimelineLite();
			var mySound:MySound = new MySound();
			mySound.play();

			//Rotate the rectangels.
			new TweenLite(rect1,.3,{rotation2:-4});
			new TweenLite(rect2,.3,{rotation2:0});
			new TweenLite(rect3,.3,{rotation2:5});

			//Tween the text.
			timeline.append(new TweenLite(txt,.3,{x:X+45,scaleX:1.1,scaleY:1.1}));
			timeline.append(new TweenLite(txt,.3,{x:X+70,alpha:1}));

			//Add a Glow Filter to the text.;
			new TweenMax(txt,.3,{glowFilter:{color:0xffffff,alpha:1,blurX:5,blurY:5,strength:1,quality:3}});

			//Left bubbles.
			bubbles(70,1);

			//Right bubbles
			bubbles(270,-1);
		}

		private function mouseOut(e:MouseEvent)
		{
			var timeline:TimelineLite = new TimelineLite();

			//Rotate the rectangles to their initial position.
			new TweenLite(rect1,.3,{rotation2:3});
			new TweenLite(rect2,.3,{rotation2:0});
			new TweenLite(rect3,.3,{rotation2:-2});

			//backward the text animation.
			timeline.append(new TweenLite(txt,.3,{x:X+65,alpha:.9}));
			timeline.append(new TweenLite(txt,.3,{x:X+70}));
			new TweenMax(txt,.3,{glowFilter:{color:0xffffff,alpha:0,blurX:0,blurY:0,strength:0,quality:3}});
		}

		private function mouseClick(e:MouseEvent)
		{
			//Open the requested URL.
			navigateToURL(new URLRequest(myURL));
		}

		private function bubbles(position:Number,direction:Number)
		{
			//Create 50 bubble, you can modify the number to get more or less bubbles.
			for (var i=0; i<50; i++)
			{
				var bubble:DynamicMovie= new DynamicMovie();

				//Set the registration point for the bubble.
				bubble.setRegistration(X+position,Y);

				//Give the bubble the same color as the menu item and a random alpha but upper than 0.2.
				bubble.graphics.beginFill(Color,Math.random()+0.2);

				//draw a circle with a random Position and Radius. ;
				bubble.graphics.drawCircle(X + position + Math.random() * i,Y + 55  - Math.random() * i,Math.random()*5);

				//add the bubble at the third index to be under the menuButton.;
				addChildAt(bubble,3);

				//Tween the Bubble randomly according to the direction.
				new TweenLite(bubble,Math.random() + 1,{x2:X - 80 * direction + position - Math.random() * i,y2:Y - Math.random() * i,alpha:0,ease:Circ.easeOut});
			}
		}

	}
}

And here is the final result:


Conclusion

Now you can create your own menu and customize it by adding more menu items, changing the colors, changing the text…

The menu was coded in a separate ActionScript class which allows you to use it easily in other projects.

I want to thank you for reading; I hope you enjoyed it!



View full post on Activetuts+

Create a Mac Dock Style Menu with AS3

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in March, 2010.

In this tutorial I’ll show you how to create a menu like Apple’s Dock using AS3 classes. We will create a single .as file that will perform all the magic, extending it to add new features.


Final Result Preview

First, let’s take a look at what we’ll be creating. Roll your mouse over the icons to see how they move and scale.


Step 1: Create a New ActionScript File

Begin by creating a new ActionScript file and saving it as “DockItem.as”. I’m saving mine at c:/macmenu/org/effects/DockItem.as.

Note that our document root (where the .fla lives) will be c:/macmenu; the folder /org/effects will form the package for the DockItem class.


Step 2: Create a New AS3 Flash File

Create a new ActionScript 3.0 Flash File and open it, so that we have both DockItem.as and this .fla file opened. Save this .fla in the root folder (the DockItem.as is at c:/macmenu/org/effects, so our site root is c:/macmenu) the /org/effects is the package of DockItem Object and we save the .fla as c:/macmenu/macmenu.fla.


Step 3: Import Icons

Now we import or draw some icons to the .fla. I’ve imported some icons I have here from an Illustrator file, but you can of course draw your own and apply a gradient to them.


Step 4: Begin Converting Icons to Symbols

Select any icon and click Modify > Convert To Symbol.

In the box that opens, give it a name (I named this symbol “Star”) and pay attention to the registration point; it needs to be bottom center. For the class use the same name (remember that you can’t use spaces) and for the Base class, use org.effects.DockItem (the class that we’ll create). Also, make sure your Type is set to Movie Clip.

Then, align all the objects to the bottom: select all, click Window > Align, make sure the button "To stage" is unselected (otherwise it will align at the botton of the stage), then click the top-right button in this panel to align all the objects.


Step 5: Convert All Icons to Symbols

We can have as many buttons as we want, so let’s convert all our icons to symbols. Remember to give them a name and a Class, set all their registration points to bottom center and set the Base class to org.effects.DockItem.

See below for how our library and the icons should look; note the space between them, it’s important for creating a good effect.


Step 6: Start Coding the DockItem Class

If we test the movie now it will throw an error saying that an ActionScript file must have at least one external and visible definition; that’s because all our menu items are extending the DockItem class, which we haven’t yet written. Let’s write it now…

Start creating the package by extending the Sprite class (we will extend Sprite since we don’t have a timeline animation.)

package org.effects{

	import flash.display.Sprite;

	public class DockItem extends Sprite{
	}
}

At this point we have our DockItem extending the Sprite class, so if you test it now it will work, but you’ll see no effects.

(Confused? Not used to coding with classes? Check out this Quick Tip on using a document class for an introduction.)


Step 7: Import Necessary Classes

Now we will import all the necessary classes. A custom class is being used here, the TweenLite class, which you can download from GreenSock.com. When you’ve downloaded TweenLite, extract it to your /macmenu/ folder (so you will have a folder /macmenu/com/greensock/).

package org.effects{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite; //http://www.greensock.com/tweenlite
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{
	}
}

I’ve imported the Sprite class because it’s what we are extending; if you have animations on the timeline, extend the MovieClip class. We will use the Event class when the custom object is added to stage and we’ll use the MouseEvent when checking the distance of each icon from the mouse.


Step 8: Declare Necessary Variables

During this step we’ll declare the necessary variables:

package org.effects{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{

		private var _initPosition:Number;
		public var maxXDistance:Number;
		public var maxYDistance:Number;
		public var maxScale:Number;

	}
}

Note that I used the _initPosition as private: it just sets the initial x-position of the icon. The distance of the mouse will always be measured from this point, because the actual x-position of the item will always be changing.

maxXDistance is the maximum x-distance over which the mouse will affect the icon, maxYDistance is the maximum y-distance over which mouse will affect the icon and maxScale is the maximum scale that will be added to the icon (for example, if you set it to 2, the maximum scale the object can reach is 3.)

I’ve used public variables for the last three so we can change them at runtime.


Step 9: Coding the Constructor Function

The constructor function must have the same name as the class (and therefore the same name as the file), hence DockItem():

package org.effects{

   import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{

		private var _initPosition:Number;
		public var maxXDistance:Number;
		public var maxYDistance:Number;
		public var maxScale:Number;

		public function DockItem($maxXDistance:Number=60,$maxYDistance:Number=30,$maxScale:Number=2):void{
			maxXDistance=$maxXDistance;
			maxYDistance=$maxYDistance;
			maxScale=$maxScale;
			if(stage) init();
			else addEventListener(Event.ADDED_TO_STAGE,init);
			addEventListener(Event.REMOVED_FROM_STAGE,end);
		}

	}
}

Why do we have some parameters here? This allows us to use different combinations of distances and scales: we can have a short distance with a very big scale or a long distance with a small scale. Also, we can determine the y distance within which the mouse will affect the icon.

As we are extending the Sprite class we can add children or even code a custom class for each icon extending the DockItem class, so if we extend it we can use the super() function to pass the new parameters to the superclass. We can then use the DockItem class anytime and anywhere.

In this step we set the maxXDistance variable, maxYDistance variable and the maxScale variable to the values passed as parameters. Also, we check if the object is on the stage – if not, we add an Event to check when it is. We also add another event listener to detect when the icon is removed from the stage. We’ll add a MOUSE_MOVE event to the stage to get the distance, so it’s important to know whether it’s on the stage.


Step 10: The init() Function

This is the function that will be run once the icon is created and added to the stage. In the init() function we just add an MouseEvent.MOUSE_MOVE listener to the stage, set the _initPosition variable to the x value of the object, and listen for the mouse leaving the area of stage.

package org.effects{

   import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{

		private var _initPosition:Number;
		public var maxXDistance:Number;
		public var maxYDistance:Number;
		public var maxScale:Number;

		public function DockItem($maxXDistance:Number=60,$maxYDistance:Number=30,$maxScale:Number=2):void{
			maxXDistance=$maxXDistance;
			maxYDistance=$maxYDistance;
			maxScale=$maxScale;
			if(stage) init();
			else addEventListener(Event.ADDED_TO_STAGE,init);
			addEventListener(Event.REMOVED_FROM_STAGE,end);
		}

		private function init(e:Event=null):void{
			_initPosition=x;
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
			stage.addEventListener(Event.MOUSE_LEAVE,mouseLeave);
		}

	}
}

Step 11: The Mouse Functions

When the mouse moves over the stage, this function (triggered by the MOUSE_MOVE event we added a listener for in the last step) will check the mouse position of the parent object and measure the distance from the object to the mouse parent position.

We use parent.mouseX because that gets us the x-position of the mouse relative to whichever object contains the icon, rather than relative to the registration point of the icon.

We also tween the icons back to their starting positions if the mouse leaves the stage in the mouseLeave() handler.

package org.effects{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{

		private var _initPosition:Number;
		public var maxXDistance:Number;
		public var maxYDistance:Number;
		public var maxScale:Number;

		public function DockItem($maxXDistance:Number=60,$maxYDistance:Number=30,$maxScale:Number=2):void{
			maxXDistance=$maxXDistance;
			maxYDistance=$maxYDistance;
			maxScale=$maxScale;
			if(stage) init();
			else addEventListener(Event.ADDED_TO_STAGE,init);
			addEventListener(Event.REMOVED_FROM_STAGE,end);
		}

		private function init(e:Event=null):void{
			_initPosition=x;
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
			stage.addEventListener(Event.MOUSE_LEAVE,mouseLeave);
		}

		private function mouseMove(e:MouseEvent):void{
			var yDistance:Number=Math.abs(parent.mouseY-y);
			if(yDistance>maxYDistance){
				if(_initPosition==x) return;
				else{
					TweenLite.to(this,.3,{x:_initPosition,scaleX:1,scaleY:1});
					return;
				}
			}
			//get the difference between the parent mouse x position and the initial position of the object
			var xDistance:Number=parent.mouseX-_initPosition;

			//check if the distance of the mouse from the object is more than max distance, it can't be bigger...
			xDistance = xDistance &gt; maxXDistance ? maxXDistance : xDistance;

			//check if the distance is lower than the negative of the max distance, it can't be lower...
			xDistance = xDistance &lt; -maxXDistance ? -maxXDistance : xDistance;

			//create a variable for the position, assuming that the x position must be the initial position plus the distance of the mouse, but it can't be more than the max distance.
			var posX=_initPosition-xDistance;

			//we get the scale proportion here, it goes from 0 to maxScale variable
			var scale:Number=(maxXDistance-Math.abs(xDistance))/maxXDistance;

			//the minimum scale is 1, the original size, and the max scale will be maxScale variable + 1
			scale=1+(maxScale*scale);

			//here we use a Tween to set the new position according to the mouse position
			TweenLite.to(this,.3,{x:posX,scaleX:scale,scaleY:scale});
		}

		private function mouseLeave(e:Event):void{
			TweenLite.to(this,.3,{x:_initPosition,scaleX:1,scaleY:1});
		}
	}
}

First, we check the y distance (vertical distance between the icon and the mouse); if it’s further away than the range we set with the maxYDistanceVariable, then we check whether the icon is back in its original position, and, if not, we tween it there. The return keyword breaks out of the function, so none of the rest of the code will be run in this case.

If the mouse is close to the icon vertically, we use some maths to figure out a new scale and position for the icon based on its horizontal distance from the mouse, then tween it to those values.


Step 12: The end() Function

If we remove the object from the stage, we need to remove the mouseMove and mouseLeave listeners; if not we can get errors every time the mouse is moved. This function is the handler for the REMOVED_FROM_STAGE listener we added earlier, so will be triggered when the object is removed.

package org.effects{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class DockItem extends Sprite{

		private var _initPosition:Number;
		public var maxXDistance:Number;
		public var maxYDistance:Number;
		public var maxScale:Number;

		public function DockItem($maxXDistance:Number=60,$maxYDistance:Number=30,$maxScale:Number=2):void{
			maxXDistance=$maxXDistance;
			maxYDistance=$maxYDistance;
			maxScale=$maxScale;
			if(stage) init();
			else addEventListener(Event.ADDED_TO_STAGE,init);
			addEventListener(Event.REMOVED_FROM_STAGE,end);
		}

		private function init(e:Event=null):void{
			_initPosition=x;
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
			stage.addEventListener(Event.MOUSE_LEAVE,mouseLeave);
		}

		private function mouseMove(e:MouseEvent):void{
			var yDistance:Number=Math.abs(parent.mouseY-y);
			if(yDistance>maxYDistance){
				if(_initPosition==x) return;
				else{
					TweenLite.to(this,.3,{x:_initPosition,scaleX:1,scaleY:1});
					return;
				}
			}
			//get the difference between the parent mouse x position and the initial position of the object
			var xDistance:Number=parent.mouseX-_initPosition;

			//check if the distance of the mouse from the object is more than max distance, it can't be bigger...
			xDistance = xDistance &gt; maxXDistance ? maxXDistance : xDistance;

			//check if the distance is lower than the negative of the max distance, it can't be lower...
			xDistance = xDistance &lt; -maxXDistance ? -maxXDistance : xDistance;

			//create a variable for the position, assuming that the x position must be the initial position plus the distance of the mouse, but it can't be more than the max distance.
			var posX=_initPosition-xDistance;

			//we get the scale proportion here, it goes from 0 to maxScale variable
			var scale:Number=(maxXDistance-Math.abs(xDistance))/maxXDistance;

			//the minimum scale is 1, the original size, and the max scale will be maxScale variable + 1
			scale=1+(maxScale*scale);

			//here we use a Tween to set the new position according to the mouse position
			TweenLite.to(this,.3,{x:posX,scaleX:scale,scaleY:scale});
		}

		private function mouseLeave(e:Event):void{
			TweenLite.to(this,.3,{x:_initPosition,scaleX:1,scaleY:1});
		}

		private function end(e:Event=null):void{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
			stage.removeEventListener(Event.MOUSE_LEAVE,mouseLeave);
		}

	}
}

All we do in this function is remove the event listener from the stage.


Step 13: Test it!

At this point we can already test it; it will work since each object is linked with the Base class DockItem. However, we don’t have a bounding box for clicking (if we set our object’s buttonMode property to true, we’ll see that we can click it only when it’s over the actual graphic.)


Step 14: Start Turning Icons into Buttons

So far we can see the effect working, so now let’s turn each item into a button. We’ll create a new ActionScript file and this one will extend the DockItem – let’s name it DockButton. Its package will be the same as DockItem (org.effects), so we’ll save itb in the same folder as DockItem.as (example: c:/macmenu/org/effects/DockButton.as)


Step 15: Change the Base Class

Now we change the base class of each object in the library. We are currently using org.effects.DockItem as Base class, let’s now use org.effects.DockButton.

If we test it now, there will be an error. This is because DockButton.as is still empty, so let’s code it.


Step 16: Start Coding DockButton.as

OK, now we’ll extend the DockItem class, because we want to use everything that we have in DockItem and add some more tricks (allowing it to act as a button), but we don’t want to add the new features to DockItem directly. This way, if we want to use the DockItem as anything other than a Button later on, we can, but if we want to use it as a Button we can use the DockButton.

package org.effects{

	public class DockButton extends DockItem{
	}
}

If we test our project now, it will work, but it will work exactly as the DockItem as we haven’t yet added anything new.


Step 17: Import Classes for DockButton

Let’s import some things we will need to extend the DockItem. As we are extending the DockItem we don’t need to import the classes that are already there, since we wont use them directly in DockButton.

package org.effects{

	import flash.geom.Rectangle;

	public class DockButton extends DockItem{
	}
}

I’ve imported the Rectangle class, but why? It’s because we will use the bounding box of our object to create a fake background, to allow the button to be clickable even if the mouse isn’t precisely over a colored area. Let’s create a background graphic with alpha 0 (transparent), so we will have a square to click.


Step 18: Constructor for DockButton

Since we need to create a bounding box for DockButton, we will get its own bounds, that’s why we imported the flash.geom.Rectangle class

package org.effects{

	import flash.geom.Rectangle;

	public class DockButton extends DockItem{

		public function DockButton():void{
			buttonMode=true;
			mouseChildren=false;
			var bounds:Rectangle=getBounds(this);
			this.graphics.beginFill(0,0);
			this.graphics.drawRect(bounds.x,bounds.y,bounds.width,bounds.height);
			this.graphics.endFill();
		}
	}
}

What we have done? We created a constructor which first sets the object’s buttonMode to true, so our DockButton will be treated as a Button. Then we set mouseChildren to false, so mouse events will come from the DockButton object, not any other object inside it. Next we get the bounds of the object using getBounds() and draw a transparent rectangle using the graphics object. (The graphics property comes with the Sprite class, and we extended Sprite to make our DockItem object. Now we’ve extended our DockItem to make our DockButton object, DockButton has everything from the Sprite class and the DockItem class.)


Step 19: Check Everything and Test It

OK, let’s perform a check:

  • We need a .fla file (example: c:/macmenu/macmenu.fla).
  • In the same folder as the .fla file we need to have another folder: /org/effects (example: c:/macmenu/org/effects).
  • Inside this folder we need to have two .as documents (DockItem.as and DockButton.as)
  • Within the .fla, each item in the library must be linked to a class, and the base class of each item must be org.effects.DockButton.

If it’s all OK, test the movie…

(At this point, if you want to put the folder org/effects in your classpath you can, so you won’t need to copy this folder to each project you create and use the DockItem or DockButton.)


Step 20: Change the Color on Mouse Over

Why not change the color of the button when the mouse passes over it? In this section I will teach how. For this we will use the TweenLite engine again to give some tint to the object. However, we are already using TweenLite in the DockItem object and we are extending this object at DockButton. We want to extend DockButton to change the color, but we can’t use TweenLite anymore in the same object since the new TweenLite object will overwrite the other one (even with the property overwrite:false in TweenLite it will reduce the performance a lot if we use it directly in the same object). All is not lost; we have an icon inside each object of the library and we can apply the tint to that.

To do this, let’s create another ActionScript File, but now save this one at the same folder as the .fla with the name “OverButton.as” (example: c:/macmenu/OverButton.as.)


Step 21: Coding the OverButton Object

First we create the package and import the necessary classes; since we saved the OverButton.as file in the same folder of the .fla file the package will be top level, so there’s no need to write “package org.effects”:

package{

	import org.effects.DockButton;
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class OverButton extends DockButton{
	}
}

OK, so we’re extending DockButton this time and we’ve imported the DisplayObject class because we will treat the icon as a DisplayObject. We’ve also imported MouseEvent which we’ll use to check when the mouse is over the icon and when it’s out. We also have TweenLite to create some tween effects with the color.


Step 22: OverButton Constructor

package{

	import org.effects.DockButton;
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class OverButton extends DockButton{

		private var _object:DisplayObject;

		public function OverButton():void{
			_object=this.getChildAt(0) as DisplayObject;
			this.addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
			this.addEventListener(MouseEvent.MOUSE_OUT, mouseOut);
			TweenPlugin.activate([TintPlugin]);
		}
	}
}

Why have we created a private var _object as DisplayObject? Our actual icon is stored in this variable (that’s what line 13 does) and is treated as a DisplayObject; we will use the color effect on our icon, not in the whole object.

We add the event listeners of the mouse to check when the mouse is over and when the mouse is out.


Step 23: Coding Mouse Functions

Since we have created the listeners for mouse over and mouse out, we will now create their functions:

package{

	import org.effects.DockButton;
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import com.greensock.TweenLite;
	import com.greensock.plugins.TweenPlugin;
	import com.greensock.plugins.TintPlugin;

	public class OverButton extends DockButton{

		private var _object:DisplayObject;

		public function OverButton():void{
			_object=this.getChildAt(0) as DisplayObject;
			this.addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
			this.addEventListener(MouseEvent.MOUSE_OUT, mouseOut);
			TweenPlugin.activate([TintPlugin]);
		}  

		private function mouseOver(e:MouseEvent):void{
			new TweenLite(_object,.5,{tint:0x990099});
		}

		private function mouseOut(e:MouseEvent):void{
			new TweenLite(_object,.5,{tint:null});
		}
	}
}

Note that we are using the TweenLite on _object now, not on “this” any more. That’s because the OverButton extends the DockButton which extends the DockItem where there is already a TweenLite being used. Also, in DockButton we have a fake alpha 0 background that doesn’t need to be painted.

For the tint property of TweenLite I used a color code of 0×990099, which is a medium purple; if you use null as the value the tint will be removed softly.


Step 24: Change the Base Classes

At this point if you test the movie, you won’t see any color change, because we need to change the base class of each object in the library again. Open the Library once more in the .fla (Window > Library). Right-click each object and change its base class to OverButton (not org.effects.OverButton, because the class file is not in the /org/effects folder).

OK, now you can test it!

Conclusion

In this tutorial I’ve explained about extending objects. The actual dock effect is pure math – it’s distance calculations, scale settings – but it’s important we see in the code that we cant use the “x” property as position reference, because the “x” property is changed every time. I hope now you all have a better understanding of the “extends” keyword, and can appreciate how the calculations are done here. Thanks for reading :)



View full post on Activetuts+

Page 1 of 3123
top