NOTE:: This site’s design is only visible in a graphical browser that supports web standards, but its content should be accessible to most browsers or Internet devices.

Flash 5 code — where?

 

Dear Reader;

The content of this tutorial is out of date. Flash (and the underlying ActionScript language) has moved on. I have, regrettably, not moved on with it.

Flash is currently a great deal more capable, but also much more complex, than it was when I wrote this tutorial.

I have kept this content online because I still get mail from readers who have found it useful. While I am very pleased by this, I want to make it clear that this material can no longer be considered “best practice,” and I can no longer offer support.

If you can use it, you are welcome to it. The code has been tested and refined thanks to input of many generous readers. I offer it as is.

This article is not so much about how to write Flash ActionScript code but rather where to write the code. It is geared primarily for developers who have a coding background in environments other than Flash, but I hope it will also be of some use to those new to both Flash and scripting.

Flash 5 permits, even encourages a scattered dispersal of ActionScript code. This can be terribly disorienting and confusing for both coding neophytes and those with extensive experience coding JavaScript and compiled languages. Once you have become immersed in the object oriented paradigm of Flash 5 ActionScript, the freedom to attach bits of code to discrete objects actually makes a lot of sense. And then, once you reach the point where it makes complete sense to tack the code onto the object the code pertains to, you discover there are strategies to consider in order to make your code more accessible to team members or even yourself! A helter skelter approach, while functional, can be catastrophic in a group development environment, and difficult even for the original author to decipher after some time has elapsed. Many of us have learned much of what we know by studying downloaded .fla files, and most who have learned this way have experienced the frustration of trying to locate where in the movie the relevant code is buried! This article will attempt to clarify for the newcomer to Flash where the code can reside. It will also offer some strategic suggestions for those already comfortable with the essentials of writing ActionScript.

Possible locations for ActionScript code

There are four "places" where ActionScript code might be found:

1) Frames in a time line

At the core of Flash's functionality is the time line. A Flash movie unfolds over time at a set speed defined by the frame rate. A movie's frame rate is established either by accepting the default 12 fps or by modifying it to a faster or slower rate. This establishes the movie's foundation. Any frame in any layer of any time line (either the main movie's time line, or a movie clip in the library) can contain ActionScript code. However as we will see, just because they can doesn't mean they should.

frame action screen captureA frame needs to be a keyframe, and the keyframe needs to be selected before it will accept code. Click once on a frame to target it, and remember to press the F6 function key if it is not already defined as a keyframe. Note that the frame highlights and the header of the ActionScript editor window reads "Frame Actions". Also note that once a frame contains any code at all, a small script "a" appears to indicate the presence of code data.

What can go in a Frame Action?

Just about anything that is okay to occur in a linear fashion can go in a frame's ActionScript code. The emphasis here is linear. With the exception of looping structures, once the play head has moved on, the past is history! As we will soon see, button and movie clip actions offer unique capabilities for non-linear, event based scripts, but the root time line, "Scene 1", is an ideal place to establish functions and variables that the movie will need later on. It is also an ideal place to collect script that is not necessarily event driven in nature. This means the root time line should be used as much as possible to declare and define variables and functions - basic groundwork and initialization.

Nearly every ActionScript authority I have read advises reserving the top layer of Scene 1's time line for code. Name this layer "logic", or "code" or something descriptive and use it exclusively for this purpose. If you adhere to this advice, it won't take long for you, and any of your collaborators, to appreciate how much easier it is to find code. Placing the function definitions on the main time line allows you to consolidate much of your code; for instance, buttons can now call a function rather than contain the function itself. This won't necessarily make the movie play any better, but it sure will make it easier to debug, and it will make it much easier for a collaborating author to pick up what's going on. Consider this discipline to be a good, professional work habit.

Of course having said that, I hasten to remind you that every movie clip in your library has its own unique time line. This makes each movie clip an independent "bubble", encapsulated within the over all movie framework. Add to this the fact that instances of any clip on stage can have attached events and you see how very quickly a movie can become an impenetrable mess. Use all the tools available to you, but keep in mind that the fewer places you have code "stashed", the easier your project will be to work with.

