Monday, December 6, 2010

AS3 Animation Tutorial - Using the AS3 EnterFrame Event to Create Animation in Flash [Video Tutorial]

by Alberto Medalla
Lecturer, Ateneo de Manila University

You can use AS3 to add some animation to your Flash project using code. Instead of adding tweens on the timeline, you'll be using AS3 to animate objects. In this ActionScript video tutorial, I'll show you a few simple examples on how to create animation in Flash using the AS3 EnterFrame event.

AS3 Animation Tutorial - Using the AS3 EnterFrame Event to Create Animation in Flash



AS3 EnterFrame Event Animation Sample Code #1
Here is the code for the first example where the circle will continue to scale up as long as the movie is running.
var growthRate:Number = 2;

circle_mc.addEventListener(Event.ENTER_FRAME, grow);

function grow(e:Event):void
{
     e.target.width += growthRate;
     e.target.height += growthRate;
}

AS3 EnterFrame Event Animation Sample Code #2
In the second example, the animation will stop when the circle's size reaches 150 pixels.
var growthRate:Number = 2;
var maxSize:Number = 150;

circle_mc.addEventListener(Event.ENTER_FRAME, grow);

function grow(e:Event):void
{
     e.target.width += growthRate;
     e.target.height += growthRate;
     if(e.target.width >= maxSize)
     {
          circle_mc.removeEventListener(Event.ENTER_FRAME, grow);
     }
}

AS3 EnterFrame Event Animation Sample Code #3
In the third example, the code has been modified to make the circle grow and then shrink repeatedly.
var growthRate:Number = 2;
var maxSize:Number = 150;
var minSize:Number = 100;
var scaleMode:String = "grow";

circle_mc.addEventListener(Event.ENTER_FRAME, growShrink);

function growShrink(e:Event):void
{
     if(scaleMode == "grow")
     {
          e.target.width += growthRate;
          e.target.height += growthRate;
          if(e.target.width >= maxSize)
          {
               scaleMode = "shrink";
          }
     }
     else if(scaleMode == "shrink")
     {
          e.target.width -= growthRate;
          e.target.height -= growthRate;
          if(e.target.width <= minSize)
          {
               scaleMode = "grow";
          }
     }
}

Click on the link to view more AS3 enterframe animation samples

Monday, November 29, 2010

How to Create an AS3 Event Listener

Part 1: Introduction to AS3 event handling
Part 2: How to create an AS3 event listener
Part 3: The AS3 event object
by Alberto Medalla
Lecturer, Ateneo de Manila University

In this next part of the Flash AS3 Event Handling tutorial series, we're going take a look at how to write event handling code.

According to the Adobe Flash ActionScript 3 documentation, there are 3 important elements that need to be identified when working with event handling in Flash. These are: (1) the event, (2) the response, and (3) the event source. We've already introduced the concepts of events and responses in the first part of this lesson, but let's go ahead and take a look at them again with a little more detail. And then after that, let's take a look at what the event source is.

EVENT
An event refers to a specific occurrence that happens as your Flash movie runs. In ActionScript 3 event handling, events are identified by specifying the event class as well as the event constant.

Event classes can be thought of as the different groups used to classify different kinds of events. There's an event class, which is also called Event. Some events that fall under this class are the complete, deactivate, and open events. Another example is the keyboard event class, which is written as KeyboardEvent. Some events that fall under this class are the key down (i.e. when the user presses a keyboard key) and key up (i.e. when a key is released) events. There's also another class for mouse events, which is written as MouseEvent.

Event constants are specific names that refer to the events themselves. Let's consider the MouseEvent class, a few of the events that fall under this class are: mouse clicks and mouse roll overs (i.e. when the cursor hovers over a button). The constant for a mouse click is written as CLICK. For a mouse roll over, it is written as ROLL_OVER.

Once these elements have been identified, writing the event in code takes on this form:
EventClass.EVENT_CONSTANT

So for example, if you were to specify a mouse click event then you would write: MouseEvent.CLICK. And if you were to specify a mouse roll over event, then you would write: MouseEvent.ROLL_OVER.

RESPONSE
A response refers to what is going to happen once Flash detects the occurrence of an event. For example, after a button is clicked (MouseEvent.CLICK), we can instruct the Flash movie to respond by playing an audio file. The response is specified as a function. This function's body will contain the line(s) of code that will tell Flash what to do. This function, referred to as an event listener (also sometimes referred to as an event listener function or listener function), will be called immediately after the specified event is dispatched and detected.
function eventListener()
{
     // response to make when the event happens
}
REMINDER: The terms event listener, event listener function and listener function all refer to the same thing - it is a function that is registered to execute when a specific event occurs.

EVENT SOURCE
An event source refers to the object that is directly related to the event. In most cases, it is the object from which the event originates from. For example, when dealing with mouse click events, the button that was clicked would be the object that the mouse click happens to, and is therefore considered as the event source. Another example would be when a URLLoader object loads an external text file. For instance, when a URLLoader finishes loading the file, this is considered as an event as well. In this case, the URLLoader is the one responsible for loading the external text file and is therefore considered as the event source. This event source can also be alternatively referred to as the event target.

After identifying these 3 elements, you bring them all together using the addEventListener() method. The addEventListener() method registers the event listener function with the event source so that the event listener function can "hear" when the event is announced. This is essentially what connects the event listener function to the event. Once an event listener function is registered with an event source, you can think of it as the event listener function sitting there quietly, just waiting to be told or "listening" for when the event is dispatched or announced. Once the event is announced, the event listener function will then run, enabling the Flash movie to make the appropriate response.


FLASH ACTIONSCRIPT 3 EVENT HANDLING SYNTAX
The syntax for writing event handling code would be:
eventSource.addEventListener(EventClass.EVENT_CONSTANT, eventListenerFunctionName);

function eventListenerFunctionName(e:EventClass):void 
{
     // code for response goes here
}

Let's create an example:
  1. Create a new Flash ActionScript 3.0 document
  2. Draw a shape on the stage and convert it into a Button symbol
  3. Give this instance an instance name of my_btn
  4. Create a new layer for the ActionScript, then select frame one of this layer
  5. Go to the Actions Panel and type the following code in the Script pane:
    my_btn.addEventListener(MouseEvent.CLICK, onClick);
    
    function onClick(e:MouseEvent):void
    {
         trace("The event handler works!");
    }
