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

Beginning ActionScript 2.0 2006

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

Chapter 6

How It Works

This example acquainted you with importing images, preparing them for the stage, and keeping them organized.

The header image was imported, placed on the stage, and then placed in its own movie clip. There was no particular need to place it in a clip now, but part of setting up a project is to plan for possible changes. By placing the bitmap image in a movie clip rather than just placing it directly on the stage, it allows the possibility for it to be animated in the future.

You looked at the properties panel for the bitmap image and for the image once placed within a movie clip. Two of the differences in properties were the instance name text field and the color drop-down. The instance name text field enables an instance name to be given to the clip so that ActionScript can be used to manipulate the clip. The color drop-down allows color and transparency effects to be applied. If you are working with the Macromedia Flash 8 development environment, you will also see a blend drop-down menu that enables you to set how the movie clip blends with the content behind the clip. (You find more about blending modes in later in the book.)

The featured photo bitmap was placed within a movie clip, which was then placed within a button. A button movie clip allows graphics for up, over, and down button states to be included in the button. You applied a simple color effect to the down state, which was possible because the image was wrapped in its own movie clip. In addition, whenever a new featured photo is to be shown, the bitmap needs only to be swapped within the one movie clip and all button states will get the new image.

Nesting Sections within a Movie Clip

In the preceding Try It Out, the home screen had all of its content directly on the main timeline. This is generally not a good idea because it makes managing the site increasingly difficult as more screens are needed and more layers are added to the main timeline. To simplify management of each screen, group related content together in one movie clip. A single container movie clip can be more easily manipulated than a spread-out group of movie clips can. Here are several reasons why using a container movie clip is a good thing:

Moving a screen involves moving just a single movie clip.

Manipulating an entire screen programmatically involves manipulating a single movie clip using ActionScript.

The base timeline contains fewer layers, and becomes easier to work with.

Try It Out

Using a Movie Clip as a Base

In this exercise, you take a group of content on the main timeline and place it in its own movie clip.

1.Open the completed portfolio.fla file from the preceding Try It Out, or open portfolio.fla from the book’s source files at <source file directory>/Chapter 6/portfolio v2/.

148

Setting Up Flash Projects

2.Make sure that you are looking at the main stage and are not in edit mode for any movie clips. (You can return to the main stage by clicking the Scene 1 button just above the timeline.)

3.Open the Home layer set. Select the keyframes for all the layers within the Home layer set by dragging across them. You can also click the keyframe for the first layer, and then hold down the Shift key and click the keyframe for the last layer.

4.Select Edit Timeline Cut Frames.

5.Open the library (Window Library). Select New Symbol from the tools menu on the top right of the library panel. Give the new symbol the name screen_home, and make sure that the Movie Clip radio button is selected. Click the Yes button.

6.Drag the screen_home movie clip from the library to the screens/home folder.

7.Click the only empty keyframe on the timeline. Select Edit Timeline Paste Frames.

8.With all of the content still selected, open the properties panel (Window Properties) and set the x position to 25 and the y position to 50.

9.Return to the main stage. Click the Home layer set to select it, and then click the delete icon just below the timeline. Click OK.

10.Create a new layer, and drag it between the Header layer set and the Script layer. Name the new layer Home Screen.

11.Click the empty keyframe on the Home Screen layer, and then drag the screen_home movie clip from the library to the stage. Use the two stage guides to help align the movie clip in the top-left corner. You should end up with an arrow right underneath the Home button in the main menu.

12.Save the file.

How It Works

In previous Try It Out exercises, new movie clips were created using the Convert to Symbol command. You could have done this here as well, but you would have lost the layer setup. The organization that the layers give you is retained when frames are copied from the main timeline and pasted into the new movie clip instead.

Using Keyframes to Manage Application State

One technique to manage application state is to use keyframes as a way to navigate to individual screens. The content for each screen is fit into a frame, with one frame corresponding to one screen. Each frame is assigned a label, and the playhead is moved from one screen to another simply by calling gotoAndStop(“framelabel”). The gotoAndStop() method could just reference the frame number for the screen you want to display, but if another screen is inserted before this one, the wrong screen would show. Using labels ensures that if a screen is moved, the link is not lost. It also is more meaningful to look at a text label in the code rather than a frame number.

Figure 6-4 shows the timeline for a project that uses keyframes to manage screen state.

149

Chapter 6

Figure 6-4

Next, explore how to use keyframes on the main timeline to navigate between screens.

Try It Out

Managing Screen State with Frames

In this exercise you use separate frames to hold different screens.

1.Open the completed portfolio.fla file from the preceding Try It Out, or open portfolio.fla from the book’s source files at <source file directory>/Chapter 6/portfolio v3/.

