Introduction to Buttons & Events in Flash (AS3)

Buttons are objects categorized as Symbols and are used to enhance user interaction. Their timeline consists of four frames or states namely Up, Over, Down, Hit which are respectively the frame to display when the button is inactive, when the user brings his mouse over it, when the user clicks it and the area in which the button should accept mouse events...

Creating a Button ::
To create a new button, select "New Symbol" from the insert menu or use the keyboard shortcut, Ctrl+F8 and choose Button as the type for the new symbol. 
Select the Up frame and draw on the stage, in a way you would like the button when idle. 
Now right click the Over frame and select "Insert KeyFrame" this should create a duplicate of the Up frame which you can edit or you could select "Insert Blank KeyFrame" if you wish to edit from scratch either way, make the Over frame reflect how you would like the button to look when the mouse moves over. 
Similarly, edit the Down frame and the Hit frame.
Note that the Hit frame is not essential for the button to function but then it's advised you use it to define the button area. This can be done by drawing a shape in the hit frame to reflect the buttons area of effect. 

Now that we are done with creating our button, we need to write some actionscript to tell the button how it need to react to Mouse Events (when a mouse moves over, mouse button is pressed, etc.).

Before we do that,we need to move back to the main stage by clicking on the Scene1 link toward the top right corner of the window as show...

Now open the library (Ctrl+L) where the button we just created is listed and drag it and drop it on the stage of the main movie. This should create an instance of the button. 
Open the properties window (Ctrl+F3) and select the button on the stage. In the properties pane, change the instance name to "my_btn".

Now Select the first frame from the timeline, right click and select "Actions" this should open the actions pane where you will need to put the following code.


Code ::

my_btn.addEventListener(MouseEvent.CLICK,handleClick);

function handleClick(e:MouseEvent)
{
trace("my_btn was clicked !!!");
// code to be executed on click here
}


 Code Description ::
my_btn.addEventListener(MouseEvent.CLICK,handleClick);

In this line, we are assigning an Event Listener to the button (instance name : "my_btn") to listen to the Events Stream and call the function "handleClick" when a MouseEvent, "CLICK" is registered.
In simple words, the function is called when the user clicks the button we put on the stage.
Syntax for initializing an eventHandler :: Object.addEventListener(Event,function_name);

function handleClick(e:MouseEvent)
{
trace("my_btn was clicked !!!");
// code to be executed on click here
}

Here, we are defining a function by name handleClick which will be called when a mouse click event is registered.
Here a parameter variable, "e" of the type MouseEvent is set because the eventHandler function passes an event variable as arguments and the function needs to accept it though we dont use it in the code.


Now that you have a basic idea about using buttons and listening to events, you can extend your knowledge to different events and also edit the basic handleClick function in this tutorial and extend it for more complex operations.

Implementing Custom Classes in AS3

Now that we know how to create classes in AS3, we can now learn to implement these custom classes written by us into objects in the flash movie.
Before continuing, it is highly recommended you go through the article, Getting Started with ActionScript 3.0 to learn how to create your own classes.

The custom class :: 
To start off, we will need an actionscript class. You could use the sample greeter class provided below or you could use any other class you have at hand.
Copy the code below, open Flash and create a new ActionScript 3.0 class and paste the code and save the file as "greeter.as"
Sample greeter Class ::

package {
public class greeter
{
    private var my_name:String;
   
    public function greeter()
    {
        }
   
    public function init_name(n:String)
    {    my_name=n;
        trace("Initialized Name!")
        }
   
    public function hello()
    {    trace("Welcome "+my_name+".");
        }   
    }
}

Creating Objects from our class ::
Now that we are done writing the actionscript class, we can start with Flash.
Open Flash and create a new file (Ctrl+N) and select ActionScript 3.0 from the list. This should open a blank Flash movie with a white stage.
Now before we start working, save the movie (Ctrl+S) and choose a file name of your choice and make sure you save it along with the actionscript file in the same directory.

Now select the first keyframe, right click and select Actions from the context menu... This should open the actions window, a miniature version of the one which you would have seen while writing your class.
This is where the code goes...