You've just written some code that handles a mouse click event. Go ahead and test your movie. When you click on the button, you should see the phrase The event handler works! come out in the output window.

FLASH ACTIONSCRIPT 3 EVENT HANDLING CODE EXPLAINED
We've learned that there are 3 important elements when it comes to working with event handling in Flash AS3 (the event, the response, and the event source). But when it comes to writing the event handling code, the code itself is made up of 2 parts: (1) the add event listener statement, and (2) the event listener function.

ADD EVENT LISTENER STATEMENT
Whenever an ActionScript 3 event happens, the event gets dispatched or announced within the Flash player. Once the event is announced, the event listener function that is registered with the event's source will execute. To register an event listener function with an event source, the addEventListener() method is used. Registering the event listener function with the event source will enable the event listener function to know when to respond.

In order for the event listener function to respond at the right time, the add event listener statement must contain the following 3 pieces of information:
  1. the event source
  2. the event
  3. the name of the event listener function to be executed once the event is triggered
In the example we created, the add event listener statement would be:
my_btn.addEventListener(MouseEvent.CLICK, onClick);
Event Source: my_btn
Event: MouseEvent.CLICK
Event Listener Function Name: onClick

THE EVENT LISTENER FUNCTION
This is the function that gets executed in response to the event. The event listener function's body will contain the lines of code that will make up whatever response we'd like the Flash movie to make whenever the event is dispatched (e.g. playing a sound when a button is clicked, displaying an image when you roll over a button, etc...). In the example that we created, the event listener function would be:
function onClick(e:MouseEvent):void
{
     trace("The event handler works!");
}
The event listener knows that it is the function that needs to be executed because its name matches the event listener function name that was specified in the add event listener statement.


NOTE: You will also notice that the event listener function has a single parameter - e. We'll talk about that later.

At this point, let's take a look at a summary of the event and response process that took place in our code example:
  1. User clicks on the my_btn button

  2. The event (my_btn being clicked) is immediately dispatched

  3. The event listener function "hears" the event being dispatched

  4. The event listener function runs

So that is the basic flow of how events in AS3 are handled: (1) the event occurs, (2) it gets dispatched, (3) the event listener "hears" the event being dispatched, (4) and the event listener function runs.

Now let's go back to the event listener function and lets talk about the single parameter that it is set to accept. In our example, the parameter is named e and is of the MouseEvent data type.
function onClick(e:MouseEvent):void
{
     trace("The event handler works!");
}

Every time a dispatched event triggers an event listener function to run, information gets passed to that event listener function. This information is contained in what is referred to as an event object. This parameter is what is used to accept that event object whenever it gets passed to the event listener function. Some of the information contained in this event object include: the event source and the event that occurred.


All event listener functions must always have a parameter for the event object regardless of whether or not the parameter will be used anywhere in the function body. In our example, we do not make use of the event object parameter, but if we removed that parameter, our event handler code will NOT work.


When creating the event object parameter, its data type is set to match the event class of the event that is being watched out for. In our example, the event listener is watching out for a mouse click, which is under the MouseEvent class. So the data type for the parameter should be MouseEvent as well:
myObject.addEventListener(MouseEvent.CLICK, myListenerFunction);

function myListenerFunction(e:MouseEvent):void
{
     // function body
}

If we were watching out for a KeyboardEvent, then the parameter should have the KeyboardEvent data type instead:
myObject.addEventListener(KeyboardEvent.KEY_DOWN, myListenerFunction);

function myListenerFunction(e:KeyboardEvent):void
{
     // function body
}

In the examples, the parameter name used is e. It's NOT a requirement that you use the name e, since parameter names are author defined. The usage of e is more of a common convention, and is what will be used throughout this tutorial series.

In the next part of this series on Flash AS3 event handling, we are going to take a closer look at the AS3 event object.

PREV: Introduction to Flash AS3 Event Handling
NEXT: The AS3 Event Object

Sunday, November 28, 2010

Introduction to AS3 Event Handling - Learn All About AS3 Event Listeners

Part 1: Introduction to AS3 event handling
Part 2: How to create an AS3 event listener
Part 3: The AS3 event object
by Alberto Medalla
Lecturer, Ateneo de Manila University

In this series of articles, we're going to learn all about the basics of Flash AS3 event handling. This first part will introduce to you the concept of events within Flash and how these events can be handled throughout a Flash movie or application. Let's begin.

ActionScript code inside a Flash movie or application only gets executed after specific events occur. Let's say we have Event A, Event B and Event C - some parts of the code will run only after Event A happens (whatever that event may be), while other parts of the code will wait for either Event B or Event C. Now, I know the word "event" can sound a bit dramatic. Are we talking about a catastrophic event? A mysterious event? Or an explosive event, perhaps? Not really. This simply means that the various blocks of code in a Flash movie wait for specific things to happen - events - before they respond. They don't just get executed all at the same time. Let's say, for example, you have a Flash space fighter game. And in this game, your character is a small spaceship that shoots lasers, and your enemy is a giant mother ship. Your task is to keep firing at this mother ship until you break down its force field so that you can then destroy the entire mother ship altogether. Destroy the mother ship before it destroys you, and achieve this goal before your time runs out.

So in this game, you'll have some code that controls the firing of the lasers, while some other part of your code will enable the user to control the movement of your spaceship. And then you'll have more code that will control the energy of the enemy mother ship's force field, code for the game's time limit, code for the scoring, and so on... Now, obviously, you don't want all of that code to just keep running all at the same time. For instance, the code that creates the time limit should run immediately when the game begins, while the code for firing the lasers should run only when the user presses the space bar on the keyboard. Here, you see that there is an event and a response. An event would be something that happens while the Flash movie or application is running. That event could be anything - a user clicking on a button or an image being downloaded, for example. A response would be how the Flash movie or application would react after a specific event occurs. That response could be anything as well - play an audio file, go to the next frame, display some text, etc... In the 2 previous examples, the events would be: (1) the starting of the game, and (2) the user pressing the space bar key. The respective responses would be: (1) the starting of the counter for the time limit, and (2) the firing of the lasers.

Event Response
Game starts Time limit starts running
User presses space bar Lasers are fired

