Home Contact RSS

Archive for April, 2008

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: , , , , , , ,

Update to Wordpress 2.5

Circlecube Blog is now enjoying the speed and ease of the latest Wordpress, 2.5 is hot.

Enjoy! I know I am, thanks Wordpress

Note: So far my theme and every plugin are functioning perfectly!

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.hasChildNodes() )
  121. {
  122. this.nodesToProperties( node, path, name, position );
  123. }
  124. }
  125.  
  126. }
  127. return this._result;
  128. }
  129.  
  130. private function sanitizeLineBreaks( raw:String )
  131. {
  132. if( raw.indexOf( "\r\n" ) &gt; -1 )
  133. {
  134. return raw.split( "\r\n" ).join( "\n" );
  135. }
  136. return raw;
  137. }
  138. }

Example:

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

Source:

Here is my example file. But since you cant really see Objects in the code on the stage, I’ve included a recursive trace function to loop through the object and print the data.

  1. import XML2Object;
  2.  
  3. var xmlObject:Object;
  4. var xml:XML = new XML();
  5.  
  6. var xmlLoaded = function( success:Boolean ){
  7. if( success ) {
  8. xmlObject = XML2Object.deserialize( this );
  9. this['timeline'].play();
  10. recurseTrace(xmlObject, " ");
  11. myTrace("\n\n")
  12. myTrace("xmlObject.catagories.catagory[10].name.data = "+xmlObject.catagories.catagory[10].name.data);
  13. }
  14. }
  15.  
  16. xml.ignoreWhite = true;
  17. xml.onLoad = xmlLoaded;
  18. xml.load( 'sampleXML.xml' );
  19.  
  20. function recurseTrace(info:Object, indent:String) {
  21. for (var i in info) {
  22. if (info[i] == null){}
  23. else if (typeof info[i] == "object") {
  24. myTrace(indent + i + " -");
  25. recurseTrace(info[i], indent);
  26. }
  27. else {
  28. myTrace(indent + i + " = " + info[i] +", ");
  29. }
  30. }
  31. }
  32.  
  33. function myTrace(myLine:String){
  34. feedback.text += "|"+myLine;
  35. trace(myLine);
  36. }

And here’s my sample xml file: (it’s the same one I use in my Dynamic Flash Scrolling Link List files)

  1. <catagories>
  2. <catagory>
  3. <name>3D</name>
  4. <url>http://blog.circlecube.com/tag/3d/</url>
  5. </catagory>
  6. <catagory>
  7. <name>abstract</name>
  8. <url>http://blog.circlecube.com/tag/abstract/</url>
  9. </catagory>
  10. <catagory>
  11. <name>actionscript</name>
  12. <url>http://blog.circlecube.com/tag/actionscript/</url>
  13. </catagory>
  14. <catagory>
  15. <name>animation</name>
  16. <url>http://blog.circlecube.com/tag/animation/</url>
  17. </catagory>
  18. <catagory>
  19. <name>blog</name>
  20. <url>http://blog.circlecube.com/tag/blog/</url>
  21. </catagory>
  22. <catagory>
  23. <name>book</name>
  24. <url>http://blog.circlecube.com/tag/book/</url>
  25. </catagory>
  26. <catagory>
  27. <name>CG</name>
  28. <url>http://blog.circlecube.com/tag/cg/</url>
  29. </catagory>
  30. <catagory>
  31. <name>charcoal</name>
  32. <url>http://blog.circlecube.com/tag/charcoal/</url>
  33. </catagory>
  34. <catagory>
  35. <name>circle cube</name>
  36. <url>http://blog.circlecube.com/tag/circle-cube/</url>
  37. </catagory>
  38. <catagory>
  39. <name>collage</name>
  40. <url>http://blog.circlecube.com/tag/collage/</url>
  41. </catagory>
  42. <catagory>
  43. <name>color</name>
  44. <url>http://blog.circlecube.com/tag/color/</url>
  45. </catagory>
  46. <catagory>
  47. <name>css</name>
  48. <url>http://blog.circlecube.com/tag/css/</url>
  49. </catagory>
  50. <catagory>
  51. <name>drawing</name>
  52. <url>http://blog.circlecube.com/tag/drawing/</url>
  53. </catagory>
  54. <catagory>
  55. <name>dreamweaver</name>
  56. <url>http://blog.circlecube.com/tag/dreamweaver/</url>
  57. </catagory>
  58. <catagory>
  59. <name>experiment</name>
  60. <url>http://blog.circlecube.com/tag/experiment/</url>
  61. </catagory>
  62. <catagory>
  63. <name>film</name>
  64. <url>http://blog.circlecube.com/tag/film/</url>
  65. </catagory>
  66. <catagory>
  67. <name>final cut</name>
  68. <url>http://blog.circlecube.com/tag/final-cut/</url>
  69. </catagory>
  70. <catagory>
  71. <name>flash</name>
  72. <url>http://blog.circlecube.com/tag/flash/</url>
  73. </catagory>
  74. </catagories>

Download:

Here’s the XML2Object.as class: XML2Object.as class
Here’s a zip containing everything and the working example: xmlToObject.zip

Tags: , , , , , ,

Poll Results are in!

You have spoken, and here’s the Flash and XML made easy Post!
XML and Flash Actionscript made Easy | Parse XML to Object | Tutorial

Please write about:

View Results

Loading ... Loading ...

Be sure to vote on the new poll, for your Most Wanted Post (here or over in the sidebar)

Please write about:

View Results

Loading ... Loading ...

Choose your most wanted post(s):

  • Flash cookie | Shared Object
  • Reference Dynamic Instances in Actionscript
  • Flashvar
  • Visual Flash Preloader
  • Dynamic 3d space | Floating Sketches Tutorial

Tags: