Tutorial:Buttons (AS3)
From Anipedia
Buttons are a staple of the Flash development world. You're not going anywhere unless you can code your own by hand.
Luckily, Matty's here to save the day.
Along with basic rollover behaviors, I have included code that dynamically creates a sprite along with a rectangle.
So here's the code.
//BUTTON CODE
var button:Sprite = new Sprite();
button.graphics.beginFill(0xCCCCCC);
button.graphics.drawRect(0, 0, 200, 100);
button.graphics.endFill();
button.alpha = .5;
addChild(button);
button.addEventListener(MouseEvent.ROLL_OVER, buttonOver);
function buttonOver(evt:MouseEvent):void{
button.alpha = 1;
}
button.addEventListener(MouseEvent.ROLL_OUT, buttonOut);
function buttonOut(evt:MouseEvent):void{
button.alpha = .5;
}
var button:Sprite = new Sprite();
This line creates a variable named "button". Flash will remember this name and store it as the datatype I set it as (In this case, a Sprite). You can set variables to a wide array of datatypes including MovieClips, TextFormats, and Videos.
button.graphics.beginFill(0xCCCCCC); button.graphics.drawRect(0, 0, 200, 100); button.graphics.endFill(); button.alpha = .5; addChild(button);
These lines create a box 200px wide and 100px high. Its position is x = 0 and y = 0. The fill color is set to #CCC. Do keep in mind that Flash will only accept hex values that begin with "0x" instead of "#". The first three lines must be in the exact order I put them in, or the box won't have a fill.
Next, I set the alpha of the box to 50%. Flash reads alphas in decimals, so 100% would be 1, etc. Finally, I add the button onto the stage with the addChild command. Without it, the button won't show up.
button.addEventListener(MouseEvent.ROLL_OVER, buttonOver);
function buttonOver(evt:MouseEvent):void{
button.alpha = 1;
}
These lines create a mouse behavior for the button that calls the function "buttonOver" once the mouse rolls over the button. You must have the instance name of the name of the variable before the "addEventListener" command unless you are giving the stage itself a behavior.
Inside the function, I set the alpha to 1 to add a pseudo rollover effect.
button.addEventListener(MouseEvent.ROLL_OUT, buttonOut);
function buttonOut(evt:MouseEvent):void{
button.alpha = .5;
}
Here, most of the code is the same as above. The only difference is a different behavior assigned to the button along with a different function. Flash will not allow functions of the same name to exist.
Next lesson, I'll cover click behaviors and creating graphics dynamically through the actions panel.
- Click on "Player" to view
-Matt