Let's take a look at an actual example. In the image below, you will see that there is some ActionScript on the keyframe on the last frame of the Flash movie.


This last frame contains a stop() action, which will prevent the animation from looping when it reaches the end.


And since this stop() action is placed in the last frame, then it only gets executed once the playhead reaches that last frame. Not the first frame, not the middle frame, not any other frame except for the last one. So the event that Flash is waiting for in this example would be: the moment that the playhead enters the last frame. While the response would be: the Flash animation stops.

Event Response
Playhead enters last frame Flash animation stops

If, for example, we wanted to stop the animation on frame 25 instead, then we should place the stop() action on a keyframe on frame 25.


So the event that invokes the response here would be: the playhead entering frame 25 (instead of the playhead entering the last frame).

But this is a rather simple example. Here, the event that we are waiting for is simply dependent on the movement of the playhead along the frames of our animation. We just have to write the code, run the movie, and then wait for the playhead to enter the frames that contain ActionScript code.

But what about other types of events? 
Let's take user-based events, for example. User-based events are those that are initiated directly by the user, such as a mouse click or a keyboard press. In the space fighter game example, the user pressing the spacebar key is considered a user-based event. Whenever the user presses the spacebar, the spaceship fires its lasers. So whatever code in the Flash movie is responsible for shooting the lasers should be executed only when the user-based event of pressing the spacebar key happens. And then there are also other types of events other than user-based events that occur while the Flash movie is running. For example, when an external image is loaded into a Flash movie, the moment the loading of the image finishes can be considered as an event as well.

So how do we write ActionScript code that will allow us to identify a specific event and then tell Flash to respond only after that event occurs?
The process of identifying events and telling Flash how to respond is referred to as event handling. In order for you to be able to handle events in Flash, you must write what is called an event listener. An event listener is a function that will execute only when the specified event occurs (a mouse click, a press of a keyboard key, etc...). In order for an event listener to know the right moment at which to execute, it must be registered to an event's source. It's quite common to have numerous event listeners in one Flash project in order to deal with the many different events that can happen while the Flash movie is running. This is one of the reasons why AS3 event handling is one of the most important things that you should get a good grasp of when you are starting to learn ActionScript 3.

In the next article, we're going to learn how to write an ActionScript 3 event listener and how to register it to an event's source.

NEXT: How to Create AS3 Event Listeners

Saturday, November 13, 2010

Adding Sound to Flash Movie Timeline and Choosing Flash Sync Sound Options - Flash Event Sound vs Flash Stream Sound Tutorial

This tutorial comes with exercise files. Click the link below to visit the download page:
[GO TO EXERCISE FILES DOWNLOAD PAGE]

In this Flash Sound tutorial, we'll be learning the basics of adding sound to Flash documents. Here, I'll show you how to add sound to the timeline of a Flash movie. We'll also be taking a closer look at 2 of the Adobe Flash Sync Sound options - Flash Event Sound vs Flash Stream Sound. These are options that allow you to control the synchronization of sound in your Flash movie and we'll take a look at the difference between the two.

Open the add-bg-music.fla file. This is just a simple 16-second Flash animation of a jumping stickman. Take a look at the timeline and you will see a layer called bgmusic. This is where we will be placing the sound for our Flash movie. You'll see that the layer has one blank keyframe and nothing else.

NOTE: You DO NOT need a dedicated layer for your audio in Flash. You can place the sound on a layer that also has some animation in it. But even if creating a dedicated layer for your sound is not required, I would still recommend that you do so, in order to keep things more organized within your Flash document.

To add sound to Flash documents, let's first import the audio file. Import the CheerfulSong.mp3 file into the Flash document by choosing File > Import > Import to Library. Navigate to where the file is on your hard drive and import it. Once it's imported, select the blank keyframe on frame 1 of the bgmusic layer. A keyframe is needed in order to place sound on a layer in the timeline.

Next, go to the Properties Inspector. Here, you should now see the frame properties. Under the SOUND heading, click on the Name drop-down menu in order to expand the list. Whenever you import an audio file into your Flash document's library, it automatically gets added to this list. You should see CheerfulSong.mp3 as the second option.

Go ahead and select it. This applies the audio to our selected keyframe.

Take a moment to look at the other properties under the sound heading. You'll see Effect and Sync.

The Effect menu let's you choose from a few basic effects that you can apply to the selected sound.

Sync is short for synchronization. The Sync options let you choose the type of synchronization that the selected sound should follow: Event, Start, Stop or Stream. You can also instruct the sound to play more than once by specifying a Repeat value greater than one, or by choosing the Loop option.

When adding sound to Flash, the synchronization options will affect how the sound behaves when it is playing. Let's take a closer look at 2 of the synchronization options - Event and Stream.

Let's try to understand the difference between those two:

Event - This synchronizes the sound in your Flash movie to an event. That event would be when the playhead enters the frame that contains the sound. Once the playhead enters that frame, the sound will start playing and will only stop when the sound is explicitly told to stop (e.g. using ActionScript code that will stop the sound). Even if the animation is already at the end, an Event sound will keep on playing until it is explicitly told to stop (or until the song reaches the end).

Stream - This synchronizes the audio to the frames of the Flash movie. When the Flash movie stops, so does the sound. Also, when there are no more frames in the layer that contains the sound, then the sound will stop playing as well, even if the other layers still have frames to play.

Let's choose the Event option first and let's see how it will work in this example. But before you test the movie, let me explain what will happen: First, you need to know that the CheerfulSong.mp3 audio file is about 30 seconds long, while the Flash animation of the jumping stickman is only 16 seconds long. So our song is almost twice as long as the animation. And also, by default, a Flash animation is going to loop. This means that when the playhead reaches the last frame, it will go back to frame 1 and play the animation again, and so on... And since the animation is shorter than the song's duration, this means that the animation will loop back even before the song reaches its end. It's important that you understand this because when you preview this animation with the Event sound, you will notice that when the Flash animation loops, the same sound will play again, but the previous instance of the sound will still continue playing. So you'll end up with two instances of the song playing on top of each other. This happens because an Event sound will play every time the playhead enters the frame that contains that sound. When the animation loops, the playhead enters the frame with that sound once again, and therefore, another instance of the song is played as well. But we also know that an Event sound will not stop unless you explicitly tell it to stop. That's why the first instance of the sound will still continue playing along with the new instance of the sound. This will keep happening as long as the animation keeps looping and the Event sound is NOT explicitly told to stop. In cases where the sound is much, much longer than the looping animation, you'll end up with not just two instances of the sound playing on top of each other, but more! So go ahead and choose the Event option and then test the movie to verify what happens.

