Animation and Effects with Macromedia Flash MX 1002004 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Animation and Effects with Macromedia Flash MX 1002004 [Electronic resources] - نسخه متنی

Jen deHaan

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید




Understanding Events And Interactivity


When creating animations and effects in your FLA files, you might want to make parts of your SWF files interactive. This might be as simple as letting a user click buttons on the Stage to navigate to different parts a website, or perhaps you're building a complex game in which users can move characters around and interact with an environment. It might also be draggable scrollbars or menus. However intricate your SWF files become, it is important that you understand how to capture user events, such as button clicks, mouse movements, and key presses. Interactivity typically improves the user experiencethe reaction visitors have to your sites.

An event, which is an action that occurs while an SWF file is playing back, is triggered by things happening when the SWF file places. Events could be keyboard input, a sound file finishes playing, external files finish loading, or when you click a button. Events alert you when something happens when the SWF file plays, so you can make something else happen as a result. For example, an event occurs when a movie clip or external file loads, a user clicks a button or moves the mouse, or a playhead reaches a frame. Then, you can use event handlers and listeners to help manage those events. So, when a user clicks a button, you can make the playhead go to a new frame; or you can create a progress bar that increases in size as a file loads.

A few common event handlers in the MovieClip class are commonly used for interactive animation: onRollOver, onRollOut, onRelease, and onEnterFrame.

Events are the cornerstone of ActionScript; they allow you to detect when things happen in a SWF file. By understanding events and knowing how to handle them, you're on your way to adding interactive elements to your projects.

Exercise 3: Interacting with other objects


Interactivity involving the mouse is quite common. Simple interactivity is adding clickable elements, but it is a bit more interesting when you add draggable elements to the Stage. This exercise adds ActionScript to your file that allows the user to drag shapes around the Stage and try and fit them into the corresponding holes.


1. Select frame 1 of the actions layer. Open the Actions panel (Window > Development Panels > Actions). Type the following code into the Script pane, following the ActionScript you added in earlier exercises:


circle_mc.onPress = function() {
circle_mc.startDrag();
};
circle_mc.onRelease = function() {
circle_mc.stopDrag();
};

You create two anonymous functions for circle_mc that executes code when you press the mouse button over the instance and release the mouse button. When you press and hold the mouse button, you can start dragging the instance around the Stage. The instance stops dragging when you release the mouse button.


Anonymous and Named Functions


A function consists of statements that you write to perform a certain task in your SWF file. You have already used anonymous functions (also sometimes called inline functions) such as the function in step 1. An anonymous function is a function that does not have a name. And a named function is a function with a name. Both kinds of functions do the same thing as each other; however, because anonymous functions do not have names, you cannot call this kind of function throughout your project. So, an anonymous (nameless) function is


myInstance.onRelease = function(){
//do something...
//trace("clicked");
};

And the equivalent named function that you could call throughout your code using its name is


function myFunction(){
trace("clicked");
};
myInstance.onRelease = myFunction;

Then you could call the function elsewhere in your ActionScript using the previous format or this one:


myFunction();

2. Select Control > Test Movie to test the file. Because of the code you added in step 1, you can click the circle movie clip on the Stage and, while holding the mouse button down, drag the symbol (Figure 6.13). Release the mouse button to stop the movie clip from moving.

Figure 6.13. Drag the circle around the Stage using the mouse. The cursor changes to a hand when it's over the circle.

3. Adding interaction is relatively easy because Flash has the capability to detect collisions between objects. This means that an event occurs when one instance intersects another, so you can cause something to happen after this event. Modify the previous code for circle_mc's onRelease event handler. Add the following boldface code:


circle_mc.onRelease = function() {
circle_mc.stopDrag();
if (circle_mc.hitTest(circleHole_mc)) {
trace("hit");
}
};

Now if you click circle_mc, you stop dragging the instance and see whether circle_mc intersects with a different instance: circleHole_mc. If the two instances intersect, hit displays in the Output panel because of the TRace statement.

