Home Contact RSS

Actionscript to Reference Dynamically created instances Flash Movie Clip | Array notation | Tutorial

Overview:

Often I’ve had some dynamically created movieclip and then wanted to reference it in my code. This is hard to do if it is named dynamically as well, such as with an incrementing variable. If you use one (or more) variable to name an instance in runtime, you can’t always know what it will be called.
There are two ways (that I know of) to reference these clips, one is the array operator [] and the other is using the eval() function is as2 (but I’ve noticed that as3 has removed the eval function, so I’d recommend getting used to array notation).

Steps:

  1. Create the object dynamically (or with a variable) (_root.myClip.duplicateMovieClip (”myClip”+i, i);)
  2. Reference it with either array notation or with eval. (thisOne = _root["myClip"+i];) or (eval(”myClip” + i))

Example:

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)
I create some movie clips dynamically using a for loop and name them all incrementally with a variable (myClip+i). But then i want to refer to some of them later, specifically. I don’t know what they are named though. They are all myClip1 myClip2 myClip3 and so on. I can use array notation to reference these (or eval). I’ve found it’s easiest to create a reference to the name once and then use it to refer to the clip I want. I imagined a scenario that when you click a mc you would want a different one to be moved. So clicking myClip3 moves myClip4 and so on. I’ve made it wrap so that 5 moves 1… They change the _y property of the next to match the one that’s clicked. Clicking the refresh button will loop through all the clips and (this time using eval) randomize the y coordinate.

Actionscript:

  1. var myLimit = 5;
  2. //myClip._visible = false;
  3.  
  4. for(var i=1; i<=myLimit; i++) {
  5. _root.myClip.duplicateMovieClip ("myClip"+i, i);
  6.  
  7. thisOne = _root["myClip"+i];
  8. thisOne._y = Math.random() * Stage.height;
  9. thisOne._x = Stage.width/(myLimit+1) * i ;
  10. thisOne.id = i;
  11. thisOne.idDisplay.text = i;
  12.  
  13. thisOne.onRelease = function() {
  14. nextOne = (this.id == myLimit) ? _root["myClip"+1]: _root["myClip"+(this.id+1)];
  15. nextOne._y = this._y;
  16. }
  17. }
  18.  
  19. myClip.onRelease = function() {
  20. for (var i=1; i<=myLimit; i++) {
  21. eval("myClip" + i)._y = Math.random() * Stage.height;
  22. }
  23. }

Download:

Source fla file: download

Reference:

Nuno Mira shows a good example:

this.createEmptyMovieClip("outer_mc", 1); // create a mc called outer_mc
outer_mc.createEmptyMovieClip("inner_mc", 1); // create a mc called inner_mc inside outer_mc
// 3 different ways of targeting inner_mc
trace(outer_mc.inner_mc);
trace(outer_mc["inner_mc"]);
trace(this["outer_mc"]["inner_mc"]);
// all output _level0.outer_mc.inner_mc

TheCanadian@Kirupa states it nicely:
The Problem
How can I reference objects using a variable? This is commonly a problem with dynamically created buttons:

