<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>monkeyflash.com &#187; Flash &amp; ActionScript</title>
	<atom:link href="http://monkeyflash.com/category/flash/feed/" rel="self" type="application/rss+xml" />
	<link>http://monkeyflash.com</link>
	<description>Greg Lunn's blog, with tutorials on Flash, CSS, ActionScript and more.</description>
	<lastBuildDate>Wed, 31 Dec 2008 18:13:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Custom Preloader in Flash CS3</title>
		<link>http://monkeyflash.com/tutorials/custom-preloader/</link>
		<comments>http://monkeyflash.com/tutorials/custom-preloader/#comments</comments>
		<pubDate>Mon, 21 Jan 2008 17:15:35 +0000</pubDate>
		<dc:creator>Greg</dc:creator>
				<category><![CDATA[Flash & ActionScript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://beta.monkeyflash.com/?p=46</guid>
		<description><![CDATA[The ability to create a custom preloader is a must in any Flash developer&#8217;s toolbox, but the process is very different in ActionScript 3.0. External files are no longer loaded into a waiting empty movie clip on the stage like you might have done in earlier versions. Instead images, SWF files, and any other external [...]]]></description>
			<content:encoded><![CDATA[<p>The ability to create a custom preloader is a must in any Flash developer&#8217;s toolbox, but the process is very different in ActionScript 3.0. External files are no longer loaded into a waiting empty movie clip on the stage like you might have done in earlier versions. Instead images, SWF files, and any other external content are loaded using the Loader class. The process is different, but not difficult. Let&#8217;s put together a basic custom preloader that can be used in a Flash movie for loading external images or other SWF files.<span id="more-46"></span></p>
<p>Since I want to focus on the code, I&#8217;ve provided an example file to get you started. <a href="/files/preloader.zip">Download the example files</a>, and open preloader.fla.</p>
<h3>Getting started</h3>
<h4>1. Open preloader.fla and review its contents.</h4>
<p>Inside <strong>preloader.fla</strong>, you&#8217;ll notice that the stage is empty. That&#8217;s because we&#8217;re going to load an external file and display it here. We&#8217;re also going to use code to dynamically place the preloader on the stage and to remove it when loading is complete.</p>
<p>Press <strong>Ctrl-L</strong> to open the Library. Inside you&#8217;ll see two movie clips. The first, <strong>barMC</strong>, is a simple green rectangle that will be used to create a visual progress bar while our file is loading. Notice that the registration point of this shape is on the far left side. This shape will scale from that point as it grows. <strong>Preloader</strong> is a movie clip that will contain all of the pieces of our preloader. If you <strong>right-click</strong> (Ctrl-click on a Mac) on the Preloader movie clip in the Library and select <strong>Linkage&#8230;</strong> you will see that the checkbox for &#8220;<strong>Export for ActionScript</strong>&#8221; has been selected. This means that when the file runs, we can access this movie clip dynamically by its class name, &#8220;<strong>Preloader</strong>.&#8221;</p>
<p class="image"><img src="/images/preloader01.jpg" alt="The Linkage properties for the Preloader movie clip." /></p>
<p class="caption">The Linkage properties for the Preloader movie clip.</p>
<p><strong>Double-click</strong> on Preloader in the Library to open it. There are three layers in this timeline. The &#8220;<strong>text</strong>&#8221; layer contains the &#8220;Loading&#8221; text that will tell the user what percentage of the file has been downloaded. Notice that the text box has an instance name of &#8220;<strong>loading_txt</strong>.&#8221; The &#8220;<strong>bar</strong>&#8221; layer contains an instance of the barMC movie clip that will expand to visually indicate how much of the download has completed. The green bar has an instance name of &#8220;<strong>bar_mc</strong>.&#8221; The &#8220;<strong>frame</strong>&#8221; layer simply contains an open box shape. This is an extremely simple preloader &#8211; feel free to create your own graphics that will better match your project.</p>
<p class="image"><img src="/images/preloader02.gif" alt="The barMC movie clip has an instance name of bar_mc in the Properties inspector." /></p>
<p class="caption">The barMC movie clip has an instance name of bar_mc in the Properties inspector.</p>
<h4>2. Add ActionScript to load the external file.</h4>
<p>Return to the main timeline by clicking <strong>Scene 1</strong> under the timeline. Click in the first frame of the <strong>actions</strong> layer and press <strong>F9</strong> to open the <strong>Actions</strong> panel.  Begin by telling Flash what file you want to load. This can be any image or even another SWF file. I&#8217;ve included an (intentionally rather large) JPG file in the example files for you to use as practice.</p>
<p>The <strong>Loader</strong> class expects to receive a <strong>URLRequest</strong> pointing to the file you wish to load, so we&#8217;ll need to start by creating a new URLRequest for to the external file. We&#8217;ll also need to create an instance of the <strong>Loader</strong> class to begin. Add the following code to the Actions panel. (If you&#8217;re loading a different file that the example, replace &#8220;<code>large_image.jpg</code>&#8221; with the name of your file.)</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myRequest:URLRequest = <span style="color: #000000; font-weight: bold;">new</span> URLRequest<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;large_image.jpg&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> myLoader:Loader = <span style="color: #000000; font-weight: bold;">new</span> Loader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>3. Begin loading the external file.</h4>
<p>Tell the <strong>myLoader</strong> instance of the Loader class that we just created to begin loading the file with the next line:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myLoader.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span>myRequest<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>4. Create listeners to monitor the progress of the file.</h4>
<p>At this point in the code, Flash will begin loading the file. We want to create a few <strong>event listeners</strong> to monitor the progress. The first will run a function called <strong>showPreloader()</strong> that will place the Preloader movie clip on the stage. The second listener will run a function called <strong>showProgress()</strong> that will visually update the preloader bar and text to reflect the download progress. The third listener will run the function <strong>showContent()</strong>, which will remove the preloader and show the content once the download is complete.</p>
<p>The Loader class has a property called <strong>contentLoaderInfo</strong> that contains information about the file being loaded. Adding the listeners to this property allows us to monitor the download as it happens. Add the following code to the Actions panel:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">OPEN</span>,showPreloader<span style="color: #66cc66;">&#41;</span>;
myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>ProgressEvent.<span style="color: #006600;">PROGRESS</span>,showProgress<span style="color: #66cc66;">&#41;</span>;
myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">COMPLETE</span>,showContent<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>5. Create an instance of the Preloader movie clip.</h4>
<p>Before we can display the Preloader on the stage, we&#8217;ll need to create an <strong>instance</strong> of it in ActionScript, so that we can refer to it by name. We&#8217;ll call this new instance &#8220;<strong>myPreloader</strong>.&#8221; Add the next line to the Actions panel.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myPreloader:Preloader = <span style="color: #000000; font-weight: bold;">new</span> Preloader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>6. Create the showPreloader function to display the preloader.</h4>
<p>The first event listener above will run a function called <strong>showPreloader()</strong>. This function will place the myPreloader instance on the stage using <strong>addChild()</strong>. Then it will position the preloader in the center of the stage by modifying its <strong>x</strong> and <strong>y</strong> properties. (If you&#8217;d like your preloader to appear someplace else on the screen, you can modify these properties here.)</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> showPreloader<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
	addChild<span style="color: #66cc66;">&#40;</span>myPreloader<span style="color: #66cc66;">&#41;</span>;
	myPreloader.<span style="color: #006600;">x</span> = <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageWidth</span><span style="color: #66cc66;">/</span><span style="color: #cc66cc;">2</span>;
	myPreloader.<span style="color: #006600;">y</span> = <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageHeight</span><span style="color: #66cc66;">/</span><span style="color: #cc66cc;">2</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>7. Add the showProgress function to update the preloader as the download progresses.</h4>
<p>The function that handles the visual updates to our preloader is called <strong>showProgress()</strong>, and is called from the second listener each time the ProgressEvent <strong>PROGRESS</strong> is triggered, which is when additional data from the download is received. This function will calculate the percentage completed by dividing the number of bytes downloaded so far by the total number of bytes. It will update the text display to reflect that amount, multiplied by 100 and rounded to a whole number. Then the function will update the width of the progress bar by setting its width to the maximum width  multiplied by the percent loaded. (The maximum width in this case is 198 pixels &#8211; you might need to adjust this value if you created your own custom graphics.)</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> showProgress<span style="color: #66cc66;">&#40;</span>event:ProgressEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> percentLoaded:<span style="color: #0066CC;">Number</span> = event.<span style="color: #0066CC;">bytesLoaded</span><span style="color: #66cc66;">/</span>event.<span style="color: #0066CC;">bytesTotal</span>;
	myPreloader.<span style="color: #006600;">loading_txt</span>.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Loading - &quot;</span> + <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">round</span><span style="color: #66cc66;">&#40;</span>percentLoaded <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;%&quot;</span>;
	myPreloader.<span style="color: #006600;">bar_mc</span>.<span style="color: #0066CC;">width</span> = <span style="color: #cc66cc;">198</span> <span style="color: #66cc66;">*</span> percentLoaded;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>8. Add the showContent function to display the file after it has been loaded.</h4>
<p>The last listener above will run the <strong>showContent()</strong> function once all of the bytes of the external file have been completely loaded. The showContent() function simply removes the preloader from the stage, and then adds the <strong>myLoader</strong> instance, making the loaded content appear.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> showContent<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
	removeChild<span style="color: #66cc66;">&#40;</span>myPreloader<span style="color: #66cc66;">&#41;</span>;
	addChild<span style="color: #66cc66;">&#40;</span>myLoader<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>9. Test the preloader by simulating a download.</h4>
<p>To test the preloader, we will use Flash&#8217;s built-in bandwidth simulator. Previewing the file from our local drive will cause the content to be loaded almost instantly, and you will only see the preloader for a fraction of a second. By simulating a slower download speed, we can test the functionality of the preloader.</p>
<p>First test the movie by pressing <strong>Ctrl-Enter</strong>. If you do not have any errors, you will see your loaded content appear immediately.  To simulate a download, and to test the preloader, press <strong>CTRL-Enter a second time</strong>. Flash will reload the test movie, and then simulate a download of the content at a controlled speed. The default setting is a 56kbps modem, and will give you time to study the behavior of the preloader. It should slowly count up the percentage in the text box, and the progress bar should slowly grow. When the download is complete, your loaded content will display.</p>
<p class="image"><img src="/images/preloader03.gif" alt="The preloader in action." /></p>
<p class="caption">The preloader in action.</p>
<h3>What about loading the entire movie?</h3>
<p>How can you use this same technique to load the entire SWF file and not an external asset? One way is to create a &#8220;wrapper&#8221; swf that only contains your preloader and the code above. You can then load your main SWF file into this wrapper container, and avoid the need to add a preloader to an already-completed Flash file. This is a very efficient and easy way to add a preloader to any site.</p>
<p>As with all things in ActionScript, there are other methods as well, but some are more difficult and best saved for a future tutorial. :)</p>
<p>Here&#8217;s the completed code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myRequest:URLRequest = <span style="color: #000000; font-weight: bold;">new</span> URLRequest<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;large_image.jpg&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> myLoader:Loader = <span style="color: #000000; font-weight: bold;">new</span> Loader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
myLoader.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span>myRequest<span style="color: #66cc66;">&#41;</span>;
&nbsp;
myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">OPEN</span>,showPreloader<span style="color: #66cc66;">&#41;</span>;
myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>ProgressEvent.<span style="color: #006600;">PROGRESS</span>,showProgress<span style="color: #66cc66;">&#41;</span>;
myLoader.<span style="color: #006600;">contentLoaderInfo</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">COMPLETE</span>,showContent<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> myPreloader:Preloader = <span style="color: #000000; font-weight: bold;">new</span> Preloader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> showPreloader<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
        addChild<span style="color: #66cc66;">&#40;</span>myPreloader<span style="color: #66cc66;">&#41;</span>;
        myPreloader.<span style="color: #006600;">x</span> = <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageWidth</span><span style="color: #66cc66;">/</span><span style="color: #cc66cc;">2</span>;
        myPreloader.<span style="color: #006600;">y</span> = <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageHeight</span><span style="color: #66cc66;">/</span><span style="color: #cc66cc;">2</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> showProgress<span style="color: #66cc66;">&#40;</span>event:ProgressEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">var</span> percentLoaded:<span style="color: #0066CC;">Number</span> = event.<span style="color: #0066CC;">bytesLoaded</span><span style="color: #66cc66;">/</span>event.<span style="color: #0066CC;">bytesTotal</span>;
        myPreloader.<span style="color: #006600;">loading_txt</span>.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Loading - &quot;</span> + <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">round</span><span style="color: #66cc66;">&#40;</span>percentLoaded <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;%&quot;</span>;
        myPreloader.<span style="color: #006600;">bar_mc</span>.<span style="color: #0066CC;">width</span> = <span style="color: #cc66cc;">198</span> <span style="color: #66cc66;">*</span> percentLoaded;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> showContent<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
        removeChild<span style="color: #66cc66;">&#40;</span>myPreloader<span style="color: #66cc66;">&#41;</span>;
        addChild<span style="color: #66cc66;">&#40;</span>myLoader<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p class="flasource"><a href="/files/preloader.zip">Download the example files</a></p>
]]></content:encoded>
			<wfw:commentRss>http://monkeyflash.com/tutorials/custom-preloader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding a Poster Frame to Flash Video</title>
		<link>http://monkeyflash.com/tutorials/poster-frame-for-flash-video/</link>
		<comments>http://monkeyflash.com/tutorials/poster-frame-for-flash-video/#comments</comments>
		<pubDate>Wed, 16 Jan 2008 14:40:12 +0000</pubDate>
		<dc:creator>Greg</dc:creator>
				<category><![CDATA[Flash & ActionScript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://beta.monkeyflash.com/?p=42</guid>
		<description><![CDATA[One of the new features of the video playback component in Flash CS3 is the ability to assign a preview image, or a poster frame, to an FLV to make it easier to position and adjust. However, this new feature comes with a footnote that reads, &#8220;The preview image is displayed at authoring time only. [...]]]></description>
			<content:encoded><![CDATA[<p>One of the new features of the video playback component in Flash CS3 is the ability to assign a preview image, or a poster frame, to an FLV to make it easier to position and adjust. However, this new feature comes with a footnote that reads, &#8220;The preview image is displayed at authoring time only. To generate a runtime preview image, use the export button and load the image back by writing your own ActionScript.&#8221; Unfortunately, the missing ActionScript is not included in the documentation. In this tutorial, I will show you one way to include a poster frame in front of a Flash video.<span id="more-42"></span></p>
<h3>What&#8217;s the plan?</h3>
<p>I&#8217;m going to add a video to my site using the Flash CS3 video playback component and one of the default skins. I want to create a preview, or poster, image that appears when the video is first loaded. The video should wait until the user clicks on either the poster image itself, or on the play button in the component controls to start playing. Then, the preview image should disappear while the video plays. Finally, once the video is complete, I&#8217;d like the preview image to reappear so that the process can be repeated.</p>
<p>To start you&#8217;ll need an <strong>FLV</strong> file. Any video will do, but I&#8217;ve included one in the example files to get you started. I&#8217;ve also included the finished file in case you&#8217;d like to refer to it later.</p>
<p class="flasource"><a href="http://www.monkeyflash.com/files/poster.zip">Download the example files</a></p>
<h3>Getting started</h3>
<h4>1. Begin by creating a new Flash document.</h4>
<p>For this tutorial, begin by creating a new Flash ActionScript 3.0 document. Set the dimensions to <strong>320 x 280</strong> pixels by clicking the <strong>Size</strong> button in the <strong>Properties</strong> Inspector. The included sample FLV is 320&#215;240, and I&#8217;m leaving an extra 40 pixels for the playback controls. Save this file as <strong>player.fla</strong> in the same folder as your FLV file.</p>
<h4>2. Import the FLV video file into Flash.</h4>
<p>Import the video by choosing <strong>File</strong> > <strong>Import</strong> > <strong>Import Video</strong>.  Click the <strong>Browse</strong> button, locate your FLV, and click <strong>Open</strong>. Click <strong>Next</strong>. Under the <strong>Deployment</strong> screen, keep the default setting and click <strong>Next</strong>. On the <strong>Skinning</strong> screen, select a playback skin and a color. I chose <em>&#8220;SkinUnderPlaySeekMute.swf&#8221;</em> and a dark gray color. Click <strong>Next</strong>, and then click <strong>Finish</strong>.</p>
<p class="image"><img src="/images/poster01.gif" alt="Select a playback skin and color." /></p>
<p class="caption">Select a playback skin and color.</p>
<blockquote><p><strong>Note:</strong> For a little more information about the Video Import wizard, as well as an easy way to make your Flash video play in full-screen mode, see the previous tutorial, <a href="http://www.monkeyflash.com/tutorials/full-screen-video/"><strong>Full-Screen Video in Flash CS3</strong></a>.</p></blockquote>
<p>You should now see the video in the stage. In fact, if you test the movie (press <strong>Ctrl-Enter</strong>) you can watch the video play. You&#8217;ll notice that the video begins playing immediately. We&#8217;ll change that and create our preview image next.</p>
<h4>3. Give the video component an instance name of myVideo.</h4>
<p>Click on the video on the stage to select it, and then give it an <strong>instance name</strong> of <code>myVideo</code> in the <strong>Properties</strong> inspector at the bottom of the screen. <strong>Don&#8217;t forget this step</strong>, or our code won&#8217;t be able to talk to the video later.</p>
<p class="image"><img src="/images/poster02.gif" alt="Adding an instance name in the Property inspector." /></p>
<p class="caption">Adding an instance name in the Property inspector.</p>
<h4>4. Change the video component&#8217;s autoPlay value to false.</h4>
<p>Click the <strong>Parameters</strong> tab in the <strong>Properties</strong> Inspector at the bottom of the screen. You&#8217;ll see several parameters specific to the playback component. To prevent the video from playing on its own, click to the right of <strong>autoPlay</strong> and set it to <code>false</code>.</p>
<p class="image"><img src="/images/poster03.gif" alt="Change the autoPlay value to false." /></p>
<p class="caption">Change the autoPlay value to false.</p>
<h3>Creating the preview image</h3>
<h4>5. Select the preview frame from the video.</h4>
<p>To select a preview frame from the video, <strong>double-click</strong> next to the <strong>preview</strong> parameter, where it says, &#8220;<code>None</code>.&#8221; A small version of the video will begin to play, and time code will be displayed underneath it. You&#8217;ll also see the note below the video reminding us that a preview image selected here will only be available in authoring mode. Yep, that&#8217;s why we&#8217;re here.</p>
<p>If you move the cursor over the video, small playback controls will appear that will allow you to move through the video. Press <strong>Pause</strong>, and then use the controls to choose a suitable frame to become the preview image.</p>
<p class="image"><img src="/images/poster04.jpg" alt="Selecting a preview frame." /></p>
<p class="caption">Selecting a preview frame.</p>
<h4>6. Export the frame as a PNG image file.</h4>
<p>Click <strong>Export</strong> to save the frame as a PNG file. Save the image as <strong>poster.png</strong> in the same folder as your FLV. Close the <em>&#8220;Select Preview Frame&#8221;</em> window.</p>
<h3>Importing the PNG and setting up the preview</h3>
<h4>7. Import the preview image PNG file to the stage.</h4>
<p>Select <strong>File</strong> &gt; <strong>Import</strong> &gt; <strong>Import to Stage&#8230;</strong> Browse to the poster.png image, and click <strong>Open</strong>. Importing the image into the Flash file ensures that it will be loaded within the SWF file, ready to display.</p>
<h4>8. Convert the image to a movie clip.</h4>
<p>Click on the image and press <strong>F8</strong> to convert it to a symbol. Name the symbol &#8220;<strong>PosterFrame</strong>&#8221; and choose <strong>Movie clip</strong> as the type. Click <strong>OK</strong>. Converting the bitmap image to a movie clip will allow us to customize its appearance to indicate to the user that they can click the image to start the video.</p>
<p class="image"><img src="/images/poster05.jpg" alt="Converting the image bitmap into a movie clip named PosterFrame." /></p>
<p class="caption">Converting the image bitmap into a movie clip named &#8220;PosterFrame.&#8221;</p>
<p>Optionally, you can edit the movie clip to include a button or any other visual cues that you&#8217;d like. I&#8217;m going to add large play button to make it obvious that this is a video waiting to be played.</p>
<h4>9. Add a play button or icon to the movie clip.</h4>
<p><strong>Double-click</strong> on the poster frame clip on the stage to edit it. From here, I&#8217;m going to add one of Flash&#8217;s pre-built buttons for simplicity, but of course you can create a button of your own to use here as well.</p>
<p>Choose <strong>Window</strong> &gt; <strong>Common Libraries</strong> &gt; <strong>Buttons</strong>. Open the &#8220;<strong>playback rounded</strong>&#8221; folder, and drag an instance of the &#8220;<strong>rounded green play</strong>&#8221; button onto the stage. You can use the <strong>Free Transform</strong> tool to resize the button and position it over the image. <strong>Close</strong> the &#8220;<em>Library – Buttons.fla</em>&#8221; panel.</p>
<p class="image"><img src="/images/poster06.jpg" alt="Adding a button to the poster frame clip." /></p>
<p class="caption">Adding a button to the poster frame movie clip.</p>
<h4>10. Give the movie clip an instance name of &#8220;myPoster&#8221;.</h4>
<p>Return to the main stage by clicking &#8220;<strong>Scene 1</strong>&#8221; underneath the timeline. Click on the PosterFrame movie clip on the stage, and in the Properties inspector, give it an instance name of &#8220;<strong>myPoster</strong>.&#8221;</p>
<p class="image"><img src="/images/poster07.gif" alt="Adding an instance name in the Property inspector." /></p>
<p class="caption">Adding an instance name in the Property inspector.</p>
<h3>Adding the ActionScript to make it work</h3>
<p>Ok, the busy work is over. Now it&#8217;s time to add the elusive ActionScript to make the poster frame show up. I&#8217;m sure there are several ways to do this, and maybe some even more efficient, but I&#8217;m going to show you what has worked reliably for me.</p>
<h4>11. Create a new actions layer.</h4>
<p>Create a new <strong>layer</strong> in the timeline, and rename it &#8220;<strong>actions</strong>&#8220;. Click the first frame of the actions layer, and press <strong>F9</strong> to open the <strong>Actions</strong> panel.</p>
<h4>12. Create a function called playMovie.</h4>
<p>The <strong>playMovie</strong> function is very simple. It will run when the user clicks on the poster frame, and will start the video. Add this code underneath the previous line:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> playMovie<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myVideo.<span style="color: #0066CC;">play</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>13. Create two functions to turn the preview image on or off.</h4>
<p>The easiest way to hide the preview movie clip is to change its <strong>visible</strong> property to <strong>false</strong>. This not only hides the movie clip from the display, but it also prevents the user clicking on the same clip again, essentially <em>disabling</em> the clip until we need it again. To bring the clip back, return its <strong>visible</strong> property to <strong>true</strong>. Add two more functions below the existing code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> showPosterFrame<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myPoster.<span style="color: #0066CC;">visible</span> = <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> hidePosterFrame<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myPoster.<span style="color: #0066CC;">visible</span> = <span style="color: #000000; font-weight: bold;">false</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h4>14. Add a CLICK event listener to the poster frame movie clip.</h4>
<p>Enter the following in the Actions panel:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myPoster.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">CLICK</span>, playMovie<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>This will create an event listener that tells Flash to run the <strong>playMovie()</strong> function when the user clicks anywhere on the poster frame.</p>
<h4>15. Toggle the visiblity of the poster frame by listening for video events.</h4>
<p>Now we need to turn the preview image on or off at the right time. The most reliable way to do this is to listen for a specific type of event called a video event that will be triggered by the playing FLV file. When the FLV begins to play, it will trigger a <strong>PLAYING_STATE_ENTERED</strong> event, and we should then remove the poster frame. When the FLV is finished, it will trigger a <strong>COMPLETE</strong> video event, and we will make the poster frame visible again.</p>
<p>Before we can use the <strong>Video Event</strong> class, we must import it. Add the following line <strong>AT THE TOP</strong> of the rest of the code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> fl.<span style="color: #0066CC;">video</span>.<span style="color: #006600;">VideoEvent</span>;</pre></div></div>

<p>Then, add event listeners to toggle the poster frame when the video plays and ends. Add these two lines at the bottom of the code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myVideo.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>VideoEvent.<span style="color: #006600;">PLAYING_STATE_ENTERED</span>, hidePosterFrame<span style="color: #66cc66;">&#41;</span>;
myVideo.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>VideoEvent.<span style="color: #006600;">COMPLETE</span>, showPosterFrame<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>16. Test the movie, and correct any errors.</h4>
<p>Test the movie now by pressing <strong>Ctrl-Enter</strong>. You should see your preview picture on the stage. When you click on the poster frame (or the play button in the video component) the poster frame will disappear and the FLV will begin to play, and when the video ends, the poster frame will reappear!</p>
<p>If you have any ActionScript errors, please carefully review the code and correct any typos.</p>
<p id="preview">If you have JavaScript enabled, you will see the example here.</p>
<p><script type='text/javascript' src='/swf/swfobject.js'></script><br />
<script type='text/javascript'>
var s1 = new SWFObject('/swf/posterframe.swf','player','320','280','9');
s1.addParam('allowscriptaccess','always');
s1.write('preview');
</script></p>
<p>That&#8217;s it! You&#8217;ve created a very functional preview image, or a poster frame, using just a little ActionScript and the built-in Flash video components. Here&#8217;s a look at the completed code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> fl.<span style="color: #0066CC;">video</span>.<span style="color: #006600;">VideoEvent</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> showPosterFrame<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myPoster.<span style="color: #0066CC;">visible</span> = <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> hidePosterFrame<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myPoster.<span style="color: #0066CC;">visible</span> = <span style="color: #000000; font-weight: bold;">false</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> playMovie<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    myVideo.<span style="color: #0066CC;">play</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
myPoster.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">CLICK</span>, playMovie<span style="color: #66cc66;">&#41;</span>;
myVideo.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>VideoEvent.<span style="color: #006600;">PLAYING_STATE_ENTERED</span>, hidePosterFrame<span style="color: #66cc66;">&#41;</span>;
myVideo.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>VideoEvent.<span style="color: #006600;">COMPLETE</span>, showPosterFrame<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p class="flasource"><a href="http://www.monkeyflash.com/files/poster.zip">Download the example files</a></p>
]]></content:encoded>
			<wfw:commentRss>http://monkeyflash.com/tutorials/poster-frame-for-flash-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Full-Screen Video in Flash CS3</title>
		<link>http://monkeyflash.com/tutorials/full-screen-video/</link>
		<comments>http://monkeyflash.com/tutorials/full-screen-video/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 13:46:17 +0000</pubDate>
		<dc:creator>Greg</dc:creator>
				<category><![CDATA[Flash & ActionScript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://beta.monkeyflash.com/?p=35</guid>
		<description><![CDATA[One of the best new features in Flash Player 9 is its ability to play video full-screen, using the same outside-the-browser technique you&#8217;ve seen on YouTube and other video sites. One click opens the video to the full width of your monitor with a black background, and even includes a message letting the user know [...]]]></description>
			<content:encoded><![CDATA[<p>One of the best new features in Flash Player 9 is its ability to play video full-screen, using the same outside-the-browser technique you&#8217;ve seen on <a href="http://www.youtube.com">YouTube</a> and other video sites. One click opens the video to the full width of your monitor with a black background, and even includes a message letting the user know that they can return to their desktop by pressing the <strong>Esc</strong> key. Here&#8217;s the best part: using Flash CS3, you can add full-screen capability to your Flash video without writing a single line of ActionScript, and with only a tiny change to your HTML. Let&#8217;s take a look at how easy it can be.<span id="more-35"></span></p>
<h3>Encode your video to FLV</h3>
<p>Even though Flash CS3 can encode your videos when you import them, I prefer to use the Flash Video Encoder for converting my video files to FLV. Using the Video Encoder allows you to encode several files at once using a queue, letting you continue to work in Flash while the conversion is completed. The original video file should be the highest quality possible, preferably uncompressed, and can be saved as .mov, .avi, .mpeg, or .wmv. I&#8217;ve already included an FLV for you in the <a href="http://www.monkeyflash.com/files/fullscreen.zip">example files</a>, but here&#8217;s how it was created.</p>
<p>Begin by pressing the <strong>Add…</strong> button in the Flash Video Encoder. Browse to the file that you wish to convert, and press <strong>Open</strong>. Although the default settings will usually produce acceptable results, it&#8217;s a good idea to adjust the quality settings, especially since this video will be shown full screen.</p>
<p>Click <strong>Settings…</strong>. Here you can adjust the encoding rates for video and audio, as well as crop and resize the video if necessary. Under the <strong>Video</strong> tab, medium or high quality will give you the best results full-screen. I usually reduce the <strong>frame rate</strong> to 15 FPS as well to keep the file size under control, but you can choose <code>Same as source</code> to leave the frame rate unchanged.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen1.gif" alt="Adjusting the compression settings for the FLV file." /></p>
<p class="caption">Adjusting the compression settings for the FLV file.</p>
<p>Under the <strong>Crop and Resize</strong> tab, it&#8217;s a good idea to resize your video to more reasonable dimensions if your original is very large. Typically, web video is encoded at <code>320x240</code> pixels, but if you are going to display video full-screen, you might consider <code>480x360</code> or even <code>640x480</code> pixels to provide the best quality. Keep in mind that larger dimensions equal much larger file sizes, and it might be a good idea to experiment to find the settings that work best for your project. For this example, I&#8217;m using <code>320x240</code> pixels for my video.</p>
<p>Press <strong>OK</strong> once you&#8217;ve made your changes. You can add more files to your queue in the same manner, duplicate the current job and change the settings, or press <strong>Start Queue</strong> to begin the conversion. This will create FLV files with the same names as your original media in the same folders, unless you specified otherwise.</p>
<h3>Importing video into Flash</h3>
<p>Once you have an FLV file, it&#8217;s time to bring it into Flash CS3. Create a new <strong>Flash File (ActionScript 3.0)</strong>. In the <strong>Properties</strong> inspector, click the <strong>Size</strong> button and adjust the document to be the same width as your video file, and the same height plus 40 pixels to leave room for the player controls. In the example here, that will be <code>320x280</code> pixels. Change the background color of the document to black. <strong>Save</strong> the Flash file in the same folder as your FLV.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen2.gif" alt="Adjusting the size of the Flash document in the Properties Inspector." /></p>
<p class="caption">Adjusting the size of the Flash document in the Properties Inspector.</p>
<h4>Import the FLV</h4>
<p>Choose <strong>File</strong> &gt; <strong>Import</strong> &gt; <strong>Import Video</strong>. Click <strong>Browse</strong>, find the FLV file you created earlier, and click <strong>OK</strong>. (If you didn&#8217;t create the FLV file beforehand, you could point to your original file as well. Flash will create the FLV at the end of this wizard, but you&#8217;ll have to wait on the process to complete before continuing.) Click <strong>Next</strong>.</p>
<p>On the <strong>Deployment</strong> screen, you can choose how the FLV file will be streamed to your viewers. Unless you subscribe to a Flash Streaming Service or own a Flash Media Server, you&#8217;ll likely select the first option, <code>Progressive download from a web server</code>. This will allow the viewer to begin playing the video as soon as it begins to load, instead of waiting for the full download to complete. Click <strong>Next</strong>.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen3.gif" alt="Select Progressive stream from a web server." /></p>
<p class="caption">Select Progressive stream from a web server.</p>
<p>On the <strong>Skinning</strong> screen, you can select a set of player buttons to use to control video playback. There are many different combinations, but to enable full-screen mode, select one with a full screen button. For this example, I&#8217;ve selected <code>SkinUnderPlaySeekFullscreen.swf</code>. You can also choose a color for the controls, and I&#8217;ve chosen a dark gray. Click <strong>Next</strong>.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen4.gif" alt="Choosing a playback skin with a full screen button and a color." /></p>
<p class="caption">Choosing a playback skin with a full screen button and a color.</p>
<p>You will see a summary of your selections, and you can go back and make any changes you want. Click <strong>Finish</strong> to complete the video import, and after a few moments, the video will appear on the stage. Click the video, and use the Properties inspector to adjust its <code>x</code> and <code>y</code> positions to <code>0</code>.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen5.gif" alt="Move the video to the top left corner of the stage." /></p>
<p class="caption">Move the video to the top left corner of the stage.</p>
<p><strong>Save</strong> the Flash file, and choose <strong>File</strong> &gt; <strong>Publish Settings</strong>. Make sure that <code>Flash (.swf)</code> and <code>HTML (.html)</code> are checked, then click <strong>OK</strong>. Choose <strong>File</strong> &gt; <strong>Publish Preview</strong> &gt; <strong>Default (HTML)</strong> to create the SWF and HTML files and preview them in a browser. You&#8217;ll notice that the video will play, but the full screen button won&#8217;t work yet. We need to make one minor change in the HTML page to enable full screen mode.</p>
<h3>Edit the HTML file</h3>
<p><strong>Open</strong> the HTML file that was created in your favorite HTML or text editor. There are three places that <code>allowFullScreen</code> will be set to false by default: once inside the <code>script </code>tags, and twice between the <code>noscript</code> tags, within the <code>object</code> and <code>embed</code> tags. Locate these three variables and change their values to <code>true</code>. </p>
<p class="image"><img src="http://www.monkeyflash.com/images/fullscreen6.gif" alt="Change the allowFullScreen value in the HTML file to true." /></p>
<p class="caption">Change the <code>allowFullScreen</code> value in the HTML file to true.</p>
<p><strong>Save</strong> the file and reload the HTML page in your browser. This time, when you click the full screen button, you&#8217;ll watch your video in complete full screen glory!</p>
<p id="preview">If you have JavaScript enabled, you will see the example here.</p>
<p><script type='text/javascript' src='/swf/swfobject.js'></script><br />
<script type='text/javascript'>
var s1 = new SWFObject('/swf/fullscreen.swf','player','320','280','9');
s1.addParam('allowfullscreen','true');
s1.addParam('allowscriptaccess','always');
s1.addParam('autoplay','false');
s1.write('preview');
</script></p>
<p class="flasource"><a href="http://www.monkeyflash.com/files/fullscreen.zip">Download the demo files</a></p>
<h3>A few notes</h3>
<p>Remember when you upload the files to the server that all of the necessary files will need to be uploaded together: the HTML file, the SWF, the skin SWF file, the FLV, and the <code>AC_RunActiveContent.js</code> file that is used to embed the movie. </p>
<p>Also, if you would like to embed the video on a pre-existing HTML page, simply copy the code from the HTML page that Flash created (everything between the <code>body</code> tags) and paste it into the appropriate place in your existing page. Make sure that the other files are moved into the same folder as that page on the server as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://monkeyflash.com/tutorials/full-screen-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Tween Class</title>
		<link>http://monkeyflash.com/tutorials/using-the-tween-class/</link>
		<comments>http://monkeyflash.com/tutorials/using-the-tween-class/#comments</comments>
		<pubDate>Tue, 03 Jul 2007 01:07:42 +0000</pubDate>
		<dc:creator>Greg</dc:creator>
				<category><![CDATA[Flash & ActionScript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://beta.monkeyflash.com/?p=28</guid>
		<description><![CDATA[In the past, if you wanted to create a bouncing animation using code, you&#8217;d spend hours pouring over physics equations and adjusting variables until you got it just right. By using the Tween class instead, you can create the same effect with just a few lines of code, and skip the high school physics review. [...]]]></description>
			<content:encoded><![CDATA[<p>In the past, if you wanted to create a bouncing animation using code, you&#8217;d spend hours pouring over physics equations and adjusting variables until you got it just right. By using the Tween class instead, you can create the same effect with just a few lines of code, and skip the high school physics review. A recent project gave me a chance to play with the Tween class, a relatively obscure set of scripts that can be used to create varying programmatic animation.<span id="more-28"></span></p>
<blockquote><p><strong>Important note:</strong> This tutorial will be written using ActionScript 3 and Flash CS3.
</p></blockquote>
<h3>Understanding the Tween class</h3>
<p>The Tween class lets you move, resize, rotate, or fade a movieclip using only ActionScript. You can animate any property of a movieclip, such as <code>x</code>, <code>y</code>, <code>rotation</code>, <code>scaleX</code>, <code>scaleY</code>, and <code>alpha</code>. You can also specify how long the animation will last in either seconds or frames. The code will follow this example:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">new</span> Tween<span style="color: #66cc66;">&#40;</span>obj, prop, func, begin, finish, <span style="color: #0066CC;">duration</span>, useSeconds<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The Tween constructor function accepts these parameters:</p>
<ol>
<li><strong>obj</strong> &#8211; The instance name of the movieclip that you want to animate.</li>
<li><strong>prop</strong> &#8211; The property of the movieclip that you want to change, such as x or alpha, as a text string.</li>
<li><strong>func</strong> &#8211; The type of easing you want to apply to the animation to change its acceleration.</li>
<li><strong>begin</strong> &#8211; The starting value of the property being animated.</li>
<li><strong>finish</strong> &#8211; The ending value of the property being animated.</li>
<li><strong>duration:</strong> &#8211; How long the animation will take, either in frames or seconds.</li>
<li><strong>useSeconds</strong> &#8211; If your duration is in seconds, set this to true. If your duration is in frames, set this to false.</li>
</ol>
<p>Before using the Tween class, you&#8217;ll need to import the classes into your code. Here&#8217;s what the ActionScript would look like to animate a banana movieclip from left to right across the stage within three seconds:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> fl.<span style="color: #006600;">transitions</span>.<span style="color: #006600;">Tween</span>;
<span style="color: #0066CC;">import</span> fl.<span style="color: #006600;">transitions</span>.<span style="color: #006600;">easing</span>.<span style="color: #66cc66;">*</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">var</span> myTween:Tween = <span style="color: #000000; font-weight: bold;">new</span> Tween<span style="color: #66cc66;">&#40;</span>banana_mc, <span style="color: #ff0000;">&quot;x&quot;</span>, Elastic.<span style="color: #006600;">easeOut</span>, <span style="color: #cc66cc;">50</span>, <span style="color: #cc66cc;">450</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Isn&#8217;t that much cleaner and easier that doing the math yourself? First, the two <code>import</code> lines make these classes available to us. Keep in mind that <code>import</code> statements must be at the top of all of your actions. Then we tell Flash to create a new Tween instance called <code>myTween</code>, and using the model above, we&#8217;re telling Flash to animate the movieclip <code>banana_mc</code> along the x axis, from position 50 to position 450 in three seconds. We&#8217;re using the <code>Elastic.easeOut</code> function, one of several options to control the acceleration of the animation. </p>
<p>Click the play button below to see the result:</p>
<p id="preview">If you have JavaScript enabled, you will see the example here.</p>
<p><script type='text/javascript' src='/swf/swfobject.js'></script><br />
<script type='text/javascript'>
var s1 = new SWFObject('/swf/tweenexample.swf','player','550','150','9');
s1.addParam('allowscriptaccess','always');
s1.write('preview');
</script></p>
<h3>Easing options</h3>
<p>The banana uses <code>Elastic.easeOut</code> to create an overshoot effect at the end of the animation, but there are several other options to add lifelike movement to your tweens. You can select an Easing class from these choices:</p>
<ul>
<li><strong>Back</strong> &#8211; Causes the animation to overshoot, and return to its position.</li>
<li><strong>Bounce</strong> &#8211; Causes the animation to reverse direction, like a ball bouncing on a floor.</li>
<li><strong>Elastic</strong> &#8211; Causes the animation to overshoot and reverse, like at the end of a rubber band.</li>
<li><strong>Regular</strong> &#8211; Accelerates along a steady curve.</li>
<li><strong>Strong</strong> &#8211; Accelerates along a steady curve, more aggressive than Regular.</li>
<li><strong>None</strong> &#8211; Results in no acceleration; a steady speed.</li>
</ul>
<p>Then, you pair any Easing class with an easing function to control which end of the tween (beginning, ending, or both) is affected:</p>
<ul>
<li><strong>easeIn</strong>  &#8211; The ease is applied to the beginning of the tween.</li>
<li><strong>easeInOut</strong> &#8211; The ease is applied to bothe the beginning and the end of the tween.</li>
<li><strong>easeOut</strong> &#8211; The ease is applied to the end of the tween.</li>
</ul>
<p>Combinations such as <code>Bounce.easeOut</code> or <code>Strong.easeIn</code> result in different effects. Click each of the buttons below to see the effect that each Easing class creates.</p>
<p id="preview2">If you have JavaScript enabled, you will see the example here.</p>
<p><script type='text/javascript' src='/swf/swfobject.js'></script><br />
<script type='text/javascript'>
var s1 = new SWFObject('/swf/easingClasses.swf','player2','550','220','9');
s1.addParam('allowscriptaccess','always');
s1.write('preview2');
</script></p>
<h3>Controlling Tween playback</h3>
<p>You can alter the Tween&#8217;s playback by using any of several methods:</p>
<ul>
<li><strong>continueTo(finish, duration)</strong> &#8211; Instructs the animation to continue tweening from its current animation point to a new finish and duration point.</li>
<li><strong>fforward()</strong> &#8211; Fast-forwards to the end of the animation.</li>
<li><strong>nextFrame()</strong> &#8211; Forwards a stopped animation to the next frame.</li>
<li><strong>prevFrame()</strong> &#8211; Reverses a stopped animation to its previous frame.</li>
<li><strong>resume()</strong> &#8211; Plays an animation that has been stopped.</li>
<li><strong>start()</strong> &#8211; Plays an animation from its begin value.</li>
<li><strong>stop()</strong> &#8211; stops the animation.</li>
<li><strong>yoyo()</strong> &#8211; Plays the animation in reverse.</li>
</ul>
<p>Flash will begin playing the animation the moment that the Tween is instantiated. Using the above code on its own would trigger the animation the instant that the animation is loaded, or the moment that the frame with the code is reached. If you would rather have the effect wait for some user input, such as a button click, you could stop the Tween, and then start it from within an Event handler, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myTween.<span style="color: #0066CC;">stop</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
play_btn.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">CLICK</span>, moveBanana<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">function</span> moveBanana<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span><span style="color: #66cc66;">&#123;</span>
	myTween.<span style="color: #0066CC;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h3>Allowing the Tween to trigger additional code</h3>
<p>The Tween class has several events that can be used to detect what the tween is currently doing:</p>
<ul>
<li><strong>MOTION_CHANGE</strong> &#8211; Indicates when the animation has changed.</li>
<li><strong>MOTION_FINISH</strong> &#8211; Indicated the animation is complete.</li>
<li><strong>MOTION_LOOP</strong> &#8211; Indicates the animation has started again in looping mode.</li>
<li><strong>MOTION_RESUME</strong> &#8211; Indicates that the animation has been resumes after being paused.</li>
<li><strong>MOTION_START</strong> &#8211; Indicates that the animation has started.</li>
<li><strong>MOTION_STOP</strong> &#8211; Indicates that the animation has stopped.</li>
</ul>
<p>For instance, you could reset the banana to its original position once the animation is complete. First, import the <code>TweenEvent</code> class using another import statement at the top of your code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> fl.<span style="color: #006600;">transitions</span>.<span style="color: #006600;">TweenEvent</span>;</pre></div></div>

<p>Then, add the following code to wait for the motion to finish and reset the <code>banana_mc</code> movieclip’s <code>x</code> value to 30.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">myTween.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>TweenEvent.<span style="color: #006600;">MOTION_FINISH</span>, handleReset<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> handleReset<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:TweenEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
	banana_mc.<span style="color: #006600;">x</span> = <span style="color: #cc66cc;">30</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p class="flasource"><a href="/files/tweenclass.zip">Download the Demo FLA</a></p>
<p>For more information on the Tween class, please see the excellent Adobe documentation for <a href="http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&#038;file=00000965.html">Flash CS3</a> or <a href="http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&#038;file=00004142.html">Flash 8</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://monkeyflash.com/tutorials/using-the-tween-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flash Drag and Drop</title>
		<link>http://monkeyflash.com/tutorials/flash-drag-and-drop/</link>
		<comments>http://monkeyflash.com/tutorials/flash-drag-and-drop/#comments</comments>
		<pubDate>Thu, 14 Jun 2007 19:19:57 +0000</pubDate>
		<dc:creator>Greg</dc:creator>
				<category><![CDATA[Flash & ActionScript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://beta.monkeyflash.com/?p=7</guid>
		<description><![CDATA[Creating drag and drop functionality in Flash CS3 is quite different than in older versions if you&#8217;re using the new ActionScript 3.0. While still relatively straightforward, the code can be a little more intimidating to users who are less familiar with ActionScript programming. If you&#8217;re like me, you&#8217;re here to try to keep your knowledge [...]]]></description>
			<content:encoded><![CDATA[<p>Creating drag and drop functionality in Flash CS3 is quite different than in older versions if you&#8217;re using the new ActionScript 3.0. While still relatively straightforward, the code can be a little more intimidating to users who are less familiar with ActionScript programming. If you&#8217;re like me, you&#8217;re here to try to keep your knowledge up-to-date, so let&#8217;s learn how to create a simple ActionScript 3.0 drag and drop game step-by-step. <a href="/files/dragdrop.zip">Download the FLA</a> and follow along with these steps.<span id="more-7"></span></p>
<h3>Setting up the Flash file</h3>
<p>Open <strong><a href="/files/dragdrop.zip">dragdrop.fla</a></strong> and review its organization. There are five layers in the file – one containing the &#8220;pegs&#8221; that we will drag and drop, one for the &#8220;targets&#8221; that we will drop the shapes onto, and one for the wooden box image. The text layer and the actions layer are currently empty. The pegs and the targets are movieclip symbols saved in the library. Press <strong>CTRL-L</strong> to view the library.</p>
<h4>1. Create a dynamic text field to display the right or wrong responses on the text layer.</h4>
<p>In order to provide the user with some feedback, we will display a message when the shapes are dropped, indicating whether or not they were placed successfully. Click <strong>frame 1</strong> of the <strong>text</strong> layer. Use the <strong>Text tool</strong> to draw a text box underneath the peg shapes. Type &#8220;<em>Put the shapes away!</em>&#8221; to give the box an initial message.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/ddas301.gif" alt="Adding the dynamic text box." /></p>
<p class="caption">Adding the dynamic text box.</p>
<p>In the Properties inspector, change the text box to a <strong>Dynamic</strong> Text box using the drop down menu. Set the font to <strong>Arial bold</strong>, the font color to <strong>#990000</strong>, and the size to <strong>18pt</strong>. Give the text box an instance name of &#8220;<strong>reply_txt</strong>&#8220;. Use the Selection tool to position the text box if necessary.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/ddas302.gif" alt="Setting the properties of the dynamic text box." /></p>
<p class="caption">Setting the properties of the dynamic text box.</p>
<h4>2. Assign instance names to the peg and target movie clips.</h4>
<p>In order to determine which target we drop our shapes over, we need to name them. Click the bright green pentagon target on the stage, and in the <strong>Properties</strong> inspector, give it an instance name of &#8220;<strong>targetpentagon_mc</strong>&#8220;. Repeat the process, giving the other three green targets instance names of &#8220;<strong>targetsquare_mc</strong>&#8220;, &#8220;<strong>targettriangle_mc</strong>&#8220;, and &#8220;<strong>targetflower_mc</strong>&#8220;. Take special note of the lowercase values &#8211; this will be important later.</p>
<p>Click the red square peg on the stage and give it an instance name of &#8220;<strong>square_mc</strong>&#8220;. Repeat the process, giving the other three colored pegs instance names of &#8220;<strong>flower_mc</strong>&#8220;, &#8220;<strong>triangle_mc</strong>&#8220;, and &#8220;<strong>pentagon_mc</strong>&#8220;.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/ddas303.gif" alt="Adding an instance name to the pentagon target." /></p>
<p class="caption">Adding an instance name to the pentagon target.</p>
<blockquote><p><strong>Why are the targets so small?</strong><br />
The targets are smaller than the holes on the toy to provide a little more accuracy. Smaller targets mean that the shape has to be more closely lined up to register as a match.</p></blockquote>
<h4>3. Adjust the targets to make them invisible.</h4>
<p>Since the appearance of bright green targets spoils the illusion of a child&#8217;s toy, we will make them transparent. Using the <strong>Selection</strong> tool, click the first green target. Then, holding down <strong>Shift</strong> on the keyboard, click to select the other three targets. In the Properties inspector, choose <strong>Alpha</strong> from the <strong>Color</strong> dropdown menu. Then set the Alpha value to <strong>0</strong>, making the targets transparent.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/ddas304.gif" alt="Setting the alpha value of the targets to zero." /></p>
<p class="caption">Setting the alpha value of the targets to zero.</p>
<h3>Adding Drag and Drop functionality</h3>
<p>Now it&#8217;s time to dive into the code. Since ActionScript 3.0 no longer uses <code>onPress</code> and <code>onRelease</code> events, we&#8217;ll need some new code to create the same effect.</p>
<h4>4. Add ActionScript to make the red square dragable.</h4>
<p>We&#8217;ll write some ActionScript to allow us to drag and drop the square peg. Select <strong>frame 1</strong> of the <strong>actions</strong> layer, and open the <strong>Actions</strong> panel by pressing <strong>F9</strong>. Type in the following actions:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">square_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
square_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">function</span> pickUp<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">startDrag</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> dropIt<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">stopDrag</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
square_mc.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">true</span>;</pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas305.gif" alt="Adding the drag and drop Actionscript." /></p>
<p class="caption">Adding the drag and drop Actionscript.</p>
<p>This tells Flash to begin dragging the movie clip when the user presses the mouse button, and stop when the mouse is released. In ActionScript 3.0, this is created by setting an event listener for each event, <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>, and assigning event handler functions (here called <code>pickUp</code> and <code>dropIt</code>) to tell Flash what to do once the event is triggered. Within these event handlers, <code>event.target</code> refers to the object that initiated this event, which in this case will be <code>square_mc</code>. Using <code>event.target</code> instead of naming the object specifically will let us reuse this code for all four pegs in a few steps. The &#8220;true&#8221; parameter of the <code>startDrag</code> function causes the shape to be picked up from its center, which will make it easier to place later. To display the hand cursor when clicking movieclip symbols, we set the <code>buttonMode</code> property to true. Press <strong>CTRL-Enter</strong> to test the movie, and try dragging the square.</p>
<h4>5. Add ActionScript to display a message in the text box when the peg is dropped.</h4>
<p>Here is where we determine where we release the peg, and provide feedback. Add the following code just below <code>event.target.startDrag(true);</code></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;&quot;</span>;</pre></div></div>

<p>Adding this code inside the <code>pickUp</code> event handler will force the text inside the dynamic text field to clear when we pick up the peg.</p>
<p>Add the following lines below <code>event.target.stopDrag();</code></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myTargetName:<span style="color: #0066CC;">String</span> = <span style="color: #ff0000;">&quot;target&quot;</span> + event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">name</span>;
<span style="color: #000000; font-weight: bold;">var</span> myTarget:DisplayObject = getChildByName<span style="color: #66cc66;">&#40;</span>myTargetName<span style="color: #66cc66;">&#41;</span>;
<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">dropTarget</span> <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">&amp;&amp;</span> event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">dropTarget</span>.<span style="color: #006600;">parent</span> == myTarget<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Good Job!&quot;</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
    reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Try Again!&quot;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas306.gif" alt="Adding conditional logic to give a proper response." /></p>
<p class="caption">Adding conditional logic to give a proper response.</p>
<p>The first new line creates a text string from the word &#8220;target&#8221; plus the name of the peg we just dropped, creating a name that matches one of our targets, such as &#8220;<code>targetsquare_mc</code>&#8220;. The next line looks through our document for an object with that name, and saves a reference to it in a variable called &#8220;<code>myTarget</code>&#8220;. The <code>if</code> statement checks to make sure that the <code>dropTarget</code>, or the item that is under our shape when we release the mouse button, is not <code>null</code>, or empty. It also checks to see if the dropTarget&#8217;s parent is our <code>myTarget</code> . In other words, if we release <code>square_mc</code> over the movie clip named &#8220;<code>targetsquare_mc</code>&#8220;, we receive a positive reply. If the peg is released anywhere else, we will receive a negative reply.</p>
<p>Test the movie by pressing <strong>CTRL-Enter</strong>. Try clicking the square and dragging it over an incorrect hole in the toy. Now, try dropping it over the correct hole. Check your code and fix any errors you encounter.</p>
<h4>6. Use similar ActionScript to activate the other three pegs.</h4>
<p>Copy the event listener lines from the Actions panel and paste them three more times. Change each reference of <code>square_mc</code> to <code>flower_mc</code>, <code>triangle_mc</code>, and <code>pentagon_mc</code>, respectively. Do the same for the <code>buttonMode</code> line for each of the pegs. Since the event handler functions use references to <code>event.target</code>, there is no need to modify any other sections for it to work with all four pegs.</p>
<p class="image"><img src="http://www.monkeyflash.com/images/ddas307.gif" alt="Copying and pasting the event listeners for the other three pegs." /></p>
<p class="caption">Copying and pasting the event listeners for the other three pegs.</p>
<p>Press <strong>CRTL-Enter</strong> to test the movie. Try dragging each of the pegs into both incorrect and correct places on the toy. You should receive the correct messages each time.</p>
<h3>Bring the selected peg to the top</h3>
<p>Currently, if you drag the yellow triangle, it passes over the square, but underneath the pentagon and flower shapes. That&#8217;s because they were added to the Flash document in a specific order, and the newest objects end up on top in the stacking order. ActionScript 3.0 no longer uses depths when placing objects, as the <code>z-index</code> is handled automatically. In order to change the item&#8217;s z-index, we&#8217;ll use the <code>addChild()</code> method.</p>
<h4>7. Use addChild() to increase the peg&#8217;s stackin order</h4>
<p>We want to set the peg&#8217;s depth higher each time we drag it so that it will drag above the others. Add the following code within the <code>pickUp()</code> event handler, after the line <code>reply_txt.text = "";</code></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">parent</span>.<span style="color: #006600;">addChild</span><span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">target</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>In this line of code, <code>event.target.parent</code> refers to the main timeline. Using <code>addChild(event.target)</code> essentially adds the currently selected peg to the stage at the top of the stacking order, creating the appearance that we&#8217;ve picked it up above the others. Press <strong>CTRL-Enter</strong> to test the movie. As you drag each piece, it should always remain on top of the others.</p>
<h3>Locking pegs that have been placed correctly</h3>
<p>Once the user has placed a peg in the right hole, it is a good idea to &#8220;lock&#8221; it into place so that they can&#8217;t accidentally move it again. We&#8217;ll also make sure that the peg is perfectly positioned when it is released.</p>
<h4>8. Remove the event listeners when a peg is correctly placed.</h4>
<p>Once a peg is placed, the easiest way to ensure that we can&#8217;t move it again is to remove the event listeners, and set <code>buttonMode</code> back to false to remove the hand cursor. Add the following code within the <code>dropIt()</code> event handler, within the <code>if</code> statement, immediately after the line, <code>reply_txt.text="Good Job!";</code></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">removeEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">removeEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">false</span>;</pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas308.gif" alt="Removing the event listeners and buttonMode." /></p>
<p class="caption">Removing the event listeners and buttonMode.</p>
<p>When a peg is placed over the correct target, the <code>if</code> statement returns <code>true</code>, and that peg will be locked and no longer dragable. Test the movie with <strong>CTRL-Enter</strong> and see for yourself.</p>
<h4>9. Adjust the peg&#8217;s position when it is correctly placed</h4>
<p>We should also make sure that once a peg is placed, it fits perfectly over the target. Add the following code immediately under the code you just added:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span> = myTarget.<span style="color: #006600;">x</span>;
event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span> = myTarget.<span style="color: #006600;">y</span>;</pre></div></div>

<p>This will set the dropped peg&#8217;s <code>x</code> and <code>y</code> coordinates to match those of the target movie clip. Note that in ActionScript 3.0, <code>x</code> and <code>y</code> properties no longer have an underscore. Test the movie with <strong>CTRL-Enter</strong>.</p>
<h3>Resetting incorrectly placed pegs to their original position</h3>
<p>Currently, if you drag and drop a peg to either the wrong place or an empty area of the screen, it just stays there until you drag it again, which can be a little confusing. Let&#8217;s make each peg snap back to its original spot if it&#8217;s placed incorrectly.</p>
<h4>10. When clicked, record the peg&#8217;s starting position</h4>
<p>Since we&#8217;ll need this information within two event handlers, let&#8217;s set up a pair of variables. Add the following code to above all the rest in the Actions panel:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> startX:<span style="color: #0066CC;">Number</span>;
<span style="color: #000000; font-weight: bold;">var</span> startY:<span style="color: #0066CC;">Number</span>;</pre></div></div>

<p>This creates two variables, <code>startX</code> and <code>startY</code>, that will contain our starting position. For now, they&#8217;re empty. When we pick up the shape, we&#8217;ll record its coordinates. Add this next code within the <code>pickUp()</code> event handler:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">startX = event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span>;
startY = event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span>;</pre></div></div>

<h4>11. If the peg is released outside of its target, reset its x and y position</h4>
<p>Now that the starting position is recorded, we can use those values to reset the peg when we miss the target. Add the following code within the <code>dropIt()</code> handler, within the else statement:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span> = startX;
event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span> = startY;</pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas309.gif" alt="Recording and resetting the peg's starting position." /></p>
<p class="caption">Recording and resetting the peg&#8217;s starting position.</p>
<p>This will reset the <code>x</code> and <code>y</code> properties to their original values, but only when we release the shape outside of its target. Test your movie with <strong>CTRL-Enter</strong>, and drag the square to an incorrect space. It should snap back to its starting position.</p>
<h3>Using a counter to determine when the user is finished</h3>
<p>Let&#8217;s add a congratulatory message that tells the user that all pegs have been placed correctly. We&#8217;ll need to keep a count of each correct peg drop, and when the count reaches four, we&#8217;ll change the text message.</p>
<h4>12. Create a global counter variable</h4>
<p>Since the counter will keep track of all four pegs, we will create a variable in the actions layer. Add the following code above all of the other code in the actions panel:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> counter:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;</pre></div></div>

<h4>13. Increment the counter variable each time a peg is correctly placed</h4>
<p>We will add one to the counter variable each time we release a peg over the right target. Add the following line of code within the <code>dropIt()</code> event handler, within the if statement:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">counter++;</pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas310.gif" alt="Adding the counter increment to the dropIt() event handler." /></p>
<p class="caption">Adding the counter increment to the dropIt() event handler.</p>
<p>This will add one to the value of the counter variable when the square peg is placed correctly.</p>
<h4>14. Check the counter and update the text when it reaches four</h4>
<p>Add the following code within the <code>dropIt()</code> event handler, making sure that it comes after the <code>else</code> statement:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>counter == <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Congrats, you're finished!&quot;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p class="image"><img src="http://www.monkeyflash.com/images/ddas311.gif" alt="Checking the counter variable, and congratulating the user." /></p>
<p class="caption">Checking the counter variable, and congratulating the user.</p>
<p>This checks the <code>counter</code> variable&#8217;s value, and if it equals 4, it will change the text in the dynamic text field to read, &#8220;Congrats, you&#8217;re finished!&#8221;.</p>
<p id="preview">If you have JavaScript enabled, you will see the completed project here.</p>
<p><script type='text/javascript' src='/swf/swfobject.js'></script><br />
<script type='text/javascript'>
var s1 = new SWFObject('/swf/dragdrop_complete.swf','player','550','300','9');
s1.addParam('allowscriptaccess','always');
s1.write('preview');
</script></p>
<p>Here&#8217;s a look at the completed code.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> counter:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;
<span style="color: #000000; font-weight: bold;">var</span> startX:<span style="color: #0066CC;">Number</span>;
<span style="color: #000000; font-weight: bold;">var</span> startY:<span style="color: #0066CC;">Number</span>;
&nbsp;
square_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
square_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
triangle_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
triangle_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
flower_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
flower_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
pentagon_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
pentagon_mc.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> pickUp<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">startDrag</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
    reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;&quot;</span>;
    event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">parent</span>.<span style="color: #006600;">addChild</span><span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">target</span><span style="color: #66cc66;">&#41;</span>;
    startX = event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span>;
    startY = event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> dropIt<span style="color: #66cc66;">&#40;</span>event:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
    event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">stopDrag</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">var</span> myTargetName:<span style="color: #0066CC;">String</span> = <span style="color: #ff0000;">&quot;target&quot;</span> + event.<span style="color: #0066CC;">target</span>.<span style="color: #0066CC;">name</span>;
    <span style="color: #000000; font-weight: bold;">var</span> myTarget:DisplayObject = getChildByName<span style="color: #66cc66;">&#40;</span>myTargetName<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">dropTarget</span> <span style="color: #66cc66;">!</span>= <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">&amp;&amp;</span> event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">dropTarget</span>.<span style="color: #006600;">parent</span> == myTarget<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Good Job!&quot;</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">removeEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_DOWN</span>, pickUp<span style="color: #66cc66;">&#41;</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">removeEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">MOUSE_UP</span>, dropIt<span style="color: #66cc66;">&#41;</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">false</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span> = myTarget.<span style="color: #006600;">x</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span> = myTarget.<span style="color: #006600;">y</span>;
        counter++;
    <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
        reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Try Again!&quot;</span>;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">x</span> = startX;
        event.<span style="color: #0066CC;">target</span>.<span style="color: #006600;">y</span> = startY;
    <span style="color: #66cc66;">&#125;</span>
    <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>counter == <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        reply_txt.<span style="color: #0066CC;">text</span> = <span style="color: #ff0000;">&quot;Congrats, you're finished!&quot;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
square_mc.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">true</span>;
flower_mc.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">true</span>;
triangle_mc.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">true</span>;
pentagon_mc.<span style="color: #006600;">buttonMode</span> = <span style="color: #000000; font-weight: bold;">true</span>;</pre></div></div>

<p class="flasource"><a href="/files/dragdrop.zip">Download the source FLA.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://monkeyflash.com/tutorials/flash-drag-and-drop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