2.Make sure that you are looking at the main stage and are not in edit mode for any movie clips.

3.Create three new layers and change the names to Labels, Tutorial Screen, and Photography Screen. Place the Labels layer on top, and place the other two underneath the Home Screen layer.

4.Click frame 10 of the Labels layer and select Insert Timeline Keyframe. Do the same on frames 20 and 30.

5.Click the keyframe on frame 1 of the Labels layer. Open the properties panel (Window Properties) and type home into the frame label field. Click frame 10 of the Labels layer and label it tutorials. Click frame 20 of the Labels layer and label it photography.

6.Click the keyframe on frame 1 of the Labels layer. Open the Actions panel (Window Actions) and type stop(); into the panel. Repeat for frames 10 and 20.

7.Click the keyframe on frame 1 of the Scripts layer. Enter the following script into the Actions panel:

//Set up code to respond to main menu buttons

home_btn.onRelease = function()

{

gotoAndStop(“home”);

}

tutorials_btn.onRelease = function()

{

gotoAndStop(“tutorials”);

}

photography_btn.onRelease = function()

{

gotoAndStop(“photography”);

}

150

Setting Up Flash Projects

8.Click frame 10 of the Tutorial Screen layer and select Insert Timeline Keyframe.

9.Open the library, locate the movie clip called tutorials_screen in the folder screens/tutorials, and drag the clip to the stage. Use the guides to help you position the movie clip.

10.Click frame 20 of the Tutorial Screen layer and select Insert Timeline Keyframe.

11.Open the library, locate the movie clip called photography_screen in the folder screens/photography, and drag the clip to the stage. Use the guides to help you position the movie clip.

12.Save the file and test the movie. Clicking the home, tutorials, and photography buttons should switch between screens.

How It Works

To use frames to switch between screens, you first set up a system of labels and keyframes. For each screen to be displayed, you need one keyframe and one keyframe label. The keyframes can be in adjacent frames, or they can be separated by other frames. Using a number of frames between the frames for each screen makes it easier to see the separation and to read the frame labels on the timeline. Additional frames are added to the right of the rightmost keyframe so that the label photography is visible in the timeline.

The code placed within the Actions panel responds to user clicks on the main navigation buttons. The names of each button used in the code (namely home_btn, tutorials_btn, and photography_btn) correspond with instance names given to each of those buttons. Click any of those buttons and look in the properties panel; you will see the same ID in the instance name text field.

Each screen is contained within its own movie clip. As a result, each movie clip holding a screen can be easily assigned to an individual keyframe. Compare this setup with the earlier one in which the home screen was spread across layers in the main timeline and it is readily apparent that containing each screen within a movie clip is considerably cleaner.

Keeping Code in External Files

In general, it is not a good idea to place any significant amount of code directly on the timeline. Some reasons for this include the following:

If the .fla file becomes corrupted and you have to revert to a previous version, any code changes made in between those two versions will also be lost.

Having code scattered throughout different timelines makes the code hard to find.

You can use any text editor to edit code in an external file; you must use the editor in the Macromedia Flash development environment if the code is in a timeline.

The #include directive allows external files to hold ActionScript code. Adding the following line to the timeline does the equivalent of placing all the code from the text file into that same spot in the timeline:

#include “<filename>.as”

151

Chapter 6

Note that there is no semicolon at the end of the line. #include is called a pre-processor statement, in that it is executed before any other code runs. When a project is compiled, the compiler does a pass through all the code looking for pre-processor statements. When an #include statement is found, the compiler replaces the directive with all the code from that external file. The compiler then parses all included code as if it were typed directly in the Actions panel.

As the amount of script gets large, it can help to further break the code out into separate files. Simply create as many script files as are needed, and then place the #include statements one after another in the Actions panel.

It is a common error to keep the .as files used for compilation next to the compiled .swf file when deploying the project to a server. The .swf contains the compiled version of the code from the included script file(s), so it is not necessary to place your script files on the web server with the .swf files. It is not a good practice, either, because others might then find the source code.

Try It Out

Attaching Code to a Project

In this exercise, you remove code embedded in the .fla and place it in an external text file. You also make some changes to improve the style of the code.

1.Open the completed portfolio.fla file from the preceding Try It Out, or open the portfolio

.fla file from the book’s source files at <source file directory>/Chapter 6/portfolio v4/.

2.Make sure that you are looking at the main stage and are not in edit mode for any movie clips.

3.Click the keyframe on the Script layer, open the Actions panel (Window Actions), and copy all the code within the panel.