ActionScript Code:
for(i = 0; i < 3; i++) { button+i.someProp = "Hello World!"; //error }

The Answer
This is probably the question that gets asked the most. Referencing an object with a variable is done using something called associative array referencing or array notation. The fundamental concept behind this is that:

ActionScript Code:
myObject.prop = "value"; //and myObject["prop"] = "value";

Are the same thing. Associative array referencing follows the pattern of scope["prop"] where scope is the object which contains the property and prop is the name of the property you wish to reference. Save appearance, array notation works in exactly the same way as dot notation.

Going back to the original, problematic, example, the correct code would look like this:

ActionScript Code:
for(i = 0; i < 3; i++) { this["button"+i].someProp = "Hello World!"; }

The button string is concatenated (joined) with the i variable, forming a new reference with each iteration of the loop. First button0, then button1, et cetera.

That’s the quick, but some of you may think that that’s the same notation that is used with instances of the Array class. While that is true, the converse is actually more correct: Array instances use that notation.

Arrays are exactly the same as generic Objects, the only difference is that they have a collection of methods to deal with their properties. And because they require a need for organization, they typically only use numerical properties. Given the array myArray = ["a", "b", "c"], you could theoretically reference the indices using myArray.0, myArray.1 and myArray.2. The reason that we must use array notation is because the compiler doesn’t allow the reference of numerical properties with dot notation.

Tags: , , , , , ,

Brownian Movement in Actionscript | Random Motion Tutorial

Overview

Having things drift around or move randomly has always interested me. Having an animation that is never going to be the exact same thing is very exciting. The focus turns from key-ing exact animations to programming a feel and letting the animations take car of themselves! One type of seemingly random motion is Brownian motion. This gives the movement a random walk wandering look, it will just drift around with no real direction.

Steps

Step by step this process is very simple. In every random motion you create the random number, and apply it to the property. If you want constant random action (motion) rather than just random placement, you repeat that over and over.

  1. Make a random number (random velocity)
  2. Apply the random number (apply velocity to property)
  3. Repeat (if needed)

To create a random number in actionscript, use Math.random(), which creates a random number between 0 and 1. Usually you’ll want to scale it to a range you want to use. If you want a number between 50 and 100, you’d do Math.random() * 50 + 50. *50 to scale it to 0-50, and + 50 to bring it up to 50 - 100. Also if we want to get a 100 range around 0 (-50 - 50) we would do Math.random() * 100 - 50. In the code below I’ve abstracted this to Math.random() * this.randomRange - this.randomRange/2.

Example

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)
Here I’ve got dots created and placed randomly, with randomly set scale and alpha. On every frame each dot has a random velocity applied to it’s x and y coordinates.
The yellow dot is the simple example (code below) and the rest are included in the complex example below.

Actionscript

Simple Example:

  1. dotOne.onEnterFrame = function() {
  2. //create a random velocity for x and y direction
  3. vx = Math.random() * 4 - 2;
  4. vy = Math.random() * 4 - 2;
  5. //apply velocity to coordinates
  6. this._x += vx;
  7. this._y += vy;
  8. }

Complex example:

  1. var numDots = 25;
  2. var randomRange = 1;
  3.  
  4. for(var i=1; i&lt;=numDots; i++) {
  5. //create a new dot
  6. duplicateMovieClip(_root.dot, "dot"+i, i);
  7. //save it's ref path for use
  8. theDot = _root["dot"+i];
  9. //give it random coordinates
  10. theDot._y = Math.random() * Stage.height;
  11. theDot._x = Math.random() * Stage.width;
  12. //give each dot a distinct random range
  13. theDot.randomRange = i/numDots;
  14. //give each dot a random size and transparency
  15. theDot._xscale =
  16. theDot._yscale =
  17. theDot._alpha =  i*4;
  18.  
  19. //apply this code on the dot every frame
  20. theDot.onEnterFrame = function() {
  21. //create a random velocity for x and y direction within the specifically created random range for each dot
  22. vx = Math.random() * this.randomRange - this.randomRange/2;
  23. vy = Math.random() * this.randomRange - this.randomRange/2;
  24. //apply velocity to coordinates
  25. this._x += vx;
  26. this._y += vy;
  27. }
  28. }

Download

randomMotion.fla

Tags: , , , , , , , ,

Style htmlText with CSS in your Actionscript | Flash/CSS Tutorial

Overview

In flash you can have text areas that are rendered as html. You can also apply formatting styles to this html. This will show a simple example on how to apply css to html text in flash. I’ll do a simple anchor tag style to show you the ropes. We’ll style a link to be underlined and then when you hover or mouse over it, we’ll change the color. It’s a design style that is widely used online in html, but flash doesn’t natively do it. As a matter of fact, flash doesn’t even natively underline links.