Code ::

var n1:greeter=new greeter();
n1.init_name("Anand");
n1.hello();

var n2:greeter=new greeter();
n2.init_name("Dimitri");
n2.hello();

Code Description ::

var n1:greeter=new greeter();

This line of code creates a new object with an instance name "n1", in this case an object of class greeter.
As soon as an instance of the object is created, the constructor function is called and instances of variables and functions are created, specific to each instance.
n1.init_name("Anand");

Here, we are calling the "init_name" function from the n1 instance of the greeter object with arguments "Anand".
n1.hello();

This calls the hello function of the n1 instance of greeter object.

 Similarly, in the next few lines, a new instance of the object greeter, "n2" is created and functions are called from this instance.



Now that we are done with the code, we can test the movie. 
 To do so, press Ctrl+Enter and you can see the output generated by the trace function in the output window...




In case of any existing confusion about objects and classes, this schematic should help you better understand them...



Incase you face any problems or if you have any sujjestions, feel free to leave a comment.

Getting Started with ActionScript 3.0

Before we begin with ActionScript, we should know that As3 is an object oriendted programming language (OOP) and thus it's highly sujjested you go through the Introduction of OOP article before continuing...
A quick Summary of OOP ::
In the oop model, pieces of code are considered objects and each such object is properly defined by a class with variables and functions specific to the object. Such discrete pieces of code can be easily reused and allows for encapsulation.
Creating you first class and package
A package is a collection of classes, more like a folder with all the classes needed for the project.
And classes are pieces of code that define functions and variables specific to an object.
lets not get into the details now and start with our first class which defines a Ball Object.

Open Flash and choose to create a new file (Ctrl+N) and select ActionScriptFile and write the code as shown below and save it as Ball.as

Note:: A package name is also the relative path to the class with respect to the flash files. So in this case if you intent to save your flash files in the C:\ Drive, the the actionscript file (Ball.as) sholud be saved in C:\mypackage\as3\

Code::
package mypackage.as3 {
class Ball
{
 import flash.display.*;
 var x:Number;
 var y;Number;

function Ball(){
// some initialization code here 
trace("Object Successfully created");
}

public function changeSize(){
// code to change size here
} 

private function secret(){
// some code, whose functionality you wish to hide
}
}
}


   Code Description ::
package mypackage.as3

in this line, we are defining a package, which acts as a repository of all our classes written for the specific application.
class Ball{
import flash.display.*;

in the first line, we are defining our class which contains properties and functions of any Ball object that we use in our program. And the second line imports all classes from the display package so that they could be used in our class.
 var x:Number;
 var y:Number;

Now we are creating two variables x and y which will exist for every instance of the ball object which we create in the future.
here "var" keyword indicates that we are creating a new variable of name "x" and ":Number" tells it what type of variable it is. In this case, a number.
Syntax for Creating a new Variable :: var variableName:variableType;

function Ball(){
// some initialization code here 
trace("Object Successfully created");
}
Here, we are defining a constructor. A constructor is a special function which is executed as soon as an instance of an object is created. It is distinguished from other functions as it has the same name as the class.
The trace function is one that is heavily used for debugging in flash. This function prints the arguments passed into an output window. In this case, it prints "Object Successfully created".

public function changeSize(){
// code to change size here
} 
Here, we are defining a normal function by the name changeSize. The function type is set to public (access modifier) which means that it can be accessed from outside the class too.
  • AcessModifiers can be prefixed to classes, functions and any kind of variables.
private function secret(){
// some code, whose functionality you wish to hide
}
Here, we are defining another function, only this time, the access modifier set to private which means it can only be called from inside the class.

Syntax for Defining a function :: function functionName(parameters-here){ }


This is just the actionscript class for an object, Ball. You will not be able to see the output as we have'nt created any instance of the ball object yet. And even if you feel a little intimidated by all the jargon and complexity of OOP, i can best assure you you can still go ahead as one can develop applications without using classes too...
Read the acticle, Implementing Custom classes to know how to implement classes and custom objects into Flash.
 

Related Posts with Thumbnails