4. Select Control > Test Movie to retest the SWF file in the Flash environment. Now the Output panel displays hit when you drag the circle_mc movie clip instance on top of the circleHole_mc instance and release the mouse button, as seen in Figure 6.14.

Figure 6.14. Hit displays in the Output panel when the two instances intersect.

5. Because text that displays in the Output panel isn't very useful after you upload the file to the Internet, you need to remove the trace statement from the previous snippet. Remember, you cannot use TRace statements to return information outside of the test environment. So, now that you have tested the SWF using trace, delete the following line of code:


trace("hit");

Then, replace the line you just deleted with the following two lines of code:


circle_mc._x = circleHole_mc._x;
circle_mc._y = circleHole_mc._y;

These two lines of code set the X and Y coordinates of circle_mc to the X and Y coordinates of the circleHole_mc. This code places the circle_mc instance directly above the circleHole_mc instance, and gives the illusion that the shape is in the hole. You can also set any other properties or even call functions in this part of the code. For example, if you want to modify the shape's transparency, you can set the _alpha property of the instance in this part of the code.

6. Repeat steps 14 for both the square_mc and TRiangle_mc instances. In each of these steps, you need to replace the circle_mc and circleHole_mc instance names in your ActionScript with those of the other shapes.

7. Select Insert > New Symbol, name the symbol reset, select Button as the symbol's behavior, and click OK. Select the Text tool and type reset near the center of the Stage, and any other graphics you might want to add.

Select the Hit frame on the Timeline and press F6. Use the Rectangle tool to draw a square over the text you added, as shown in the following figure.

Figure 6.15. Add a hit area for the button, so users can easily click the text. Without a hit area, users would have to click exactly within the lines of "reset", which would be difficult and frustrating to do.

Click Scene 1 to return to the main Timeline, and then drag an instance of the button you just created from the Library to the Stage. Open the Property inspector, and give it an instance name of reset_btn.

You can select the graphics you create for the button when they're on the Up frame, and convert them into a graphic symbol.

You use this button to reset the position of the shapes to their original position. This lets users restart a game after they successfully place the shapes or run out of time.


Using Conditionals


The ActionScript you just added in step 3 is called a conditional statement. A conditional performs a particular action depending on whether a condition exists. For example, if something is true, do this action. You might have code that says if the value of the variable myNumber is 5, then go and play frame 2.


if (myNumber==5){
gotoAndPlay(2);
}

This statement checks if a condition (myNumber = 5) is true or false. If it's true, the next statement executes (gotoAndPlay). If the condition is false, ActionScript skips to the next statement outside the block of code. Additionally, you could add an else or else if statement.


if (myNumber==5) {
gotoAndPlay("pageone");
} else if (myNumber=10) {
gotoAndPlay("pagetwo");
} else {
gotoAndStop("end");
}

In this code, if the first condition is false, ActionScript skips to the else if statement. If myNumber evaluates to true, then the playhead moves to "pageone". If the condition myNumber=10 evaluates to false, the else statement catches it and sends the playhead to "pagetwo". Therefore, any value of myNumber other than 5 or 10 sends the playhead to "end".

There are other kinds of conditional statements that you can use in your code, which you will encounter later in this book.

8. Select frame 1 of the actions layer, and type the following code into the script pane, following the code you already have there:


reset_btn.onRelease = function() {
triangle_mc._x = triangleInitX;
triangle_mc._y = triangleInitY;
square_mc._x = squareInitX;
square_mc._y = squareInitY;
circle_mc._x = circleInitX;
circle_mc._y = circleInitY;
}

Now you can click the reset_btn button and have each shape return to its original position on the Stage when you test the SWF file. If your code in step 3 modifies the transparency or any other properties, you would also want to reset those properties here. Otherwise, if the user tries the game again, the shapes might be too transparent to see easily.