NOTE: The Start option behaves similar to the Event option in that it waits for an event (the playhead entering the frame where the sound is placed), but it differs in that the Start option will NOT play the sound again while the previous instance is still playing.

Now let's go back to the Flash document, and let's change the Sync option to Stream so we can understand how it will make the sound behave in this example. But before you test the movie, let me tell you that you will NOT hear the sound playing. We'll have to fix one more thing first to make the sound work properly. But in the meantime, go ahead and test the movie to verify, and then continue reading the article.

So now that you've tested the movie, let me explain why we don't hear the sound playing: The reason why you don't hear the sound playing is because there is only one frame on the layer where we placed the sound. If you recall, the Stream option will synchronize the sound to the frames of the animation. And right now, the sound is only being synchronized to one frame. That's not enough. So in order to hear the sound, we'll need to add more frames. Let's do that. Select the empty slot for frame 193 on the bgmusic layer, then right-click on it and choose Insert FRAME in order to add more frames to the layer. So now that there are more frames on the bgmusic layer, you should be able to hear the sound. Go ahead and test the movie to verify. You will notice that whenever the animation loops, the previous instance of the sound stops playing and the new instance starts from the beginning. And again, that's because the sound is being synchronized with the frames of the animation whenever the Stream option is used.

So when should I choose Event and when should I choose Stream?
Well, it really depends on what you're trying to do in your Flash movie. But as a general rule, I choose Stream whenever I need the sound to be in sync with the animation. I choose Event when I need to have a sound play regardless of how many frames I may have in the animation (for example if I'd like a song to keep playing even though the animation has already reached the end). But as you've seen in the example, this can be quite tricky because Event sounds can end up playing on top of each other. So in some cases I will just choose the Start sync option or I would add some ActionScript to make sure that the sound plays the way I want it to. With Button symbols, however, when you want to add sound inside a Button symbol's timeline (e.g. a sound effect whenever the user clicks on it), you must use the Event option. Button symbols' timelines only have a limited number of frames (just 4 to be exact), so most likely, the Stream option won't play the sound properly in this case.

Adding sound to Flash is fairly simple. It's usually with the way the sound behaves when playing where most new Flash users have a little trouble with. Hopefully, this tutorial has made it a bit more clear for those of you who are just learning how to add sound to Flash movies.

PREVIOUS: Flash Sound Basics | Adding Sound to Flash Movies - Importing Audio Files into a Flash Document's Library

Friday, November 12, 2010

Flash Sound Tutorial | How to Add Sound to Flash Movies - Importing Audio Files into a Flash Document's Library

In this beginner's Flash sound tutorial, we're going to talk about the basics of how to add sound in Flash. Adding sound to your Flash projects can make them a little more interesting. You can use audio files to add voice over narrations, background music and sound effects, for example. One way of being able to work with sound using Flash is by importing the sound files into your Flash document. Some of the audio formats that Flash gives you the ability to import include, but are not limited to:
  • MP3
  • WAV
  • AIFF
NOTE: Working with audio in Flash can take up a lot of resources. You might want to consider working with MP3 files over WAV and AIFF files since MP3 files are compressed and will take up less disk space. Also, if you won't be using the entire audio file, you might want to create a shorter version of the audio file using an audio editing application, and use that shortened version instead. This will help save more disk space.

To be able to add sound to the timeline of your Flash movie, import the audio file into your Flash document first. Here's how:
  1. From the main menu, choose File > Import > Import to Library
  2. When the Import to Library dialog box comes up, navigate to the folder that contains the audio file, select the file, and click on Open
  3. Once Flash finishes importing the file, you should be able to see it in the Flash document's library
You can preview the audio file by selecting it in the library, and then clicking on the play button in the preview window.

In the next article, we're going to learn how to add imported audio files to a Flash document's timeline. That article is also going to talk about the difference between the Flash Event Sound and the Flash Stream Sound options - two options for synchronizing sound in Flash.

NEXT: Adding Sound to Flash Movie Timeline and Choosing Flash Sync Sound Options - Flash Event Sound vs Flash Stream Sound

Friday, November 5, 2010

Flash 8 Masking Effect | How to Create a Mask in Flash 8 Video Tutorials

In this series of Macromedia Flash 8 video tutorial clips, we'll show you how to create a Flash 8 Masking effect. A Flash 8 mask layer can be used to hide some portions of a layer underneath it, revealing only select areas. It's pretty simple and easy to learn, but there are a number of different, creative ways to make use of a mask in flash.

Part 1: Working with Flash 8 Masking - What is a Layer Mask?


In part 1, we'll show you a simple example that demonstrates the Flash 8 masking effect.
[ALTERNATE LINK]

Part 2: Working with Flash 8 Masking - Creating the Layer that will be Masked

NOTE: If you're working in Flash CS5 and you're having trouble finding the Static Text type option, make sure that in the Properties Inspector (while you have the Text Tool selected), you have Classic Text instead of TLF Text selected.

In part 2 of Working with Flash 8 Masking, we'll be creating the layer that will be masked. This layer will consist of some text.
[ALTERNATE LINK]

Part 3: Working with Flash 8 Masking - Creating the Animation in the Mask Layer

NOTE: If you're following along with this video, but you're working in Flash CS5, choose Create Classic Tween instead of Create Motion Tween.

In part 3 of Working with Flash 8 Masking, we will be creating the motion tween animation in the layer that we will use as the mask. The motion tween animation will consist of a circle that moves from the left to the right side of the stage.
[ALTERNATE LINK]

Part 4: Working with Flash 8 Masking - Converting a Layer into a Mask


In part 4 of Working with Flash 8 Masking, we'll show you how to convert a regular layer into a layer mask.
[ALTERNATE LINK]

Part 5: Working with Flash 8 Masking - Editing a Layer Mask


In part 5 of Working with Flash 8 Masking, we'll show you how to edit an already existing layer mask.
[ALTERNATE LINK]

Thursday, November 4, 2010

