<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="http://feedproxy.google.com/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feedproxy.google.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>The Tech Labs » Effects</title>
	
	<link>http://www.thetechlabs.com</link>
	<description>Adobe Air, Flash and Flex Tutorials</description>
	<pubDate>Thu, 23 Oct 2008 22:58:12 +0000</pubDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feedproxy.google.com/TheTechLabs_effects" type="application/rss+xml" /><item>
		<title>Simulating PicLens with Flex and Away3D – Part 1</title>
		<link>http://feedproxy.google.com/~r/TheTechLabs_effects/~3/HC3nPEmO0ww/</link>
		<comments>http://www.thetechlabs.com/3d/simulating-piclens-with-flex-and-away3d-%e2%80%93-part-1/#comments</comments>
		<pubDate>Tue, 16 Sep 2008 23:02:11 +0000</pubDate>
		<dc:creator>Alejandro Santander</dc:creator>
		
		<category><![CDATA[3D]]></category>

		<category><![CDATA[Effects]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Flex]]></category>

		<category><![CDATA[Interfaces]]></category>

		<category><![CDATA[Latest]]></category>

		<category><![CDATA[adobe flash]]></category>

		<category><![CDATA[adobe flex]]></category>

		<category><![CDATA[as3]]></category>

		<category><![CDATA[Away3D]]></category>

		<category><![CDATA[caurina]]></category>

		<category><![CDATA[loading images]]></category>

		<category><![CDATA[oop]]></category>

		<category><![CDATA[photo viewer]]></category>

		<category><![CDATA[PicLens]]></category>

		<category><![CDATA[planes]]></category>

		<category><![CDATA[scene]]></category>

		<category><![CDATA[skinning]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[tweener]]></category>

		<category><![CDATA[web-design]]></category>

		<category><![CDATA[web-development]]></category>

		<guid isPermaLink="false">http://www.thetechlabs.com/?p=116</guid>
		<description><![CDATA[<p>This tutorial article is a Step by step guide for creating a PicLens type 3D photo viewer with Flex and Away3d. This is step 1, of a 3 part tutorial that will sweep many useful techniques used in web application design, Flex, and Flash 3D design.</p>
<small><em>posted in <a href="http://www.thetechlabs.com/category/3d/">3D</a> by Alejandro Santander <a href="http://www.thetechlabs.com/3d/simulating-piclens-with-flex-and-away3d-%e2%80%93-part-1/#comments">Leave A Comment</a><br />&copy;2008 <a href="http://www.thetechlabs.com">The Tech Labs</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>This tutorial article is a Step by  step guide for creating a PicLens type 3D photo viewer with Flex and Away3d.  This is step 1, of a 3 part tutorial that will sweep many useful techniques  used in web application design, Flex, and Flash 3D design.</p>
<p>In the final the result will be <a title="See the Final Application Demo" href="http://thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Demos/Finished/"  target="_blank">this</a>.</p>
<h3>Requirements</h3>
<ul>
<li><a title="Try / Buy Adobe Flash CS3" href="http://www.adobe.com/products/flash/" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/flash/');" target="_blank">Adobe Flash CS3</a></li>
<li><a title="Try / Buy Adobe Flex Builder 3" href="http://www.adobe.com/products/flex/?promoid=BPDEQ" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/flex/?promoid=BPDEQ');" target="_blank">Adobe Flex Builder 3</a></li>
<li><a title="Download Away3D Library" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/away3d.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/away3d.zip');" target="_blank">Away3d Library</a> (I recommend using the version I used)</li>
<li><a title="Download Tweener Library" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/caurina.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/caurina.zip');" target="_blank">Tweener Library</a></li>
<li><a title="Download Source Files" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Sources/Part1.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Sources/Part1.zip');" target="_blank">Source Files</a></li>
</ul>
<h3>Pre Requisites</h3>
<ul>
<li>Intermediate  programming skills</li>
<li>Moderate  knowledge of AS3</li>
<li>Basic  Familiarity with OOP</li>
<li>Basic  knowledge of Flash CS3</li>
</ul>
<p><img src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image001.jpg" alt="" width="541" height="196" /></p>
<h3>Step 0</h3>
<p>In this  tutorial I will assume that you are familiar with the basics of building an  Actionscript Away3D project in Flex. If you haven’t used these two technologies  together before, it would be best if you go through my <a title="Setting up Away3d with Flex" href="http://www.thetechlabs.com/3d/setting-up-away3d-with-flex/"  target="_self">previous tutorial</a> first. Due to the complexity of this  application, I will need to skip some things to go faster. So, if something is  not explained here, or suddenly a large chunk of code is dropped with no  descriptions, it has been covered (hopefully) in the mentioned tutorial.</p>
<h3>Step 1 – New Project</h3>
<p>Lets get  started. Create a new Actionscript Project in Flex and name it “PhotoViewer3D”.  Then, download the libraries I listed in the requirements and paste them in the  project’s folder.</p>
<p>Now, one of  the things that will be covered here is a very simplified application  architecture that could be a good starting point for any project you do that  implies a moderate level of complexity. For this, all code will be placed in a  folder structure, carefully separating functions between different classes, and  hence emulating the basics of a Model View Controller design pattern. You  should have a general grasp of it by the end of this series.</p>
<p>Right click  on the project’s folder in the Flex Navigator and choose New -&gt; Folder, then  type “com/li/photoviewer/view” and press Finish. Naming folders this way is  known as Reverse Domain Syntax, and is a good programming practice.</p>
<h3>Step 2 – Setting up the scene</h3>
<p>Go to  PhotoViewer3D.as and build a basic main class:</p>
<pre><strong>package</strong>
{
     <strong>import</strong> flash.display.Sprite;
     <strong>import</strong> flash.display.StageAlign;
     <strong>import</strong> flash.display.StageScaleMode;

     <strong>import</strong> com.li.photoviewer.view.TestScene;

[SWF(backgroundColor=<strong>"0x000000"</strong>, frameRate=<strong>"30"</strong>)] 

     <strong>public</strong> <strong>class</strong> <span lang="EN-GB">PhotoViewer3D</span><strong> extends</strong> Sprite
     {
          <strong>public</strong> <strong>function</strong> <span lang="EN-GB">PhotoViewer3D</span>()
          {
               stage.scaleMode  = StageScaleMode.NO_SCALE;
               stage.align  = StageAlign.TOP_LEFT;

               <strong>var</strong> testScene:TestScene = <strong>new</strong> TestScene();
               addChild(testScene);
          }
     }
}</pre>
<p>Line 7  imports an away3D holding class that we haven’t made yet, so we should create it  right away. Right click on the “view” folder and choose New -&gt; Actionscript  Class and name it “TestScene”. It should have the following code in it:</p>
<pre><strong>package</strong> com.li.photoviewer.view 

{ 

     <strong>import</strong> away3d.cameras.Camera3D;
     <strong>import</strong> away3d.containers.Scene3D;
     <strong>import</strong> away3d.containers.View3D;
     <strong>import</strong> away3d.core.clip.RectangleClipping;
     <strong>import</strong> away3d.core.math.Number3D; 

     <strong>import</strong> flash.display.Sprite;
     <strong>import</strong> flash.events.Event; 

     <strong>public</strong> <strong>class</strong> TestScene <strong>extends</strong> Sprite
     {
          <strong>private</strong> <strong>var</strong> scene:Scene3D;
          <strong>private</strong> <strong>var</strong> camera:Camera3D;
          <strong>private</strong> <strong>var</strong> view:View3D; 

          <strong>public</strong> <strong>function</strong> TestScene()
          {
               addEventListener(Event.ADDED_TO_STAGE,  init, <strong>false</strong>, 0, <strong>true</strong>);
          } 

          <strong>public</strong> <strong>function</strong> init(evt:Event):<strong>void</strong>
          {
               removeEventListener(Event.ADDED_TO_STAGE,  init); 

               initScene();
               initObjects();
               addEventListener(Event.ENTER_FRAME,  renderScene);
          } 

          <strong>private</strong> <strong>function</strong> initScene():<strong>void</strong>
          {
               scene  = <strong>new</strong> Scene3D(); 

               camera  = <strong>new</strong> Camera3D();
               camera.zoom  = 10;
               camera.focus  = 200;
               camera.z  = -2000; 

               view  = <strong>new</strong> View3D();
               view.camera  = camera;
               view.scene  = scene;
               view.x  = stage.stageWidth/2;
               view.y  = stage.stageHeight/2;
               view.clip  = <strong>new</strong> RectangleClipping(-stage.stageWidth/2,  -stage.stageHeight/2, stage.stageWidth/2, stage.stageHeight/2);
               addChild(view);
          } 

          <strong>private</strong> <strong>function</strong> initObjects():<strong>void</strong>
          {
               <strong> </strong>
          } 

          <strong>private</strong> <strong>function</strong> renderScene(evt:Event):<strong>void</strong>
          {
               camera.x  = 3*(mouseX - stage.stageWidth/2);
               camera.y  = 3*(mouseY - stage.stageHeight/2);
               camera.lookAt(<strong>new</strong> Number3D(0, 0, 0)); 

               view.render();
          }
     }
}</pre>
<p><strong>NOTE: </strong>If any  of this shocked you, it has all been explained in the tutorial mentioned in Step  0.</p>
<h3>Step 3 – Setting up our PhotoLoader  component</h3>
<p>Create a  new Actionscript Class in the view folder and name it “PhotoLoader”. These will  be our 3D photograph object. The class will extend Away3D’s Plane primitive,  with a few additional features, more particularly, the ability to load an  external image. So, lets start by setting up the plane:</p>
<pre><strong>package</strong> com.li.photoviewer.view
{
<strong>import</strong> away3d.primitives.Plane;

<strong>public</strong> <strong>class</strong> PhotoLoader <strong>extends</strong> Plane
     {
<strong>private</strong> <strong>var</strong> urlPath:String;

          <strong>public</strong> <strong>function</strong> PhotoLoader(urlPath:String)
          { 

               <strong>super</strong>();

               <strong>this</strong>.urlPath = urlPath;

               <strong>this</strong>.rotationX = 90;
               <strong>this</strong>.width = 640;
               <strong>this</strong>.height = 480;
               <strong>this</strong>.segmentsH = 4;
               <strong>this</strong>.segmentsW = 4;
          }
     }
}</pre>
<p>As you can  see, we’ve set up the constructor so that when we instantiate a PhotoLoader  object, we pass it the image name it has to load as a parameter. Now, go back  to TestScene, and in the “iniObjects()” method, make an instance of PhotoLoader  and add it to the scene:</p>
<pre><strong>var</strong> testPhoto:PhotoLoader = <strong>new</strong> PhotoLoader(<strong>&#8220;imgs/testImage.jpg&#8221;</strong>);

scene.addChild(testPhoto);</pre>
<p>The urlPath we passed this time will be irrelevant,  but we’ll pass it anyway so no errors are thrown. Go ahead and test the  application, you should see something like this:</p>
<p><img src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image003.jpg" alt="" width="540" height="400" /></p>
<h3>Step 4 – Skinning the plane with Flash</h3>
<p>First of  all, we need to give the plane a skin or texture. Even though it will contain  an image, it needs to contain something else while it’s loading, and somehow  show progress for that load process. For this, we will design some graphics in  Flash, and bring them to Flex with what I find to be a very practical and  simple technique. We will use a fla file to generate a library.swf file that  will contain some graphics for our application, and then embed that swf in Flex  and extract the clips as we need them. This is a very useful technique, and I  definitely recommend it for any Flex projects that contain design based vector  graphics.</p>
<p>Open Flash,  create a new AS3 Flash File and save it in your project’s folder, next to  PhotoViewer3D.as. Once in it, select File -&gt; Publish Settings and type “assets/library.swf” for the swf output path (deselect  the html output). Now, create a new folder next to that fla called “assets”  either from your file explorer or by right clicking the project’s folder in the  Flex Navigator. Now, if you publish the fla you will see that library.swf shows  up in your newly created assets folder.</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image005.jpg" alt="" width="283" height="312" /></p>
<h3>Step 5 – Creating and extracting the  graphics created in Flash</h3>
<p>Great, now  I wont be describing how to make the graphics in Flash since I believe you must  be very familiar with this. You should <a title="Download the fla file" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/library.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/library.zip');" target="_self"><strong>download the </strong></a><strong><a title="Download the fla file" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/library.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/library.zip');" target="_self">fla</a></strong> and overwrite the one you just made.  Sorry! Just wanted to make sure you understood what’s going on. Now, open the  downloaded fla. You will see a clip called “LoaderFront” made up of a gray box  and a progressBar clip which has in turn a sub clip. The important thing to  notice here is that LoaderFront has a Linkage and its Base Class was changed to  Sprite. Publish it again, go back to Flex, right click on library.swf in the  assets folder and choose Refresh.</p>
<p>This is the  only code you’ll need to pull those graphics from Flex, type it at the top of  the PhotoLoader class (inside Public class…):</p>
<pre>[<strong>Embed</strong>(source=<strong>"assets/library.swf"</strong>, symbol=<strong>"LoaderFront"</strong>)]
<strong>public</strong> <strong>var</strong> LoaderFront:Class;</pre>
<p>You’ve just  extracted the symbol from the swf’s library and assigned it to a LoaderFront  class. If you create a new instance of this class (and add it to the display  tree), you’ll have a graphics object that extends Sprite! And you can treat it  as any other sprite. Great isn’t it?</p>
<h3>Step 6 – Applying the graphics to the  plane</h3>
<p>Go back to  PhotoLoader.as and create these variables for the class:</p>
<pre><strong>private</strong> <strong>var</strong> materialSprite:Sprite;
<strong>private</strong> <strong>var</strong> progressBar:Sprite;
<strong>private</strong> <strong>var</strong> progressBarSubClip:Sprite;</pre>
<p>And then  this method:</p>
<pre><strong>private</strong> <strong>function</strong> initClips():<strong>void</strong>
{
     materialSprite  = <strong>new</strong> LoaderFront();

     progressBar  = Sprite(materialSprite.getChildByName(<strong>&#8220;progressBar&#8221;</strong>));
     progressBarSubClip  = Sprite(progressBar.getChildByName(<strong>&#8220;subClip&#8221;</strong>));
}</pre>
<p>Now we have references to all the clips that we  need. You have to add the “initClips()” call at the end of the constructor  class.</p>
<p>Next, type this new method under the last one  and also make sure you call it from the constructor:</p>
<pre><strong>private</strong> <strong>function</strong> initMaterial():<strong>void</strong>
{
     <strong>var</strong> material:MovieMaterial = <strong>new</strong> MovieMaterial(materialSprite);
     material.smooth  = <strong>true</strong>;

     <strong>this</strong>.<span style="text-decoration: underline;">material</span> = material;
}</pre>
<p>And Test the application. You should now see that the  plane has taken the graphics as its material. Your PhotoLoader class should  look like this so far:</p>
<pre><strong>package</strong> com.li.photoviewer.view
{
     <strong>import</strong> away3d.materials.MovieMaterial;
     <strong>import</strong> away3d.primitives.Plane;
     <strong>import</strong> flash.display.Sprite;
     <strong>public</strong> <strong>class</strong> PhotoLoader <strong>extends</strong> Plane
     {
         [<strong>Embed</strong>(source=<strong>"assets/library.swf"</strong>, symbol=<strong>"LoaderFront"</strong>)]
          <strong>public</strong> <strong>var</strong> LoaderFront:Class;
          <strong>private</strong> <strong>var</strong> urlPath:String;
          <strong>private</strong> <strong>var</strong> materialSprite:Sprite;
          <strong>private</strong> <strong>var</strong> progressBar:Sprite;
          <strong>private</strong> <strong>var</strong> progressBarSubClip:Sprite;
          <strong>public</strong> <strong>function</strong> PhotoLoader(urlPath:String)
          {
               <strong>super</strong>();
               <strong>this</strong>.urlPath = urlPath;
               <strong>this</strong>.rotationX = 90;
               <strong>this</strong>.width = 640;
               <strong>this</strong>.height = 480;
               <strong>this</strong>.segmentsH = 4;
               <strong>this</strong>.segmentsW = 4;
               initClips();
               initMaterial();
          }
          <strong>private</strong> <strong>function</strong> initClips():<strong>void</strong>
          {
               materialSprite  = <strong>new</strong> LoaderFront();
               progressBar  = Sprite(materialSprite.getChildByName(<strong>&#8220;progressBar&#8221;</strong>));
               progressBarSubClip  = Sprite(progressBar.getChildByName(<strong>&#8220;subClip&#8221;</strong>));
          }
          <strong>private</strong> <strong>function</strong> initMaterial():<strong>void</strong>
          {
               <strong>var</strong> material:MovieMaterial = <strong>new</strong> MovieMaterial(materialSprite);
               material.smooth  = <strong>true</strong>;
               <strong>this</strong>.material = material;
          }
     }
}</pre>
<h3>Step 7 – Loading images into the plane</h3>
<p>The final  thing to do for Part 1 of this tutorial, is implement all the image loading  features of our extended plane. For this, we will use a regular Loader instance  and add a few event listeners to check for progress and complete events.</p>
<p>Add the  loader variable next to the other class variables:</p>
<pre><strong>private</strong> <strong>var</strong> loader:Loader;</pre>
<p>And call a new method under the  “initMaterial()” call in the constructor as “initLoader()”, then build the  method:</p>
<pre><strong>private</strong> <strong>function</strong> initLoader():<strong>void</strong>
{
     loader = <strong>new</strong> Loader();
     loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,  progressHandler);
     loader.contentLoaderInfo.addEventListener(Event.INIT,  initHandler);
     materialSprite.addChild(loader);
     loader.alpha  = 0;
}</pre>
<p>The loader is initialized, two listeners are registered,  then the loader is injected to the plane’s material sprite completely  invisible. I’ve made it invisible because I&#8217;m going to make it fade in once the  image has been loaded into it.</p>
<p>Now, lets set up the handlers and a little  “setProgress()” utilitary method:</p>
<pre><strong>private</strong> <strong>function</strong> progressHandler(evt:ProgressEvent):<strong>void</strong>
{
     setProgress(evt.bytesLoaded/evt.bytesTotal);
}
<strong>private</strong> <strong>function</strong> initHandler(evt:Event):<strong>void</strong>
{
     Tweener.addTween(loader,  {alpha:1, time:1, transition:<strong>&#8220;easeoutexpo&#8221;</strong>});
}
<span lang="EN-GB"> </span>
<strong>private</strong> <strong>function</strong> setProgress(value:Number):<strong>void</strong>
{
     progressBarSubClip.scaleX  = value;
}</pre>
<p>Pretty  straight forward. As the image downloads, the progress handler calls the “setProgress()”  function which in turn sets the horizontal scale of the progress bar, and when  the download completes, or more precisely when the loaded content is  initialized, Tweener makes the loader fade in by animating its alpha. Don’t  forget to import Tweener for this:</p>
<pre><strong>import</strong> caurina.transitions.Tweener;</pre>
<h3>Step 8 – Triggering the load</h3>
<p>Next, lets  trigger the load by adding a “loadImage()” method as the last method called in  the constructor and defining it:</p>
<pre><strong>private</strong> <strong>function</strong> loadImage():<strong>void</strong>
{
     loader.unload();
     loader.alpha  = 0;
     setProgress(0);
     loader.load(<strong>new</strong> URLRequest(urlPath));
}</pre>
<p>Finally,  create the imgs folder in the project, download <a title="Download the images" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/imgs.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flex/asantander/PicLensAway3D/Final/Downloads/imgs.zip');" target="_self">THESE</a> images and paste them in it. Test  the app, you should see the image loaded on the plane:</p>
<p><img src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image007.jpg" alt="" width="540" height="400" /></p>
<p>Watch the Demo <a title="The the Part 1 Demo" href="http://www.thetechlabs.com/tutorials/files/flex/asantander/PicLensAway3D/Final/Demos/Part1"  target="_blank">HERE</a>.</p>
<address><strong>NOTE:</strong> </address>
<address>If  you have any security issues at this point you should disable the compilers  network for now. Do this by right clicking the projects folder, choosing  properties, then clicking on the Actionscript Compiler tab and in the  Additional Compiler Settings, type “-use-network=false”. Don’t forget to  disable this when you go online… This is something anyone using Flex gets to  know one way or the other for quickly getting over any sandbox issues.</address>
<p>Next:</p>
<p>On the next  part we will continue to develop our application by using multiple instances of  this PhotoLoader object, developing advanced camera motion and interactivity.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" onmouseover="a2a_show_dropdown(this)" onmouseout="a2a_onMouseOut_delay()" href="http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Simulating%20PicLens%20with%20Flex%20and%20Away3D%20%E2%80%93%20Part%201&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2F3d%2Fsimulating-piclens-with-flex-and-away3d-%25e2%2580%2593-part-1%2F" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Simulating%20PicLens%20with%20Flex%20and%20Away3D%20%E2%80%93%20Part%201&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2F3d%2Fsimulating-piclens-with-flex-and-away3d-%25e2%2580%2593-part-1%2F');"><img src="http://www.thetechlabs.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p><img src="http://feedproxy.google.com/~r/TheTechLabs_effects/~4/HC3nPEmO0ww" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.thetechlabs.com/3d/simulating-piclens-with-flex-and-away3d-%e2%80%93-part-1/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.thetechlabs.com/3d/simulating-piclens-with-flex-and-away3d-%e2%80%93-part-1/</feedburner:origLink></item>
		<item>
		<title>Extending the AS3/Flash9 Slideshow with XML</title>
		<link>http://feedproxy.google.com/~r/TheTechLabs_effects/~3/kTabWLNQ_pg/</link>
		<comments>http://www.thetechlabs.com/xml/extending-the-as3flash9-slideshow-with-xml/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 22:34:00 +0000</pubDate>
		<dc:creator>Rafael Nuenlist</dc:creator>
		
		<category><![CDATA[Effects]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Interfaces]]></category>

		<category><![CDATA[Latest]]></category>

		<category><![CDATA[XML]]></category>

		<category><![CDATA[adobe flash]]></category>

		<category><![CDATA[as3]]></category>

		<category><![CDATA[caurinas engine]]></category>

		<category><![CDATA[how-to]]></category>

		<category><![CDATA[slideshow]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[tweener]]></category>

		<guid isPermaLink="false">http://www.thetechlabs.com/?p=105</guid>
		<description><![CDATA[<p>In this second part tutorial we&#8217;re going to add some more features to the slideshow application.</p>
<p>Those would be forwarding and rewinding slides, play and pause the slideshow and linkable slides. If you haven&#8217;t read the first part tutorial yet, you should do it before continue. You can read it here.</p>
<small><em>posted in <a href="http://www.thetechlabs.com/category/effects/">Effects</a> by Rafael Nuenlist <a href="http://www.thetechlabs.com/xml/extending-the-as3flash9-slideshow-with-xml/#comments">Leave A Comment</a><br />&copy;2008 <a href="http://www.thetechlabs.com">The Tech Labs</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>In this second part tutorial we&#8217;re going to add some more features to <a title="Extended Slideshow" href="http://www.thetechlabs.com/tutorials/files/flash/rnunlist/slideshow2/"  target="_blank">the slideshow application</a>.</p>
<p>Those would be forwarding and rewinding slides, play and pause the slideshow and linkable slides. If you haven&#8217;t read the first part tutorial yet, you should do it before continue. You can read it <a title="Create a AS3 Slideshow with XML Tutorial" href="http://www.thetechlabs.com/xml/create-a-as3-slideshow-with-xml/"  target="_blank">here</a>.</p>
<h3>Requirements</h3>
<p>Adobe Flash CS3</p>
<p><a title="Try / buy" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.adobe.com/products/flash/');" href="http://www.adobe.com/products/flash/" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/flash/');" target="_blank">Try / Buy</a></p>
<p>Sample files:</p>
<p><a title="Source Files" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/cardflip_fp10/CardFlip_FP10_source_files.zip');" href="http://thetechlabs.com/tutorials/files/flash/rnunlist/slideshow2/slideshowprt2.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flash/rnunlist/slideshow2/slideshowprt2.zip');" target="_self">slideshowprt2.zip</a></p>
<h3>Adjust XML structure</h3>
<p>To store the link of each slide, we just add it as an attribute to the xml file, or to be more accurate, on the image nodes. We also set the target window of the link, which might be neccesary to set in some cases. So, our xml is looking now like this:</p>
<pre>&lt;slideshow&gt;
	&lt;image src="images/fly.jpg" desc="Fly" link="http://www.wikipedia.org" target="_self"/&gt;
	&lt;image src="images/mouse.jpg" desc="Computer mouse" link="http://www.google.com" target="_blank"/&gt;
	&lt;image src="images/country.jpg" desc="Country" link="http://www.thetechlabs.com" target="_self"/&gt;
	&lt;image src="images/rope.jpg" desc="Rope" link="http://www.amazon.com" target="_blank"/&gt;
	&lt;image src="images/flower.jpg" desc="Flower" link="http://www.adobe.com" target="_self"/&gt;
&lt;/slideshow&gt;</pre>
<h3>Adding new objects</h3>
<p>Since we know, how the xml looks like, we can move on to the knew stuff on the stage. In the mcInfo movieclip we&#8217;ve added 4 new buttons. Pause/Play and Forward/Rewind, which will later be assigned to event listeners. On the main stage is a invisible button as big as the size of the slides which will be used to open the links defined in the xml.<br />
Alright, that&#8217;s already enough to go on with the coding part.</p>
<h3>Adding new variables</h3>
<p>First of all, we need to add some new variables to our script.</p>
<p>To know, if the slideshow is currently playing or paused, we set a flag:</p>
<pre>var bolPlaying:Boolean = true;</pre>
<p>And we also store the current slide link and target window in a variable:</p>
<pre>var strLink:String = "";
var strTarget:String = "";</pre>
<h3>Init function</h3>
<p>This is all we need for the variable. Now let&#8217;s take a look about what&#8217;s changing in the init function of the slideshow. We added the following two lines at the beginning of the function to prevent the user to click any button as long as the xml file hasn&#8217;t been loaded completely:</p>
<pre>	mcInfo.visible = false;
	btnLink.visible = false;</pre>
<p>We&#8217;ve also changed the function that will be called once the slideTimer event is fired. Now the function nextSlide() will be called, which we&#8217;ll create later:</p>
<pre>	slideTimer.addEventListener(TimerEvent.TIMER, nextSlide);</pre>
<p>On the last line of the initSlideshow() function we add the event listeners for the buttons. The play and button pause event listeners will be assigned to the same function togglePause(). The next and previous button will be asssigned to the nextSlide() and previousSlide() function. And last of all, we connect the invisible link button that covers the slide area with the goToWebsite() function. And since our slideshow will automatically be playing at the beginning, we hide the play button.</p>
<pre>	btnLink.addEventListener(MouseEvent.CLICK, goToWebsite);
	mcInfo.btnPlay.addEventListener(MouseEvent.CLICK, togglePause);
	mcInfo.btnPause.addEventListener(MouseEvent.CLICK, togglePause);
	mcInfo.btnNext.addEventListener(MouseEvent.CLICK, nextSlide);
	mcInfo.btnPrevious.addEventListener(MouseEvent.CLICK, previousSlide);
	mcInfo.btnPlay.visible = false;</pre>
<h3>onXMLLoadComplete function</h3>
<p>Once the xml is completely loaded, we need to show the mcInfo and the button link again. So we add the following two line of code to the function onXMLLoadComplete()</p>
<pre>	mcInfo.visible = true;
	btnLink.visible = true;</pre>
<p>And since our switchSlide() function will now need to have the index number of the slide, we add a zero as the parameter. We&#8217;ll explain the changes in the switchSlide() function later.</p>
<pre>	switchSlide(0);</pre>
<h3>NextSlide/PreviousSide function</h3>
<p>Let&#8217;s take a look at the nextSlide() and previousSlide() functions. They are called when clicking the next and previous button and the nextSlide() function is also called when the Timer event of the sliderTimer has been fired.<br />
The nextSlide() function checks, if there are any slides left to move on. If so, the current switchSlide() function will be called with the next slide index. If there are no more slides left, then the parameter will be zero standing for the first slide.<br />
The previousSlide() function works the same way. If there are slide we can go back, then the switchSlide() function will be called with the previous slide index. If we&#8217;re already on the first slide, then we start the slideshow from the last slide with calling the switchSlide() function with the parameter of the total slide count minus one since the array count begins with zero.</p>
<pre>function nextSlide(e:Event = null):void {
	if(intCurrentSlide + 1 &lt; intSlideCount)
		switchSlide(intCurrentSlide + 1);
	else
		switchSlide(0);

}

function previousSlide(e:Event = null):void {
	if(intCurrentSlide - 1 &gt;= 0)
		switchSlide(intCurrentSlide - 1);
	else
		switchSlide(intSlideCount - 1);
}</pre>
<h3>SwitchSlide function</h3>
<p>Since the nextSlide() and previousSlide() functions are now handling the checking for the slides, we can take out this part in the switchSlide() function.<br />
To prevent the user from clicking too fast on the next and previous button, we check, if the tweener is still fading in the slides. If so, we just ignore the action. We&#8217;re doing this by adding the following if-statement to the first line of the switchSlide() function.</p>
<pre>	if(!Tweener.isTweening(currentContainer)) {</pre>
<p>Now we only need to set the new link and the target of it. This will be done exactly the same way as setting the description of the slide.</p>
<pre>		strLink		= xmlSlideshow..image[intCurrentSlide].@link;
		strTarget	= xmlSlideshow..image[intCurrentSlide].@target;</pre>
<h3>FadeSideIn function</h3>
<p>The fadeSlideIn() function has also a small addition. We check if the slideshow is currently playing and show the number of seconds to the next slide. If the slideshow is paused, we show a status message. The text will be assigned to the lbl_info label.</p>
<pre>	if(bolPlaying) {
		mcInfo.lbl_loading.text = "Next slide in " + TIMER_DELAY / 1000 + " sec.";
	} else {
		mcInfo.lbl_loading.text = "Slideshow paused";
	}</pre>
<h3>OnSlideFadeIn function</h3>
<p>On the onSlideFadeIn() function we now need to check, if the slideshow is playing. If so, we can start the timer again:</p>
<pre>	if(bolPlaying &amp;&amp; !slideTimer.running)
		slideTimer.start();</pre>
<h3>TogglePause function</h3>
<p>The togglePause() function will be called when the user clicks on the play and pause button. First, we check, if the slideshow is playing, if so, we show the play button, set the bolPlaying variable to false, change the status message of the lbl_info label to &#8220;Slideshow paused&#8221; and stop the timer.<br />
If the slideshow is currently paused, we show the pause button, set the bolPlaying variable to true again, show the time to the next slide and restart the timer.</p>
<pre>function togglePause(e:MouseEvent):void {
	if(bolPlaying) {
		mcInfo.btnPlay.visible = true;
		mcInfo.btnPause.visible = false;

		bolPlaying = false;
		mcInfo.lbl_loading.text = "Slideshow paused";
		slideTimer.stop();
	} else {
		mcInfo.btnPlay.visible = false;
		mcInfo.btnPause.visible = true;

		bolPlaying = true;
		mcInfo.lbl_loading.text = "Next slide in " + TIMER_DELAY / 1000 + " sec.";
		slideTimer.reset();
		slideTimer.start();
	}
}</pre>
<h3>GotToWebsite function</h3>
<p>The last function we need to define is the goToWebsite() function. This function will be called once the user clicks on the invisible button. It will check, if the strLink variable is empty or null. If not, the link will be opened.</p>
<pre>function goToWebsite(e:MouseEvent):void {
	if(strLink != "" &amp;&amp; strLink != null) {
		navigateToURL(new URLRequest(strLink), strTarget);
	}
}</pre>
<p>We&#8217;ve already reached the end of the second part of the slideshow tutorial. We hope that you enjoyed reading it and we appreciate any kind of feedback.</p>
<h3>Note</h3>
<p>The feature for clicking the invisible button only works, when you&#8217;re running the flash on a webserver or in the flash sdk.</p>
<h3>Full code with comments</h3>
<pre>// import tweener
import caurina.transitions.Tweener;

// delay between slides
const TIMER_DELAY:int = 5000;
// fade time between slides
const FADE_TIME:Number =	1;

// flag for knowing if slideshow is playing
var bolPlaying:Boolean = true;
// reference to the current slider container
var currentContainer:Sprite;
// index of the current slide
var intCurrentSlide:int = -1;
// total slides
var intSlideCount:int;
// timer for switching slides
var slideTimer:Timer;
// slides holder
var sprContainer1:Sprite;
var sprContainer2:Sprite;
// slides loader
var slideLoader:Loader;
// current slide link
var strLink:String = "";
// current slide link target
var strTarget:String = "";
// url to slideshow xml
var strXMLPath:String = "slideshow-data.xml";
// slideshow xml loader
var xmlLoader:URLLoader;
// slideshow xml
var xmlSlideshow:XML;

function initSlideshow():void {
	// hide buttons, labels and link
	mcInfo.visible = false;
	btnLink.visible = false;

	// create new urlloader for xml file
	xmlLoader = new URLLoader();
	// add listener for complete event
	xmlLoader.addEventListener(Event.COMPLETE, onXMLLoadComplete);
	// load xml file
	xmlLoader.load(new URLRequest(strXMLPath));

	// create new timer with delay from constant
	slideTimer = new Timer(TIMER_DELAY);
	// add event listener for timer event
	slideTimer.addEventListener(TimerEvent.TIMER, nextSlide);

	// create 2 container sprite which will hold the slides and
	// add them to the masked movieclip
	sprContainer1 = new Sprite();
	sprContainer2 = new Sprite();
	mcSlideHolder.addChild(sprContainer1);
	mcSlideHolder.addChild(sprContainer2);

	// keep a reference of the container which is currently
	// in the front
	currentContainer = sprContainer2;

	// add event listeners for buttons
	btnLink.addEventListener(MouseEvent.CLICK, goToWebsite);
	mcInfo.btnPlay.addEventListener(MouseEvent.CLICK, togglePause);
	mcInfo.btnPause.addEventListener(MouseEvent.CLICK, togglePause);
	mcInfo.btnNext.addEventListener(MouseEvent.CLICK, nextSlide);
	mcInfo.btnPrevious.addEventListener(MouseEvent.CLICK, previousSlide);

	// hide play button
	mcInfo.btnPlay.visible = false;
}

function onXMLLoadComplete(e:Event):void {
	// show buttons, labels and link
	mcInfo.visible = true;
	btnLink.visible = true;	

	// create new xml with the received data
	xmlSlideshow = new XML(e.target.data);
	// get total slide count
	intSlideCount = xmlSlideshow..image.length();
	// switch the first slide without a delay
	switchSlide(0);
}

function fadeSlideIn(e:Event):void {
	// add loaded slide from slide loader to the
	// current container
	currentContainer.addChild(slideLoader.content);
	// clear preloader text
	mcInfo.lbl_loading.text = "";

	// check if the slideshow is currently playing
	// if so, show time to the next slide. If not, show
	// a status message
	if(bolPlaying) {
		mcInfo.lbl_loading.text = "Next slide in " + TIMER_DELAY / 1000 + " sec.";
	} else {
		mcInfo.lbl_loading.text = "Slideshow paused";
	}

	// fade the current container in and start the slide timer
	// when the tween is finished
	Tweener.addTween(currentContainer, {alpha:1, time:FADE_TIME, onComplete:onSlideFadeIn});
}

function onSlideFadeIn():void {
	// check, if the slideshow is currently playing
	// if so, start the timer again
	if(bolPlaying &amp;&amp; !slideTimer.running)
		slideTimer.start();
}

function togglePause(e:MouseEvent):void {
	// check if the slideshow is currently playing
	if(bolPlaying) {
		// show play button
		mcInfo.btnPlay.visible = true;
		mcInfo.btnPause.visible = false;

		// set playing flag to false
		bolPlaying = false;
		// set status message
		mcInfo.lbl_loading.text = "Slideshow paused";
		// stop the timer
		slideTimer.stop();
	} else {
		// show pause button
		mcInfo.btnPlay.visible = false;
		mcInfo.btnPause.visible = true;

		// set playing flag to true
		bolPlaying = true;
		// show time to next slide
		mcInfo.lbl_loading.text = "Next slide in " + TIMER_DELAY / 1000 + " sec.";
		// reset and start timer
		slideTimer.reset();
		slideTimer.start();
	}
}

function switchSlide(intSlide:int):void {
	// check if the last slide is still fading in
	if(!Tweener.isTweening(currentContainer)) {
		// check, if the timer is running (needed for the
		// very first switch of the slide)
		if(slideTimer.running)
			slideTimer.stop();

		// change slide index
		intCurrentSlide = intSlide;

		// check which container is currently in the front and
		// assign currentContainer to the one that's in the back with
		// the old slide
		if(currentContainer == sprContainer2)
			currentContainer = sprContainer1;
		else
			currentContainer = sprContainer2;

		// hide the old slide
		currentContainer.alpha = 0;
		// bring the old slide to the front
		mcSlideHolder.swapChildren(sprContainer2, sprContainer1);

		// create a new loader for the slide
		slideLoader = new Loader();
		// add event listener when slide is loaded
		slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, fadeSlideIn);
		// add event listener for the progress
		slideLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
		// load the next slide
		slideLoader.load(new URLRequest(xmlSlideshow..image[intCurrentSlide].@src));

		// show description of the next slide
		mcInfo.lbl_description.text = xmlSlideshow..image[intCurrentSlide].@desc;

		// set link and link target variable of the slide
		strLink		= xmlSlideshow..image[intCurrentSlide].@link;
		strTarget	= xmlSlideshow..image[intCurrentSlide].@target;

		// show current slide and total slides
		mcInfo.lbl_count.text = (intCurrentSlide + 1) + &#8221; / &#8221; + intSlideCount + &#8221; Slides&#8221;;
	}
}

function showProgress(e:ProgressEvent):void {
	// show percentage of the bytes loaded from the current slide
	mcInfo.lbl_loading.text = &#8220;Loading&#8230;&#8221; + Math.ceil(e.bytesLoaded * 100 / e.bytesTotal) + &#8220;%&#8221;;
}

function goToWebsite(e:MouseEvent):void {
	// check if the strLink is not empty and open the link in the
	// defined target window
	if(strLink != &#8220;&#8221; &amp;&amp; strLink != null) {
		navigateToURL(new URLRequest(strLink), strTarget);
	}
}

function nextSlide(e:Event = null):void {
	// check, if there are any slides left, if so, increment slide
	// index
	if(intCurrentSlide + 1 &lt; intSlideCount)
		switchSlide(intCurrentSlide + 1);
	// if not, start slideshow from beginning
	else
		switchSlide(0);

}

function previousSlide(e:Event = null):void {
	// check, if there are any slides left, if so, decrement slide
	// index
	if(intCurrentSlide - 1 &gt;= 0)
		switchSlide(intCurrentSlide - 1);
	// if not, start slideshow from the last slide
	else
		switchSlide(intSlideCount - 1);
}

// init slideshow
initSlideshow();</pre>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" onmouseover="a2a_show_dropdown(this)" onmouseout="a2a_onMouseOut_delay()" href="http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Extending%20the%20AS3%2FFlash9%20Slideshow%20with%20XML&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fxml%2Fextending-the-as3flash9-slideshow-with-xml%2F" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Extending%20the%20AS3%2FFlash9%20Slideshow%20with%20XML&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fxml%2Fextending-the-as3flash9-slideshow-with-xml%2F');"><img src="http://www.thetechlabs.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p><img src="http://feedproxy.google.com/~r/TheTechLabs_effects/~4/kTabWLNQ_pg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.thetechlabs.com/xml/extending-the-as3flash9-slideshow-with-xml/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.thetechlabs.com/xml/extending-the-as3flash9-slideshow-with-xml/</feedburner:origLink></item>
		<item>
		<title>Create a Card Flip Effect For Flash Player 10 using ActionScript 3</title>
		<link>http://feedproxy.google.com/~r/TheTechLabs_effects/~3/VpYhoiKb7xY/</link>
		<comments>http://www.thetechlabs.com/flash/create-a-card-flip-effect-for-flash-player-10-using-actionscript-3/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 16:53:32 +0000</pubDate>
		<dc:creator>Ben Pritchard</dc:creator>
		
		<category><![CDATA[Effects]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[3D]]></category>

		<category><![CDATA[adobe]]></category>

		<category><![CDATA[card clip effect]]></category>

		<category><![CDATA[flash player 10]]></category>

		<category><![CDATA[how-to]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://thetechlabs.com/?p=28</guid>
		<description><![CDATA[<p>It surprises me that one of the most commented upon and downloaded classes from my blog is a card flipping effect. With that in mind, I thought it might be an interesting exercise to recreate this effect targeting Flash Player 10. As of the writing of this article, Flash Player 10 Beta (Astro) and the corresponding API documentation have been released. This article will step you through the classes used to achieve a card flipping effect using the new rotationY property that exists in Flash Player 10.</p>
<small><em>posted in <a href="http://www.thetechlabs.com/category/effects/">Effects</a> by Ben Pritchard <a href="http://www.thetechlabs.com/flash/create-a-card-flip-effect-for-flash-player-10-using-actionscript-3/#comments">Leave A Comment</a><br />&copy;2008 <a href="http://www.thetechlabs.com">The Tech Labs</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>It surprises me that one of the most commented upon and downloaded classes from my blog is a card flipping effect. With that in mind, I thought it might be an interesting exercise to recreate this effect targeting Flash Player 10. As of the writing of this article, Flash Player 10 Beta (Astro) and the corresponding API documentation have been released. This article will step you through the classes used to achieve a card flipping effect using the new rotationY property that exists in Flash Player 10.</p>
<h3>Requirements</h3>
<p>TextMate or Your Choice of text editor</p>
<p><a href="http://macromates.com/" onclick="javascript:pageTracker._trackPageview('oclicks/http://macromates.com/');">TRY</a> <a href="http://macromates.com/license/" onclick="javascript:pageTracker._trackPageview('oclicks/http://macromates.com/license/');">BUY</a></p>
<p>Flash Player 10</p>
<p><a href="http://labs.adobe.com/technologies/flashplayer10/" onclick="javascript:pageTracker._trackPageview('oclicks/http://labs.adobe.com/technologies/flashplayer10/');">Download</a></p>
<p>Sample files:</p>
<p><a title="Source Files" href="http://thetechlabs.com/tutorials/files/cardflip_fp10/CardFlip_FP10_source_files.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/cardflip_fp10/CardFlip_FP10_source_files.zip');" target="_self">CardFlip_FP10.zip</a></p>
<h3>Prerequisites</h3>
<p>Before you get started you will need a means by which to publish Flash 10 SWF files. This process involves downloading a nightly build of the Flex 3 SDK. Lee Brimelow of <a href="http://gotoandlearn.com/" onclick="javascript:pageTracker._trackPageview('oclicks/http://gotoandlearn.com/');">gotoAndLearn.com</a> has a great <a href="http://gotoandlearn.com/player.php?id=73" onclick="javascript:pageTracker._trackPageview('oclicks/http://gotoandlearn.com/player.php?id=73');">video tutorial</a> You will also need to make sure that you have the Flash Player 10 Beta installed on your machine. This article also assumes a basic understanding of ActionScript 3. which steps you through the process of downloading and publishing your Flash 10 SWFs.</p>
<p><strong>Getting Started</strong></p>
<p>Let’s take a look at what we are going to be building before we dive into the code. Click on the image below to see the card flip effect (requires Flash Player 10):</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="400" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://thetechlabs.com/tutorials/files/cardflip_fp10/CardFlip/CardFlip.swf" /><embed type="application/x-shockwave-flash" width="400" height="400" src="http://thetechlabs.com/tutorials/files/cardflip_fp10/CardFlip/CardFlip.swf"></embed></object></p>
<p>Once you have Flash Player 10 installed and have your system setup to publish using the Flex 3 SDK you can get started writing the CardFlip class. Getting started with the class should be easy for those of you familiar with writing ActionScript 3 classes. This article will detail a simple card flip using external image files and external SWF files. To start, we will create the class using image files and then cover the changes that are made to use an external SWF in their place.</p>
<p>First let’s take a look at the classes we will be using in our package:</p>
<pre>package{
	import flash.display.Sprite;
	import flash.display.StageQuality;
	import flash.display.Bitmap;
	import flash.events.*;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;
	import flash.filters.DropShadowFilter;
	import gs.TweenMax;</pre>
<p>As you can see we import a number of classes that will be leveraged to make our class function. Most of these are native classes that you have probably used before with the exception of PerspectiveProject and TweenMax. PerspectiveProject is a class that is new to Flash Player 10, we will get into its usage later.TweenMax is an excellent class which provides easy and efficient tweening for DisplayObject properties and filters. More about TweenMax is available at <a href="http://blog.greensock.com/tweenmaxas3/" onclick="javascript:pageTracker._trackPageview('oclicks/http://blog.greensock.com/tweenmaxas3/');">GreenSock</a>.</p>
<p><strong>Setting up the SWF for the Flex 3 SDK</strong></p>
<p>If you are new to Flex or have not used the Flex SDK you may not have ever worked with Flex Meta Tags. The following code is pretty self-explanatory and is used to setup the stage for our SWF since we are not creating this content in FlexBuilder or the Flash IDE.</p>
<pre>[SWF(width="600",height="400",backgroundColor="#FFFFFF",framerate="30")]</pre>
<p><strong>Creating the Class</strong></p>
<p>Now that our stage has been setup we can start writing the class and defining our variables. In the example below you will see that I am using additional Flex Meta Tags. In this case I am using the Embed Meta Tag.This will allow me to import external assets into my SWF at compile time. In the example below I import front.jpg and back.jpg. On the line following each of the Embed Meta Tags I create a variable to hold a reference to the external assets. As you can see, the variables defined, CardFrontBitmap and CardBackBitmap are data typed as Class. This will allow me to easily create new instances of these items from within my class. In the code below you will also see variables defined to hold our images, drop shadow, rotation values and which side of the card is being viewed.</p>
<pre>public class CardFlip extends Sprite{
[Embed(source='front.jpg')]
	public var CardFrontBitmap:Class;
	[Embed(source='back.jpg')]
	public var CardBackBitmap:Class;

	private var card:Sprite;
	private var cardFront:Sprite;
	private var cardBack:Sprite;
	private var cfb:Bitmap;
	private var cbb:Bitmap;

	private var ds:DropShadowFilter;

	private var cardRotationFront:Number = 0;
	private var cardRotationBack:Number = 45;
	private var side:String = &#8220;front&#8221;;</pre>
<p><strong>Creating the Constructor</strong></p>
<p>Now that our variables are out of the way we can setup the constructor for the class. Initially we setup our stage to keep our content from scaling. Next, we create a new DropShadowFilter to be used on our card to help achieve the effect of the card flipping. I also create a new Sprite named card, it will be used to hold all of the Sprites and external images that we will be using in the class.</p>
<pre>public function CardFlip(){
	stage.quality = StageQuality.BEST;
	stage.scaleMode = "noScale";
	stage.showDefaultContextMenu = false;
	stage.align = "TL";

	ds = new DropShadowFilter(10, 45, 0x000000, 0.5, 5, 5, 1, 3, false, false, false);

	card = new Sprite();
	card.filters = [ds];</pre>
<p>Remember the variables we set when we created our Embed Meta Tags? Now is the time to use them. Here I assign the variables cfb (which I made stand for “Card Front Bitmap”) and cbb (“Card Back Bitmap”) to new instances of our CardFrontBitmap and CardBackBitmap class. The cfb and cbb variables are bitmaps so that they are able to easily load in my external image files.</p>
<p>I want my card to have its registration point in the middle of itself instead of having a 0x and 0y registration.In order to do that I offset the position of cfb and cbb by half of their width and height. You will also notice that I set the scaleX property of the cbb to -1. This flips the image horizontally so that the back of the card appears correctly when the card is flipped. Had I not set the scaleX property here, the back of the card would appear flipped horizontally and the text would be backwards reading from right to left.</p>
<p>Once all of my properties are set I add cfb and cbb to two Sprite containers. I named the sprites cardFront and cardBack. I add these Sprites to the card Sprite I created earlier. You will also notice that I then initially set the visibility to false for the back of the card since we don’t need to see that yet.</p>
<pre>cfb = new CardFrontBitmap();
	cfb.x = (cfb.width/2)*-1
	cfb.y = (cfb.height/2)*-1

	cardFront = new Sprite();
	cardFront.addChild(cfb);
	card.addChild(cardFront);

	cbb = new CardBackBitmap();
	cbb.scaleX = -1;
	cbb.x = (cbb.width/2);
	cbb.y = (cbb.height/2)*-1

	cardBack = new Sprite();
	cardBack.addChild(cbb);
	cardBack.visible = false;
	card.addChild(cardBack);</pre>
<p>Now that we have our external images created and card face Sprites created and added to our card Sprite, we can add the card Sprite to the Display List. I pushed the x and y properties to 200 just to get my card away from the edge of the stage a bit. I also update the initial rotation of the card to my cardRotationFront variable that I defined.</p>
<pre>addChild(card);
	card.x = 200;
	card.y = 200;

card.rotation = cardRotationFront;</pre>
<p><strong>Setting the PerspectiveProjection</strong></p>
<p>PerspectiveProjection is new in Flash Player 10. Basically it works somewhat like a 3D camera. It will control the perspective in which we are looking at a give object. PersepectiveProjection defaults to the origin of the parent container. If we did not change our PerspectiveProjection projectionCenter, the card would not appear to be flipped when we set the rotationY property to 180. In order to make sure that we are looking dead center on the card from the front we set the perspectiveProjection projectionCenter to 200x and 200y so that it matches the location to which we have moved the card Sprite to on the stage. You can learn more about PerspectiveProjection by reading the <a href="http://download.macromedia.com/pub/labs/flashplayer10/flashplayer10_as3langref_052008.zip" onclick="javascript:pageTracker._trackPageview('oclicks/http://download.macromedia.com/pub/labs/flashplayer10/flashplayer10_as3langref_052008.zip');">Flash Player 10 API Documentation</a>.</p>
<pre>this.transform.perspectiveProjection.projectionCenter = new Point(200,200);
this.transform.perspectiveProjection.fieldOfView = 45;</pre>
<p><strong>Creating and Assigning the Flip</strong></p>
<p>To finish off the constructor I add an event to the card Sprite that will call the flip method whenever the card is clicked.</p>
<p style="margin-left: 36pt;">
<pre>card.addEventListener(MouseEvent.MOUSE_DOWN,flip)
}</pre>
<p>Now that we have the flip method being called we can create the flip method itself. The flip method is a pretty basic function. It contains a basic switch statement which checks to see which side of the card we are currently viewing. Once that is determined, it uses the TweenMax class to handle several property changes.The beautiful thing about TweenMax is that it allows us to update multiple properties and filters in one call.If you are unfamiliar with the usage of TweenMax you can rad up on it at <a href="http://blog.greensock.com/tweenmaxas3/" onclick="javascript:pageTracker._trackPageview('oclicks/http://blog.greensock.com/tweenmaxas3/');">GreenSock</a>.</p>
<p>In the flip method below, you will see that for flipping to the back we set the new rotationY property to 180, rotate the card to the specified rotation and modify the drop shadow. The same logic applies in the case of flipping the card from the back to the front again.</p>
<p>In addition to changing the properties mentioned above, we also created a parameter called onUpdate. This allows us to call a function every time the property values have been changed through the cycle of the tween. In this case, we call the setSideVisibility method which we will discuss next.</p>
<pre>public function flip(e:MouseEvent):void{
			switch(side){
				case "front":
				side = "back";
				TweenMax.to(card, 1, {rotationY:180,rotation:cardRotationBack,onUpdate:setSideVisibility,dropShadowFilter:{blurX:5, blurY:5, alpha:0.5, distance:-10}});
				break;
				case "back":
				side = "front";
				TweenMax.to(card, 1, {rotationY:0,rotation:cardRotationFront,onUpdate:setSideVisibility,dropShadowFilter:{blurX:5, blurY:5, alpha:0.5, distance:10}});
				break;
			}
		}</pre>
<p><strong>Determining Which Side of the Card to Make Visible:</strong></p>
<p>At this point all of the heavy lifting is done. All we need to do is determine which side of the card to show at any given point. This could be done any number of ways; I choose to keep it simple and change the visibility of the card face whenever the very edge of the card is being viewed. In the code below I look for a 90 degree angle in the tween cycle and use that opportunity to swap the visibility of my card faces.</p>
<pre>private function setSideVisibility():void{
			if(card.rotationY &gt;= 90){
				cardBack.visible = true;
			}else if(card.rotationY &lt; 90){
				cardBack.visible = false;
			}
		}
	}
}</pre>
<p><strong>Wrapping Up and Using External SWFs</strong></p>
<p>So, for the most part this is a pretty simple class to write and implement. It could easily be modified to suit whatever need you may have. To wrap up I thought it might be useful to show you a quick example of how you would use external SWF files in the card flip and use an object other than the card itself to call the flip method. The full class for this example is in the resources zip file for this article so I will only go into some of the basic modifications to the class above that I made.</p>
<p>Really, only two simple changes allow me to import external SWF files for use in the card flip. Take a look at the result below and scroll down to see the changes made:</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="350" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://thetechlabs.com/tutorials/files/cardflip_fp10/CardFlip/CardFlipSWF.swf" /><embed type="application/x-shockwave-flash" width="400" height="350" src="http://thetechlabs.com/tutorials/files/cardflip_fp10/CardFlip/CardFlipSWF.swf"></embed></object></p>
<p>The first change was a simple one, we simply need to change the source our oEmbed Meta Tags to load the SWFs:</p>
<pre>[Embed(source='helloCardFront.swf')]
		public var CardFrontSWF:Class;
		[Embed(source='helloCardBack.swf')]
		public var CardBackSWF:Class;
		[Embed(source='flipButton.swf')]
		public var FlipButton:Class;</pre>
<p>The next change is just as simple, we just need change cfb and cbb to Sprites instead of Bitmaps:</p>
<pre>private var cfb:Sprite;
private var cbb:Sprite;</pre>
<p>Again, the full version of the card flip using both SWFs and images is available in the resources zip for this article. It will be much easier to view them in your text editor in their full glory.</p>
<p><strong>Conclusion</strong></p>
<p>Well, that pretty much sums it up. Flash Player 10 looks like it is going to provide developers with a lot of new toys! As always, I would love to see any updates or creations you make using this class! Please shoot me a comment to show me your experiments and findings!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" onmouseover="a2a_show_dropdown(this)" onmouseout="a2a_onMouseOut_delay()" href="http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Create%20a%20Card%20Flip%20Effect%20For%20Flash%20Player%2010%20using%20ActionScript%203&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fflash%2Fcreate-a-card-flip-effect-for-flash-player-10-using-actionscript-3%2F" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Create%20a%20Card%20Flip%20Effect%20For%20Flash%20Player%2010%20using%20ActionScript%203&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fflash%2Fcreate-a-card-flip-effect-for-flash-player-10-using-actionscript-3%2F');"><img src="http://www.thetechlabs.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p><img src="http://feedproxy.google.com/~r/TheTechLabs_effects/~4/VpYhoiKb7xY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.thetechlabs.com/flash/create-a-card-flip-effect-for-flash-player-10-using-actionscript-3/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.thetechlabs.com/flash/create-a-card-flip-effect-for-flash-player-10-using-actionscript-3/</feedburner:origLink></item>
	</channel>
</rss>