You use an operator to specify how to compare, modify, or combine values of an expression. An operator performs these operations on elements that are called operands. So in the example in step 9, the logical AND (&&) operator evaluates the expressions on both sides of the operators. Other operators include = (assignment operator that evaluates equality between two expressions) and + (addition operator that concatenates strings or adds numeric values).

9. Using the hitTest() method again as you did in step 3, you can write a function that checks to see if each piece is successfully released over the hole. Add the following code to frame 1 of the actions layer:


function checkShapes() {
if (circle_mc.hitTest(circleHole_mc) &&
square_mc.hitTest(squareHole_mc) &&
triangle_mc.hitTest(triangleHole_mc)) {
trace("success");
}
}

This named function (see sidebar titled "Anonymous and Named Functions") checks to see if each of the three shapes is currently hitting the corresponding "hole" movie clip in line 2. The && operator is called the logical AND operator, and you use it to evaluate both the expressions on each side of the operator to see whether they are true or false.

If each of the expressions is true, the statements within the if statement executes the code that's inside it (within its codeblock). In this case, if each expression in the if statement is TRue, the value success displays in the Output panel.

10. Add the checkShapes() function call to each of the three main shape movie clips on the Stage. Modify the existing code so that it looks like the following:


circle_mc.onRelease = function() {
circle_mc.stopDrag();
if (circle_mc.hitTest(circleHole_mc)) {
circle_mc._x = circleHole_mc._x;
circle_mc._y = circleHole_mc._y;
checkShapes();
}
};

If you need to size the symbol in relation to the shapes or holes on the Stage, click Scene 1 on the Edit Bar, and drag the symbol from the Library to the Stage. Double-click the instance to enter symbol-editing mode again, and you can see the items on the Stage while you edit. When you finish, return to the Stage and delete the instance.

Now when you drag a shape over the proper hole, this ActionScript aligns the shape directly over the hole by making sure that the X and Y coordinates match using the assignment operator (=).Flash then checks to see if each of the three shapes is successfully positioned by calling the checkShapes() function. If all three shapes are in place, a success message displays in the Output panel.

11. Repeat step 10 for both the square_mc and triangle_mc instances. Remember to replace all the circle_mc and circleHole_mc instance names with the instance names of the other two shapes.

12. Select Insert > New Symbol to create a new movie clip in the Library. Name the symbol success, and set the symbol's behavior to Movie Clip. Before you click OK, click the Advanced button on the dialog box to display a few more options. In the Linkage section, select the Export for ActionScript checkbox next to the Linkage, and success_mc automatically enters into the Identifier field. This lets you dynamically add a copy of the movie clip from the Library to the Stage.

13. Click OK in the Create New Symbol dialog box to enter symbol-editing mode for the success movie clip. Draw a medium-sized rectangle on the Stage and using the Text tool that doesn't overlap the shape holes on the Stage, and add a message that appears after all three pieces are placed in their proper holes. You can make the symbol look like anything you want, such as that shown in the Figure 6.16.

Figure 6.16. Create a message that the user sees when he successfully matches a shape to its respective hole.

14. Return to the main Timeline. Now you need to modify the checkShapes function you wrote in step 9, so instead of displaying text in the Output panel, the success movie clip displays instead. Select frame 1 of the actions layer to replace the TRace statement in the checkShapes function with the boldface code, so it matches the following:


function checkShapes() {
if (circle_mc.hitTest(circleHole_mc) &&
square_mc.hitTest(squareHole_mc) &&
triangle_mc.hitTest(triangleHole_mc)) {
attachMovie("success_mc", "mySuccess_mc", 1);
}
}

Instead of using a trace statement to display the success message, now you "attach" the movie clip from the Library onto the Stage when the SWF plays. You can test the SWF file now (Control > Test Movie) and see that after all three shapes position over their matching holes, the success symbol from the library attaches into the SWF file in the upper-left corner using its Linkage ID (success_mc). The attachMovie() method takes three, or sometimes four, parameters. The first parameter is the Linkage identifier (the one that you specified earlier in step 12). The second parameter is the instance name that you assign the symbol when it attaches to the Stage. You need to specify an instance name if you want to move the movie clip on the Stage or be able to get or set any of its properties. The third parameter is the target depth of the movie clip.