Flash ActionScript 3 Tutorials - Beginners

ActionScript is a programming language used to develop applications that will run on the Adobe Flash Player platform. In this page, you'll find a list of beginner's level ActionScript 3 tutorials that will help you understand how to use the ActionScript 3 language to add interactivity to your Flash movies. If you're a Flash designer or animator who is looking to expand your skills in Flash by learning ActionScript 3, I encourage you to browse through these articles, and hope that you will learn a few new things. The lessons are grouped into different categories, which include topics such as Flash AS3 Event Handling, Working with Sound in AS3, and Creating ActionScript 3 Preloaders to name a few. This page is also updated whenever new tutorials are available. And to provide a more hands-on approach to learning, some lessons come with exercise files as well, which you can download for free and work with as you read the articles. So if you're ready to learn ActionScript 3, start reading the lessons and get on track to becoming knowledgeable in this powerful programming language. Have fun learning ActionScript 3!

Introduction to AS3

Assigning Instance Names and Modifying some Movie Clip Properties in AS3
Introduction to Flash AS3 Variables
Expressions and Operators in ActionScript 3

Flash AS3 Events

Introduction to Flash AS3 Event Handling
How to Create an AS3 Event Listener
The AS3 Event Object
Using the AS3 EnterFrame Event to Create Coded Animation in Flash

Working with MovieClips

The AS3 'this' keyword and how to randomize the size of a MovieClip instance on the stage
Enabling Users to Drag and Drop MovieClips
Testing Collision Between Two MoveClips

Flash ActionScript 3.0 Preloader Tutorial

Preloading in Flash AS3 [PART 1]
Preloading in Flash AS3 [PART 2]

Working with the Flash ActionScript 3.0 Timer Class

Introduction to the Flash ActionScript 3 Timer Class

Working with Text in Flash AS3

AS3 TextFields - The Basics
Working with AS3 Input Text Fields
Formatting Text in AS3
ActionScript 3 String to Number Conversion
ActionScript 3 Number to String Conversion
Enabling the User to Submit the Contents Inside an Input Text Field
[PART 1] Working with External Text in Flash ActionScript 3 - Loading the Text
[PART 2] Working with External Text in Flash ActionScript 3 - Formatting the Text
[PART 3] Working with External Text in Flash ActionScript 3 - Scrolling the Text

Working with Sound in Flash ActionScript 3

Introduction to the AS3 Sound and SoundChannel Classes
Playing Sound from the Library and Making a Sound Clip Loop in AS3
Pausing and Resuming Sound using Flash AS3
Flash AS3 Volume Controls

Working with Arrays in Flash ActionScript 3.0

Creating a Simple Quiz Game with Flash AS3 [PART 1]
Creating a Simple Quiz Game with Flash AS3 [PART 2]
Creating Multiple TextFields and Arranging their Positions using Arrays and For Loops in AS3
Retrieving the Index Value of an Item in a Flash AS3 Array

Working with the Flash AS3 Tween Class

The Flash AS3 Tween Class - Introduction
Flash AS3 Tween Events

Miscellaneous Flash AS3 Topics

Passing Custom Parameters to Flash ActionScript 3 Event Handlers
How to Fix the Error #1009 Preloading Issue in Flash AS3
Flash AS3 Stage Focus and Keyboard Event Issue and How to Remove the Yellow Border around Objects in Focus
AS3 Random Numbers Generator

Featured ActionScript 3 Video Tutorial

Animating an Object Using the AS3 Enter Frame Event


Mobile tutorialsSEO tutorials

Featured ActionScript 3 Training Courses
If you're looking for more ActionScript 3 training, check out these great training courses from lynda.com. Click on the links below to learn more about the courses, and to watch some free sample videos. If you want free access to all of the videos in these courses, you can sign-up for a free 10-day trial pass. Lynda.com is a great site for software training, and I use it myself so that I can stay updated on the latest training courses for Adobe products, and more.

ActionScript 3.0 Training by

START LEARNING TODAY!


10 day free trial

Thank you for visiting our Flash ActionScript 3 Tutorials for Beginners page. Like us on Facebook if you enjoyed this page, and feel free to share this with others who might be interested. We hope you visit us again! :)

Flash 8 Motion Tween Video Tutorials | The Basics of Motion Tweening - Animating Position, Color, Size and Using the Easing Property

In this set of Macromedia Flash tutorial online video training clips, we'll show you the basics of Motion Tweens in Macromedia Flash 8. In these tutorials, you'll learn how to animate the following properties of an object: position - make an object move from one side of the stage to the other, color - make the object change in color as the animation happens, size - change the scale of an object over time. You'll also learn how to use the Flash 8 easing property of motion tweens. This will give you greater control over the motion tween's speed. You can make the movement of objects accelerate or decelerate using the Flash 8 easing property.

NOTE: If you're working in Flash CS5, choose CREATE CLASSIC TWEEN instead of Create Motion Tween when you follow along with the videos.

Part 1: Working with Motion Tweens in Flash 8 - Animating an Object's Position


In this video, we demonstrate a basic Flash 8 motion tween example - how to animate an object's position.
[ALTERNATE LINK]

Part 2: Working with Motion Tweens in Flash 8 - Animating 2 Objects at the Same Time


In part 2 of Working with Motion Tweens in Flash 8, we show you how to properly animate 2 different objects at the same time. We'll also show you how you can reuse the media assets in your Flash document's library.
[ALTERNATE LINK]

Part 3: Working with Motion Tweens in Flash 8 - The Easing Property

NOTE: If you're working in Flash CS5, the Ease property can be found in the Properties Inspector (while a frame is selected) under Tweening.

In part 3 of Working with Motion Tweens in Flash 8, we talk about the Flash 8 easing property of motion tweens. The easing property allows you to adjust the distribution of the speed of an animation. With the easing property, you can make motion tweens accelerate or decelerate.
[ALTERNATE LINK]

Part 4: Working with Motion Tweens in Flash 8 - Animating Color

NOTE: If you're working in Flash CS5, the Tint property can be found in the Properties Inspector (while a symbol instance is selected) in the Style menu under Color Effect.

In part 4 of Working with Motion Tweens in Flash 8, we'll teach you how to animate an object's color. In this example, we'll make one of the circle's change color over time.
[ALTERNATE LINK]

