Basic Animation

To start off, lets quickly review what Chapter 1 covered.

  • Animation is made with frames , with each frame slightly different to present the illusion of motion.

  • Frame-by-frame or tweened animation contains an image or description of an image for each frame.

  • Dynamic animation contains an initial description of an image and rules that are applied to alter the description on each frame.

Most of the rest of this book will focus on the rules for dynamic animation, providing a catalog of techniques to change the image description, resulting in realistic motion. In this chapter, youll see how to structure the initial description, how to apply those rules on each frame, and how to put the whole thing together. Youll be creating some working examples as you go, and most of these will be based on the same basic file.

A note on versions

The examples in this book were written in ActionScript 2. Most of them will also work in ActionScript 1 with a few minor adjustments. Probably the major one will be data typing. In ActionScript 1, you cannot specify which type of data a variable is supposed to hold. Starting with ActionScript 2, you can add a colon and a data type after declaring a variable with the key word var , like so:

 var name:String = "Keith"; 

In ActionScript 1, this causes an error. So, if for some reason you are still using ActionScript 1, you can just drop the data type, like this:

 var name = "Keith"; 

Of course, if you want to use classes, or any of the new expressiveness features (filters, blend modes, and so on) introduced in Flash 8, youll need to upgrade to ActionScript 2, since these features are not supported in ActionScript 1.

Setup

To get started, create the basic file youll be working with in this chapter. Fire up your copy of Flash and follow these steps:

  1. Create a new document and save it as chapter2base.fla .

  2. Use the oval tool to make a circle 50 pixels across.

  3. Select the circle and press F8 to convert it to a movie clip. Give it the name ball and make sure the registration point is set to be in the center, as shown in Figure 2-1.

    image from book
    Figure 2-1: Converting to a movie clip

  4. Click OK, and you should have an instance of the new ball movie clip on stage and selected.

  5. Use the Property inspector to name this instance ball , as shown in Figure 2-2.

    image from book
    Figure 2-2: Naming the instance

  6. In the timeline, click the Insert Layer icon, or choose Insert image from book Timeline image from book Layer from the menu.

  7. Double-click the new layers name and change it to code or actions , or whatever name you prefer to use to signify that this layer is for ActionScript only. (Ill refer to this as the code layer .)

  8. With frame 1 of the code layer selected, open the Actions panel by pressing F9 or by choosing Window image from book Development Panels image from book Actions from the menu.

You are now ready to write code. Keep this file open, as youll be jumping right into it after a quick background discussion of what youll be doing.

Looping

Almost all coded animation contains some kind of loop. If you think about a frame-by-frame animation, you might come up with a flowchart that would be something like a series of bitmaps, where each frame is already an image and just needs to be shown, as shown in Figure 2-3.

image from book
Figure 2-3: Frame-by-frame animation

When you get into shapes or symbols in Flash though, things are a bit different. Flash doesnt create and store a new bitmap image for each frame, even in a frame-by-frame movie. For each frame, Flash stores the position, size , color , and so on of each object on the stage. So, if you had a ball moving across the screen, each frame would store the position of the ball on that frame. Maybe frame 1 would say the ball is 10 pixels from the left side, frame 2 would say its 15 pixels, and so on. The Flash player reads in this data, sets up the stage according to the description given, and displays that frame. From that, you get a bit of an expanded flowchart, as shown in Figure 2-4.

image from book
Figure 2-4: Rendering frames, then displaying

But when you consider how I described a dynamic, coded animation, the flowchart looks more like Figure 2-5.

image from book
Figure 2-5: Scripted animation

As you see in Figure 2-5, there is no concept of frame 1, frame 2, and so on. ActionScripted animation generally can, and usually does, occur all in just one frame. And here you can start to see what I mean by a loop.

First, you set up an initial state. You can do this by dragging movie clips onto the stage, just as if you were creating a tweened animation. Or you can describe the entire scene in code alone. Either way, you then render and display the frame.

