Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 15

14.Change the following line value from 2 to 100:

xpos += 100;

15.Test your movie now and check the stage. You should see a copy of your movie clip being blurred by a set of overlapping rectangles.

How It Works

In this example the bitmap was obtained using the draw method. The bitmap could have been created using methods provided by the geom objects and the drawing API, but the movie clip copy provided an interesting way to see how robust the Bitmap object can be.

Applying the filter was accomplished easily using the applyFilter method. The bitmap sourced itself, meaning that the source bitmap parameter in the applyFilter method referred to the same bitmap as the bitmap that had the method applied to it. This allowed the applyFilter method to modify the pixels directly. Once the source bitmap was determined, the rectangle of the blur area was defined. You can see that this rectangle is the visibly blurred rectangle in the final resulting SWF. The Point object parameter also placed the blurred rectangle over the image in a specific place. The point chosen was identical to the start index of the rectangle object. You can specify a different point to begin drawing the blur. Notice that the original rectangle source is used, while the point object has the capability to offset the result. Finally the filter was defined as myBlur easily and is the exact same object that could have been used on a movieclip,filters array property.

By making small and easy changes to this code you can begin to see how easy it is to create interesting and varied results with filters and the Bitmap object.

Summar y

This chapter explained the bitmapData object and the many methods provided. The bitmapData object presents a powerful way for you to manipulate the stage at runtime. With precise control over each pixel on the stage, within each movie clip and potentially in any graphic being displayed, you can create and manipulate the stage in ways never before realized in Flash.

When used in conjunction with movie clips, you can utilize the object to amazingly improve performance over vector graphics. When combined with video and animation, the Bitmap object enables you to achieve not only effects, but the capability to fire events and to act upon pixel changes in real time within your application.

The bitmapData object should excite any designer with its fresh access to pixel-level manipulation.

Exercises

1.Using the getPixel method in a for loop, try to find the existence of a particular color in a bitmap by checking each pixel. Place a movie clip at the x and y position of the result.

2.Using perlinNoise within a bitmap, use getPixel to randomly place movie clips on the stage.

368

16

Using ActionScript for Animation

Macromedia Flash can be used for all sorts of design and development activities; however, its roots lie with animation. Right from when the product was called FutureSplash, the focus was on cultivating a product that would provide developers with ways to easily create animated content. Although Flash is now much more than an animation tool, it still does that very well.

Unfortunately, Macromedia Flash has been marred as well by years of “Skip Intro” content. Many sites have been created where the focus was on the animation, not on the message. Many people have gotten very tired of this and have dismissed Flash overall as a nuisance plug-in. Fortunately, the tool has matured, and best practices have come out to guide developers in creating content that can be both cool and usable.

Developers have also realized that Flash can be used for more than just site intro animations. For instance, the plug-in makes an ideal distribution mechanism for online learning applications where animation provides clarity to the concepts being taught. Animations can also be used sparingly within web applications to provide feedback to users. Many sophisticated games are developed using Flash, and aspiring artists use Flash animation as a tool for self-expression.

All-in-all, Flash animation is still alive and well and has evolved into a mature means toward both productivity and self-expression. This chapter introduces the concepts and techniques needed to make the most out of scripted Flash animation.

Scripted Versus Non-Scripted Animation

Two primary ways exist to animate content in Flash: using the authoring tool’s timeline and through ActionScript code.

The traditional approach in Flash has always been to use the authoring tool. This provides the most creative control and best matches more traditional non–computer-based animation techniques. It lends itself very well to movie-type animations where the purpose is to tell a story. In these situations, the animations can be very complex, and scripting the movements a much more onerous job than visually manipulating the animation as you go.

Chapter 16

Scripted animation is necessary when the user interacts with the animation, or where the animation can be different each time, such as for games or for interactive art pieces. Script is also handy for animating repeating elements, such as rain or snow falling. This is something that is difficult to do by hand in a way that looks realistic.

Creating Animations Using Keyframes

If you have not previously worked with Flash, first review how a clip can be animated on the timeline. This process involves creating movie clips and defining their position, size, and shape at points throughout the animation. First, start with some definitions:

A frame is an opportunity for the player to change something on the screen. In the same way that a television updates its image 60 times every second, the Flash player updates the content a certain number of times per second.

The fps (frames per second) value represents the rate at which frames are displayed. The default value set in a new Flash document is 12 fps, which represents 12 opportunities to change the content for every second that goes by. The fps value is set to the base timeline and applies throughout the movie, including to movies loaded on-the-fly.

The playhead is an internal marker that keeps track of which frame to display. By manipulating the playhead, you manipulate which frame is shown.

A keyframe is a marker frame that you set to hold specific content with a specific size, shape, and position. The frames between pairs of keyframes calculate what the content should look like and where the content should be using keyframes as start and end points.

A tween is an animated transition from one keyframe to another.

The timeline is the container holding the frames, the keyframes, and the playhead.

Animating content in the timeline involves the following steps:

1.Place content on the screen in an existing keyframe or a new keyframe that you create. There is always at least one keyframe available to use.

2.Create a second keyframe later on the timeline that contains the same content.

3.Manipulate the content in the second keyframe.

4.Tell Flash to create a tween between the two keyframes.

In this first Try It Out exercise, you create an animation using the authoring tool.

Try It Out

Using the Authoring Tool for Animation

This exercise illustrates the process of animating a simple shape on the screen using the Flash authoring tool. It provides you with a conceptual base for using ActionScript for animation a little later. In Figure 16-1, onion skins show the progression of the animation.

370

Using ActionScript for Animation

Figure 16-1

1.Create a new Macromedia Flash document.

2.Use the Oval tool in the Tools panel to draw a circle on the left side of the stage. Use any color for fill and line that you want.

3.Double-click the shape to select both the fill and the line. Select Modify Convert to Symbol, name the clip circleClip, and make sure the Movie Clip radio button is selected. Click OK.

4.Click frame 12 of the timeline. Select Insert Timeline Keyframe.

5.With the red playhead marker over the new keyframe on frame 12, drag the circle to the right of the screen.

6.Open the Transform panel (Window Transform). Change the vertical scale percentage (the second text field) to 50%. Change the rotation to 90 degrees.

7.Click the timeline between the two keyframes. Select Insert Timeline Create Motion Tween.

8.Select File Save As, name the file tryItOut_firstAnimation.fla, choose an appropriate directory, and save it. Select Control Test Movie.

9.Close the SWF file and click the onion skin icon just below the timeline area, just to the right of the layer trash icon. Extend the onion skin bracket on the top of the timeline to include the whole animation.

How It Works

When you create a tweened animation, Flash calculates most of the frames for you. You set a starting and an ending keyframe for the animation, and Flash calculates how to get from the starting point to the ending point. By showing the animation in onionskin mode, you can see each frame as it is to be drawn out to the screen. If you were to further change the content at either of the keyframes, the onionskin feature would update all the intermediate frames automatically to show the transition between both keyframes.

371

Chapter 16

Creating Animations Using ActionScript

Start to look now at how to animate a movie clip with script. Code techniques give you these same kinds of tweening techniques, but first look at how to do this at a low level so that you can develop a foundation for how the more automated techniques work.

The first problem that you come across is that by creating a tween in the timeline, Flash automatically moves the movie clip for each frame. You need a way to move the content yourself, and to do that, you need a way of calling code on a regular basis. You can do this in two ways: with the onEnterFrame() technique and with the setInterval() technique.

Moving a Movie Clip Using onEnterFrame()

Every time the playhead moves for each movie clip, that movie clip generates an event indicating it is about to draw the next frame. This is a very convenient way of calling code repeatedly. The following code snippet shows the technique used to capture that event:

containerClip.onEnterFrame = function()

{

this.animatedClip._x += 10;

}

In this example, a container movie clip called containerClip captures the onEnterFrame event. Every time onEnterFrame fires, by default 12 times per second, the code in the event handler is called. It moves a movie clip called animatedClip to the right by 10 pixels. Unfortunately, there is nothing to stop this animation, so it just keeps on going even after the movie clip is off the screen. The technique can be revised to provide a condition for stopping the animation:

containerClip.onEnterFrame = function()