Part 5: Working with Motion Tweens in Flash 8 - Animating an Object's Size


In Part 5 of Working with Motion Tweens in Flash 8, we'll teach you how to scale or resize an instance of a symbol using the Free Transform tool so that you can animate the object's size over time.
[ALTERNATE LINK]

Tuesday, November 2, 2010

Flash 8 Frame by Frame Animation and Flash 8 Onion Skin Feature Video Tutorial Series

NOTE: If you are looking for a version of this tutorial for Flash CS5, then check out Creating a Frame by Frame Animation - Flash CS5 Video Tutorials for Beginners.

In this set of Macromedia Flash tutorial online video training clips, we'll show you the basics of creating a simple frame by frame animation in Macromedia Flash 8. In these tutorials, you'll learn how to insert blank keyframes, draw using the brush tool, and you'll also learn how to use the helpful Flash 8 onion skin feature, which is a very useful tool when doing frame by frame animation in Flash 8. We'll also be explaining what the FLA and SWF file formats are.

Part 1: Flash 8 Frame-By-Frame Animation Tutorial - Introduction


Macromedia Flash 8 let's you easily create your own frame-by-frame animation. In this video, we explain how a frame by frame animation works and we show you a simple example of a Flash 8 stickman animation.
[ALTERNATE LINK]

Part 2: Flash 8 Frame-By-Frame Animation Tutorial - Drawing on the Stage


In part 2 of the Flash Frame-By-Frame Animation Tutorial for beginners series, we show you how to draw a simple stickman on the stage of your Flash document.
[ALTERNATE LINK]

Part 3: Flash 8 Frame-By-Frame Animation Tutorial - Adding Keyframes and the Onion Skin Feature


In Part 3 of this Flash 8 video training series, we'll teach you how to add keyframes and how to use the Flash 8 Onion Skin feature - a feature that let's you see a tracing guide based on the objects in previous or next keyframes.
[ALTERNATE LINK]

Part 4: Flash 8 Frame-By-Frame Animation Tutorial - Saving Your Document


Make it a habit to save your work often! It can save you from the frustration of losing all of your hard work.
[ALTERNATE LINK]

Part 5: Flash 8 Frame-By-Frame Animation Tutorial - Previewing Your Animation


In Part 5 of the Flash Frame-By-Frame Animation video tutorial series, we'll show you how to preview your animation. This video also explains what a SWF file is.
[ALTERNATE LINK]

Part 6: Flash 8 Frame-By-Frame Animation Tutorial - Adjusting the Frame Rate


In the final part of the Flash Frame-By-Frame Animation Tutorial series, we'll show you how you can adjust the frame rate of your animation.
[ALTERNATE LINK]

Monday, November 1, 2010

Flash 8 Motion Guide Animation Tutorial Video Series

This tutorial was made for Flash 8. For Flash CS5 users, check out adding a motion guide in Flash CS5.

In this Macromedia Flash 8 tutorial video training series, we'll teach you how to use the Flash 8 Motion Guide. When creating motion tween movements in Flash 8, you're not just limited to horizontal, vertical or straight diagonal directions. The Flash 8 Motion Path or Guide let's you draw a path (such as a curving path for example) that a tweened object can follow as the animation progresses. Watch these online video tutorials to learn how.

Part 1: Working with Motion Guides in Flash 8 - What is a Motion Guide?


In part 1, we talk about what a Flash 8 Motion Guide is and we show you a Flash 8 animation example of the motion guide being used.
[ALTERNATE LINK]

Part 2: Working with Motion Guides in Flash 8 - Creating the Object that will Follow the Guide


In part 2, we'll draw a circle and convert it into a graphic symbol. This will be the object that will move along the motion guide.
[ALTERNATE LINK]

Part 3: Working with Motion Guides in Flash 8 - Creating the Motion Guide

NOTE: If you're working in Flash CS5, right-click on the layer name on the timeline, then choose Add Classic Motion Guide in order to add a classic motion guide to the layer.

In part 3, we'll show you how to create a motion guide layer. On this layer, we will draw a path using the pencil tool. This path that we will draw, will be the path that our tweened object will follow.
[ALTERNATE LINK]

Part 4: Working with Motion Guides in Flash 8 - Making the Object Follow the Path

NOTE: If you're working in Flash CS5, choose Create Classic Tween instead of Create Motion Tween.

In part 4, we'll show you how to make the instance of the circle symbol follow the path.
[ALTERNATE LINK]

Part 5: Working with Motion Guides in Flash 8 - Path Drawing DON'Ts


In part 5, we give you some tips on what to avoid when drawing paths for the motion guide.
[ALTERNATE LINK]

Thursday, October 7, 2010

Keyboard Events Won't Work Unless User Clicks Inside the Flash Movie First (and how to remove the yellow border around objects that are in focus)

If you find that, for some reason, you'll have to click inside your Flash movie first before the keyboard event listeners start working, then try adding a stage.focus statement to your code:
stage.focus = this;

Place this on the main timeline in order to set the focus to your Flash movie. Focus refers to the currently active object in your Flash movie. Whenever you click on something, like a MovieClip or a TextField, it becomes the active object and becomes the object that is in focus. Here, we are setting the focus back to the entire Flash movie without having to click on anywhere inside the movie. This way, the keyboard events that you've created will work right away. I've encountered this problem a couple of times and I was able to solve them by adding this line. However, adding this line might cause a yellow border to appear around the object that is in focus. If that happens, then try adding this line before the stage.focus statement:
stage.stageFocusRect = false;
stage.focus = this;

That yellow border is the stage focus rectangle which serves to highlight the object that is currently in focus. Here, we're setting the stageFocusRect property to false so that the border will not show up.

Friday, September 3, 2010

5 Cool Semi-Realistic Effects in Flash

Flash has definitely come a long way since its initial release in 1996. From simple tweening and drawing effects, Flash now gives designers the capability to create much, much more. Here's a short list of some articles / tutorials / sample files that demonstrate a couple of interesting semi-realistic effects created in Flash.