Next , you apply your rules. The rules can be as simple as, The ball will move 5 pixels to the right, or they can be made up of dozens of lines of complex trigonometry. The examples in the book will cover most of that spectrum.

Applying the rules will result in a new statea new description that is then rendered and displayed. Then you apply the same rules all over again.

Note that it is the same set of rules being applied over and over. You dont have one set of rules for the first frame, and then another set for the next, and so on. So, your challenge is to come up with a set of rules that will handle every possible situation that can arise in your scene. What happens when your ball moves so far to the right that its off the stage? Your set of rules needs to account for this. Do you want to allow the user to interact with the ball with his mouse? Your rules will need to take that into account as well.

It sounds daunting, but its really not that complex. Basically, you start off with some very simple behavior by creating a rule or two, and when that works, add another rule.

These rules, as I keep calling them, are actually ActionScript statements. Each rule can be a single statement or composed of several or even many statements. In the example of moving the ball 5 pixels to the right, the rule would look something like this:

 ball._x = ball._x + 5; 

Youre just saying take whatever the balls x position (horizontal axis) is, add 5 to it, and make that its new x position. You can even simplify that by saying this:

 ball._x += 5; 

The += operator just says add the value on the right to the value of the variable on the right, and assign the result back to that variable.

Heres a more advanced set of rules that youll see later in the book:

 var dx:Number = ball._x - _xmouse; var dy:Number = ball._y - _ymouse; var angle:Number = Math.atan2(dy, dx); var targetX:Number = _xmouse + Math.cos(angle) * springLength; var targetY:Number = _ymouse + Math.sin(angle) * springLength; vx += (targetX - ball._x) * spring; vy += (targetY - ball._y) * spring; vx *= friction; vy *= friction; ball._x += vx; ball._y += vy; clear(); lineStyle(1, 0, 100); moveTo(ball._x, ball._y); lineTo(_xmouse, _ymouse); 

Dont worry about what it all means just yet. Just know that Flash is going to need to run this code over and over to generate each new frame.

So, how do you get these loops to run? Ill show you my first attempt to do this, which reflects the error that many beginning ActionScripters make. Its based on the loop structures that exist in almost every programming language, such as for and while . You set up a loop with one of those structures, which will cause the code within it to execute repeatedly. Heres what I did:

 for(i = 0; i < 500; i++){     ball._x = i; } 

It seems pretty simple. The variable i starts out as 0, so the ball movie clip is placed at zero on the x axisthe far left of the stage. The i++ causes the value of i to be increased by one each time through the loop, from 0 to 1 to 2, 3, 4, and so on, and each time, that value is assigned to ball._x , moving it across the stage left to right. When it hits the value of 500, the statement i < 500 will be false, and the loop will end.

Go ahead and put that code into the Actions panel of the chapter2base.fla file. Run it and see what happens.

Youll find that the ball doesnt move across the stage; it simply appears on the right side. Why didnt it move to all the points in between? Well, actually it did! You just didnt see it, because you never let Flash update the screen. Figure 2-6 is another flowchart that shows essentially what happened .

image from book
Figure 2-6: Why you cant animate with a for loop

You actually applied the rules and moved the ball into position, creating a new scene 500 times. But it didnt get displayed until after the loop was done. This is because Flash updates the screen only at the end of a frame. This is a very important point.

Here is the sequence of actions Flash takes on each frame:

  1. Position all objects that are currently on the stage, in any level, layer, loaded movie clip, and so on.

  2. Execute all ActionScript that needs to be called on that frame, on any layer or level on any movie clip or button, or nested within any movie clip, no matter how deep.

  3. Check if it is time to display the frame yet. If you set your frame rate to 20 frames per second, Flash will check if at least 50 milliseconds have gone by since the last time it displayed a frame. If so, it will display the frame it just rendered, and move to the next frame. If not, it will wait until the right amount of time has passed.

