Building a Basic Menu in ActionScript 3.0 Tutorial – Part 1 – Array
Today I have decided to build a simple ActionScript 3.0 horizontal menu based on an array. This is a fairly common practice in Flash development as we are often using data provided from a XML file to dynamically update content within our movies. To simplify this tutorial I am going to use an array that is written within my code instead of parsing it from a XML file.
The following example will demonstrate how to loop through an array and draw a button for each item in that array. Each button will have a label, an up state and an over state. I have read that it is good practice to use the SimbleButton object whenever possible, but I am not going to use the it in this tutorial because I am interested in learning more about addChild(), getChildByName(), currentTarget, mouseChildren and other features of ActionScript 3.0 that could be avoided using the SimpleButton.
package ca.flashdev.example {
import flash.display.Sprite;
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class BasicMenu extends Sprite {
// Create the array of button names.
private var __MenuArray:Array = new Array("Button 0",
"Button 1",
"Button 2",
"Button 3",
"Button 4");
/**
* The constructor. This method is fired automatically
* when the class is instantiated.
*/
public function BasicMenu():void {
drawMenu();
}
/**
* Draw the menu.
*/
private function drawMenu():void {
// This variable will hold the x position
// of the next button in the menu.
var xPos:Number = 0;
// Create a holder that will contain the menu.
var menuHolder:Sprite = new Sprite();
// Add the holder to the stage.
addChild(menuHolder);
// Create text formatting for the text fields in the menu.
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0x000000;
format.size = 12;
format.bold = true;
// Loop through the array.
//Create each item listed in the array.
for (var i in __MenuArray) {
// Create the button.
var button:Sprite = new Sprite();
button.name = "button"+i;
// Disable the mouse events of all the
// objects within the button.
button.mouseChildren = false;
// Make the sprite behave as a button.
button.buttonMode = true;
// Create the label for the down button state.
var label:TextField = new TextField();
label.autoSize = TextFieldAutoSize.LEFT;
label.selectable = false;
label.defaultTextFormat = format;
label.text = __MenuArray[i];
// Create an up state for the button.
var up:Sprite = new Sprite();
up.graphics.lineStyle(1, 0x000000);
up.graphics.beginFill(0x00FF00);
up.graphics.drawRect(0, 0, 100, 30);
up.name = "up";
// Create an over state for the button.
var over:Sprite = new Sprite();
over.graphics.lineStyle(1, 0x000000);
over.graphics.beginFill(0xFFCC00);
over.graphics.drawRect(0, 0, 100, 30);
over.name = "over";
// Adder the states and label to the button.
button.addChild(up);
button.addChild(over);
button.addChild(label);
// Position the text in the center of the button.
label.x = (button.width/2) - (label.width/2);
label.y = (button.height/2) - (label.height/2);
// Add mouse events to the button.
button.addEventListener(MouseEvent.MOUSE_OVER,
displayActiveState);
button.addEventListener(MouseEvent.MOUSE_OUT,
displayInactiveState);
button.addEventListener(MouseEvent.CLICK,
displayMessage);
// Add the button to the holder.
menuHolder.addChild(button);
// Position the button.
button.x = xPos;
// Increase the x position for the next button.
xPos += button.width + 2;
// Hide the over state of the button.
over.alpha = 0;
}
// Postion The Menu.
menuHolder.x = 20;
menuHolder.y = 20;
}
/**
* Show the active state of the button.
*/
private function displayActiveState(event:MouseEvent):void {
// Show the over state of the button.
event.currentTarget.getChildByName("over").alpha = 100;
}
/**
* Hide the active state of the button.
*/
private function displayInactiveState(event:MouseEvent):void {
// Hide the over state of the button.
event.currentTarget.getChildByName("over").alpha = 0;
}
/**
* Display a message in the Output window.
*/
private function displayMessage(event:MouseEvent):void {
// Output the name of the clicked button.
trace(event.currentTarget.name)
}
}
}
Save this file as BasicMenu.as in a folder structure of ca.flashdev.example.
Create a new movie and add ca.flashdev.example.BasicMenu to the ActionScript 3.0 Settings Document class field. Save this file as basicMenu.fla in the same directory as your ca folder. Publish (Ctrl+Enter) your movie and you should see the menu.
Great article! However, for the lazy like me I prefer FMF.
See: http://www.flashmenufactory.com/
Hallo,
if I compile this sample with flashDevelop, then I get the following error msg.
Anybody know whats wrong with it?
TypeError: Error #1009: Der Zugriff auf eine Eigenschaft oder eine Methode eines null-Objektverweises ist nicht möglich.
at appClasses::BasicMenu/::displayActiveState()
bye
Markus
hi,Markus .u must change the code:
over.name = “down”;
to
over.name = “over”;
I think it’s a little mistake by author.
or u can download the source files,it works fine.
Thanks BlueLife… I fixed the code.
I’m a student familiar with java-programming and I decided to get some flash skills, but things didn’t go as smooth as I expected. Luckily I found your site. Your tutorials are simple and very understandable. Thanks and keep up the good work
Hi, thanks for this tutorial code. Its nicely formatted and easy to understand. It would be even nicer if you could include the completed Flash Object on the page as an example of how it will look.
Thanks for the suggestion Chris. I have added the Flash movies for my tutorials throughout the site.
Thanks for this example.
I have been looking for help in making a single play button that I would use to play my Flash animation. I am extremly new to Actionscript and am still learning what certain things mean. Is there anyway anyone can help me understand how to create a play button that would actually link to the rest of my animation?
Thank you,
CLS
Hi CLS,
1) Create your animation on the timeline.
2) Add another layer and draw a play button in it. Select the button and hit F8. Choose Button.
3) Select the play button and look in the Properties panel (bottom of screen).
4) Type play_mc where you see Instance Name.
5) Create a new layer in the timeline. Click into the new layer and press F9 (Actions Panel).
6) Add the following code to the Actions panel:
play_mc.addEventListener(MouseEvent.MOUSE_DOWN, playAnim);
function playAnim(event:MouseEvent):void {
play();
}
stop();
I emailed you my test file. LMK if you have any questions.
It’s taken me at least 2 hours to find a decent tutorial on creating a navigation from an Array and finally I’ve found one that helped. Cheers! I’ve modified your code to work with multidimensional arrays, I hope you don’t mind.
Not at all.
ya, god, why does it have to be so hard to find something so simple >_<.. thanks a bunch Crosbie, works great
thank you for tutorial
2 hours? You’re lucky, I’ve found this after 3 weeks of searching. Not even anything on Adobe livedocs.
Maybe someone can tell me why there is SO little documentation around, even for common things like this?
Great thank’s!!!
I’ve spend several hour to find the menu quite simple and clear to use. Because I’m not a big expert in programing this tutorial suite’s me the best.
Hi this is a great site – consider it bookmarked! Your ActionScript 3 stuff is really helpful for me as I’m just learning and you keep things rather straightforward.
One thing I would recommend is to allow for a bigger area to display your example code…the textarea right now (at least in IE6) is very small and scrolling through a large amount of lines is tricky. Other than that the site is great!
Keep up the good work.
Thanks,
Mikey.
PS – Only using IE6 because I’m on a locked-down network.
Thanks Mikey! I recently updated the theme of this blog and never realized that the height of the code samples shrunk.
How can I change the text color while on Mouse_Over. I see you are changing the sprite only, what would be the best way to change the Text Format on Mouse Over to each Menu.
Thanks,
Thank you for this well thought out tutorial!!!
I wish all programmers would comment like you. Kudos!
This is the most simple, clear and understandable Menu-AS3-Tutorial I found.
Thanks very much.
Ok so we need to build a Menu in Flash, lets hire someone for a ridiculous hourly wage, pffftt please.
Basic Menu, complicated code. AS3 is not for designers, that is all.
Thanks Fraser, this was the exact thing I have been looking for the last three day.
Excellent! thanks for doing a tutorial on this topic. Very helpful.
Great menu,
how can I do to have the clicked button as inactive ? thanks…
how to animate button to use As3?