0% found this document useful (0 votes)
71 views

A. B. C. D. E. F. 1

1. This code creates two tween animations that rotate and move a movie clip called kText. 2. The tweens use different easing functions to control the animation speed and create bouncing or repeating effects. 3. Event handlers are used to loop or continue the tweens to new values once finished.

Uploaded by

sskathait
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

A. B. C. D. E. F. 1

1. This code creates two tween animations that rotate and move a movie clip called kText. 2. The tweens use different easing functions to control the animation speed and create bouncing or repeating effects. 3. Event handlers are used to loop or continue the tweens to new values once finished.

Uploaded by

sskathait
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

You should see the following code: import mx.transitions.Tween; import mx.transitions.easing.

*; var xScaleT:Tween = new Tween(kText, "_rotation", Elastic.easeOut, 0, 360,3, true); var xPosT:Tween = new Tween(kText, "_x", Bounce.easeOut, 0, Stage.width,3, true); xScaleT.onMotionFinished = function() { this.yoyo(); }; xPosT.onMotionFinished = function() { this.continueTo(Stage.width / 2, 3); }; Before I explain the code, you should be aware that kText in our code references the instance name of our movie clip on the stage. import mx.transitions.Tween; import mx.transitions.easing.*; The first line imports the Tween class file into your Flash document. You can find the class file called Tween.as at C:\Program Files\Macromedia\Flash 8\<language>\First Run\Classes\mx\ transitions\ assuming a default installation. Here you should find 16 class files used by Flash for various other effects (including the slideshow templates). For this tutorial we are only interested in the Tween class and the 6 easing classes contained within the easing folder. The second line imports the latter. var xScaleT:Tween = new Tween(kText, "_rotation", Elastic.easeOut, 0, 360,3, true); var xPosT:Tween = new Tween(kText, "_x", Elastic.easeOut, 0, Stage.width /2, 3, true); These two lines create two new tween instances and store them as the variables xScaleT and xPosT. The Tween class constructor requires seven parameters, which are in order:

1. 2. 3.

object The instance of an object in which to apply the tween. This can be any object, and is not just limited to movie clips. property The numeric property of the previous object in which to Tween. The property name is passed to the constructor as a string. ease class and method The type of tween and the method of ease applied to it. Flash comes bundled with 6 easing classes:

a. b. c. d. e. 1.

Back Extends the animation over one or both ends of the tween. Bounce Creates a bouncing effect in the tween at one or both ends.

Elastic Creates a mixture of the bounce and back classes. The animation is extended over and bounces back at one or both ends of the Tween. Regular Slower motion at one or both ends of the tween.

Strong Similar to regular but is more pronounced when combined with the various easing methods.

f. None A simple linear transition from a to b.


These six easing classes each have three methods to control the ease: easeIn The ease is applied only at the start of the tween.

easeInOut The ease is applied at both the beginning and end of the tween. By combing the six easing classes with the three easing methods, we can create a possible 18 different effects for each property.

2. 3. 1. 2. 3. 4.

easeOut The ease is applied only at the end of the tween.

begin The beginning value for the property in the tween. end The end value for the property in the tween.

duration The duration of the tween. This value can either be specified as a number of frames or a number of seconds depending on the value of the next parameter. use seconds Specifies whether or not the duration parameter should be measured in frames or seconds. Requires a Boolean of either true (use seconds) or false (use frames).