Steps

  1. Import TextField.StyleSheet
  2. create a style sheet object: var myCSS:StyleSheet = new StyleSheet();
  3. Specify your styles: myCSS.setStyle(”a:link”, {color:’#0000CC’,textDecoration:’underline’});
  4. Ensure that the text box is html enabled: myHTML.htmlText = myHTMLText;
  5. Apply the style sheet object to your html text box: myHTML.styleSheet = myCSS;

Example

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Actionscript

  1. import TextField.StyleSheet;
  2.  
  3. myHTMLText = "
  4. <h1>HTML Text (sample header)</h1>
  5. Here is some <em>sample</em> <strong>html text</strong> "+
  6. "filling a text box <a href="http://blog.circlecube.com">this link to circlecube</a> and example headers"+
  7. "<h1>Header h1</h1><h2>Header h2</h2>";
  8.  
  9. //create and initialize css
  10. var myCSS:StyleSheet = new StyleSheet();
  11. myCSS.setStyle("body", {fontSize:'15',color:'#000066'});
  12. myCSS.setStyle("h1", {fontSize:'25',color:'#000000'});
  13. myCSS.setStyle("h2", {fontSize:'19',color:'#000000'});
  14. myCSS.setStyle("a:link", {color:'#0000CC',textDecoration:'none'});
  15. myCSS.setStyle("a:hover", {color:'#0000FF',textDecoration:'underline'});
  16. myCSS.setStyle("b", {fontWeight:'bold'});
  17. myCSS.setStyle("em", {fontWeight:'bold'});
  18.  
  19. //ensure html support and apply css to it
  20. myHTML.html = true;
  21. myHTML.styleSheet = myCSS;
  22. myHTML.htmlText = myHTMLText;
  23. //resize the textbox to exact fit the text in it
  24. //myHTML.autoSize = "left";

Download

open source flashhtmlcss.zip

Tags: , , , , , ,

Calling actionscript functions through HTML text | asfunction Tutorial

Add this to the list of things I should have already known!

Story

I’ve got an html enabled text box and was trying to devise a way that I could have a hyperlink anchor tag not link to a webpage but actually do something flash. It didn’t seem possible, and I looked through all the different html css combinations I could think of. I finally resorted to trying to use some component like Deng or FlashML. FlashML had a smaller footprint and seemed to do more what I wanted, so I started investigating it. To my dismay, the support for it was few and far between. I found an older version that came with an example file and then a newer one with some documentation but no example and I found no examples any where else. So Lee, if you ever read this, some new examples could be nice. In the documentation I was reading about a functino called AddASFunction and the example html line was very interesting:

  1. <a href="asfunction:doSomething, startFrame">link</a>

I started looking through the rest of the documentation to find this asfunction use. But all it had was:
The href attribute can include the asfunction string which allows the link provided by the anchor to call a function in Flash. More of this can be found within the addASFunction definition in this help document.
I knew I was on to something, asfunction. So a quick google search and I found the official doc! I was shocked that I had the tool to do this the whole time! Well, shocked and feeling like an idiot for never having heard of it before. I knew it could be done somehow, but had no idea that it was already a feature of htmlText in flash! So now that you know my embarrassing story, I’ll let you in on the secret.

Overview

In flash, you can allow html text within a text area. You either set the text html property as true with actionscript (my_txt.html = true;) or click the ‘Render text as HTML’ button in the properties window of the text area. You cannot enable html text on static text areas however. You can have links and various html elements (but not full html). Usually links have a url in the href attribut of the anchor tag, but flash will read a special value of ‘asfunction’ which specifies that an actionscript function is to be called rather than a url. The correct syntax is asfunction followed by a colon and then the name of the actionscript function to be called, optionally followed by a comma and a possible single argument to be passed to the specified function (href=”asfunction:functionName,argument”).

Steps

  1. Enable html in the text box.
  2. Have your function (ex: functionName) ready to be called from the html link.
  3. Give the href attribute of the anchor tag a property “asfunction:functionName,argument” Notice that the official documentation calls for spaces after punctuation, but any space you put after the colon (:) or comma (,) will be sent to the function in the argument, or will expect a space in the function name and give you a headache.

Example

In this example I’ve got an html enabled text box with 4 links. The first is a standard link (I hope you know what that does). The next link calls an actionscript function with asfunction. The third link sends a single argument to another function. And the last link sends multiple arguments to yet another function. Wait! Multiple arguments? I thought I said only one was supported, well this example shows how to send multiple arguments disguised as a single param and parse them. It’s pretty simple actually.
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Actionscript

  1. import TextField.StyleSheet;
  2.  
  3. myHTMLText = "Sample text in an html enabled text box. "+
  4. "Here's a normal link to <a href='http://blog.circlecube.com' target='_blank'>circlecube</a>! "+
  5. "And some more links that don't go anywhere, they call functions in actionscript. "+
  6. "<a href='asfunction:clickLink'>Click this one</a>, "+
  7. "to see the actionscript function called from the html text box. "+
  8. "<a href='asfunction:clickWithArg,Click this too'>Click this too</a>, "+
  9. "and see that the actionscript function you're calling can have an argument passed to it. And "+
  10. "<a href='asfunction:clickWithMultipleArgs, one,two,three args'>click me three and four</a> "+
  11. "to see a way to send multiple arguments from your htmlText. "+
  12. "Also, one last example of what not to do "+
  13. "<a href='asfunction: clickWithArg, arg with preceding space'>Click for nothing</a>";
  14.  
  15. //create and initialize css
  16. var myCSS:StyleSheet = new StyleSheet();
  17. myCSS.setStyle("a:link", {color:'#0000CC',textDecoration:'none'});
  18. myCSS.setStyle("a:hover", {color:'#0000FF',textDecoration:'underline'});
  19.  
  20. myHTML.html = true;
  21. myHTML.htmlText = myHTMLText;
  22. myHTML.styleSheet = myCSS;
  23.  
  24. //function to be called from html text
  25. function clickLink() {
  26.     giveFeedback("Hyperlink clicked!");
  27. }
  28.  
  29. //another function to be called from html text, recieves one argument
  30. function clickWithArg(arg) {
  31.     giveFeedback("Hyperlink clicked! Argument: "+arg);
  32. }
  33.  
  34. //a simple trick to allow passing of multiple arguments
  35. function clickWithMultipleArgs(args) {
  36.     giveFeedback("Hyperlink clicked! Multiple arguments passed: "+args);
  37.     argArray = new Array();
  38.     argArray = args.split(',');
  39.     for (i = 0; i < argArray.length; i++) {
  40.         giveFeedback("arg "+i+": "+argArray[i]);
  41.     }
  42. }
  43.  
  44. function giveFeedback(str) {
  45.     trace(str);
  46.     feedback.text += str +"\n";
  47.     feedback.scroll = feedback.maxscroll;
  48. }

HTML

  1. Sample text in an html enabled text box.
  2. Here's a normal link to <a href='http://blog.circlecube.com' target='_blank'>circlecube</a>!
  3. And some more links that don't go anywhere, they call functions in actionscript.
  4. <a href='asfunction:clickLink'>Click this one</a>,
  5. to see the actionscript function called from the html text box.
  6. <a href='asfunction:clickWithArg,Click this too'>Click this too</a>,
  7. and see that the actionscript function you're calling can have an argument passed to it. And
  8. <a href='asfunction:clickWithMultipleArgs, one,two,three args'>click me three and four</a>
  9. to see a way to send multiple arguments from your htmlText.
  10. Also, one last example of what not to do
  11. <a href='asfunction: clickWithArg, arg with preceding space'>Click for nothing</a>

Download Source

asfunction.zip

Tags: , , , , , , ,

Intro to Flashvars | Passing variables to actionscript from the html embed | Tutorial

I’ve had a couple special requests to explain flashvars and how to use it and show it in action.

Overview

The property “FlashVars” can be used to import root level variables to the flash movie or swf. The flashvars propery is used in codes for embedding flash in the html page. The string of variables passed in as flashvars, will be imported into the top level of the movie when it is first instantiated. Variables are created before the first frame of the SWF is played. The format of the string is a set of name=value combinations separated by ampersand (&) symbols.

Steps

  1. Include the flashvars property in your embed codes and voila! You have these variables to use in your swf.
  2. That’s the one step

Code

HTML Embed Codes

  1. Here's some sample embed codes, including object and embed tags:
  2. <object width="540" height="240" title="sample">
  3.   <param name="movie" value="flashvarsTutorial.swf" />
  4.   <param name="flashvars" value="var1=here&var2=are&var3=my&var4=flashvars" />
  5.   <embed src="flashvarsTutorial.swf" flashvars="var1=here&var2=are&var3=my&var4=flashvars" type="application/x-shockwave-flash" width="540" height="240" ></embed>
  6. </object>

Actionscript using flashvars

  1. //flashvars="var1=val1&var2=val2&var3=val3";
  2.  
  3. display("var1 = "+ var1);
  4.  
  5. display("var2 = "+ var2);
  6.  
  7. display("var3 = "+ var3);
  8.  
  9. display("var4 = "+ var4);
  10.  
  11. function display(todisplay:String){
  12.   feedback.text += todisplay+"\n";
  13.   trace(todisplay);
  14. }

Example

Page 1 (var1=val1&var2=val2&var3=val3)
Page 2 (var1=here&var2=are&var3=my&var4=flashvars)

Source

Download the html files and the fla and swf in this flashvars.zip

Tags: , , , , , ,

Going Natural 3.0 at StomperNet

Here’s a new site and series from StomperNet called Going Natural 3!
It’s a bit of free videos made and released to showcase the talents and business of what StomperNet is about and what they do for their clients. They’re ‘moving the freeline’ so to speak…

The first video series begins with Dan Thies talking about his ‘Crazy Theory’ for AdWords.

On signing in there are a couple BONUS videos for you as well. So go check them out as well!
Watch Going Natural 3 - Adwords Triangulation Method and more

This site contains the latest flash video player built by yours truly. I also did the design of the site: involving html, css, php, javascript and dealing with drupal too!

Tags: , , , , , , , , , , , ,

Shared Object - utilizing the Flash cookie

Overview

The Shared Object is like a cookie for flash. It lets flash store some data on the local machine, so between sessions it can remember things. Learn more from wikipedia.
Shared Objects are used to store data on the client machine in much the same way that data is stored in a cookie created through a web browser. The data can only be read by movies originating from the same domain that created the Shared Object. This is the only way Macromedia Flash Player can write data to a user’s machine. Shared Objects can not remember a user’s e-mail address or other personal information unless they willingly provide such information.

I’ve seen many Local Shared Object tutorials and examples, which have users input their name and/or hometown and other filler data. But I wanted to show how to creatively incorporate shared objects into interactions. So I’ve thrown in many simultaneous examples including the uber-simple ‘input your name and I’ll remember it’ approach. I hope I didn’t throw in so much that it got confusing… just let me know if you have any questions or anything is unclear. Keeping it simply and broad there’s only a few things to know about Shared Objects.

Steps

    Simply put there are only a couple things to worry about with Local Shared Objects

  • Create them.
    • As in create the shared object
  • Write them.
    • As is write to the shared object
  • Set them.
    • As in setting variables in the shared object
  • Get them.
    • As in getting variables back out of the shared object
  • Clear them.
    • As in clearing the shared objec

Actionscript

here’s samples on how to do each of those

  1. /* Create them. */
  2. //make Local Shared Object named myLocalSO(in as) called "myflashcookie" on disk
  3. var myLocalSO:SharedObject = SharedObject.getLocal("myflashcookie");
  4.  
  5. /* Write them. */
  6. //flush the SO, write the SO to disk
  7. myLocalSO.flush();
  8.  
  9. /* Set them. */
  10. //set key's value to specified value in SO
  11. //key is the name of the data
  12. //val is key's value
  13. function setVal(key, val) {
  14. myLocalSO.data[key] = val;
  15. trace(key +" set to "+val);
  16. /* including writing to Shared Object in the setter function */
  17. //flush the SO, write the SO to disk
  18. myLocalSO.flush();
  19. }
  20. /* Get them. */
  21. //get key's value from SO
  22. function getVal(key) {
  23. return myLocalSO.data[key];
  24. trace(myLocalSO.data[key] +" received from "+key);
  25. }
  26. /* Clear them. */
  27. myLocalSO.clear();

Example

here’s my colorful example.
The purple/yellow circle is draggable, so place it where you want it. Enter your name and age in the input boxes. Press the center red ‘Set cookie’ button to copy those values to the shared object that is on your computer now. The red transparent circle represents the cookie positions. You can position the purple/yellow circle from the cookie contents with the dark green ‘Position from cookie’ button, or position it randomly with the blue ‘Position randomly’ button. Erase the cookie with the orange ‘Erase cookie’ button. Toggle easing (animation) with the Bright green button (which changes to dark red when off), it tells the current mode of ease. I have the cookie coordinates displayed and the current coordinates of the purple/yellow circle also displayed.
The cookie includes a date object, which is used to calculate the age of the cookie (watch it reset when you erase the cookie (orange button)).
The ‘All Time Visit’ stat is the only thing that does not get reset when you erase the cookie,

and source code:

  1. ////////////////////////  Initialize variables  ///////////////////////
  2.  
  3. //make Local Shared Object named myLocalSO(in as) called "myflashcookie" on disk
  4. var myLocalSO:SharedObject = SharedObject.getLocal("myflashcookie");
  5. //speed var for easing
  6. var speed = 3;
  7. var w = myCircle._width/2;
  8. //toggle var for easing
  9. var ease = true;
  10. //as var to store alltime cookie
  11. var allTimeVisitCount=0;
  12. countVisit();
  13. cookieFeedback();
  14. //line style for tracing movement
  15. lineStyle(1, 0, 50);
  16.  
  17.  
  18. ////////////////////////  Functions  ///////////////////////
  19.  
  20. //set key's value to specified value in SO
  21. //key is the name of the data
  22. //val is key's value
  23. function setVal(key, val) {
  24.   myLocalSO.data[key] = val;
  25.   trace(key +" set to "+val);
  26.   //flush the SO, write the SO to disk
  27.   myLocalSO.flush();
  28. }
  29. //get key's value from SO
  30. function getVal(key) {
  31.   return myLocalSO.data[key];
  32.   trace(myLocalSO.data[key] +" received from "+key);
  33. }
  34.  
  35. function countVisit() {
  36.   //if first visit
  37.   if (getVal('visitCount') == undefined) {
  38.     //create date for now and store in cookie
  39.     var todayDate:Date = new Date();
  40.     setVal('date', todayDate);
  41.     trace("creating date");
  42.     //start/reset counting visits
  43.     var visitCount = 0;
  44.     //notice allTimeVisitCount is not reset, but stored still as a var in actionscript
  45.   }
  46.  
  47.   //not first visit
  48.   else {
  49.     visitCount = getVal('visitCount');
  50.     allTimeVisitCount = getVal('allTimeVisitCount');
  51.   }
  52.   //increment visit counter
  53.   setVal('visitCount', visitCount+1);
  54.   setVal('allTimeVisitCount', allTimeVisitCount+1);
  55.   //feedback of visit counting
  56.   visitsFeedback.text = getVal('visitCount');
  57.   allTimeVisitsFeedback.text = getVal('allTimeVisitCount');
  58. }
  59. //feedback of cookie contents
  60. function cookieFeedback() {
  61.   //in defined print coordinate contents
  62.   cookiex.text = getVal('circleX') == undefined ? "no cookie" : getVal('circleX');
  63.   cookiey.text = getVal('circleY') == undefined ? "no cookie" : getVal('circleY');
  64.  
  65.   //if not easing assign coordinates from cookie
  66.   if (!ease) {
  67.     myCookie._x = getVal('circleX');
  68.     myCookie._y = getVal('circleY');
  69.   }
  70.   //set target to cookie coordinates
  71.   else {
  72.     ctargetx = getVal('circleX');
  73.     ctargety = getVal('circleY');
  74.   }
  75.   //if name then trace cookie contents
  76.   if (getVal('name') != undefined) {
  77.     visitorFeedback.text = "Returning Visitor";
  78.     nameInput.text = getVal('name');
  79.     ageInput.text = getVal('age');
  80.   }
  81.   //no name then a new visitor
  82.   else {
  83.     visitorFeedback.text = "First Time Visitor";
  84.     nameInput.text = "";
  85.     ageInput.text = "";
  86.   }
  87.   calculateCookieAge();
  88. }
  89. function calculateCookieAge() {
  90.   //make a date now
  91.   todayDate = new Date();
  92.   //get the cookie's stored date
  93.   cookieDate = getVal('date');
  94.   //difference between two dates
  95.   cookieDateAge = Math.floor(todayDate - cookieDate);
  96.   //convert miliseconds to a timecode
  97.   cookieAge.text = msToTimeCode(cookieDateAge);cookieDateAge;
  98. }
  99.  
  100. //convert miliseconds to a hh:mm:ss
  101. function msToTimeCode(ms) {
  102.   //make sure value is within bounds. if a number grater than zero and less than the duration of video
  103.     if (isNaN(ms) || ms< 0) {
  104.         ms = 0;
  105.     }
  106.   //find seconds
  107.   var sec = ms/1000;
  108.   //find minutes
  109.     var min = Math.floor(sec/60);
  110.   //adjust seconds
  111.     sec = sec - min*60;
  112.   //find hours
  113.   var hour = Math.floor(min/60);
  114.   //adjust minutes
  115.   min = min - hour*60;
  116.   //floor seconds down to whole number
  117.   sec = Math.floor(sec);
  118.   //make time code with hours
  119.   if (hour == 0) {
  120.     if (sec < 10) {
  121.           sec = "0"+sec;
  122.       }
  123.       if (min < 10) {
  124.           min = "0"+min;
  125.       }
  126.       var tc = min+":"+sec;
  127.   }
  128.   //make time code without hours
  129.   else {
  130.     if (sec < 10) {
  131.           sec = "0"+sec;
  132.       }
  133.       if (min < 10) {
  134.           min = "0"+min;
  135.       }
  136.       var tc = hour+":"+min+":"+sec;
  137.   }
  138.   return tc;
  139. }
  140.  
  141.  
  142.  
  143.  
  144.  
  145. //////  Actionscript attached to Objects/handlers  //////////
  146.  
  147. //place data on stage into cookie (circle coordinates and input text)
  148. setCookieButton.onRelease = function() {
  149.   setVal('circleX', myCircle._x);
  150.   setVal('circleY', myCircle._y);
  151.   setVal('name', nameInput.text);
  152.   setVal('age', ageInput.text);
  153.   //update the display on stage
  154.   cookieFeedback();
  155. }
  156. //make random coordinates on stage
  157. randomButton.onRelease = function() {
  158.   //if not easing assign coordinates to myCircle
  159.   if (!ease) {
  160.     myCircle._x = Math.random() * (Stage.width - w);
  161.     myCircle._y = Math.random() * (Stage.height - w);
  162.   }
  163.   //if easing assign coordinates to myCircle's target coords
  164.   else {
  165.     targetx = Math.random() * (Stage.width - w);
  166.     targety = Math.random() * (Stage.height - w);
  167.   }
  168. }
  169.  
  170. myCircle.onPress = function() {
  171.   this.startDrag();
  172.   dragging = true;
  173.   lineStyle(1, 200, 30);
  174. }
  175.  
  176. myCircle.onRelease = myCircle.onReleaseOutside = function() {
  177.   targetx = this._x;
  178.   targety = this._y;
  179.  
  180.   lineStyle(1, 0, 50);
  181.  
  182.   dragging = false;
  183.   this.stopDrag();
  184. }
  185.  
  186. myCircle.onEnterFrame = function() {
  187.   //print position feedback
  188.   currentx.text = this._x;
  189.   currenty.text = this._y;
  190.   //if eas move to target
  191.   if (ease) {
  192.     if (!dragging) {
  193.       moveTo(this._x+w, this._y+w);
  194.       this._x+=(targetx-this._x)/speed;
  195.       this._y+=(targety-this._y)/speed;
  196.     }
  197.     //draw line
  198.     lineTo(this._x+w, this._y+w);
  199.   }
  200. }
  201.  
  202. myCookie.onEnterFrame = function() {
  203.   //if ease move cookie to target
  204.   if (ease) {
  205.     this._x+=(ctargetx-this._x)/speed;
  206.     this._y+=(ctargety-this._y)/speed;
  207.   }
  208.   calculateCookieAge();
  209. }
  210.  
  211. //Position from Cookie
  212. cookieButton.onRelease = function() {
  213.   //if not easing set coordinates from cookie
  214.   if (!ease) {
  215.     myCircle._x = getVal('circleX');
  216.     myCircle._y = getVal('circleY');
  217.   }
  218.   //if easing set target coordinates from cookie
  219.   else {
  220.     targetx = getVal('circleX');
  221.     targety = getVal('circleY');
  222.   }
  223. }
  224. easeBtn.onRelease = function () {
  225.   //toggle easing
  226.   ease = !ease;
  227.   //advance the frame of this button...
  228.   this.play();
  229. }
  230. clearCookieBtn.onRelease = function() {
  231.   //clear the cookie (swipe all data)
  232.   myLocalSO.clear();
  233.   //restart visit count
  234.   countVisit();
  235.   //read cookie and give feedback
  236.   cookieFeedback();
  237. }

Source

download the source for this example: sharedObject.fla

Tags: , , , , , , ,

XML and Flash Actionscript made Easy | Parse XML to Object | Tutorial

XML and flash is something that always seemed to be more complicated than it needed to be. Then I had an idea to parse the xml nodes into actionscript as objects, that would make working with xml tons easier for me, I could just parse it once and then forget about the xml, I could refer to something with the familiar dot syntax rather than worry about firstChild and nextChild and so forth…

And then I found someone who’d already done that with XML2Object.as, here it is:

XML@Object.as Class

Actionscript Class:

  1. //////////////////
  2. // - Derived from code written by Alessandro Crugnola - http://www.sephiroth.it/file_detail.php?id=129#
  3. // - Refactored and documented by Phil Powell - http://www.sillydomainname.com
  4. // - 25 July 2006 - Added helper method to sanitize Windows line breaks.
  5. //////////////////
  6. // Convert an XML object to an object with nested properties.
  7. //
  8. // Example usage:
  9. //
  10. //   import net.produxion.util.XML2Object;
  11. //   var contentObj:Object;
  12. //   var xml:XML = new XML();
  13. //   var xmlLoaded = function( success:Boolean )
  14. //   {
  15. //    if( success )
  16. //    {
  17. //     contentObj = XML2Object.deserialize( this );
  18. //     this['timeline'].play();
  19. //    }
  20. //   }
  21. //
  22. //   xml.ignoreWhite = true;
  23. //   xml['timeline'] = this;
  24. //   xml.onLoad = xmlLoaded;
  25. //   xml.load( 'some.xml' );
  26. //
  27. /////////////////
  28. // What do you get back?
  29. //
  30. //   <content created="22-May-2006">
  31. //       <title>My Title</title>
  32. //       <links>
  33. //           <heading>Here be links!</heading>
  34. //           <link>http://somewhere.com</link>
  35. //           <link>http://somewhere-else.com</link>
  36. //       </links>
  37. //   </content>
  38. //
  39. //   Becomes:
  40. //
  41. //   contentObj.content.title.data => "My Title"
  42. //   contentObj.content.links.title.data => "Here be links!"
  43. //   contentObj.content.links.link => [Array]
  44. //   contentObj.content.links.link[0].data => "http://somewhere.com"
  45. //   contentObj.content.attributes.created => "22-May-2006"
  46. /////////////////
  47. class XML2Object {private var _result:Object;
  48. private var _xml:XML;
  49. private var _path:Object;
  50. private static var xml2object:XML2Object;public function XML2Object()
  51. {
  52. this._result = new Object();
  53. }
  54.  
  55. public static function deserialize( xml:XML ):Object
  56. {
  57. xml2object = new XML2Object();
  58. xml2object.xml = xml;
  59. return xml2object.nodesToProperties();
  60. }
  61.  
  62. public function get xml():XML
  63. {
  64. return _xml;
  65. }
  66.  
  67. public function set xml( xml:XML ):Void
  68. {
  69. this._xml = xml;
  70. }
  71.  
  72. private function nodesToProperties( parent:XMLNode, path:Object, name:String, position:Number ):Object
  73. {
  74. var nodes:Array;
  75. var node:XMLNode;
  76.  
  77. path == undefined ? path = this._result : path = path[name];
  78. if( parent == undefined) parent = XMLNode( this._xml );
  79.  
  80. if( parent.hasChildNodes() )
  81. {
  82. nodes = parent.childNodes;
  83. if (position != undefined) path = path[position];
  84.  
  85. while( nodes.length &gt; 0 )
  86. {
  87. node = XMLNode( nodes.shift() );
  88.  
  89. if ( node.nodeName != undefined )
  90. {
  91. var obj = new Object();
  92. obj.attributes = node.attributes;
  93. obj.data = sanitizeLineBreaks( node.firstChild.nodeValue );
  94.  
  95. if( path[node.nodeName] != undefined )
  96. {
  97.  
  98. if( path[node.nodeName].__proto__ == Array.prototype )
  99. {
  100. path[node.nodeName].push( obj );
  101. }
  102. else
  103. {
  104. var copyObj = path[node.nodeName];
  105. delete path[node.nodeName];
  106. path[node.nodeName] = new Array();
  107. path[node.nodeName].push( copyObj );
  108. path[node.nodeName].push( obj );
  109. }
  110. position = path[node.nodeName].length - 1;
  111. }
  112. else
  113. {
  114. path[node.nodeName] = obj;
  115. position = undefined;
  116. }
  117. name = node.nodeName;
  118. }
  119.  
  120. if( node.hasChildNo