{

this.animatedClip._x += 10;

if (this.animatedClip._x >= 250)

{

delete this.onEnterFrame;

}

}

After the movie clip passes an x position of 250 pixels, the event handler deletes itself, stopping the animation.

One strategy for animation is to have one onEnterFrame event handler attached to every movie clip that needs to move. Another is to have a single onEnterFrame event handler attached to a parent movie clip that handles the animation for all nested movie clips. Generally the latter is better because multiple onEnterFrame event handlers running at once can quickly bog down the CPU.

Take a look at an example of this technique at work.

372

Using ActionScript for Animation

Try It Out

Moving a Movie Clip Using onEnterFrame()

This example shows how content can be moved using the onEnterFrame event.

1.Create a new Macromedia Flash document.

2.Open the Library panel and choose New Symbol from the menu at the top right of the panel.

3.In the New Symbol dialog box, set the name to circleClip. Make sure the Movie Clip radio button is selected. Click the Export for ActionScript checkbox to select it. If you do not see the checkbox, click the Advanced button on the bottom right of the panel to reveal additional options. Click OK.

4.Use the Oval tool to draw a circle within the new movie clip. Use any color for fill and line that you want.

5.Click the Scene 1 button above the timeline to return to the main timeline.

6.The code for this example is very small, so enter it in the Actions panel instead of creating a separate ActionScript file. Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:

this.createEmptyMovieClip(“holderClip”, this.getNextHighestDepth()); holderClip.attachMovie(“circleClip”, “circleClip”, ;

holderClip.getNextHighestDepth()); holderClip.circleClip._x = 10; holderClip.circleClip._y = 10; holderClip.onEnterFrame = function()

{

this.circleClip._x += 10;

if (this.circleClip._x > 250)

{

delete this.onEnterFrame;

}

}

7.Select File Save As, name the file tryItOut_onEnterFrame.fla, choose an appropriate directory, and save it. Select Control Test Movie.

How It Works

First, a movie clip holder is created:

this.createEmptyMovieClip(“holderClip”, this.getNextHighestDepth());

It is generally a good idea to have a movie clip that acts as an overall container for animation because there may be multiple things being animated at once.

A symbol from the library is attached to the timeline for this movie clip:

holderClip.attachMovie(“circleClip”, “circleClip”, ; holderClip.getNextHighestDepth());

373

Chapter 16

The attached clip is given a starting x and y position:

holderClip.circleClip._x = 10; holderClip.circleClip._y = 10;

The onEnterFrame event is trapped for the container movie clip:

holderClip.onEnterFrame = function()

{

// ...

}

Every time onEnterFrame() fires, the attached movie clip moves right by 10 pixels:

this.circleClip._x += 10;

The keyword this refers to the parent object, the holderClip movie clip, and so gives easy access to the movie clip nested inside.

The termination condition checks every time the event fires to see whether the animation should be stopped. When that happens because the movie clip’s x coordinate is greater than or equal to 250 pixels, the onEnterFrame event handler function is deleted. In essence, the function deletes itself:

if (this.circleClip._x > 250)

{

delete this.onEnterFrame;

}

Now take a look at another way to move content.

Moving a Movie Clip Using setInterval()

There is another way to animate content that is not based on frames. Instead, it uses the setInterval() function. The function is called repeatedly in intervals that are measured in milliseconds. Here’s the basic syntax for setInterval():

setInterval(animationFunction, 83); function animationFunction()

{

animatedClip._x += 10;

}

This code also moves a movie clip to the right by 10 pixels for each call of the function. The repeat interval here is set to 83 milliseconds, which is roughly equal to 12 fps (1000 ms /12 frames = 83 ms per frame).

The animation also won’t stop moving the movie clip. A stopping condition is needed. To stop the animation, capture the ID that the setInterval() function returns when it is called, and then later pass that ID to the clearInterval() function to stop the calls to animationFunction():

374

Using ActionScript for Animation

var intervalID:Number = setInterval(animationFunction, 83); function animationFunction()

{

animatedClip._x += 10;

if (animatedClip._x >= 250)

{

clearInterval(intervalID);

}

}

Ready to try the setInterval() animation technique for yourself?

Try It Out

Moving a Movie Clip Using setInterval()