You should note a couple of things about this timing factor. First, frame rates are notoriously inaccurate. Never rely on them for strict timing. Second, it is possible that the amount of rendering and ActionScript execution will take longer than the allotted time for a frame. You dont have to worry about your script getting chopped off, though. Flash will finish executing the script (step 2) before it moves onto step 3, even if it slows down the frame rate. Flash will actually wait up to 15 seconds for your script to finish on any particular frame. It will then display the infamous, A script is causing the player to run slowly. . . message.

So, in the preceding example, Flash waited for the for loop to finish before going to the next frame, and it updated the screen only just before it went to the next frame. Thats why you saw the jump rather than the movement.

So, what you need to do is break up the loop across frames, so that you get back to the sequence of events shown in Figure 2-5.

Frame loops

Starting again with chapter2base.fla , lets get the animation to work.

  1. Delete any existing code you previously placed in the Actions panel for frame 1 of the code layer, and replace it with the following:

     ball._x++; 

The ++ means add one to the value of the variable. If you test the movie now, nothing much happens. Actually, what does happen is that Flash adds one to the x position of the ball, and then displays the result. When you have a movie consisting of only one frame, Flash executes the code on that frame, renders and displays the result, and thats pretty much the end of that. What you need to do is to run that one line over and over. One of the simplest ways to do that is to add another frame to the timeline.

  1. Select the layer with the ball graphic in it and press F5 or choose Insert image from book Timeline image from book Frame from the menu. This adds another frame identical to the existing frame 1. Your timeline should look like Figure 2-7.

    image from book
    Figure 2-7: Timeline for a frame loop

Now, Flash executes and displays frame 1, and then moves to frame 2. There is no new code to execute there, and nothing has changed on stage, so it just displays the same thing again. The magic is that, by default, Flash will loop back to frame 1 of a timeline after it has hit the final frame. When it does that, it sees the code youve placed thereas if for the first timeexecutes it, and displays the result. Then it moves on to frame 2 and back again to 1, over and over, ad infinitum.

Now, the ball slowly crawls across the stage. Nothing earth shattering, but if you are brand new to this, congratulations, youve just created your first ActionScripted animation!

Lets take this a step further and create an initialization frame. This is just a place to set things up. Here, you put any code that you want to run only a single time, rather than loop.

  1. Delete any existing code from the Actions panel and add two new frames to both layers by pressing F5 twice on each one.

  2. Click frame 2 of the code layer and press F6 , or choose Modify image from book Timeline image from book Convert to Keyframes from the menu, to change that frame to a new keyframe. Then do the same thing on frame 3 to make that a keyframe as well. The result is shown in Figure 2-8.

    image from book
    Figure 2-8: Frame loop with initialization frame

  3. Place the following code on frame 1 on the code layer:

     ball._x = 100; ball._y = 100; 
  4. Place this code on frame 2:

     ball._x += 5; 
  5. Place this code on frame 3:

     gotoAndPlay(2); 

Now, frame 1 is the initialization frame. As soon as the movie starts, it executes what it finds there and displays the results. So, no matter where you place the ball on the stage to begin with, your initialization code will make sure it starts at location 100, 100. Then it moves on to frame 2, which is your main action code. This moves the ball 5 pixels to the right. Finally, frame 3, rather than just allowing a default loop back to frame 1, sends the movie back to frame 2, to reexecute the action code.

This is the exact setup used extensively in Flash 5 and earlier, and it is still perfectly workable , if a bit outdated . Even though you will very shortly discover much more flexible and powerful setups, it is very educational to be able to see the different phases of the movie: initialization, action, and looping, as these concepts will continue to be implemented in each animation setup you will investigate hereafter.

Clip events

Hang in there, because were taking one more trip down memory lane. Clip events were the main alternative to frame loops back in the old Flash 5 days. Although now heavily frowned upon, they deserve a quick look, if only to compare their architecture to what you just did and where youll soon be going.