1. Coffee Steam Effect
This tutorial teaches you how to create a coffee steam effect using curvy lines and tweens. I have to say, this tutorial is quite long and very tedious to follow. But the author does provide a download link to the source file with the finished effect at the end of the tutorial.
[http://www.flashvault.net/tutorial.asp?ID=201]

2. Underwater Effect
This underwater effect has a very nice and subtle feel to it. It makes use of a combination of masks, gradients, AS3 and the perlinNoise() method. The effect was placed over an illustration, but you can try modifying the technique to make it suitable for a photo-realistic underwater image as well.
[http://www.andrewnprice.com/content/how-create-semi-realistic-underwater-enviroment-flash-using-perlin-noise-as3]

3. Water Ripple Effect
This is another water type effect that produces a nice, subtle water surface ripple. However, it's written in AS2. But nonetheless, it's one of the nicest effects of this type that I've seen. It uses the perlinNoise() method as well. No step-by-step guide on this one, but the source files are available for download.
[http://www.freeactionscript.com/2009/03/realistic-water-wave-effect/]


4. Lightning Effect
For this one, the author uses AS3 to create these really cool lightning / thunderbolt / electric discharge effects. The code is a little complex, and the author doesn't really explain it much, but still, the effects are pretty awesome.
[http://blog.oaxoa.com/2009/07/27/actionscript-3-as3-lightning-thunderbolt-electric-discharge-class/]

5. Waterfall Effect
This one uses a particle system to create a stunning waterfall effect. The author created a custom AS3 Waterfall class, which allows you to change the appearance and style of the waterfall by changing a few parameters. You can even set the waterfall's background to transparent and then place it over an image. This effect is quite beautiful.
[http://www.flashandmath.com/flashcs4/waterfall/index.html]

Thursday, September 2, 2010

Retreiving the Index Value of an Item in an Array in Flash AS3

In AS3, you can retrieve the index value of an item in an array by using the indexOf() method of the Array class. Let's take a look at an example:
var aPets:Array = new Array("dog", "cat" , "hamster", "turtle");
This creates an array named aPets, which is populated with 4 values: "dog", "cat" , "hamster", "turtle". Just by looking at the order in which the values were passed to the array constructor, we know that "dog" has an index of 0, "cat" has an index of 1, and so on... If we wish to retrieve an item's index value within our code, then we can use the indexOf() method of the Array class. For example:
trace(aPets.indexOf("hamster"));
To use the indexOf() method, you pass to it the array item whose index value you would like to retrieve. Flash will then go inside the array and look for that item and retrieve its index value. In the example above, "hamster" is the 3rd item in the array, so the trace statement will output a value of 2.

If an item is not found in the array, a value of -1 is returned. For example:
trace(aPets.indexOf("skunk"));
We did not put a "skunk" item inside the array so Flash won't be able to find said item. Therefore, a value of -1 will be returned.

But what if we had two identical items in the array. Let's say our aPets array had 2 "cat" items instead:
var aPets:Array = new Array("dog", "cat" , "hamster", "turtle", "cat");
Looking at the order in which the values were passed, we see that the first "cat" has an index of 1, and the next "cat" has an index of 4. If we use aPets.indexOf("cats") , Flash will return a value of 1, because that is the index value of the first "cat" that it will find in the array. What happens is that Flash will start looking from the index of 0, and then once it finds the item, it returns the index value and stops looking, regardless of whether or not there might be another identical item within the array.

So what if we wanted to skip the first "cat" and try to retrieve the index value of the other one that has a higher index?
Well, then we can tell Flash to start counting at a higher index value than that of the first "cat" (instead of starting at 0, which is the default). To do that, we simply pass a second parameter to the indexOf() method. That second parameter is called the fromIndex parameter of the indexOf() method. It tells Flash at which index number it should begin searching for the specified item. For example:
trace(aPets.indexOf("cat", 2));
Here, we've passed a value of 2 to the fromIndex parameter. This means that when Flash begins searching through the array, it will start from the index of 2, skipping the items with a lower index value. And since the first "cat" has an index value that is lower than 2, then it won't be included in the search. The "cat" that will be found, then, will be the other one that has the index value of 4.

Sunday, August 22, 2010

Preloading External SWF File Generates Error #1009: Cannot access a property or method of a null object reference

Exercise Files:
Stage_Issue_Preloader.fla
Stage_Issue_Load_This.fla

When you're preloading a SWF file that has code that makes any reference to the stage, you might encounter this error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

Let's take a look at the sample files and see if we'll get that same error. Make sure that you've downloaded them and placed them in the same folder. We have 2 files:
  1. Stage_Issue_Preloader - this Flash movie will be used to preload the other file
  2. Stage_Issue_Load_This - this Flash movie will be the one that's preloaded into the preloader movie
Both files already have code in them.

Let's open the Stage_Issue_Load_This.fla file first. Go ahead and test the movie so that Flash will generate a SWF file inside the same folder that contains our Flash documents. What happens in this movie is when you hit the enter key on your keyboard, the smiley face in the center of the stage will rotate. Try it out, but make sure that you disable keyboard shortcuts by going to Control > Disable Keyboard Shortcuts. What the movie does is not really important. What's important here is that if you take a look at the code in frame 1 of the Actions layer, you will see a reference to the stage at the beginning of the code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);
So just take note of this line. Although it does not seem to be causing any errors now, it will once we try to preload it into the preloader file. So let's try that.

Open the Stage_Issue_Preloader.fla file. Check the code on frame 1 of the Actions layer and you will see that we already have our basic preloader code that will preload the Stage_Issue_Load_This.swf file. Now test the movie and you should see that same error message I mentioned at the beginning of this article:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

This error mentions a null object. When you say null object, it means that the object has no value and, in a way, is kind of like a non-existent object. And the null object being referred to here is actually the stage.

But how can the stage be null? Isn't there already a stage when the preloader file is launched?
Yes. But the problem is that stage can only be accessed from a display object that's already in the display list. Our stage reference (the line that says stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);) is inside the Stage_Issue_Load_This.swf file. That's the file that's being preloaded, and it won't get added to the display list until it has loaded completely. So essentially, this means that for a certain amount of time while it's being loaded, it actually won't have a stage. So that's why stage is being seen as null. You see, when you're loading an external SWF file in Flash, it can actually start reading the code inside that SWF file even though it hasn't completely loaded yet. So in this circumstance, what happens is that the external SWF file hasn't been completely loaded yet, but Flash is already trying to execute the code inside it. So it's trying to execute the stage.addEventListener... line, but as we've learned, the external SWF file does not have a stage yet. But once it's been loaded completely and has been added to the display list, then the stage reference inside the Stage_Issue_Load_This.swf file will no longer be null.

So how do we fix this?
We'll take a look at 3 ways in which we can fix this issue. Basically, what we want to do is to make sure that stage is not null when the stage.addEventListener... line gets executed.


Method #1
For the first method, we will be adding some code to the Stage_Issue_Load_This.fla file (that's the file that's going to be preloaded). So make sure that file is open, then select frame 1 of the Actions layer and then go to the Actions panel. What we'll do is we will add an event handler that will tell us when the Flash movie has been added to the stage. The event for that is Event.ADDED_TO_STAGE. This event gets dispatched by the display object whenever it's been added to the stage. So when our Flash movie gets added to the stage, only then will we let Flash execute the stage.addEventListener... line. So we'll create an Event.ADDED_TO_STAGE event handler, and then place the stage.addEventListener... line inside the event listener function associated with that event handler.
this.addEventListener(Event.ADDED_TO_STAGE, checkStage);

function checkStage(e:Event):void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);
this.removeEventListener(Event.ADDED_TO_STAGE, checkStage); //Don't forget to remove the ADDED_TO_STAGE event listener after the stage.addEventListener... line has been added already
}
So here, we have an event listener function named checkStage that get's called when the Flash movie has been added to the stage. Once it's called, only then will the stage.addEventListener... line be executed. And since the Flash movie has already been added to the stage, then we won't get the previous error anymore.

*Make sure that you test this movie first in order to generate the SWF file with the updated code before you test it with the preloader movie.

The problem with this method, though, is that the movie won't work properly if you run it by itself (meaning when you don't load it using the preloader file). When you run the Flash movie by itself, then the Event.ADDED_TO_STAGE event never gets dispatched. So the stage.addEventListener... line never gets executed. The Event.ADDED_TO_STAGE event doesn't get dispatched because when you run the Flash movie by itself, it never adds itself to its own stage. It has to be loaded by another Flash movie and then be added to that Flash movie's stage, in order for the Event.ADDED_TO_STAGE event to be dispatched. So let's go ahead and take a look at other methods as well.


Method #2
For this second method, we will be adding some code to the Stage_Issue_Load_This.fla file as well (that's the file that's going to be preloaded). So make sure that file is open, then select frame 1 of the Actions layer and then go to the Actions panel. What we'll do is we will add some sort of checker that will check whether stage is not equal to null (if stage is not equal to null, then this means that our external SWF file already has a stage). If the stage is still null, then don't execute the code. But if the stage is no longer null, then Flash can go ahead and execute the stage.addEventListener... line. So let's take that stage.addEventListener... line and put it in an if statement that checks if stage is not equal to null.
if(stage != null) {
stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);
}

