Flash Quick Reference Notes by TJ Nevis – WhyWorkForever.org
/* You can not edit this document or surrounding documents and pass them off as your own. Thank you for downloading the quick reference guide, and I hope it helps you out. If you have any code that you created and would like to share it with me or would like it in the next volume of the Flash Quick Reference Notes, email them to me at TJ410@rochester.rr.com. I will absolutely give you credit for your code submission. */
Sections
¨ About this 'book' / the author
¨ Methods and properties of string objects / movie clips and buttons
¨ Pre-loader - Simple and effective [.FLA] Advanced [.FLA]
¨ Detect dropped movie - when user releases dragging [.FLA]
¨ 2 dimensional array (great for grid layout) [.FLA]
¨ Send and receive with PHP and Shared Objects [Like cookies for Flash] [.FLA]
¨ Convert bitmaps to simplified vectors [.FLA]
¨ Load external text with scroll [.FLA]
¨ Adding methods and properties with 'prototype' [.FLA]
DYNAMIC
¨ (Note: Dynamic movies need to use the set property)
¨ Create shapes dynamically - Curve [.FLA], Perfect Circle [.FLA], Square [.FLA], Dynamic Line [.FLA]
¨ Creating fills and gradients dynamically (filled box) [.FLA]
¨ Fading boxes - show image [.FLA]
¨ Concatenating variables and dynamic referencing [.FLA]
My sources are from the Macromedia.com website, Training from the source Flash MX actionscript book (ISBN: 0-321-21343-2 [I HIGHLY RECOMMEND THIS BOOK]), and many websites for small tid-bits here and there.
About this eBook' and the author [Back to Top]
This book was created to help other web design fanatics out there. I am currently 22 years old and moved to Raleigh, NC last year from Rochester, NY. I work at RegEd as an Insurance License Specialist and I work part time at Harris Teeter. In my free time I like to work on my car, my motorcycle, read programming or management books, work on websites, watch TV and play Guitar Hero. This eBook was originally written at the end of 2004 and I am reposting it now, because I feel it is still a helpful resource; I still use it myself. I will make v2 if people want it. If you have any questions about anything, just drop me a line at TJ410@rochester.rr.com .
Methods and Properties [Back to Top]
Methods make having a center place for all of the actionscript possible. If you remember in Flash 5 you would add on(press) event for example, but you had to place this code in that object. Now, you can centralize all of the code by taking a button instance on the stage and giving it an instance name of myButton and telling it what to do when it is pressed. This is done by simply myButton.onPress. Now usually you won't leave it at just that or use it as just that, you would add a function, a set of code that is exclusive to when the button is clicked, this is done by:
myButton.onPress=function(){
//Code
}
You will learn more about this later, as well as examples of code to visually see the code and the output in action. Macromedia has a great list of Events and Methods on their site, so below I have included them for your reference. Events have to be placed on the object code, methods can be placed on Frame 1 of your main timeline to centralize all actionscript code. If this isn't purely clear yet, it will be soon when you see examples.
The following table lists movie clip events and corresponding movie clip event methods:
Event Event method onClipEvent (load)
onLoad
onClipEvent (unload)
onUnload
onClipEvent (enterFrame)
onEnterFrame
onClipEvent (mouseDown)
onMouseDown
onClipEvent (mouseUp)
onMouseUp
onClipEvent (mouseMove)
onMouseMove
onClipEvent (keyDown)
onKeyDown
onClipEvent (keyUp)
onKeyUp
onClipEvent (data)
onData
Event Event method on (press)
onPress
on (release)
onRelease
on (releaseOutside)
onReleaseOutside
on (rollOver)
onRollOver
on (rollOut)
onRollOut
on (dragOver)
onDragOver
on (dragOut)
onDragOut
on (keyPress "...")
onKeyDown, onKeyUp
Then there are properties which are used to dynamically change an object. For example ._width, ._alpha. There will be more examples in the dynamic section. Each property also has a numeric value you can use if it is easier for your code creation. Below is a list of properties:
These properties I have used many times and it really helps in a more of a dynamic website, here goes the list: *Code is in Frame 1 of the main timeline
indexOf(searchString,fromIndex[optional]);
lastIndexOf(searchString,fromIndex[optional]);
substr(start,length);
toLowerCase();
charAt(index);
Substring(indexA,indexB);
concat(string1,string2);
toUpperCase();
length();You will see examples of these and how they work throughout the examples.
Properties with a check mark in the Get column can be read byTGetPropertyorTGetPropertyAsNumber. Properties with a check mark in the Set column can be modified byTSetProperty. The property number corresponding to each property is passed toTGetProperty,TGetPropertyAsNumber, orTSetPropertyto indicate which property is being accessed.
Property Property number Constant Get Set X POSITION (_x) 0 X_POS ¨ ¨ Y POSITION (_y) 1 Y_POS ¨ ¨ X SCALE 2 X_SCALE ¨ ¨ Y SCALE 3 Y_SCALE ¨ ¨ CURRENTFRAME 4 CURRENT_FRAME ¨ TOTALFRAMES 5 TOTAL_FRAMES ¨ ALPHA 6 ALPHA ¨ ¨ VISIBILITY 7 VISIBLE ¨ ¨ WIDTH 8 WIDTH ¨ HEIGHT 9 HEIGHT ¨ ROTATION 10 ROTATE ¨ ¨ TARGET 11 TARGET ¨ FRAMESLOADED 12 FRAMES_LOADED ¨ NAME 13 NAME ¨ ¨ DROPTARGET 14 DROP_TARGET ¨ URL(_url) 15 URL ¨ The following table shows global properties:
Global Property Property number Constant Get Set HIGHQUALITY 16 HIGH_QUALITY ¨ ¨ FOCUSRECT 17 FOCUS_RECT ¨ ¨ SOUNDBUFTIME 18 SOUND_BUF_TIME ¨ ¨ Some added properties I would like to include, separated by semi-colons:
getDate() [Returns day of month 1-31];
getDay() [Returns day of week 0(Sunday)-6(Saturday)]; getFullYear() [Year as a 4 digit number];
getHours() [Returns the house of the day [0-23 - You can get the 12 hour affect by subtracting 12 if it's over 12]
getMilliseconds()
getMinutes() [0-59]
getMonth() [0 (January) - 11 (December)]
getSeconds() [0-59]QuickTip: On text boxes, the square means it is a set width box, the circle means it will set the width to the text you have in it. Example:
- Will expand to the text you have in it
-Is a set width and will not expand - If you are editing text boxes and notice this, you can double-click the square and it will turn into an expanding text box
Naming your variables
Pre-loader [.FLA] [Back to Top]
Now that the basics are explained, let's start putting some code together and create a simple pre-loader. Let me tell you that I could never create a pre-loader until I found this way of doing it. A lot of the tutorials out there make it too complicated or don't explain well enough.
¨ Create a long rectangular movie clip symbol with the registration point at the far left edge. Create a line, it doesn't have to be perfect because you can edit it later, select it and press F8.I named mine scaleBar, because we will essentially be dynamically scaling it to go along with the percentage loaded. Notice the black box in the middle left where it says registration, that means it is registered at the left, like we want. Press OK. Back on the movie you see a circle with a + sign in the middle of it to the left of the movie clip symbol we just created. That is how you can tell where the registration point of an object is after it is created, if you forget. The circle in the absolute middle of the symbol is the turning point for free transform and also on use with guiding, both of which will be discussed later.
Since I want my scaleBar to look different, I will double click on the symbol to "edit in place." If you right click you can also select "edit in place." I like this better than the regular edit because you can see the rest of your movie faded in the background to give yourself the heads up of what it will look like without having to switch back and forth all of the time. This is what I got after messing around. To get this effect I right-clicked on the object and selected Envelope, mess around with it, you can create some interesting shapes.
¨ Give your movie clip an instance name. What this does is let actionscript reference the object in the code, since it does not use the names, like scaleBar - those are just for your convenience. I will give mine a reference name of progressBar. Where it is blue, highlighted, is where it says progressBar, since it is not clear enough to read. If you do not have the Properties window, go to Window>Properties [CTRL+F3]. You may want to draw a a rectangle around the movie clip on the stage, so when it is not completely loaded people will no where the 100% mark is located, or in the I'm Advanced step of this lesson you can mask it, and stretch the mask. This will show your pre-loader bar the way it is supposed to instead of stretching it like we will be doing in the next step. This method is good for just straight bars though.
¨ Click on Frame 1 and open the actions panel to insert this code:
You may also want to add
a percentage textbox to not only show the visual but the textual percentage mark of the progress. To do this, on the stage create a text box, and in the properties window select Dynamic Text. Stretch it as shown. Select the black arrow tool [V], click on the text box you just created and give it an instance name. I named mine percent_txt. Add this little bit of code right after the progressBar line and before the last curly brace:
Note: None of the // gray text needs to be copied, that is just for explanation and helpful hints and tips.
¨ The last step is to put a keyframe in the second frame, by hitting F6, and press delete. This deletes all of your pre-loader and percentage box that you just created, because it is time to start animating! Start your movie right after the first frame! Now wasn't that simple? [.FLA]
¨ I'm Advanced [.FLA] [Back to Top]
¨ Take what you've already created and all we have to do is add and change a few things.
¨ Add another layer, Insert>Timeline>Layer - Draw a box shape that is as tall as the tallest part of your object you want to reveal in the load process. Select it with the black arrow tool [V], again and press F8. Make the symbol be a movie clip and give it a name you want, the registration point should already be at the left from your previous symbol creation, but just make sure.
Give it an instance name, I gave mine a name of revealMe.
¨ Right-click on the layer with the object you've just created and select the Mask option.
¨ Now the last two things to edit. Go to the code in Frame 1 of the below layer, and where it says "progressBar._xscale..." is where you want to do these two changes. Change the progressBar to revealMe and at the end where it is multiplied by 100, multiply it by 1000.
Detecting a dropped movie [.FLA] [Back to Top]
Why would you want to detect a dropped movie? It could be for many reasons, such as in game creation, or to make a menu on your website very interactive, for example, the user might have to pick up an object and put it on top of some other object to advance to the link. I hope this gives you ideas on how to use this, and here is how you do it.
¨ I am going to expect you to know how to set instance names and create symbols in this and later lessons, so I will not be giving screenshots of that as I did in the previous lesson.
¨ Start off on your stage and create 2 objects or import them from file, as I did. Make them a movie clip symbol. If you imported them to the library, you need to drag it onto the stage, highlight it and press F8 to create a movie clip symbol of it, name it what you would like and give it an instance name, I gave mine an instance name of 'destination'. The other movie clip symbol I named 'throwAway'. If you look at my stage below you will see I have created a set up for the user to throw away junk mail in the recycling bin. Notice that little circle with the + in it, that we talked about in the previous lesson, is in the middle. That is because when I changed my bitmap image to a movie clip I set the registration point in the middle.
The reasoning for this is so when the user clicks on the junk mail movie to drag it, the mouse will move to the registration point. You will have trouble stopping the drag if you leave the registration point at the left like we had in the previous lesson. You can test it out and see what I mean. Note: You can edit the registration point when you are finished by double-clicking on the object to edit-in-place and move the image around the the crosshairs.
In this example I changed my registration point from the middle to a point towards the top left. Go back to Frame 1 of your main time line and add this script:
Explanation of the code: throwAway is the junk mail image's instance name.
¨ When you press the throwAway icon it starts the drag, having the user move an image around the stage is as simple as it looks. 'this' refers to throwAway, since it is in the function of the onPress method and true is saying to lock on to the center of the image. Notice the ' }; ', does it look different? It took me a while to figure out why it is different and it is because functions need to not only be ended, but needs the semi-colon;
¨ The onRelease is telling the movie clip to stop its drag. 'this' again refers to the throwAway movie clip and the ' / ' in front of destination refers to the main time line, in other words, _root. The IF statement is also saying when the junk email has reached the recycle bin to become invisible [like it has been 'thrown away'].
¨ This is an added chunk of code that is also good for game creation, it is the Hit Test
The code is relatively simple. The first thing you will have to edit is the throwAway movie clip. Add a stop(); on the first frame, press F6 to create another keyframe, and put something in the second frame so you will be able to tell it is different from the first frame. In my case I added a small orange box in the corner.
HitTest
hitTest is an MX method, it makes things a lot easier. All you have to do is say yourMovieClip.hitTest(movieToTest). What our code is saying is when the throwAway movie clip runs in with the recycle bin [Ex. When the user drags it over the bin but does not release the mouse], it will go to the next frame of our junk email movie clip. As said before, this is used very much in game creation for even simple games such as those space shooter games you have obviously experienced one time or another.
Creating an emptyMovieClip and attachMovie [Back to Top]
When you attach a movie clip using attachMovie, you need to prepare a movie-clip symbol in your library by creating it, assigning it an identifier and exporting it to actionscript. How do you do that? - After creating a movie clip, go to your library and right-click on the movie clip and select properties, check Export for ActionScript. Change the identifier name, that just became editable, to something that you will remember. [You can also right-click and select Linkage]. If you just need an empty movie clip you can simply use createEmptyMovieClip. This method is similar to attachMovie in that it attaches a movie clip dynamically on stage, but instead of a clip from the library it is exactly what it says, an empty movie clip. You give each newly created movie clip a unique name [Just like the instance naming] and a depth level.
Use empty movie clips as shells in preparation for additional content, modify the _x and _y properties by actionscript and use loadMovie() to load an external SWF [for example]. Empty movie clips are also important for movie clip drawing methods, covered in later lessons in the dynamic section.
2 Dimensional Array [.FLA] [Back to Top]
Arrays are great for many reasons. You can store many expressions in an easy to access array variable. For example, say you had sports scores for your favorite basketball team for the year. You could simply create an array, let's call ours bball2004 for this example, and input variables, starting at place 0 in the array. bball2004[0]=102; There is many possibilities. The thing I love about ActionScript array's over other languages is you can store all sorts of different variable types in the same array. This section is about 2D arrays, which takes the array to another useful level. In this lesson we are going to create a game board in an array, and show you two examples of outputting the array information. There are a lot of times you won't be outputting the array information, but there are also a lot of times you will, such as in our case we will be because it is a great setup for a gaming interface.
This is my stage and script windows. My stage is very simple and shows a few examples, a little bit of everything. The first Dynamic text box I created on stage has an instance name of arrayTest, the second arrayTest1 and the third arrayTest2.
¨ The script
The first 3 lines of code create 3 different arrays, named Row0, Row1, and Row2. Notice in the initialization of the new Array, there are numbers, 3 per each array. These are starting values to enter in that location of that array. If I was to find out what is at location 0 in the Row0 array, Row0[0], the result would be 1. Remember, arrays start at an index of 0. The next line of code, gameBoard=new Array(); , instantiates a new array called
gameBoard. I show another technique on how to assign values and variables to specific locations in the array you are currently working with. gameBoard[0]=Row0;, shows that at place 0 of the gameBoard array you are assigning a whole array in that location. This creates a 2 dimensional array. You may be asking how do you access this position? Great question, and the answer is very simple. Since in our example we have Row0 assigned to position 0 in the gameBoard array, you are essentially retrieving information from the Row0 array when you say: gameBoard[0][0]. But it is much simpler, because you can have a nested For Loop access all of the needed information. That will be talked about at the end of this lesson. Remember back when we instantiated our Row2 array we initialized it with values also? Notice in the line: gameBoard[2][0]="Hello". What this line is doing is overwriting the value in position 0 in the Row2 array, with the string Hello. The next line also reassigns, or overwrites, the value, but in a different array. It overwrites the third value, or index value of 2, in array Row0, with a number of 102. The next 3 lines assign values to the text boxes on the stage to output values and give you a visual note of what is in the array positions, and also a start on how to create a simple game, such as tic-tac-toe.
Create a grid with what you just learned:
You can either create a grid manually like we did in the above example, or you can create it easier in a nested For Loop. First I will cover the basics of a For Loop:
for(var i=0;i<5;i++){
This is how a for loop is started. The first of the three sections of the for loop says var i=0;, that means you are declaring a variable called 'i' for use in this for loop. [Note: Don't ask me why, but programmers usually like to use 'i' as a counter variable in For Loops, but you can use any letter or phrase you would like.] 'i<5' states you want to run this loop while the counter variable, 'i', is less than 5, starting at 0 - it will execute 5 times. 'i++' simply states you want i to be incremented by 1 every time the loop re-executes. [Note: You can use i+5, for example, or if you have another variable in previous code you can write 'i+otherVarible' - the possibilities are endless, but in our case we will just increment by 1.] Now we know the basics, let's create a grid.
Here is my code. First we declare a variable arrayTest to be an array. Following that, we have a nested For Loop. Notice in the second loop there is another variable, x. You cannot use the same variable that is currently being used. For example, if you had a For Loop using i, you COULD use i again if it is outside of the other loop using i as the counter variable. In our case, the second loop is inside the loop using i, so we had to use another variable as our counter. I inserted a simple line of code that says, array at place [i][x] should equal i multiplied by x. If this is looking familiar, good. It is a 2 dimensional array, and grid. I told that location to equal i's value at that current moment in the loop multiplied by x's value at that current moment in the loop so I could show you the output window. The last line of code has a trace line of that same expression, that just puts it in the output window for us programmers to see what is going on with our script. Over to the output screenshot, notice the first 6 lines are 0, that is because the first time through the first loop is zero, the inner loop is executed all 5 times for every 1 time of the outer loop. Anything multiplied by zero is zero, and the sixth zero comes from the outer loop having an i value of zero, but the inner loop's x value being 0, so again, 0 times anything is 0. The next four are, 1, 2, 3, 4. That is the outer loop's value still being 1 and the inner loop having values of 1, 2, 3, 4. If this is starting to make sense, good. If not, there are a few things you can do. Have the 'trace();' call be your best friend, and start off by calling a trace on x, then on i, write it down on paper, what ever you have to do to visually see the code working in your head. Now let's say you want to change the size of the grid, or array. All you have to do is change the values 5 in the inner loop and outer loop to what you prefer. Isn't that a lot easier than declaring a bunch of arrays and having the main array's places equal a whole array? I think yes.
Here is a neat little movie I made to show you the basics of the array and its methods, play around with it.
Using the #include for your ActionScript code [Back to Top]
What does the #include do and why would you want to use it?
¨ #include is used to include an actionscript file, a separate file that includes actionscript for use in the movie you include it in.
¨ To use it, all you have to do is at the first line of code add: '#include scriptName.as' and make sure it is in the same directory as your movie - that's it!
¨ The reasons you would want to use this are very simple. If you want to have a less amount of code in the current movie, just include script that you already know works correctly. The most important reason is to save time. Put code you use all the time in an .as file. I have an .as file that holds most of my code I have written and either don't want to forget it or plan to use in the future. You can include an .as file even if you don't use all of the functions that are in the actionscript file, it doesn't really have an affect on the loading time, I'm talking hundredths of a second difference. Enjoy saving time with this great tip!
Using a non-default font [Back to Top]
You can use a non-default font with a static text box and it will show up fine with ever computer, but what if you want to have a dynamic text box, something the user inputs to have a cool font? You have to approach it different. I am not sure why, but it isn't very hard so I guess it doesn't matter a whole lot.
¨ Create a dynamic text box and give it an instance name.
This is what my properties screen looks like for my text box. I took this example from my portfolio site's loading screen. The textbox shows what percent the loading is at, and chances are you have not seen "Vibrocentric" on many computers, if any at all. But I want that font to display for my loader!
¨ This one easy step takes care of that...Click on the "Character..." This screen will pop up:
Now don't go and include all of the characters. In my case I only needed the numbers, so I only included the numerals to be included. These characters get embedded in the SWF file and do increase file size, but not by that much. Also, notice the "Include these characters:" below. This is where you can pick the exact characters you want. I put the percentage sign in there because I want it to include the % sign in the Vibrocentric font. Look under numerals and see there is a punctuation selection, but it has 52 glyphs, I did not want 51 extra glyphs exported and waste space, so I simply put just the % to also include along with the numerals. That's it!
Flash and PHP - Send and Receive between the two [.FLA] [Back to Top]
If you do not know anything about coding in PHP I have a few resources you may want to check out. In this lesson we are using only the basics of PHP, creating variables and having output on the
PHP script that will go back and be displayed in Flash. First, open up a new project in Flash, save it as FlashToPHPandBack, or any name you feel like. I save little FLA files like this so I don't have to screw around with digging out the information I need with big projects if I forgot how I did something. On my scene, I created an input text box, and gave it an instance name of input_txt. You can use text boxes from the text box tool or use the components, I tried it with both and they both worked out the same. Create a button, or you can use a component button as I did, again, either way it does the same purpose. Set up a new frame with the name of Complete.
![]()
In the Complete frame, create a dynamic text box and name it output_txt. In Frame 1, insert this code:
¨ First I told Flash to stop, until we are ready to move forward. You can use the same variable names, or if it helps you out more, name them to something else. The first variable, var2, is a LoadVars class. A LoadVars class is an alternative to the loadVariables() function, and is used for transferring information between a Flash application and a server. If you read more about the LoadVars class you will notice a sendAndLoad method. The reason I didn't use it in this example is because I want the information that is returned to just be saved in the LoadVars class that sent out the information to the server. sendAndLoad is used to send variables and save them to a new LoadVars class.
¨ Next I create just a normal string variable. This variable is going to store the word(s) the user inputs in our text box.
¨ My submit button, when clicked, is told to do a function that , first takes the text the user input, output the variable to trace [which is only for us programmers to make sure everything is running smoothly], and sent it to my PHP script. Notice it is sending it as POST not GET, and the URL is in quotes, then the test variable is concatenated on the end. After it does that it is told to go to the frame with the label Complete. In the frame labeled Complete, insert this code:
When var2, our LoadVars class variable, is finished loading we want it trace the information back to us [Again this is just for us programmers to see], and output the information to a dynamic text box created on the scene. I have two text boxes because I was testing if their was a difference between outputting to a dynamic and a component text box [which I concluded there is not].
¨ Now for the simple PHP scripting in the test.php script on our server.
That's it. Two lines of code and a header and footer so the server knows it is PHP code. Where the returnvar and testvar variable are coming from is, look back up on the Code for Frame 1, after test.php there is a question mark, followed by testvar= and our test variable concatenated on. The question mark tells the PHP file that this is incoming information, testvar is automatically initialized and set at that point, that is why the first line of PHP code says "$returnvar=$testvar". returnvar is a new variable, which is set equal to the testvar variable that was passed to the script. echo is PHP's 'return'. Notice I set the script to echo returnvar= and our returned variable. This sets an access name in the LoadVars class back in flash. See our code on the Complete frame, we are accessing var2.returnvar, our LoadVars class and specifically the returnvar information to be displayed in our dyn_txt.text. Play around with this and you'll get it. Of course you would most likely do some sort of math in the PHP script and return something other than what was input into it, but this shows you the basics that you need to understand this lesson.
Shared Objects [Back to Top]
Shared Objects are like Flash's version of cookies. They are very helpful for things like remembering the users' name. I included this little lesson in the PHP and Flash section because it is small and would be good with use to remember parsed values from the PHP script, just as an example. Here goes the code:
¨ Create a SharedObject, where mine has the name TRPSHARE in quotes, this can be any name you wish.
¨ The IF statement is saying if share, our SharedObject, is not undefined, in other words it has information, output the information to a textbox with an instance name input2_txt. If share is null it will display undefined in the textbox.
¨ Create a submit button on the stage and tell it to do a function when clicked. This code is taking the text in the input2_txt textbox and saving it in share.data.name. share is our SharedObject, data is telling Flash to store the data, and name is any name you want. For example that line could say share.data.THISISATEST=input2_txt.text. Of course you would have to change the line of code in the IF statement to match whatever you want your data name to be.
This information is stored as a hard copy on the users computer, so this is how it relates to a cookie.
Create Bitmaps into simplified vectors [.FLA] [Back to Top]
This is very easy, and the reasons you may want to do it is for a stylized look, your preference, retro style.
Here is the image I started with:
In Flash select your picture; go to Modify > Bitmap > Trace Bitmap. This is my result after using the standard settings:
I came up with this idea, to me the more small animations on a Flash website the better, it is very appealing to me, as I notice all of the small details.
¨ I created two layers in my timeline, took my first image [the one on the right] and copied it into both layers, making sure it was lined up. On the second, Top, layer, I did the Trace Bitmap, using the standard settings and converted the image into a graphic. Then I made keyframes at 40 and 80. At 40 I turned the opacity to 100% and at 1 and 80 made the opacity of the graphic 0%. [.FLA]
Load External File with Scroll Bar [.FLA] [Back to Top]
¨ To set up your stage. Create a dynamic text box, in the properties window make sure it is set on Multiline, not single. Give your text box an instance name, mine is scroller_txt.
¨ Open the Component Window and drag over an instance of the UIScrollBar component. Drag it over the textbox until it locks into place, it will expand to the height of your textbox if you did it correctly, also the middle circle will turn bigger and darker.
¨ As far as the code goes:
Remember the LoadVars class we used in the previous lesson? Here it is again to help us out. This time we are not passing and receiving information we are just receiving the contents of our text file called external.txt. When the information is loaded into the loadText LoadVars object, we want it to do a function that outputs the text to our dynamic text box.
¨ Remember back in the SharedObjects we had the .name, this is similar, if you wanted your text file to start with &information= then the line of code in the onLoad function needs to change to: scroller_txt.text=this.information;
¨ IMPORTANT: The first line of your .txt file must be &text= or instead of text, your variable name.
Adding Methods and Properties with 'prototype' [.FLA] [Back to Top]
A prototype is no more than a function in Flash. Prototypes are methods added to all instances of the object you've created them for. Take the pop() method for any array, for example. This is sort of like a built in prototype that comes with Flash. You can add methods to arrays, movieclips, buttons, anything you can get your hands on.
In order to add methods and properties to existing objects, you need to use the prototype keyword. When you assign methods or properties, flash registers them with its inner object library, meaning that all objects of that type which exist in the movie [whether they were instantiated before the prototype declaration or after] will now possess this functionality.
Our Example: We will be adding a kill method to the standard movieclip object.
By default, Flash only allows you to remove movieclips that have been dynamically created. This method enables you to remove any movieclip, dynamic or not. It does this by taking advantage of the fact Flash only distinguishes between static and dynamic movie clips by placing the dynamic sort in a certain level bracket. So the first line of code [after function] puts our static movieclip into the dynamic level bracket.
MovieClip tells us which standard object to add this function we are creating, on to. I am calling the function kill. It swaps the static movieclips' depth to the dynamic level and removes the movieclip.
On my stage I have a picture that I turned into a movieclip object and gave it an instance name testClip_mc. You could also have a button and say onRelease - testClip_mc.kill(). The reason I can say this.kill() is because Flash already knows I am referring to the testClip_mc based on when I release the mouse, the function is called. Play around with it, check out my FLA if you are having problems. I added a few extras onto the FLA.
¨ I'm Advanced
This is the initial declaration of the fade method. The syntax is almost exactly the same as any other function declaration except we use the prototype keyword. We are going to pass two parameters: value [which is the alpha value we want to achieve] and duration [which represents the number of frames the tween will take. Next, we create an empty movieclip which will perform the tween scripting.
Here's a crafty little IF-ELSE test which looks at the current alpha value of the movieclip and then sets up a corresponding multiplier variable that we can use to manipulate the alpha value with [depending on which ease function we are going to use later on]. In this case we don't need to use the multiplier variable, but it's useful to have in case we alter our script.
Create Shapes Dynamically [Back to Top]
To use the drawing methods, you must start with a movieclip object. The movieclip acts as the point of reference for all of your drawing coordinates. So if your movieclip is anchored at the top-left corner of the stage (x0,y0), all of the drawing coordinates are relative to that registration point. It acts as a 'pen tip', it stays anchored and draws until its end point. There are three methods to draw lines and curves:
moveTo() - Sets the beginning point of your line or curve.
lineTo()/curveTo() - Sets the end points and in the case of curves, determines curvature.
lineStyle() - Change characteristics of stroke, point, size, color and transparency.
clear() - Erases drawings made in the movieclip.
Creating a curve [.FLA] [Back to Top]
First you create an empty movie clip on the root, I called mine 'pen' and I put it on layer 1. You then take the instance name and assign a lineStyle - mine is 2 pixels thick, a red color and 100% alpha. The moveTo method moves the 'pen' to the start location of where to draw, no line is drawn, it is simply moved to that location. The curveTo method is what does the drawing, the first 2 parameters [300,100] is the control point, it is an anchor that the curve is created around. The second 2 parameters is the end point of the curve.
Perfect Circle [.FLA] [Back to Top]
It isn't very important how it works, but this gives you more of an idea of the possibilities of drawing in Flash. It is VERY IMPORTANT that you include a LINESTYLE method onto your empty movie clip, or else NOTHING will draw!
Square [.FLA] [Back to Top]
The 'with' action is like a loop. It cuts out the annoying repetitive typing. Check out the Macromedia Actionscript Dictionary Definition.
Dynamic Line Example
[.FLA] [Back to Top]
I created a movie with 4 buttons that are included in Flash. Window > Other Panels > Common Libraries > Buttons. I gave each of them instance names of circle1, circle2, circle3, and circle4 in a clockwise rotation. I then went to the first frame of the movie and inserted the code above.
Dynamic Fills and Gradients [.FLA] [Back to Top]
Fills are relatively easy, gradients are more difficult and require knowledge of arrays. First we will start with something basic - we will create a box and then fill it with a dark blue color.
A dark blue box with a red outline is created. You can leave the lineStyle method out when using fills, and it will, in effect, create an invisible outline and fill the middle with the color you use in beginFill.
Gradients - more difficult and here's why. You must create several arrays, and you need many parameters, gradient type, colors array, alphas array, ratios array and matrix type. Check out Macromedia's explaination.
Gradient Type - Radial or linear [Radial starts from the middle and goes out to the edges, linear starts from the left and goes to the right]
Colors array - You must create an array to put hex codes for the colors in the order which you want them to appear [Our example will go from Blue to Red]
Alphas Array - Also an array that controls the controls the alpha from left to right
Ratios Array - Contains values, 0-255, that determine how they will mix. The ratio defines the width the color is at 100%
Matrix Type - Box or Matrix
Check out Macromedia's explaination.
Dynamic mask [setMask] [.FLA] [Back to Top]
It is a simple line, but you may be thinking, that's great but what do I do with it? The one idea I came up with is to make sorts of imaging effects. It combines a few things, creating a dynamic grid, simple flash skills, and the setMask method you've just learned.
-Create a new Flash movie, import a picture to the stage and have its X and Y at (0,0), hit F8 and turn the picture into a movieclip, then give it an instance name, I used 'tbMask_mc'.
-Create a new movieclip symbol, this is going to be your 'effect' for the picture. I am going to have mine be long and thin, like a window blind. 500px x 10px. *Make sure your animation registers at (0,0)! After you create something, add stop(); in the actions of the last frame.
- Back to the main scene, I created a new layer called 'code' to store all of my code. My image is 124px tall, so that means I will need 13 of my mask movieclips to see the whole image. I will take that number 13 and note it in my head, because I am going to need it when I create the for loop.....but right before we get to that, remember the linkage? You need to set the linkage on the effect clip, right click on the movieclip in the library and click linkage - I gave mine an identifier name of 'effect_mc'
I hope this is sparking ideas in your head on how to use this.
Dynamic Grid [.FLA] [Back to Top]
Remember when we used actionscript to create a small grid? Well here is a dynamic grid for using in image effects, or whatever else you can think of.
- First create an effect movieclip, maybe like that blind effect we did in the last section, give it an instance name and identifier name [in the linkage option], my instance name is 'mc_IN' and its identifier name is 'effect_mc'. Make sure to add stop(); to the actions in the last frame of the effect clip.
- Create a movieclip that is as big as the Flash movie, give it an instance name - mine is 'border_mc'. Change the alpha to 0% after setting the instance name, the option is in that same window.
There are two ways to go about this, you can use duplicateMovieClip or attachMovie. If you use duplicateMovieClip you use the instance name you gave your effect movie, and it must be on stage, at (0,0) to not mess up your image effect. If you use attachMovie, like I will be doing, you use the identifier name that you set in the linkage window. Move the movie off the view of the stage [so our script can use it in our variables - there are other ways to go about it, this is just how I decided to do it], and the attachMovie method gets the movie from the library to recreate it on stage.
Fading Boxes - Show Image [.FLA] [Back to Top]
There are some new techniques on how to create a grid and other actionscript writing techniques. This will give you more ideas on how things work and help you develop code later on.
Sound effects Dynamically [Back to Top]
This creates a new sound, in actionscript, which we will be using throughout all of this section. The second line takes a sound from the library and attaches it to the mySound variable. The 'fromLibrary' is the identifier name for that sound, in the linkage window. To get our sound to start playing, add mySound.start(); to the code.
Now that you have been introduced, we will put all of these methods, properties and event handlers to use.
There are also 3 methods I didn't cover: getPan(), getTransform() and getVolume(), they all return the value you have set, or the default value if you have not set anything.
The Sound Player [.FLA]
Frame 1 Code
Volume Slider Code
Pan Slider Code
Play Button Code
Stop Button Code
Movie [.FLA] [Back to Top]
Concatenating Variables and Dynamic Referencing [.FLA] [Back to Top]
Concatenate - To array (string of characters) into a chained list.
I am going to show you concatenation and dynamic referencing together in the example below. I think if you are concatenating you will be referencing dynamically and vice versa, you don't normally use just one. The example below is a line that you could have in a FOR loop, the variable counter could be the step variable for the FOR loop.
I created this store not too long ago, and I noticed I had a lot of "BUY NOW" buttons. I didn't want to go thru and script all of them with the same code, I thought there must be a way to write a loop that could do it all for me - and after much trial and error, there is. What I will be doing is making all of the "BUY NOW" buttons start to drag when clicked and then stop when released.
Actionscript Easing [.FLA] [Back to Top]
Flash MX has a built in tween class. The setup is relatively easy, but the line of code is lengthy. Here are the parameters and the meanings:
object - Reference name of the movieclip to tween
property - A string value of the property you wish to tween
function - Name of the easing class to use
begin - Number, of above property you would like to start the tween with
end - Number, of above property you would like to end the tween with
duration - Number of frames of seconds the tween should last
use seconds - Boolean indicating whether the above duration is in frames (false) of seconds (true) - If not included, FALSE is the default
There are 6 categories of a tween - Strong; Back; Elastic; Bounce; Regular; None
There are 4 types - easeIn; easeOut; easeInOut; easeNone
The entire easing function should look like: "mx.tranisitons.easing.Bounce.easeOut"
Let's take a movieclip with an instance name "ball_mc" from an x position of 20 to an x position of 380 in a half a second with a bounce:
It is also a good idea to put this whole line into a variable so you can use the event handlers, etc. For example if you set this line in a variable called ballTween, you can do an event handler with onMotionFinished
In my example I have 7 orbs. I Imported them to the library and made them all movieclip symbols. I set the linkage identifier name to match the orb, orb1_mc, orb2_mc, etc.
The setup function gets the 7 orbs from the library and attaches them to the stage with a random x and y value.
The setup function is called.
I tried to mix everything up and give each of the orbs a different property to manipulate, different easing, start, finish and time.
This last one is assigned to a variable called ballTween, so that I could use the event handler below "onMotionFinished," which is an undocumented handler, and then use an undocumented property, "yoyo." This simply reverses the animation.
Embedded below is my movie for this section:
-The only thing I changed was I moved all of the script that was outside of the setup function, into it and I put a button to execute the setup function when clicked, and turn invisible.
If you want to really get into dynamic animation through Actionscript, I have a book just for you. It's called 'Robert Penner's Programming Macromedia Flash MX' - ISBN# - 0-07-222356-1
Thank you very much for downloading, I hope my Flash Quick Reference Notes have helped you out and given you ideas. As always, email me for new sections to put in for version 2, or if you have some code you created and would like in Flash Quick Reference Notes v2, let me know!
TJ Nevis - WhyWorkForever.org