4.Create a new Macromedia Flash document by selecting File New and choosing ActionScript File from the New Document panel.

5.Name the file portfolio.as and save it in the directory containing the .fla file.

6.Paste the script into the new file and save it.

7.Click the keyframe on the Script layer, return to the Actions panel, and delete all the code.

8.Type the following line of code into the Actions Panel:

#include “portfolio.as”

9.Save the file and select Control Test Movie. Clicking the home, tutorials, and photography buttons should still switch between screens.

10.Add the following function to the end of the portfolio.as file:

function gotoScreen(screenName:String):Void

{

gotoAndStop(screenName);

}

11.Update the three gotoAndStop() calls to use the gotoScreen() function:

152

Setting Up Flash Projects

home_btn.onRelease = function()

{

gotoScreen(“home”);

}

tutorials_btn.onRelease = function()

{

gotoScreen(“tutorials”);

}

photography_btn.onRelease = function()

{

gotoScreen(“photography”);

}

12.Save the file and select Control Test Movie. Clicking the home, tutorials, and photography buttons should still switch between screens.

How It Works

Taking code out from the Actions panel and putting it into a separate text field is a fairly simple matter, but an important step to take for any scripting project. The #include directive is all that is needed.

The small bit of cleanup is related to the issue of code entanglement. Even though the code to switch screens is very simple, it is still not a good practice to put that code in the button handler. Instead, a function is created to perform this task. If the implementation of the screens needs to change, only the switch screen function needs to be updated.

Using Script to Manage Application State

ActionScript enables you to place items on the stage at runtime rather than having to place them in advance. The attachMovie() method allows any movie clip in the library to be attached to the stage. The attachment process copies the symbol in the library. As a result, a single movie clip can be attached to the stage multiple times. Here’s the syntax for the attachMovie() method:

baseMovieClip.attachMovie(id:String, name:String, depth:Number, initObject:Object);

The id parameter corresponds to a linkage ID given to a movie clip within the library. The name parameter is the instance name to be given to the new clip, depth is a Number that must be incremented for each attached movie, and the optional initObject allows startup parameters to be given to the new clip.

Linkage IDs must be unique within the library. To set a linkage ID, select the desired movie clip in the library and open the properties pane by right-clicking the library symbol and selecting Properties. If only the topmost properties in Figure 6-5 are visible, click the Advanced button. Select the Export for ActionScript checkbox, type in a linkage ID in the Identifier field, and click OK. The movie clip can now be attached using attachMovie().

Once a movie clip has been attached to the stage, its visibility can be easily controlled with its _visible property, which shows (true) or hides (false) the clip.

153

Chapter 6

Figure 6-5

The techniques of attaching movie clips dynamically and showing and hiding movie clips on-the-fly give you an alternative to using frames to manage screen state. Entire applications can be built with only a single frame of the main timeline being used. This provides the greatest amount of control over the project, while increasing project complexity by only a nominal amount. Screens are swapped by making movie clips visible or invisible instead of swapping frames.

This method also offers the best opportunity for expansion. Adding another screen is simply a matter of creating that screen, and inserting a reference to it within the code.

Try It Out

Creating a Single Frame Application

In this exercise, you work with an application that is entirely controlled with ActionScript.

1.Open the completed portfolio.fla file from the preceding Try It Out, or open the portfolio

.fla file from the book’s source files at <source file directory>/Chapter 6/portfolio v5/.

2.Make sure that you are looking at the main stage and are not in edit mode for any movie clips.

3.Delete the Labels, Home Screen, Tutorial Screen, and Photography Screen layers.

4.Select all the frames from frame 2 onward. In the Background layer, either click and drag from frame 2 of the Buttons layer to frame 20, or click frame 2 of the Buttons layer and, while holding down the Shift key, click frame 20. Select Edit Timeline Delete Frames.

154

Setting Up Flash Projects

5.Open the library panel (Window Library). Find the symbol called screen_home in the screens/home folder. Right-click the symbol and select Properties. (If you see only one text field, one set of radio buttons, and a few buttons, click the Advanced button.) Click the Export for ActionScript checkbox to select it. Leave the Export in First Frame checkbox selected. Ensure that the contents of the Identifier text field read screen_home.

6.Repeat step 5 for symbols screens/tutorials/screen_tutorial and screens/photography/ screen_photography.

7.Create a new function called init() at the bottom of the file, and give it the code to attach the movie clips to the stage:

function init():Void