2) Instances of Button Symbols

Button symbols are special event driven structures with the single purpose of detecting mouse and keyboard events. Their time line is restricted to 4 frames (although they can have as many layers as you need), which accommodate up to three "states" plus the over-all hit target. Code is not placed in the symbol definition but rather on an instance of the button symbol when placed on the stage. This permits efficient recycling of button symbols with specific tasks, because the instructions reside in the unique instance rather than the symbol itself.

object actions screen captureAfter creating a button symbol and dragging an instance of the symbol onto the stage, click once on the instance with the arrow selector tool and notice that the header of the ActionScript editor changes to "Object Actions". Any code will now become part of this specific button. Button code begins by invoking the built-in "on();" function which Flash reserves for buttons. There are 8 possible arguments for this function, listed below. They are mostly self descriptive, and thoroughly covered in the documentation so I won't discuss them individually.

Syntax

As is common form for functions, it begins by invoking the function ("on" in this case), passing it the required argument or arguments as listed above, and then defining what happens. These instructions are contained inside curly braces. In the very simple example above, we have told the button instance to pay attention to when the mouse button has been released, and then to advance the movie to a frame labeled "resume". Button code can get very much more complex, but this is the basis for how it works.

Note that there are time when it makes sense to pass more than one argument to the function. The above example will only fire when the mouse is released while still within the bounds of the button target area. This allows the user to change their mind - if they move the curser off the button before releasing, the event doesn't fire. However there are times when you might not want the event to be so narrowly defined. A good example would be scroll arrows - you want the scrolling to stop when they release the mouse button regardless of whether they are still over the button or not. In that case it is fine to pass two arguments to the function:

on(release, releaseOutside){
   perform an action;
}

As a final reminder to what has been stated before: where ever possible and practical try to have your functions pooled in the top layer of the root time line so that your buttons contain as little unique code as possible. Again, although this might not make the movie play any better it's good, efficient coding policy.

3) Instances of Movie Clip Symbols

There are a great many similarities between Movie Clip actions and Button actions. As implied by its name, Movie Clip Events are also event driven actions. This classification of ActionScript code is similar to our discussion of buttons above in that it is attached directly to an instance of a Movie Clip symbol, not part of the symbol definition itself. As with buttons, this means that different instances of the same symbol can behave in a unique fashion.

An instance of a movie clip symbol is dragged from the library onto the stage. Select the instance using the arrow selector and note that the ActionScript editor window again switches to "Object Actions". Sharing yet more similarity with buttons, there is a built-in function reserved for Movie Clip actions, "onClipEvent()". This time there are nine possible arguments for the function, again thoroughly discussed in the documentation:

Syntax

This should start to look familiar. The onClipEvent function is invoked, the argument is passed to say which event you have in mind, the code is placed inside curly braces. Here's a very brief example, a simple initialization routine that captures the starting coordinates of the clip:

onClipEvent(load){
    var startX = _x;
    var startY = _y;
}

Movie Clip Events are extremely powerful and useful. A thorough coverage of ClipEvents is not in the scope of this article although I will look superficially at a couple of them. For additional reference, Benjamin Mace has an excellent tutorial on ClipEvents at the We're Here site. I warmly recommend getting comfortable with the unique capabilities of ClipEvents. Let's look briefly at three I find useful.

load

This executes once, when the clip is first instantiated. As such it is a very useful place to declare variables and initialize their values such as I did in the simplistic example above.

enterFrame

Code in an enterFrame ClipEvent executes continuously once per frame for as long as the clip exists on the stage. Read that again, because this is potent stuff! It's like a built-in loop. The clip will sit there performing the same task over and over again. One consequence of this behavior is that it allows a movie clip to continuously monitor the value of, and changes to, a variable. Combined with a boolean conditional check, this can enable some powerful interactive actions. Scrolling text is one example of how this could be applied: a button might cause the value of a variable we will call "active" to change from false to true. A clip's enterFrame action could be sitting there watching, and when the variable changes the clip would increment a text field's "scroll" property by 1, once per frame. See this in action in my tutorial on scrolling text fields.