Clip events refer to code that is placed, not on the timeline, but directly on a movie clip itself. This is done by selecting a movie clip that is on stage and then opening the Actions panel. Youll notice that the Actions panel has a few different modes, depending on what is selected. Up to now, you have been putting code on frames, by selecting a frame before writing code. You might have noticed that the title bar of the Actions panel shows Actions Frame in that case. When a movie clip is selected, it should show Actions Movie Clip. Figure 2-9 shows both of these modes. The Actions panel may also tell you that you have a button selected.

image from book
Figure 2-9: The Actions panel shows where the code is going

Personally, I find the indication of what is selected and where the code is going to be far too subtle, and one of the mistakes I still make constantly is to write a bunch of code in the Actions panel, only to have my program fail to compile because I had some movie clip selected rather than the timeline. So keep an eye out for that one.

When you select a movie clip and then put some code in the Actions panel, that code is assigned directly to that clip. We usually say that the code is on the clip. Any and all code that appears on a clip must be within a clip event block. This looks something like this:

 onClipEvent(  eventName  ){    // code goes here } 

In addition to onClipEvent( eventName ) , there is on( eventName ) . The on events have to do with mouse and keyboard actions, such as press and release .

The event name refers to one of the many events that may occur in a Flash movie. An event is simply that: something happening in the movie. Events fall into two main categories: system events and user events. A system event is when something happens within the computer, Flash, or your movie, such as data loading, content loading, or a new frame starting. User events refer to something the user has done, and generally have to do with keyboard or mouse activity.

The two main events youll be looking at here are load and enterFrame . The load event occurs when the movie clip instance first occurs on stage. In other words, the movie clip has loaded into the player and is ready to be displayed. The important thing is that the load event occurs only once for any particular instance. Thus, you can use it for your initialization code. You simply place your code between the two curly brackets:

 onClipEvent(load){    // initialization code } 

The enterFrame event occurs each time Flash is ready to start rendering the next frame. The important thing to remember about this event is that, unlike the frame loop setup you just made, the enterFrame event still continues to fire on a regular basis, even on a single-frame movie. If your frame rate is set to 20 frames per second, enterFrame will fire approximately every 50 milliseconds. And, unlike the initial for loop experiment, Flash will refresh the display after each enterFrame . This makes it a perfect place to put your rules, or action code, as you have your two requirements: repeating code and a redisplay after each execution. You can set it up like so:

 onClipEvent(enterFrame){     // action code } 

Thus, if you start with a new base movie (single frame with a ball movie clip instance on stage), without altering the timeline or putting any code on it, you can just put the following code on the ball instance:

 onClipEvent(load){   this._x = 100;   this._y = 100; } onClipEvent(enterFrame){    this._x += 5; } 

Note the use of the keyword this . Since the code is on the movie clip, any code refers directly to the movie clip itself and the timeline internal to that clip. If you said ball._x += 5 , it would look inside itself for an object named ball , and not finding one, nothing would happen. It would not look on the main timeline for an object of that name. This has to do with the subject of scope , which refers to where some piece of code is and affects what it has access to from that location. Youll run into the issue of scope many times throughout the book. Here, you can use the keyword this to refer to the current objectthe ball movie clip. You could also just leave it off altogether and say _x += 5 , as this would be implicitly added by the compiler. Either way, the result is exactly the same effect you had before of the ball moving across the stage to the right.

Earlier, I mentioned that clip events were frowned upon with the release of Flash MX. Probably the biggest reason for this has to do with code centralization . Suppose someone else made the movie you just completed, and you need to make some changes to it. You open it and see a ball sitting on stage. You can see instantly by looking at the timeline that there is no code on the timeline, by the absence of the little a symbol on any of the frames, and the movie is only one frame long, so there is no tweening going on. Yet, when you test the movie, the ball moves across the stage.

To find the clip-event code, you need to do a little poking around: click the ball to select it, and then open the Actions panel. This is not such a bad scenario for this small example. But take a complex movie with dozens of buttons and movie clips on stage, and movie clips within movie clips (within movie clips within movie clips, and so on), maybe all with their own clip events, and try to find that one line of code that is causing that one effect you want to change. I swear nothing makes you want to kill your fellow Flash developer more than that situation.

Modern best practices dictate that all code within a movie be on the main timeline, preferably on frame 1 of a layer set aside for just code. Alternatively, the code can be in external ActionScript files that are included in the file. In this case, you create your ActionScript in any text or code editor and save it as a text file in the same directory as your FLA file. You can name it something like game_code.as . Then in the FLA file, on the timeline, you can type this:

 #include "game_code.as" 

Note the leading # and lack of semicolon at the end of the line. When Flash encounters this line, it will read in the text file and interpret it, just as if you had typed all that code right on the timeline itself. This basically achieves the same goal, which is to have all of the code for the movie centralized in one location, rather than forcing some later developer (possibly yourself) to go on a hunting expedition to find it all.

ActionScript 2 class files are a different way of organizing code. They usually wind up being multiple files rather than a single file for all the code in a movie. These class files are a highly structured way of organizing large amounts of complex code. Ill talk about classes in the Classes and OOP section later in this chapter.

One other issue with frame loops and clip events is that the code is not very flexible. Once you write some code on a frame or on a movie clip, theres no way to change it at runtime. Say you had a game with a spaceship that just kind of wandered around the screen until it saw an enemy, and then went into attack mode. The code for wandering would probably be very different from the code for attacking. But theres no direct way to say, On each frame, execute this code. OK, now youre in attack mode, now on each frame, execute this other code. There are indirect ways of doing this, but they can get a bit more complex than would be ideal.

So, how do you get all of your code into a single frame, and still have a loop that allows for updating the display after each loop, and make it flexible? Up through Flash 5, you couldnt do this. But then comes Flash MX to the rescue. . .

Flash MX events and event handlers

Flash MX introduced many important changes in ActionScriptchanges and improvements that were largely responsible for catapulting Flash into the serious Rich Internet Application forefront. One of the biggest changes was the new event architecture that made programming very complex behaviors far easier than was possible in earlier versions.

Ive already talked a little about events. These are things that occur when something happens in the system or the user does something with the keyboard or mouse. Prior to Flash MX, the only real way to capture these events was with an onClipEvent( eventName ) or on( eventName ) block on a movie clip or button. This meant that you had to place a movie clip on stage at author time and write the code on it. There was no way, for example, to attach a movie clip to the stage at runtime and assign some enterFrame behavior to it. Naturally, developers came up with various workarounds, but they usually resulted in very complex structures with code hidden throughout the movie and library.

With Flash MX and MX 2004, events are accessible from anywhere and can be handled by assigning a function to the event. Each time that event occurs, the function assigned to it will be executed. At any time while the movie is running, you can remove the handler function or change it to a new one. You can do this for any movie clip or button anywhere in the movie, right from the main timeline.

To understand events, you should understand a couple of additional concepts: listeners and handlers . Listeners and handlers are actually well-named entities, because thats exactly what they do. A listener is an object that listens for events. A handler is a function that handles the event when it occurs.

Listeners

A listener takes the form of an object or a movie clip or a button. An object here means an ActionScript object created by saying something like myObj = new Object() . That would be a generic object. Actually, in ActionScript, pretty much everything is an object. Even a movie clip is an object with some specialized features.

Certain types of objects can listen for only certain types of events. For example, a movie clip can listen for an enterFrame event because it has frames. A button or generic object does not have frames, so it would not make sense for it to listen for an enterFrame event. A generic object does not have any graphics that could be pressed with the mouse, so it cannot listen for a press event, as a button or movie clip can.

Some types of objects are automatically listeners for some types of events. For instance, a movie clip is always a listener for the enterFrame or press event. In other cases, you need to tell an object to listen for a certain event. In other words, you make it a listener for that event. Generally, you do this by calling the addListener method of the object that generates that event. OK, thats probably as clear as mud, so lets see an example. Say you wanted a generic object to listen for mouseDown events. First, you make the object:

 var myObj:Object = new Object(); 

A quick note on basic syntax: The keyword var here just tells Flash you are now defining a variable. The variables name is myObj . The colon and Object is the ActionScript 2 syntax for telling Flash what type of data this variable will hold. Its going to hold a generic object. Then you use the new operator to create the new instance. Again, if you are still using ActionScript 1, this syntax will cause an error, as ActionScript 1 does not support data typing. Simply lose the colon and object type:

 var myObj = new Object(); 

The Mouse object is responsible for generating any and all mouse events. So, you can use the Mouse.addListener method to make myObj a listener for any events having to do with the mouse:

 Mouse.addListener(myObj); 

Now myObj will listen for mouse events. Perhaps a more accurate way of describing it is that the listener is notified of events. Note that, in this case, you are adding a listener to the Mouse object. Internally, Mouse keeps a list of all objects that want to be informed of mouse events. This would include all buttons and movie clips, by default, and any other objects that have registered with it by using its addListener method. Whenever a mouse event occurs, Mouse runs through this list and lets each object on it know what event has occurred.

Yet another way of describing it is to say that the object that becomes a listener is subscribing to the event or set of events. And the object that generates the event is broadcasting the event to all its subscribers.

Additionally, if you no longer want an object to listen to events, you can tell it to stop listening, or unsubscribe , by calling the removeListener method:

 Mouse.removeListener(myObj); 

This tells Mouse to remove the object from its internal list of listeners so it will not receive further notifications.

Handlers

When a listener receives notification that an event has occurred, it probably wants to act on that information. It does that by executing a function specially named to correspond to that particular event. The function name usually starts with on , followed by the name of the event, such as onEnterFrame , onMouseMove , onLoad , and so on. This function is known as that objects event handler for that event. You simply give the listener object a function with that special name, in the following format: object.onEventName = function . You can create a function right there, or assign the name of a function that already exists. Here are a couple of examples, continuing from the earlier mouse listener code:

 var myObj:Object = new Object(); Mouse.addListener(myObj); myObj.onMouseDown = function(){    trace("mouse down"); } myObj.onMouseUp = mouseUpHandler; function mouseUpHandler(){    trace("mouse up"); } 

Go ahead and type the preceding code into a new movie and test it (using the same procedure as you did for this chapters first example, in the Setup section). Youll see that, as expected, Flash traces a message each time the mouse is pressed or released. If you are just a beginner in ActionScript, and understand and can apply this code, congratulations! You have just moved up to intermediate status.

The first handler example creates an anonymous function right then and there, assigning it to myObj s onMouseDown handler. The second example assigns its onMouseUp handler the variable mouseUpHandler . This happens to be the name of a function created right below the assignment. Now, that might look a little backwards to you, because the function isnt created until after it is assigned. It works though, because when Flash enters a frame with code in it, it first looks for any defined functions and parses them, and then executes the rest of the code on the frame. Thus, even if the function is defined at the very bottom of the code listing for a particular frame, it will be available to the very first line of code in that frame. However, that works only when you define your function this way:

 function myFunc(){    // do something } 

Another way to define a function is as follows :

 myFunc = function(){    // do something } 

Only functions defined the first way will be immediately parsed by Flash. If you create your functions using the second syntax, they must be defined prior to the point where they are called in the code.

OK, now that you know a little bit more about handlers, you can get a better understanding of listeners. Earlier, I said that an object that generates events broadcasts that event, or notifies its listeners of the event. How does it do that exactly? Well, all it really does is call the function on that object that has the correct handler name. For example, say a movie has two buttons, and in addition, you have added an object named myObj as a mouse listener. Mouse now contains a list of listeners something like this:

 button1 button2 myObj 

When the user presses the mouse button, Mouse says, Whoa! Mouse down! Must notify listeners! (or something like that). It then goes through its list and calls the onMouseDown function of each listener, like so:

 button1.onMouseDown(); button2.onMouseDown(); myObj.onMouseDown(); 

This example creates a function and assigns it to myObj.onMouseDown . As you can see, this function is now called, and the trace occurs. What if you had not created a function for onMouseDown ? Mouse would still attempt to call the function, but Flash would see myObj.onMouseDown as undefined and not do anything. In some languages, to assign an object as a listener, that object must conform to a certain interface. In other words, it would need to actually have a function assigned to onMouseDown , even if that function did nothing. ActionScript 2, however, is far more lenient. It allows just about anything to be a listener and deals with any missing handlers at runtime.

Those are the basics of events and handlers through the ages. Ill be introducing many other events as we move along. For now, lets get back to animation.

Events for animation

So where does all this talk about events bring us? We were looking for a way to apply code to animate an object and allow for a screen refresh after each iteration. Earlier, you saw an example of using the enterFrame clip event for animation. Lets come up to present time with this technique.

In Flash MX or MX 2004, you simply add an onEnterFrame handler to the movie clip, like so:

 ball.onEnterFrame = function() {     this._x += 5; } 

One point that is sometimes confusing to people is that you are getting an enterFrame event, even though the movie has only one frame. The playhead is not actually entering a new frame; its just stuck on frame 1. Just realize that it isnt the act of the playhead moving to a new frame that generates the enterFrame event, but more the other way aroundthe event tells Flash when to move the playhead. Think of it more as a timer, albeit a pretty inaccurate one. Flash takes the frame rate set for the movie and determines how often it should enter a new frame. It then fires the event repeatedly at that interval. If there is another frame to go to, it goes there. But regardless, you can count on the event firing.

The earlier examples had initialization code, either on an initialization frame or in an onClipEvent(load) block. You can simply put any initialization code outside the onEnterFrame function. Since your movie is only one frame, that code will run only once.

Open your master copy of chapter2base.fla , or create a new FLA file per the instructions at the beginning of the chapter, and put the following code on frame 1:

 ball._x = 100; ball._y = 100; function onEnterFrame():Void {     ball._x += 5; } 

Its a beautiful thing, isnt it? All the code right there for anyone to see, understand, and change when the time comes. And most important, it works like a charm . The ball moves across the stage just as expected. You can tidy it up a bit more though.

One principle of Flash best practices is that there shouldnt be any stray code on the timeline. The timeline should have only functions and a single call to one of those functions to start everything moving. You can move the first couple of lines of code into a function called init , and the sole action on the timeline will be a call to that function:

 init(); function init(){     ball._x = 100;     ball._y = 100; } function onEnterFrame():Void {     ball._x += 5; } 

This code couldnt be easier to understand. Everything is contained in two functions whose names describe exactly what they do. Compare this setup to a series of frames with lists of statements and gotoAndPlay calls, or code hidden on various movie clips on the stage or within other movie clips, or code hidden away on clips in the library.

Note that not every example in this book will be quite so organized. In cases where I am showing a quick example of a principle, Ill just provide the bare minimum of code necessary to demonstrate that principle. In a full application though, structure and organization are key.

Well, that covers most of the basics on how to structure animation with ActionScript. Ive explained how to get rules to run over and over, and how to update the screen after each application of those rules, causing the illusion of motion. But what do you move? So far, you have been moving around a movie clip. But are movie clips the only option, or just the best one?



Foundation ActionScript. Animation. Making Things Move
Foundation Actionscript 3.0 Animation: Making Things Move!
ISBN: 1590597915
EAN: 2147483647
Year: 2005
Pages: 137
Authors: Keith Peters

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net