Monday, June 28, 2010

AS3 Beginner Tutorial - part 2: Buttons & preloaders

Now, lets finally make something!

Before we start with the code, you need to know a little about events in programming. Events are signals that are dispatched by objects and can be 'caught' or 'listened to' by other objects. For example, a user clicks on a button - the button dispatches a MouseEvent.CLICK event. We can add a function to be called when an event is dispatched using addEventListener() method. We need to specify the type of event we're listening for, and the function we're calling. See below for examples:


1. Create a button (F8) and place it on the stage on frame 1.
2. Give it an instance name of "myButton" without the quotes.
3. Open up actions tab for frame 1 (note: you cannot write actions on movie clips/buttons in as3 anymore)
4. Use the script:

stop(); // stops the movie on this frame

function onButtonClick(evt:MouseEvent):void {
trace("worky worky!");}

/*We have made a function, which is called onButtonClick. 
It's triggered with a mouse event. We aren't returning 
anything, so we write void. If the function is triggered,
a text is traced in the output window.*/

myButton.addEventListener(MouseEvent.CLICK, onButtonClick);

// We've added an event listener for our button, 
// which triggers the onButtonClick function.

There we go! Let's move on!


1. Create a dynamic text field (on frame 1) with instance name "pShow" without the quotes.
2. Open the actions tab for frame 1.
3. Use the script:

stop(); //stops the frame

this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, pLoading)
// creating a listener to call the loading function as the movie loads
function pLoading(event:ProgressEvent):void { 
//creating the function
var pPcnt:Number=event.bytesLoaded / event.bytesTotal * 100 
//how much loaded in %
pShow.text=pPcnt + "%" 
//telling dynamic text what to show

// checking if movie loaded completely


AS3 Beginner Tutorial - part 1
AS3 Beginner Tutorial - part 3

No comments:

Post a Comment