But this is not quite complete yet. This if statement will only run once. We want it to keep running so that it's going to keep on checking until stage is no longer equal to null. And one way of making this if statement execute numerous times would be to put it in an ENTER_FRAME event handler.
this.addEventListener(Event.ENTER_FRAME, checkStage);

function checkStage(e:Event):void
{

if(stage != null)
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);
}

}
So here, I've created an ENTER_FRAME event handler that calls the listener function named checkStage. And inside the checkStage listener function is the if statement that checks if stage is not equal to null. And since this is an ENTER_FRAME event handler, this function is going to run numerous times. Therefore, the if statement inside it will keep checking if stage is no longer null. So we've ensured that only then will the stage.addEventListener... line be executed, thus avoiding the error.

And also, let's not forget to remove the ENTER_FRAME event listener once stage is no longer null, since by that time, we no longer need to check for that condition. If we don't remove the listener then it will keep on running and needlessly take up computing resources.
this.addEventListener(Event.ENTER_FRAME, checkStage);

function checkStage(e:Event):void
{

if(stage != null)
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, rotateSmileys);
this.removeEventListener(Event.ENTER_FRAME, checkStage);
}

}
*Make sure that you test this movie first in order to generate the SWF file with the updated code before you test it with the preloader movie.


Method #3
In this third method, the code will be added to the Stage_Issue_Preloader.fla file instead. This fix is much shorter. You'll only need to transfer an already existing line to the top part of the code. But before we add the code, let's take a quick look at how a loader object works:
When an external SWF file is loaded by a loader object, the SWF file gets loaded as a child of the loader object. This is another way of saying that the external SWF file actually goes inside the loader. Once loading is complete, we can then add the loader to the stage. And since the loaded SWF file is inside the loader, then the SWF file gets added to the stage along with it. Just keep that in mind as the fix in this method has something to do with that.

So now, let's go ahead and edit the code. Make sure that the Stage_Issue_Preloader.fla file is open, then select frame 1 of the Actions layer and then go to the Actions panel. Scroll down until you see the function named loaded.
function loaded(e:Event):void
{
removeChild(percent_txt);
removeChild(progressBar_mc);
addChild(myLoader);
}
This function named loaded is the listener function for the Event.COMPLETE event handler in the code. This function will get called only when the loader object has finished loading the external SWF file. It is in this function where we add the loader object named myLoader to the stage. So this means that the loader object only gets added to the stage at the end of the loading process. But we can actually add the loader earlier. We can add it to the display list immediately after we create it, and before we even start the loading process. Instead of having the addChild(myLoader); statement inside the event listener function, let's just place it after we instantiate the loader object.
var myLoader:Loader = new Loader();
var myURL:URLRequest = new URLRequest("Stage_Issue_Load_This.swf");

addChild(myLoader);
This way, the loader gets added to the stage immediately. It will be empty at first, but it will already be on the stage. And that's OK. You can place empty loader objects on the stage. It does not have to have content in order for it to be placed on the stage.

So why do we need to add the
loader before we start the loading process? Well, because if the loader is already on the stage, it means that the externally loaded SWF file gets added to the stage right away as well (since we know that the SWF actually goes inside the loader). And since it's added to the stage right away, this means that stage will not be null.

If in the first and second methods, we made it so that the Flash movie will wait for stage to NOT be null before it executes the stage.addEventListener... statement, here, we've made it so that the external SWF file has a stage right away when it starts getting loaded into the Flash movie.

You can choose any of the methods, and hopefully, it will fix this issue for you.