The attachMovie() method has an optional fourth parameter after depth. It is an object that can be used to pass default properties to the movie clip being attached. For example, you could set the _x and _y properties, or set the movie clip's _alpha property so it appears slightly transparent. You use this fourth parameter later in this exercise.

15. You can use one of two methods if you want to move the mySuccess_mc instance and position it on the Stage after you attach it.

You have already seen the first method. You set the _x and _y coordinates for the instance after you attach the clip to the Stage. This involves setting mySuccess_mc._x and mySuccess_mc._y after you call the attachMovie() method.

The second method of positioning the movie clip is to pass the optional fourth parameter in the attachMovie() method and pass an object containing _x and _y coordinates.

Depths are different from levels. When you load SWF files into another SWF file, you can load it onto a new level. Levels have a particular stacking order in a SWF file. The main Timeline is at _level0. Then you can load new SWF files onto new levels that are numbered in a stacking order (2, 3, 4, and so on). You layer the content on top of the main Timelines's content, which is visible beneath the loaded SWF's content. It is like layering transparencies on top of the main Timeline.

To position the mySuccess_mc instance using the second method, to learn a new way of manipulating movie clips, modify the checkShapes() function again to match the following code:


function checkShapes() {
if (circle_mc.hitTest(circleHole_mc) &&
square_mc.hitTest(squareHole_mc) &&
triangle_mc.hitTest(triangleHole_mc)) {
var initObj:Object = new Object();
initObj._x = 104;
initObj._y = 50;
attachMovie("success_mc", "mySuccess_mc", 1,
initObj);
}
}

The previous code defines a new Object named initObj and defines two properties (_x and _y). Then you pass this new object to the attachMovie() method by adding it as a parameter: initObj.

Now the mySuccess_mc instance positions at X:104, Y:50 on the Stage. Whichever method you choose is up to you; it's purely a matter of personal preference.


Learning About Depth


Depth is important in Flash because it dictates which objects appear on top of other objects. The objects can be on the same layer on the Timeline, and yet still appear stacked on top of each other. Therefore, two objects cannot exist on the same depth.

The one place where depth is extremely important is when you have an instance at depth 1 of your SWF file and you load a second clip into the same depth. Flash then removes the first instance at that depth and replaces it with the second instance that attaches to that depth. Although this might be the behavior that you want because it is an easy way to add and remove a clip from the Stage, in other cases you might want to add multiple instances at different depths. If you want to add several different instances dynamically, you need to keep track of the depths that you useor you can use the MovieClip class' getNextHighestDepth() method to determine the next available depth for a Timeline or movie clip. You use this method in place of setting a numerical depth value.

16. The final step is to find a way to remove the mySuccess_mc movie clip when the user clicks the reset button. If you don't remove the movie clip, users probably couldn't see the shapes on the Stage or drag them around using the mouse. Modify the onRelease handler for the reset_btn instance to add the following line of code:


reset_btn.onRelease = function() {
triangle_mc._x = triangleInitX;
triangle_mc._y = triangleInitY;
square_mc._x = squareInitX;
square_mc._y = squareInitY;
circle_mc._x = circleInitX;
circle_mc._y = circleInitY;
mySuccess_mc.removeMovieClip();
}

Now when you test your SWF file (Control > Test Movie), the success message should appear only after you correctly position all three shapes, as you can see in Figure 6.16.

The success message disappears after the user clicks reset_btn. If you cannot see reset_btn because the success movie clip is in the way, you might need to realign the reset_btn instance on the Stage, or modify the X and Y coordinates of the success movie clip, which is within the code in step 15.


/ 123