xScaleT.onMotionFinished = function() { This is an event handler for the xScaleT tween instance. So when the current tween finishes (reaches its end value), the code defined within the function will execute. this.yoyo(); Using the yoyo method, this line basically instructs the tween to flip the end and begin values creating an endless back and forth motion. xPosT.onMotionFinished = function() { Another event handler, but this time for the xPosT tween instance. this.continueTo(Stage.width / 2, 3); The final method of the easing classes which continues the tween to a new end value. The continueTo method requires two parameters, end and duration. The duration parameter assumes the use seconds Boolean from the tween in which it is applied to. Note In Flash MX 2004, the many events associated with the Tween class are not declared as members of the class. In layman's terms this means that you cannot use these functions in the way I have shown (as a property of the instance). The Tween class in MX 2004 was meant to be used with listeners, but there are several workarounds for this: Obviously using listeners is one of the solutions. This is the way the developers intended but can become quite cumbersome. All in all however this is the correct way to go since the other two methods are basically just fooling the compiler's error checking. An example of using listeners with the Tween class: import mx.transitions.Tween; import mx.transitions.easing.*; var myTween:Tween = new Tween(); var listeningObject:Object = new Object(); myTween.addListener(listeningObject); listeningObject.onMotionFinished = function():Void { //actions for motion finished };

1.

1.

Don't use dot notation but rather use array referencing, the compiler cannot check these properties and thus it can't give an error. Example:

var myTween:Tween = new Tween(); myTween["onMotionFinished"] = function ():Void { //actions for motion finished }; Don't data type the variable. If the compiler doesn't know what type the variable is there is no way for it to tell which properties belong and which do not. Alternatively you could type the variable as Object, which is a dynamic class (meaning there is no restrictions on the properties an instance can have). Example showing the variable with type Object: var myTween:Object = new Tween(); myTween.onMotionFinished = function():Void { //actions for motion finished }; when loading XML into Flash, you have to create that XML instance. The XML instance for this example, and most you will see from now on despite the fact that naming is arbitrary, will be called "my_xml." Note: using "_xml" at the end of your XML variable name in Flash MX or MX04 will give you code hints. In MX04, typing a new XML instance will provide hints without the suffix (i.e. var life:XML = new XML(); suffices). var my_xml = new XML(); In creating an XML instance in this manner, you do have the option of passing in an XML string to the XML constructor (the constructor being the function that creates the XML, here newXML()). That string would consist of XML which will be immediately defined within the XML instance created. For example: var my_xml = new XML("<some>stuff</some>"); Though, when about to load in external XML, there's really no point since whenever you load XML into an XML instance in Flash, all XML contained within that instance is replaced with that which is loaded. Passing text like that is optional, so for this example it will just be omitted. Once an instance exists, you can define the onLoad callback function. The callback function, whenever you make it, always has to be called onLoad. Just like other event handlers, this is how Flash knows to call it when its needed, i.e. when the XML content has been loaded and parsed. Additionally, a success argument is passed into each onLoad when it fires. This will let you know if your XML has actually successfully loaded or not. For example, when you try to load XML from the URL "http://get a life," success will be false "http://get a life" is obviously not a valid URL (hey, we all have lives here!). However, use a valid url (with a rock-solid internet connection) and success will be true signifying the completion of XML being loaded into Flash and ready for use. Here, we'll make an onLoad function that simply traces the XML object when successfully loaded. Tracing an XML object directly will reveal the XML in text format. var my_xml = new XML(); my_xml.onLoad = function(success){ if (success){ trace(this); } } Since onLoad is defined in the XML instance, this inside the function references the instance directly.
Preloaders With XML Just like anything else loaded into Flash, you can also create preloaders for XML. Generally, however, since XML is usually light on the loading side, preloaders aren't needed. A general "Now Loading" message usually suffices. But sometimes, for those real hefty files, you may want a preloader to show the status of the XML loading. If you're worried about learning a whole new way of making preloaders for XML, don't be. Making a preloader for XML is exactly like making one for a loaded SWF or JPEG. The only difference is that instead of calling getBytesLoaded and getBytesTotal from a movie clip, you're calling it from your XML instance. So really, you can use preloaders created for movie clips with XML so long as you reference the XML object to get bytes loaded and bytes total. Here's a quick example of a preloader that can work with XML as well as movie clips:
preloadbar_mc.onEnterFrame = function(){ if (!this.target) return (0); var loaded = target.getBytesLoaded(); var total = target.getBytesTotal(); var scale = 0;

1.

if (loaded && total){ var percent = loaded/total; scale = 100 * percent; } this._xscale = scale; } preloadbar_mc.target = my_xml;

Where preloadbar_mc is a horizonally scaling movie clip representing the preloader and my_xml is the XML instance you wish to show the preloader for. The onEnterFrame event of the preloadbar_mc runs the preloader using a generic target to get bytes loaded and bytes total. Whether this is a movie clip or an XML instance, as long as getBytesLoaded and getBytesTotal work, it doesn't matter. White Space in Loaded XML There is a certain XML option concerning loaded XML that should not go without mention. That is the option to ignore extraneous white space between elements in an XML document. This is determined by an ignoreWhite property of an XML instance.
my_xml.ignoreWhite = true;

What this does is prevents white space such as tabs and spaces used in formatting in your XML to be interpreted as text nodes which Flash likes to do (white space is text too right?). For example. How many child nodes does the happy element have here:
<happy> <joy /> </happy>

If you said three, then you were right! The happy element has one child element, joy, and two text nodes; a newline + tab text node before joy and another newline text node following it. This effect is generally not desired as such white space is meant solely for formatting purposes. By default, the ignoreWhite property for any XML instance in Flash is set to false, so you may want to get into the habit of setting it to true immediately after creating an XML instance if you don't want such white space to be considered text elements

XML OBJECTS
Since Flash objects and timelines are hierarchically structured much in the same way as XML is, such a conversion from XML to ActionScript object would seem simple enough as it could be translated fairly directly. However, because of the way XML is defined, there ends up being some complications. Lets take a look back at what the basic XML structure looks like including common node types:
<root> <child attribute="value" attribute2="value2"> Text Node: Child of child. </child> <child> Text Node 2: Child of second child. </child> <child attribute="value2" /> </root>

var parent = new Object(); parent.child = new Object(); parent.child.attribute = "value"; parent.child.attribute2 = "value2"; parent.child = new Object(); parent.child.text = "Text Node: Child of child."; parent.child = new Object(); parent.child.text = "Text Node 2: Child of second child."; parent.child = new Object(); parent.child.attribute = "value2";

What we have are a collection of hierarchically related nodes, some element nodes (some with attributes and some with not) and a couple of text nodes. This adheres to the basic structure and rules of an XML document. The structure is hierarchical with element nodes containing other nodes which they themselves can contain more nodes. The rules to keep in mind here are that elements can share similar names whereas attribute names must be unique. If we were to take the above and convert it into a similarly structured Flash object, you may get something like the following:

Immediately, you should be able to see at least one apparent problem - the assignment of child. Because XML elements don't need to have unique names, when a new child object is added to the parent object above in Flash, it effectively replaces whatever object was defined there under the same name (the original child).

Also, though far less apparent, is that you have no preservation of order in using object properties to define elements. Given the original XML layout, it's easy to tell which child is first, second, and third - information which could be important to the content (in XML node order is not redundant). With Flash objects, you have no real control of object property order, they exist just as properties. So then, what would facilitate objects in a specific order whose name's don't have to be unique? Hmm... arrays would, right? Keeping each element in an array will allow it not only to have whatever name it wants (it can be stored as a property of an object element in the array - a property under something like "nodeName" perhaps?) but also maintains the order as it is specified within the original XML document. A good array name for holding child nodes of any element may be... "childNodes," don't you think? What about attributes? Is there anything horribly wrong with them in the Flash object above? Well, for the most part, no. But being assigned directly to an element object could cause confliction with already predefined element values and methods such as those provided by Flash. You shouldn't be restricted from using a certain attribute name just because Flash might use it as an XML property in an XML instance. To keep these separated a bit to avoid such confusion, attribute definitions can be kept in a single object within the element object called... how about "attributes?" The fact that they all need unique names means that they can remain defined under a variable of a similar name instead of needing an array (attribute order is not a factor). All that remains are text nodes. They seem fine enough. But remember, text nodes are nodes and separate entities of the elements in which they exist. They, like other elements, would be children of their parent element. As such, they too will need to be placed in the childNodes array of the element containing them. Also, in being a node these entities should be created as objects in order to facilitate node properties and methods as Flash may seem fit to provide (as opposed to just being String variables). The actual text can go in a property of that node object called, lets say, oh, I don't know, "nodeValue?" Wow, things just got a little more complicated. Let's revise the Flash object from above to work with the problems we just solved:
var parent = new Object(); parent.childNodes = new Array(); parent.nodeName = "parent"; parent.childNodes[0] = new Object(); parent.childNodes[0].nodeName = "child"; parent.childNodes[0].attributes = new Object(); parent.childNodes[0].attributes.attribute = "value"; parent.childNodes[0].attributes.attribute2 = "value2"; parent.childNodes[0].childNodes = new Array(); parent.childNodes[0].childNodes[0] = new Object(); parent.childNodes[0].childNodes[0].nodeValue = "Text Node: Child of child."; parent.childNodes[1] = new Object(); parent.childNodes[1].nodeName = "child"; parent.childNodes[1].attributes = new Object(); parent.childNodes[1].childNodes = new Array(); parent.childNodes[1].childNodes[0] = new Object(); parent.childNodes[1].childNodes[0].nodeValue = "Text Node 2: Child of second child."; parent.childNodes[2] = new Object(); parent.childNodes[2].nodeName = "child"; parent.childNodes[2].attributes = new Object(); parent.childNodes[2].attributes.attribute = "value2"; parent.childNodes[2].childNodes = new Array(); parent.childNodes[3] = "I'm tired of typing...";

Suddenly that simple XML file isn't looking so simple in its ActionScripted version anymore. And in case you were wondering, the structure above is pretty much exactly how that XML would be laid out in an instance of the XML object in ActionScript. The parent variable here actually represents the first child of an XML instance (the XML instance itself acts like a node containing all XML of that instance within it as a child). Everything else is as it would be within that object. Daunting, isn't it? Fear not, you're half-way in the know now. We just went through the reasons why this complexity exists which is a large step in helping to understanding it. In summary Flash translates an XML document's structure into an ActionScript object an XML instance - through the following: The base XML object is an object containing the entire XML hierarchy beneath it (as a child). All children of any given node (including those in the base XML object which is itself a node) are contained within an Array in that object called childNodes. Each Element Node contains a property nodeName (among others) giving its name. Each Text Node node contains a property nodeValue (among others) containing the text. Attributes of an Element Node object are contained with an attributes object in that node object under their respective variable names. Navigation Through Helpful XML Properties

So far we've seen that XML nodes in Flash form have attribute objects and child nodes arrays stored as properties represent their structure. Flash ActionScript provides some additional properties added to XML nodes to help make navigation through it a little more easier. Here's a list of XML structural properties you can reference off of XML nodes. Property XML Nodes attributes childNodes** parentNode* firstChild* An object containing attribute variables assigned to this element. An array containing all child nodes belonging to this node. This node's parent node. The first child in this element's childNodes, or childNodes[0] The last child in this elements childNodes, or childNodes[childNodes.length1] The node after this node in the parent's childNodes array. The node before this node in the parent's childNodes array. Represents

lastChild*

nextSibling* previousSibling*

*Read-only and can only be checked, not directly set. **Altering element order in this array will not be reflected in the XML instance.

my_xml.firstChild

Together, these properties provide the groundwork for you being able to navigate through your XML. Of course seeing the properties, and reading and understanding what they represent is one thing. Being able to use them is a whole new slice of cheese. Making proper use of these properties is really what makes XML so difficult to deal with in Flash. We'll work through a little of that now but the Flash examples given later on will provide a better understanding of using them more effectively and in context. The first thing to remember is that an XML instance represents a single node in which the rest of the XML is defined. That means that your XML instance and the document root node of your XML are not the same thing. The root node is actually a child of the XML instance. Since there should be only one root node (DOCTYPE and XML declarations are not considered nodes and are not accessible as children), that means your root node would be the first child of the XML instance. Given the XML instance my_xml, the root node would be: From here, you can then start accessing your XML as needed. Now, you'll notice that even just getting to the document root of an XML document through an XML instance requires using firstChild. What do you think happens when you want to get to the first child of the first element in your document root? Consider the following XML:
<mydocuments> <mypictures> <family> <image title="Sister laughing" /> <image title="Brother laughing" /> <image title="Mother beating me" /> </family> <vacation location="Myrtle Beach"> <image title="Sun bathing" /> <image title="Walking the dog" /> <image title="Swimming" /> <image title="Getting eaten by shark" /> </vacation> <girls /> </mypictures> </mydocuments>

Now assume this is the XML content of the my_xml variable in Flash. The first child of the first element in the document root is family (where mypictures is the first element in the document root). So, in order to reach the family node in my_xml, you would use:
my_xml.firstChild.firstChild.firstChild

Already you can see the complexity and confusion that's just starting to unravel. If it takes that much just to get to the first pertinent element in a simple XML document such as the one above, imagine the paths needed to get to things in a more complicated XML document. How are you ever to keep track? Variables. Variables are the key to success and understanding when using XML. Variables and loops. Looping gets you through element children and variables provide you a way to give descriptive names to abnormal paths such as the one given above. What's easier to understand? my_xml.firstChild.firstChild.firstChild.firstChild or family.firstChild? Saving the original path in a family variable (as it represents the family element) you get yourself a clearer understanding in the reference to the specified image element. When using loops, you would typically use the childNodes array. Then, just like with any other array, you would loop through each element performing whatever task is needed on each. For example, to loop through all the image elements in vacation, you could use:
var family = my_xml.firstChild.firstChild.firstChild; var images = family.childNodes; for (var i=0; i<images.length; i++){ currImage = images[i]; }

Using the attributes object, you could then access the titles of each and trace them in the output window
var family = my_xml.firstChild.firstChild.firstChild; var images = family.childNodes; for (var i=0; i<images.length; i++){ currImage = images[i]; trace(currImage.attributes.title); // trace each images' title }

Lets say you then wanted to go about looping through the vacation images. How might you go about that? Well, you could use a similar path to get to vacation as you did with family. Only with vacation, the last child reference would have to be from the childNodes array since vacation is neither the firstChild nor the lastChild of mydocuments.
var vacation = my_xml.firstChild.firstChild.childNodes[1];

However, since family has already given us much of that path already, nextSibling can be used to get to vacation directly from family.
var vacation = family.nextSibling;

Unlike the child reference properties, the sibling properties stay within the same element scope being able to reference other nodes which share the same parent (in this case mypictures) as the node from which its being used. So, after going through the family image elements, you can go through vacation images using:
var vacation = family.nextSibling; var images = vacation.childNodes; for (var i=0; i<images.length; i++){ currImage = images[i]; trace(currImage.attributes.title); // trace each images' title }

You can see that the vacation node has a wide array of direct access when it comes to referencing other nodes within the XML in respect to its location using those properties available to it. The parentNode property references mypictures, the element in which it exists; previousSibling and nextSibling references the child nodes next to vacation within that parent node on either side of itself (a.k.a. "siblings" like brothers and sisters). We saw how family's nextSibling was vacation. Using vacation's previousSibling, you can go back up to family. And then of course you have firstChild, childNodes, and lastChild provide access to vacations own children, its image elements. Parents, siblings, children, XML just asks to have a family tree written in it, doesn't it? There are yet some other properties which you can use to find out more about your XML and its nodes. These don't necessarily help you navigate through your XML so much, but they provide important information nonetheless. They are as follows: Property XML Nodes nodeName The node's name. This is the tag name of an element node and null for other nodes. Represents

nodeType*

A numerical value representing the node's type: 1 = Element 3 = Text Node (or CDATA Section) The node's value. This is text for text nodes and CDATA and null for elements.

nodeValue

XML Instances xmlDecl docTypeDecl loaded status XML's declaration example: <?xml version="1.0"?> XML document DOCTYPE declaration example: <!DOCTYPE greeting SYSTEM "hello.dtd"> True or false depending on whether or not the last load() command has successfully completed for the XML instance. A numeric value representing parsing errors during Flash 's attempts to convert XML text into the ActionScript XML object. They are as follows:
0 No error; parse was completed successfully. -2 A CDATA section was not properly terminated. -3 The XML declaration was not properly terminated. -4 The DOCTYPE declaration was not properly terminated. -5 A comment was not properly terminated. -6 An XML element was malformed. -7 Out of memory. -8 An attribute value was not properly terminated. -9 A start-tag was not matched with an end-tag. -10 An end-tag was encountered without a matching start-tag.

*Read-only and can only be checked, not directly set. We've already seen nodeName and nodeValue before, but nodeType is a new one. It helps you distinguish elements from text nodes. Other properties listed are for XML objects specifically and not the nodes they contain. The first two, xmlDecl and docTypeDecl let you extract an XML document's declaration and doctype which are not, technically, otherwise included as elements in the XML structure (at least not in Flash). The other two, loaded and status, just help determine information about loading and parsing XML, whether or not they were successful. With all these properties out of the way, we can start getting into some examples which make practical use of them, hopefully in a comprehensible manner.

-----------------Playing sounds in ActionScript is fairly straightforward thanks to the Sound class. All you really need to do is put the class to good use to that you can load a sound, buffer/preload it, and then play it. In this short article, I will provide you with the code you need and explain how everything works. Note - This tutorial covers how to play sounds using ActionScript 3. For playing sounds using ActionScript 1, click here.

Overview of Playing Sound


In general, when it comes to playing sound in code, there are several things that you need to do: 1. Access an External MP3 File 2. The sound files that you load will not be included inside the SWF file. The files need to be located externally such as alongside your SWF file. 3. Preload the Sound 4. Before playing the sound, you need to make sure the sound has been fully loaded first. If you didn't do this, your sound will stutter on slower connections. Streaming sounds will be covered in a future article, so don't worry! 5. Play the Sound 6. Once your sound has been fully loaded, all that is left is for you to actually play it. Now that you know, at a very high level, what it takes to play a sound file, lets' go ahead and look at the code.

The Code
The code for pointing an external sound file, preloading it, and playing it can be written in the following lines of code:
var soundClip:Sound; function init() { soundClip = new Sound(); soundClip.load(new URLRequest("<path to sound file>")); soundClip.addEventListener(Event.COMPLETE, soundLoaded); soundClip.addEventListener(ProgressEvent.PROGRESS, soundLoading); } init(); function soundLoaded(e:Event) { soundClip.play(); } function soundLoading(e:ProgressEvent) { // preloader information goes here }

Let's look at how the code works line by line:


var soundClip:Sound;

The first line is pretty straightforward. I am declaring a variable called soundClip whose type is Sound. Another way of saying it is that I have a Sound object called soundClip. You can learn more about classes / types / objects in my earlier Classes in ActionScript 3 article. Next up is the init() function:
function init() { soundClip = new Sound(); soundClip.load(new URLRequest("<path to sound file>")); soundClip.addEventListener(Event.COMPLETE, soundLoaded); soundClip.addEventListener(ProgressEvent.PROGRESS, soundLoading); } init();

This function gets called first when you run your application because it gets called - the function call is directly below the function! The code inside the init function points to the sound file you want to load and sets up the event handlers for letting your app know when the sound has been fully downloaded. Let's look inside it to learn more. The first line of our init method initializes our soundClip object to a new Sound object: While before you simply declared a variable called soundClip whose type is Sound, it isn't until you initialize it that the Sound object is actually created. With this object created, you have access to all of the properties the Sound class provides you with. The first property we will look at is load: The load property takes the URL of the sound file to load. The moment this line gets executed, your sound file begins its download. It is important that you are aware of the sound file downloading and when it finishes downloading. The next two lines help you with just that:
soundClip.addEventListener(Event.COMPLETE, soundLoaded); soundClip.addEventListener(ProgressEvent.PROGRESS, soundLoading);

soundClip = new Sound();

soundClip.load(new URLRequest("<path to sound file>"));

Both of these lines set up listeners from our Sound object that associate an event with a function to call when that event is fired. The function that reacts to an event is often called an event handler. In the first line, we listen to the Complete event and play the soundLoaded function when the sound file's download has fully completed. In the second line, we do something similar except we play the soundLoading function as the sound file is downloading.
function soundLoading(e:ProgressEvent) { // preloader information goes here }

The last line we looked at was one that called a function as your sound file was downloading. That function is called soundLoading. With each chunk of data that gets downloaded, this function gets called. Notice that it takes an argument, and that argument is of type ProgressEvent.

The ProgressEvent class contains properties that you can use to gauge the progress of the download. The two properties that would be relevant are bytesLoaded andbytesTotal. You can use them both to get the current progress by dividing the values they return. Here is an example of me using the ProgressEvent object e and dividing the number of bytes loaded by the total size of the file:
var currentProgress = Math.round(e.bytesLoaded/e.bytesTotal);

The final thing to look at is our soundLoaded function:


function soundLoaded(e:Event) { soundClip.play(); }

This function is the event handler for the Complete event that fires when the sound file you are loading has fully downloaded. With our sound fully loaded, the only thing that remains is to actually play your sound. That is done by calling the play() method on your soundClip object of type Sound.

-------------------------

General Movieclip Manipulation 1 Make movieclip circle_mc opaque when the mouse is not over it and change to 60% opacity when the mouse goes over it. For more information: Functions Movieclip reference page Responding to mouse events 2 Make movieclip plane_mc play when control movieclip play_mc is clicked. For more information: Playhead commands Functions See next example for generic version 3 Define a function to make plane_mc play. Assign that function to play_mc's onRelease event, so that when play_mc is clicked, plane_mc will play. For more information: see reference links above 4 Define a function to make plane_mc function flyPlane() { function flyPlane() { plane_mc.play(); } play_mc.onRelease = flyPlane;

circle_mc.onRollOver = function this._alpha = 60; }; circle_mc.onRollOut = function( this._alpha = 100; };

play_mc.onRelease = function() plane_mc.play(); };

play only if it is currently "parked" in frame 1 (ie, frame 1 of plane_mc has a stop action). Assign the function to play_mc's onRelease event, so that when play_mc is clicked, if plane_mc is not already playing, it will play. For more information: Code Blocks, including If statements Playhead commands Functions 5 Make movieclip circle_mc fade to 60% opacity when the mouse goes over it and jump back to 100% when the mouse goes off. For more information: Functions Responding to mouse events Operators

if (plane_mc._currentframe = plane_mc.play(); } } play_mc.onRelease = flyPlane;

circle_mc.onRollOver = function this.onEnterFrame = function if (this._alpha > 60) { this._alpha -= 10; } else { delete this.onEnterFrame; } }; }; circle_mc.onRollOut = function( this._alpha = 100; }; var found:Boolean = false;

Declare a variable (property of the main timeline, and so available for use by any elements in the movie) named found, of type Boolean, and set its initial value to false. For more information: Declare and assign variables Simple data types

Assign properties to movieclips to hold information needed for click events 7 Create a property of movieclip bee_mc.flying = true;

bee_mc named flying and set its value to true. For more information: Movieclip reference page Intro to classes Declaration and assignment 8 Create a property associatedClip of function unhide() { movieclip c0 which is a pointer to this.associatedClip._visible = box0 and use it to unhide box0 when } c0 is clicked. c0.associatedClip = box0; c0.onRelease = unhide; Examples of assigned properties in use: Easing slider Bee game

Create the same property for several function unhide() { control movieclips, c0 - c4, and use this.associatedClip._visible = it to determine which movieclip } (box0 - box4) each one should for (var i=0; i < 5; i++) { unhide when clicked. this["c"+i].associatedClip = this["box"+i]; For more information: this["c"+i].onRelease = unhid Code blocks, including for loops } For examples of this in use: Easing slider Group of buttons

10

Create the same property for several var controlInfo:Array = [ control movieclips, c0 - c4, setting "wake up", its value from an array of "eat lunch", information, and using the property "go home", to determine what text to display in "walk the dog" textfield page_txt when a control is ]; clicked. function showText() { page_txt.text = this.mytext; For more information: } Arrays for (var i=0; i < 5; i++) { For an example of this in use: this["c"+i].mytext = controlIn Group of buttons this["c"+i].onRelease = show } Use an array to hold pointers to the var controlInfo:Array = [

11

control movieclips, the text to display in textfield page_txt and pointers to the associated picture movieclip to set to 50% opacity when the control is clicked. Use the information in the array to assign appropriate properties to each control to define its click behavior. For more information: Arrays and Objects For an example of this in use: Group of buttons

{ctl:wakeup_mc, text:"wake u pic:alarm_mc}, {ctl:eatlunch_mc, text:"eat lu pic:lunch_mc}, {ctl:gohome_mc, text:"go ho pic:door_mc}, {ctl:walkdog_mc, text:"walk t pic:dog_mc}, {ctl:sleep_mc, text:"fall aslee pic:bed_mc} ]; function onClick() { page_txt.text = this.mytext; this.myclip._alpha = 50; } for (var i=0; i < controlInfo.leng { controlInfo[i].ctl.mytext = controlInfo[i].text; controlInfo[i].ctl.myclip = controlInfo[i].pic controlInfo[i].ctl.onRelease = }

12

The same example as above, using string representations of the movieclips, rather than pointers to the actual movieclips, in the array. In this example, the pic movieclips are inside movieclip frame_mc. For more information: Arrays and Objects For an example of this in use: Group of buttons

var cInfo:Array = [ {ctl:"wakeup_mc", text:"wake pic:"alarm_mc"}, {ctl:"eatlunch_mc", text:"eat pic:"lunch_mc"}, {ctl:"gohome_mc", text:"go h pic:"door_mc"}, {ctl:"walkdog_mc", text:"walk pic:"dog_mc"}, {ctl:"sleep_mc", text:"fall asle pic:"bed_mc"} ]; function onClick() { page_txt.text = this.mytext; this.myclip._alpha = 50; } for (var i=0; i < cInfo.length; i+ this[cInfo[i].ctl].mytext = cIn this[cInfo[i].ctl].myclip = frame_mc[cInfo[i].pic];

this[cInfo[i].ctl].onRelease = } Motion 13 Move movieclip ball across the stage at a constant number of pixels per frame, using ball's timeline to control the motion: For more information: Functions Event handlers 14 Move movieclip ball across the stage at a constant number of pixels per frame. When ball hits a predefined right or left boundary, send it back the other way. Movieclip ball has an upper left registration point. For more information: Functions, If statements Event handlers Operators var xspeed:Number = 5; var leftbound:Number = 0; var rightbound:Number = 300;

var xspeed:Number = 5; function moveRight() { this._x += xspeed; } ball.onEnterFrame = moveRight

function moveRightLeft() { this._x += xspeed; if (this._x > rightbound - this. this._x = rightbound - this._ xspeed *= -1; } else if (this._x < leftbound) this._x = leftbound; xspeed *= -1; } }

ball.onEnterFrame = moveRight 15 Move movieclip ball across the stage at a random number of pixels (between 5 and 10) per frame. When ball hits a predefined right or left boundary, send it back the other way at a new random speed (between 5 and 10 pixels per frame). Movieclip ball has an upper left registration point. For more information: Functions, If statements Event handlers var xspeed:Number; var leftbound:Number = 0; var rightbound:Number = 300;

function randomBetween(a:Num b:Number):Number { return a + Math.floor(Math.random()*(b-a }

function moveRightLeftRandom( this._x += xspeed; if (this._x > rightbound - this.

Math functions Operators Registration point

this._x = rightbound - this._ xspeed = -1 * randomBetw 10); } else if (this._x < leftbound) this._x = leftbound; xspeed = randomBetween(5 } }

xspeed = randomBetween(5, 10 ball.onEnterFrame = moveRightLeftRandom; 16 Keep movieclip ball moving and bouncing off 'walls' at a fixed speed (number of pixels per frame) within a defined rectangular area (300 x 200 box at 0,0) For more information: pages above, plus Object Class

var bounds:Object = {L:0, T:0, B:200}; var xspeed:Number = 5; var yspeed:Number = 5;

function moveInBounds() { this._x += xspeed; this._y += yspeed; if (this._x > bounds.R - this._ this._x = bounds.R - this._w xspeed = -xspeed; } else if (this._x < bounds.L) this._x = bounds.L; xspeed = -xspeed; } else if (this._y > bounds.B this._height) { this._y = bounds.B - this._h yspeed = -yspeed; } else if (this._y < bounds.T) this._y = bounds.T; yspeed = -yspeed; } }

ball.onEnterFrame = moveInBou Drag and Test for Collisions

17

Make movieclip dragger_mc draggable within a 200 x 100 box on stage with its upper left corner 50 pixels from the right edge and down 40 pixels from the top edge of the stage. For more information: Drag movieclips, detect collisions

dragger_mc.onPress = function( this.startDrag(false, 50, 40, 2 };

18

Make movieclip dragger_mc stop dragging when the mouse is released. For more information: Drag movieclips, detect collisions

dragger_mc.onRelease = dragger_mc.onReleaseOutside = function() { this.stopDrag(); };

19

Make dragger_mc draggable. If the (invisible, rectangular) bounding box around movieclip dragger_mc has hit the (invisible, rectangular) bounding box of target_mc when the mouse is released after dragging, set target_mc to 50% opacity. Otherwise set it to 100% opaque. For more information: Drag movieclips, detect collisions

dragger_mc.onPress = function( this.startDrag(); } dragger_mc.onRelease = dragger_mc.onReleaseOutside = function() { this.stopDrag(); if (this.hitTest(target_mc)) { target_mc._alpha = 50; } else { target_mc._alpha = 100; } };

Load an external jpg or swf 20 Load "somepic.jpg" into movieclip holder_mc (on stage), showing a horizontal progress bar (bar_mc, on stage) during load, and sizing the jpg to 50% of its original size before displaying it. For more information: Load jpg or swf

var loader:MovieClipLoader = ne MovieClipLoader(); function onLoadProgress(_mc, l total) { var pct:Number = Math.round total * 100); bar_mc._xscale = pct; }; function onLoadInit(_mc) { bar_mc._visible = false;

_mc._xscale = _mc._yscale = _mc._visible = true; }; loader.addListener(this); bar_mc._xscale = 0; holder_mc._visible = false; loader.loadClip("somepic.jpg", holder_mc); 21 Load "mymovie.swf" in folder movies into movieclip player_mc (on stage), showing a percent loading message during load in textfield pct_txt, and calling an init function within the swf to start it once it's loaded. For more information: Load jpg or swf

var loader:MovieClipLoader = ne MovieClipLoader(); function onLoadProgress(_mc, l total) { var pct:Number = Math.round total * 100); pct_txt.text = pct + "%"; }; function onLoadInit(_mc) { pct_txt.text = ""; _mc.init(); }; loader.addListener(this); loader.loadClip("movies/mymov player_mc);

22

Load "movie.swf" into movieclip player_mc (on stage), showing a preloader clip (preloader_mc) that has been designed with a 100-frame sequence in it and a stop action in frame 1, during loading. A separate listener object is created instead of using the main timeline (or other current instance) as above. The swf is assumed to have a stop action in frame 1 and will be told to play when loaded. For more information: Load jpg or swf Make 100-frame preloader movieclip

var loader:MovieClipLoader = ne MovieClipLoader(); var lis:Object = {}; lis.onLoadProgress = function(_ loaded, total) { var pct:Number = Math.round total * 100); preloader_mc.gotoAndStop(pc }; lis.onLoadInit = function(_mc) { preloader_mc._visible = false _mc.play(); }; loader.addListener(lis); loader.loadClip("movie.swf", pla

Read text

file from web server (or local file if running a Flash executable) 23 Read the contents of a (utf-8 encoded) text file and display exactly as is in dynamic textfield page_txt. For more information: Read text file 24 Read the contents of a &var=value& formatted text file that looks like: &name0=fuschia&val0=DE11E6& &name1=limegreen&val1=00FF00& etc and save the contents in array paintcolors, converting the color value from a string to a number for later use. For more information: Read text file

var lv:LoadVars = new LoadVar

lv.onData = function(thetext:St page_txt.text = thetext; } lv.load("thetextfile.txt");

var lv:LoadVars = new LoadVar var paintcolors:Array = [];

lv.onLoad = function(success:Bo if (success) { var i:Number=0; while (this["name"+i]!=und paintcolors.push({ myname:this["name"+i mycolor:parseInt(this[" 16) }); i++; } } else { trace('problem reading file') } }; lv.load("paintcolors.txt");

25

Same example as above, using the array to color a number of swatch movieclips (swatch0, swatch1, etc) on stage, each of which contains a movieclip "dot" and a textfield "name".

var lv:LoadVars = new LoadVar var paintcolors:Array = [];

function setcolors() { var c:Color; for (var i=0; i < paintcolors.le +) {

For more information: Read text file Color class

c = new Color(this["swatch" c.setRGB(paintcolors[i].myc this["swatch"+i].name.text paintcolors[i].myname; } }

lv.onLoad = function(success:Bo if (success) { var i:Number=0; while (this["name"+i]!=und paintcolors.push({ myname:this["name"+i mycolor:parseInt(this[" 16) }); i++; } setcolors(); } else { trace('problem reading file') } }; lv.load("paintcolors.txt"); Read an XML file from the web server (or local file if running a Flash executable) 26 Read an XML file that looks like <?xml version="1.0" encoding="utf8"?> <colors> <color name="fuschia" val="DE11E6" /> <color name="limegreen" val="00FF00" /> </colors>

var colorxml:XML = new XML(); var paintcolors:Array = [];

function setcolors() { var c:Color; for (var i=0; i < paintcolors.le +) { c = new Color(this["swatch" c.setRGB(paintcolors[i].myc this["swatch"+i].name.text

and create an array of colors which are used to color a number of swatch movieclips (swatch0, swatch1, etc) on stage, each of which contains a movieclip "dot" and a textfield "name" (as in the previous text file example). For more information: XML Color class

paintcolors[i].myname; } }

colorxml.onLoad = function(success:Boolean) { if (success) { var colors:Array = this.firstChild.childNodes; for (var i=0; i < colors.leng paintcolors.push({ myname:colors[i].attrib e, mycolor:parseInt(colors tes.val, 16) }); } setcolors(); } else { trace('problem reading file') } };

colorxml.ignoreWhite = true; colorxml.load("paintcolors.xml")

You might also like