{

var screenHolderHandle:MovieClip;

_level0.createEmptyMovieClip(“screenHolder”, ; _level0.getNextHighestDepth());

screenHolderHandle = _level0[“screenHolder”]; screenHolderHandle.attachMovie(“screen_home”, “home”, ;

screenHolderHandle.getNextHighestDepth()); screenHolderHandle.attachMovie(“screen_tutorials”, “tutorials”, ;

screenHolderHandle.getNextHighestDepth()); screenHolderHandle.attachMovie(“screen_photography”, “photography”, ;

screenHolderHandle.getNextHighestDepth());

gotoScreen(“home”);

}

8.Return to the portfolio.as script file, and update the gotoScreen() function so that it looks like the following:

function gotoScreen(screenName:String):Void

{

var screenHolderHandle:MovieClip; screenHolderHandle = _level0[“screenHolder”];

//Hide all screens within the screen holder movie clip for (screen in screenHolderHandle)

{

screenHolderHandle[screen]._visible = false;

}

//Show the selected screen screenHolderHandle[screenName]._visible = true;

}

9.Add the following call to the init() function at the bottom of the file:

init();

10.Save the file, return to portfolio.fla, and select Control Test Movie. Clicking the home, tutorials, and photography buttons should still switch between screens.

155

Chapter 6

How It Works

In steps 5 and 6, linkage IDs are assigned to movie clips for three screens in the library. These IDs allow the library symbols to be linked up with the code to place copies of the library symbols on stage. The init() function then creates a base movie clip to hold all of the screens, and it attaches the three scenes to it:

function init():Void

{

var screenHolderHandle:MovieClip;

_level0.createEmptyMovieClip(“screenHolder”, _level0.getNextHighestDepth()); screenHolderHandle = _level0[“screenHolder”]; screenHolderHandle.attachMovie(“screen_home”, “home”, ;

screenHolderHandle.getNextHighestDepth()); screenHolderHandle.attachMovie(“screen_tutorials”, “tutorials”, ;

screenHolderHandle.getNextHighestDepth()); screenHolderHandle.attachMovie(“screen_photography”, “photography”, ;

screenHolderHandle.getNextHighestDepth());

gotoScreen(“home”);

}

Using a base clip to hold the screens prevents possible naming conflicts with other movie clips on the stage and gives some organization to the project. The three movie clips that are attached to the base movie clip are copies of the library symbol. At the end of the init() function is a call to the gotoScreen() function, which hides all the screens, and then shows just the home screen. The _visible properties for each screen can be directly set as they are attached, but using gotoScreen() gives a single change point if the choice of which start screen to use changes. Adding a feature to remember where the user left off and to resume at the same place when he returns could be more easily accomplished with the gotoScreen() function.

Next, the gotoScreen() function is updated to handle the new method of switching screens:

function gotoScreen(screenName:String):Void

{

var screenHolderHandle:MovieClip; screenHolderHandle = _level0[“screenHolder”];

//Hide all screens within the screen holder movie clip for (screen in screenHolderHandle)

{

screenHolderHandle[screen]._visible = false;

}

//Show the selected screen screenHolderHandle[screenName]._visible = true;

}

The extra step taken to pull the screen switch code into its own function in the preceding Try It Out pays off because now only one function needs to be changed to handle the new means of switching screens. Using the for..in loop, gotoScreen() goes through all the movie clips within the screen holder clip and makes them invisible. The function then makes the clip visible for the screen to be shown.

Finally, the last line of code makes the actual call to the init() function:

init();

156

Setting Up Flash Projects

Summar y

This chapter covered a number of techniques for setting up a Flash project. Some points to remember include the following:

Giving order to the images directory and to the library helps with finding library symbols as the project size grows.

Bitmaps should be placed within their own movie clip.

Individual screens should have a single movie clip holding all screen content.

Code should be kept within an external text file instead of placed directly within the Actions panel.

Screens can be managed both by navigating through frames on the timeline and by using script to attach and show each screen.

In the next chapter, you start learning about components, reusable assets that can be used to build fullfledged applications. Before proceeding to the next chapter, go through the following exercise to help solidify the material that you just learned.

Exercise

Modify the final Try It Out project as follows:

Remove the photo buttons in the photography section movie clip from the stage.

Dynamically attach the photo buttons to the photography section movie clip with ActionScript, and add onRelease event handlers to each button.

Tip: Create an array listing each image ID, namely aStudyInTexture, buntzenWinter, flowerInDetail, and galianoSunset. Loop through that array to attach each image from the library and to assign an onRelease event handler.

Add a function to be called by each button’s onRelease handler that will load the selected image into the movie clip holding the large image. The library contains the three additional images that are needed for this.

Tip: When attaching the button to the stage, also add an ID property to the button and assign it the ID from the array. Use this in the button handler to construct a path for loadMovie().

157