Here's another common application. In the simple example above we established the variable "startX". Let's say a button sets the value of another variable: "newX". The clip's enterFrame action could be monitoring and comparing the value of the two variables once per frame with a boolean conditional, and as soon as an inequality is detected something happens (in this case the clip would move to a new location):

onClipEvent(enterFrame){
    if(startX != newX){
    _x = newX;
    }
}

There are lots of examples of "easing" which could be added to this to make the movement fluid, but you get the idea.

data

This will delay the execution of any action(s) defined inside the curly braces until some data from a loadVariables or loadMovie action has completely loaded. You can imagine how useful this is if the success of an action depends on data being available.

Button / Movie Clip Hybrids

This isn't really a complete category in itself, but the button/movie partnership is useful enough to warrant individual attention I think. To see an example of this exotic species in action, I refer you again to the scrolling text tutorial. In summary, the up and down scroll arrows are instances of a movie clip which in turn contains an instance of a button. The button does what buttons do best: it responds to a mouse event and sets a variable's status. Let's say the variable in this example will be named "active", and the button's job will be to detect when the user is depressing their mouse button over the arrow symbol:

on(press){
    active == true;
    }
    
on(release, releaseOutside){
    active == false;
    }

(note: in the above example, "true" and "false" could be shortened to "1" and "0")

Because this is included in the construction of the symbol in the library, every instance of this symbol will exhibit the same behavior. In order to use a plain button for scrolling purposes, we would require two buttons - one for scrolling up and one for scrolling down. But since we have placed this button inside a movie clip, we can place two instances of the same movie clip on stage and modify their behavior with ClipEvents. Much more efficient use of resources.

After you have created this hybrid movie clip, two instances of it can be placed on stage. Since the mechanism for determining the mouse action is built in, all you need to do is define what action to take. This is where the unique capability of a ClipEvent can be called on. The "enterFrame" action is ideal for this as we have seen. Here's a possible scripting approach for one of the buttons, assuming the variable name you have defined for the text field is "myText":

> onClipEvent(enterFrame){ if(active == true){ myText.scroll += 1; } }

note: in the above example, the conditional test could be shortened to simply

if(active){...}

The movie clip sits there, continuously evaluating the boolean value of the variable "active". When the embedded button sets the value of the variable to "true", the clip increments the text field's scroll property by 1 once per frame. It shouldn't be hard to figure out what to change to make the other scroll arrow work.

Buttons embedded in movie clips - Quite a powerful pairing, wouldn't you say?

4) External .as Script Files

Finally we arrive at the forth and final topic. It is possible to maintain at least some of your code in an external file and include it in the movie at runtime, just as an external JavaScript file can be included in a conventional HTML document. The ActionScript file can be a plain text document, and it is recommended that the file end with a suffix of ".as".

For a small Flash movie this may be an unnecessarily complex exercise. But as your project gets increasingly complex there are distinct advantages. First, it means you can tinker with the code without having to recompile the .swf file each time. This can be a significant time saver with a large movie. It also makes collaborations and certain types of updating easier.

Syntax

Placed in a time line frame, the call to an external file would be:
#include "externalScript.as";
Of course, if the external script lives in a directory other than that in which the movie lives the path needs to be correctly stated.

If the call to the external file comes from an onClipEvent, the syntax might be as follows:

onClipEvent(load){
    #include "externalScript.as"
}

Conclusion

I hope this article has helped remove some of the mysteries surrounding where ActionScript can reside, and what you might base some of your decisions on. Button and Movie Clip objects possess unique characteristics and opportunities you can take advantage of. There are strategies which can greatly facilitate making your movies accessible to yourself and others with only a small amount of preplanning. Flash can indeed be a confusing environment at first, even for experienced code developers. Knowing how to write the code is only part of the battle for advanced developers; knowing where to place the code effectively and thoughtfully can go a long way to easing frustration and wasted time in the creation fo Flash projects.

originally written for the GurusNetwork.com, 2002

divider ornament

--top--