This example demonstrates how content can be moved using the setInterval() function.

1.Open the completed tryItOut_onEnterFrame.fla file from the previous Try It Out exercise, or open tryItOut_onEnterFrame.fla from the book’s source files at <source file directory>/ Chapter 16/.

2.Select File Save As, rename the file tryItOut_setInterval.fla, and save it to a folder of your choosing.

3.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:

this.createEmptyMovieClip(“holderClip”, this.getNextHighestDepth()); holderClip.attachMovie(“circleClip”, “circleClip”, ;

holderClip.getNextHighestDepth()); holderClip.circleClip._x = 10; holderClip.circleClip._y = 10;

var intervalID = setInterval(animateCircle, 83); function animateCircle()

{

holderClip.circleClip._x += 10;

if (holderClip.circleClip._x > 250)

{

clearInterval(intervalID);

}

}

4.Select File Save. Select Control Test Movie.

How It Works

As in the previous exercise, a movie clip holder is created, a symbol from the library is attached to the timeline for the movie clip, and the attached clip is given a starting x and y position:

this.createEmptyMovieClip(“holderClip”, this.getNextHighestDepth()); holderClip.attachMovie(“circleClip”, “circleClip”, ;

holderClip.getNextHighestDepth()); holderClip.circleClip._x = 10; holderClip.circleClip._y = 10;

375

Chapter 16

The interval is then started. It calls the animateCircle() function every 83 milliseconds, which corresponds roughly to 12 fps (1000 milliseconds / 83 milliseconds per frame = 12 fps):

var intervalID = setInterval(animateCircle, 83);

Every time setInterval() calls animateCircle(), the attached movie clip moves right by 10 pixels:

holderClip.circleClip._x += 10;

The termination condition checks every time the function is called to see whether the animation should be stopped. When that happens because the movie clip’s x coordinate is greater than or equal to 250 pixels, the setInterval() call is stopped by passing the interval’s ID to clearInterval():

if (holderClip.circleClip._x > 250)

{

clearInterval(intervalID);

}

Next, take a look at some of the implications behind these two techniques.

Frame-Based Versus Time-Based Animation

The two techniques that can be used to move content both work well, but each has performance and timing implications.

The Effect of Movie Frame Rate on Animation

The onEnterFrame() technique is tied to the frame rate of the application. You have used the default 12 fps in the examples so far, which is quite slow. If you were to raise the frame rate of the movie to 24 fps to try to make the animation smoother, the animation would take half the time to play out. This is generally not the intended result and can be a major headache if you decide to change the frame rate midway through or at the end of the development process. Figure 16-2 shows how increasing the frame rate speeds up the animation.

Distance Traveled In One Second

4 fps

8 fps

Figure 16-2

376

Using ActionScript for Animation

The setInterval() technique runs independently of the movie’s frame rate, however there is still a relationship. If you change the position of a movie clip multiple times while one frame is being displayed, you will only see the result of the last movement. For instance, consider the following loop:

for (var i:Number = 0; i < 12; i++)

{

holderClip.circleClip._x += 10;

}

The for loop runs almost instantly, so you will see only one big movement instead of 12 small ones. Even if you set the setInterval() delay to just one millisecond, the stage is updated only 12 times per second for a 12 fps movie so only 12 of those movements will be visible.

Two ways exist to make a setInterval()-based animation smoother. First, you can raise the frame rate of the movie. This makes the animation smoother by giving a greater number of rendering windows during the course of the animation. The length of time needed to get the animation from one side of the screen to the other does not change with the frame rate because the number of times setInterval() calls the animate function does not change with the frame rate (see Figure 16-3).

The number of display opportunities vs. the number of setInterval() calls

4 fps

8 fps

setInterval() 25 ms (40 fps)

Figure 16-3

The other way to make screen updates smoother with setInterval()-based animation is by adding a call to updateAfterEvent(). This global function, when invoked from within a function being called by setInterval(), tells the player to render the stage again. The stage will be redrawn, even though it has not yet advanced to the next frame-rendering opportunity. This global function makes setInterval() completely independent of the movie’s frame rate.

Take a look at trying these techniques out firsthand.

377