<?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>Activetuts+ &#187; Effects</title>
	<atom:link href="http://active.tutsplus.com/category/tutorials/effects/feed/" rel="self" type="application/rss+xml" />
	<link>http://active.tutsplus.com</link>
	<description>Flash, Flex &#38; ActionScript Tutorials</description>
	<lastBuildDate>Fri, 19 Mar 2010 19:32:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Create a Retro CRT Distortion Effect Using RGB Shifting</title>
		<link>http://active.tutsplus.com/tutorials/effects/create-a-retro-crt-distortion-effect-using-rgb-shifting/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/create-a-retro-crt-distortion-effect-using-rgb-shifting/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 12:00:54 +0000</pubDate>
		<dc:creator>Cadin Batrack</dc:creator>
				<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3359</guid>
		<description><![CDATA[In this tutorial you&#8217;ll learn how to separate an image&#8217;s three different color channels to create an RGB shift effect. I&#8217;ll also show you some graphics tricks to mimic an old CRT display.


Final Result Preview
Here&#8217;s an example of the effect we&#8217;ll be creating:



The main takeaway in this tutorial is going to be the RGB shifting [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you&#8217;ll learn how to separate an image&#8217;s three different color channels to create an RGB shift effect. I&#8217;ll also show you some graphics tricks to mimic an old CRT display.</p>
<p><span id="more-3359"></span></p>
<hr/>
<h2>Final Result Preview</h2>
<p>Here&#8217;s an example of the effect we&#8217;ll be creating:</p>
<div class="tutorial_image">
<object width="550" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/Preview.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/Preview.swf" /></object>
</div>
<p>The main takeaway in this tutorial is going to be the RGB shifting effect, but I&#8217;ll also demonstrate how to create the CRT scan lines, noise, and roll bar graphics.</p>
<hr/>
<h2><span>Step 1:</span> About RGB Images</h2>
<p>Every image on your computer screen is displayed using the colors red, blue and green. By mixing these three colors in various amounts your computer can create the other colors in the spectrum.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/1.jpg" alt="RGB Color Channels" /></div>
<p>If the three color channels don&#8217;t align properly the image won&#8217;t be composited correctly, and you&#8217;ll start to see the edges of the individual channels &#8216;bleeding&#8217; out of the sides of the image.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/2.jpg" alt="Misaligned Color Channels" /></div>
<p>This is exactly what we&#8217;re going to be doing in this tutorial; separating an image into its three color channels and then transforming each individually to create a distortion effect. Let&#8217;s get to it!</p>
<p>(You can learn a lot more about how RGB color works at <a href="http://en.wikipedia.org/wiki/RGB_color_model">Wikipedia</a>.)</p>
<hr/>
<h2><span>Step 2:</span> Create A Title Screen</h2>
<p>You&#8217;ll need to create a graphic to apply the effect to. I chose to create a video game title screen, but you can make whatever kind of graphic you want. </p>
<p>Create a new Movie Clip called &#8216;titleScreen&#8217; and put your title screen (or other graphics) inside.</p>
<p>I think something retro-themed works best with this effect since it reminds me of an old malfunctioning arcade screen. I created my title screen with a font called <a href="http://www.dafont.com/commodore-64-pixele.font">Commodore 64 Pixeled</a>. I added a Glow filter to the text to give it that smeary, blown out CRT look.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/3.jpg" alt="Glow Filter on Text" /></div>
<p>Once you&#8217;re happy with your design, add the <em>titleScreen</em> MovieClip to the stage and give it the instance name &#8216;titleScreen&#8217;.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/4.jpg" alt="titleScreen Instance" /></div>
<hr/>
<h2><span>Step 3:</span> Create the <em>RGBShift</em> class</h2>
<p>Create a new Actionscript file named &#8216;RGBShift.as&#8217;. Save this file in the same directory as your main Flash file. Add this code to create the shell for the class:</p>
<pre name="code" class="javascript">
package {

	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.display.BitmapDataChannel;
	import flash.display.BlendMode;
	import flash.events.Event;
	import flash.geom.Point;

	public class RGBShift extends Sprite {

		private var _centerX:Number;
		private var _centerY:Number;

		// CONSTRUCTOR
		public function RGBShift(dObj:DisplayObject) {

        }

	}

}
</pre>
<p><strong>Editor&#8217;s note:</strong> Not comfortable with class-based coding yet? Check out <a href="http://active.tutsplus.com/tutorials/actionscript/quick-tip-how-to-use-a-document-class-in-flash/">this Quick Tip</a> to help you get started.</p>
<p>This code doesn&#8217;t really do anything yet. The first 10 lines or so import all the extra classes we&#8217;re going to need. I have two private variables named &#8216;_centerX&#8217; and &#8216;_centerY&#8217; (I use the underscores to signify private variables). These two variables will hold the x and y coordinates of the center of our graphic.</p>
<p>Notice that the constructor function (empty for now) accepts a DisplayObject. This will allow us to use any type of DisplayObject with this effect (MovieClip, Sprite, Bitmap, etc.) We&#8217;re going to be using the <em>titleScreen</em> MovieClip from the stage, but having the class accept any DisplayObject keeps it flexible for later uses.</p>
<hr/>
<h2><span>Step 4:</span> Add the <em>createBMD</em> Function</h2>
<p>We made our class flexible by allowing it to accept any DisplayObject, but we&#8217;re actually going to need a BitmapData object to do the RGB shifting effect. Let&#8217;s create a function that can create BitmapData from a DisplayObject.</p>
<p>Add this function to your RGBShift class just below the constructor:</p>
<pre name="code" class="javascript:firstline[23]">
private function createBMD(dObj:DisplayObject):BitmapData {
	// create a new BitmapData object the size of our DisplayObject
	var bmd:BitmapData = new BitmapData(dObj.width, dObj.height,
										true, 0xFF000000);

	// draw the display object to the bitmap data
	bmd.draw(dObj);

	return bmd;
}
</pre>
<p>Take a look at what this function does. The first line uses the DisplayObject&#8217;s width and height to create a new transparent BitmapData object the same size as the DisplayObject. Next, it draws the DisplayObject to the BitmapData. Finally it returns the BitmapData to the caller.</p>
<hr/>
<h2><span>Step 5:</span> Add the <em>createRGB</em> Function</h2>
<p>Here&#8217;s where the actual color separation takes place. Add this function to your class:</p>
<pre name="code" class="javascript:firstline[33]">
private function createRGB(dObj:DisplayObject):Array {
	 var bmd:BitmapData = createBMD(dObj); // create bitmapData from the display object

	// create a new bitmap data object for each color channel
	var r:BitmapData = new BitmapData(bmd.width, bmd.height, true, 0xFF000000);
	var g:BitmapData = new BitmapData(bmd.width, bmd.height, true, 0xFF000000);
	var b:BitmapData = new BitmapData(bmd.width, bmd.height, true, 0xFF000000);

	// copy the data from each channel into the corresponding bitmap data
	r.copyChannel(bmd, bmd.rect, new Point(),
					BitmapDataChannel.RED, BitmapDataChannel.RED);
	g.copyChannel(bmd, bmd.rect, new Point(),
					BitmapDataChannel.GREEN, BitmapDataChannel.GREEN);
	b.copyChannel(bmd, bmd.rect, new Point(),
					BitmapDataChannel.BLUE, BitmapDataChannel.BLUE);

	// return an array with the bitmap data for the 3 color channels
	return [r, g, b];
}
</pre>
<p>This function also accepts a DisplayObject. It then passes that to the <em>createBMD()</em> function we wrote in the previous step, which converts it to BitmapData. Next we create three new transparent BitmapData objects; one for each color. We create them at the exact same size as our source BitmapData (from the DisplayObject).</p>
<p>We then use BitmapData&#8217;s <em>copyChannel()</em> method to copy a single color channel from the source BitmapData into each of the three new BitmapData objects.</p>
<p>The final line simply returns the three new BitmapData objects wrapped in an array.</p>
<hr/>
<h2><span>Step 6:</span> Use the <em>createRGB</em> Function in the Constructor</h2>
<p>Now that we have our <em>createBMD</em> and <em>createRGB</em> classes working together, let&#8217;s put them to use. Add this as the first line of code in the constructor function for the RGBShift class:</p>
<pre name="code" class="javascript:firstline[19]">
var rgbBMD:Array = createRGB(dObj);
</pre>
<p>This line just passes the DisplayObject to the <em>createRGB()</em> function. <em>createRGB()</em> uses the <em>createBMD()</em> function to convert it to BitmapData and then separates it onto three separate BitmapData objects (one for each channel). Finally it returns the array of those three objects to our local <em>rgbBMD</em> array. Make sense? Good.</p>
<hr/>
<h2><span>Step 7:</span> Create Bitmaps from the RGB Channels</h2>
<p>We now have an array of three BitmapData objects. We need to create a Bitmap from each in order to display them on the screen. Add this <em>for</em> loop to the constructor function of RGBShift just below  the last line we added:</p>
<p><strong>Editor&#8217;s note:</strong> Sorry for the inconvenience folks, displaying this particular bit of ActionScript trips FireFox over. Feel free to <a href="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/step7.as">download it here</a>.</p>
<p><!--
<pre name="code" class="javascript:firstline[21]">
</pre>
<p>--></p>
<p>Most of this is pretty simple. Let's take a look.</p>
<ul>
<li>With each BitmapData object in our rgbBMD array we're creating a new Bitmap.</li>
<li>We set smoothing to true so we can scale and rotate it without it getting pixelated. (line 23)</li>
<li>Next we create a container Sprite and add the new Bitmap to the container's display list. (lines 25 &amp; 26)</li>
<li>Now we finally start using the _centerX and _centerY variables. We set each to the center of the Bitmap by dividing the width and height in half.</li>
<li>We use this center point to offset the Bitmap inside the container Sprite, and then to offset the container Sprite on the stage. I'll explain why in the next step.</li>
<li>Finally we add the container Sprite to the stage (remember there is a container for each of our three color channels).</li>
</ul>
<hr/>
<h2><span>Step 8:</span> Why Use the Container Sprite?</h2>
<p>You could create this effect without the container Sprite by just adding the Bitmaps directly to the stage. I like to wrap them in a container because it makes it easier to control the transform point when you do things like scale and rotate.</p>
<p>Normally, when you perform a scale or a rotate on an object it transforms from the origin point (0,0) of that object. That's seldom what I want to happen. Usually I want the transformations to be applied from the center of the object.</p>
<p>Notice that in the last section we set the x and y of the Bitmaps to <em>negative</em> one half the width and height. This places the Bitmap so that its center point is at 0,0 in the container Sprite. If we perform any transformations on the container Sprite it will transform from 0,0 of the container, which is now the center of our Bitmap.</p>
<p>The only problem is that only the bottom corner of our Bitmap is visible now, so I set the container Sprite x and y to half the height and width of the Bitmap to get everything back its correct position.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/5.jpg" alt="Container Sprite Offset" /></div>
<hr/>
<h2><span>Step 9:</span> RGBShift Class</h2>
<p>Here's the RGBShift class up to this point in case you got lost along the way:</p>
<p><strong>Editor's note:</strong> Me again, once more you'll have to <a href="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/step9.as">download the AS here</a>. Sorry for the inconvenience.</p>
<p><!--
<pre name="code" class="javascript">
</pre>
<p>--></p>
<hr/>
<h2><span>Step 10:</span> Create the Main Document Class</h2>
<p>So, we have our RGBShift class, but how do we use it? Begin by creating a new Actionscript file called Main.as, then add this code:</p>
<pre name="code" class="javascript">
package {

	import flash.display.MovieClip;

	public class Main extends MovieClip {

		public function Main() {

			var rgb = new RGBShift(titleScreen); // create a new RGBShift from the titleScreen
			removeChild(titleScreen); // remove the original title screen from the stage

			// add it to the stage
			addChild(rgb);

		}
	}

}
</pre>
<p>Here we're creating a new instance of the RGBShift class and passing it the <em>titleScreen</em> MovieClip from the stage. We no longer need that MovieClip, so we remove it from the stage and add the new RGBShift instance instead.</p>
<p>Now we just have to link this class to our Flash document. Go back to Flash and set the document class to 'Main'.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/6.jpg" alt="Set the Document Class" /></div>
<hr/>
<h2><span>Step 11:</span> Test</h2>
<p>You should now be able to test your Flash file (Control -> Test Movie) without getting any errors or warnings.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/7.jpg" alt="First Test" /></div>
<p>Hmm, that doesn't look quite right does it?</p>
<p>What's happening here is we've layered the three color channels on top of each other, but they're not combining and mixing the colors, so we're only seeing the top layer (blue). Let's fix that now.</p>
<hr/>
<h2><span>Step 12:</span> Change the Blend Mode</h2>
<p>To get the color channels to blend properly we need to change their BlendMode to SCREEN. We only want to change the blend mode of the second and third layers though. We'll leave the first (bottom) layer normal and blend the other two layers into it.</p>
<p>Add this code to the <em>for</em> loop in the RGBShift class constructor function:</p>
<pre name="code" class="code javascript:firstline[25]">
if(i>0) {
	// set SCREEN blend mode for the 2nd and 3rd images
	bmp.blendMode = BlendMode.SCREEN;
}
</pre>
<p>This checks to make sure the current image is not the first image (0) and then sets the blendMode property to SCREEN.</p>
<hr/>
<h2><span>Step 13:</span> Test Again</h2>
<p>Test your movie again and you should see something that looks identical to your titleScreen MovieClip.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/8.jpg" alt="Successful Test" /></div>
<p>I know what you're thinking; 'That was a lot of work to recreate the same graphic that was already there.'</p>
<p>But now the graphic is made up of three objects that we can transform individually to create our distortion. So quit your whining and let's continue...</p>
<hr/>
<h2><span>Step 14:</span> Download the Tweener Library</h2>
<p>We're going to use the Tweener Library to do our animation. <a href="http://tweener.googlecode.com/files/tweener_1_33_74_as3.zip">Download it here</a> if you don't already have it.</p>
<p>To use Tweener, place the main 'caurina' folder in the same directory as your Flash file and add this import statement to the top of the RGBShift class:</p>
<pre name="code" class="javascript:firstline[12]">
import caurina.transitions.Tweener;
</pre>
<hr/>
<h2><span>Step 15:</span> Add the <em>randRange</em> File</h2>
<p>I use this <em>randRange</em> function as an easy way to generate random integers within a given range. You could just add this function to the RGBShift class, but I use this function so often that I like to keep it in a separate file, so it's easier to share among different projects.</p>
<p>Create a new Actionscript file named 'randRange.as' in the same folder as your main Flash file. Add this code:</p>
<pre name="code" class="javascript">
package {
	// returns a random number between specified range (inclusive)
	public function randRange(min:int, max:int):int {
	    var randomNum:int = Math.floor(Math.random() * (max - min + 1)) + min;
	    return randomNum;
	}
}
</pre>
<p>As you can see it's just a single function wrapped in a package declaration. We can now use this function as if it were a part of our class.</p>
<p>(For more information on how this function works, check out <a href="http://active.tutsplus.com/tutorials/actionscript/quick-tip-get-a-random-number-within-a-specified-range-using-as3/">Carlos's Quick Tip</a>.)</p>
<hr/>
<h2><span>Step 16:</span> Add the <em>distort()</em> Function</h2>
<p>Here's where the magic happens. Add this function to the RGBShift class:</p>
<pre name="code" class="javascript:firstline[52]">
private function distort(img:Sprite):void {
	Tweener.addTween(img, {
			y: randRange(_centerY-3, _centerY+3),	// randomize y shift
			time:randRange(1,2) /10, 		// randomize time
			alpha: randRange(8,10) /10,		// randomize alpha
			transition:"easeInOutSine",

			onComplete:distort, 			// when finished start the distortion again
			onCompleteParams:[img]
			}
	);
}
</pre>
<p>We're going to run this <em>distort()</em> function on each of our color channels separately to create the distortion effect. </p>
<p>The function accepts a Sprite (one of our color channel containers). It then starts a Tweener animation on the channel using a random Y value (between -3 and 3), and a random length of time (between 1 and 2 seconds). This will make each channel shift up and down by different amounts at different speeds.</p>
<p>Notice I'm using the _centerY variable here again to offset the Y value. We also tween to a random alpha value (between .8 and 1) to make each channel flicker a bit. When the tween finishes we use the onComplete property to call the same <em>distort()</em> function again. Using onCompleteParams we send it the same color channel Sprite. This causes the distort function to loop over and over on each of our color channels.</p>
<p>See, what did I tell you..? Magic!</p>
<p>To kick off this distortion loop we need to call it once on each of our color channel Sprites. Add this line to the end of the <em>for</em> loop in the RGBShift constructor function:</p>
<pre name="code" class="javascript:firstline[46]">
distort(container);  // start the bitmap distortion
</pre>
<hr/>
<h2><span>Step 17:</span> Experiment</h2>
<p>You should now be able to test your movie and see the distortion effect in action.</p>
<p>Personally, I like the subtle Y shift that we've got going here, but you can do a lot of crazy stuff with the distortion now that we've got the channels animating separately.</p>
<p>To experiment with the distortion you can just modify the properties and values in the Tweener call in the <em>distort</em> function. Check the <a href="http://hosted.zeh.com.br/tweener/docs/en-us/">Tweener Documentation</a> for a complete list of tweenable properties.</p>
<p>Here's an example of some severe distortion I created by simply adding a few more properties to the Tweener call:</p>
<div class="tutorial_image">
<object width="550" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/milestone1.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/milestone1.swf" /></object>
</div>
<p>Check out the <em>distort()</em> function that created the effect:</p>
<pre name="code" class="javascript:firstline[52]">
private function distort(img:Sprite):void {
	Tweener.addTween(img, {
			y: randRange(_centerY-3, _centerY+3), 	// ranomize y shift
			x: randRange(_centerX-10, _centerX+10),
			time:randRange(1,2) /10, 		// randomize time
			scaleX: randRange(9,11)/10,		// randimize x scale

			alpha: randRange(5,10) /10,		// randomize alpha
			transition:"easeInOutSine",

			onComplete:distort, 			// when finished start the distortion again
			onCompleteParams:[img]
			}
	);
}
</pre>
<hr/>
<h2><span>Step 18:</span> Enhance the CRT Look</h2>
<p>You can stop here if you want. The RGB separation and distortion should be working at this point.</p>
<p>To enhance the CRT effect I think we need to add a few more graphical elements. In the next few steps we'll be adding scan lines, a rolling black bar, some static, and a shiny reflection.</p>
<hr/>
<h2><span>Step 19:</span> Add the Scan Lines</h2>
<p>Create a new MovieClip on the stage called 'lines'. Inside the MovieClip draw a 1 pixel horizontal line that spans the entire width of your movie. Set the stroke color to black with 40% alpha.</p>
<p>Now copy and paste this line over and over, moving it down 2 pixels each time, until you have lines covering the entire height of your movie. The effect you want is a 1 pixel line, then a 1 pixel space before the next line.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/9.jpg" alt="Scan Lines" /></div>
<hr/>
<h2><span>Step 20:</span> Add the Rolling Bar</h2>
<p>Now we'll add the rolling black bar. Create a new MovieClip called 'bar'. Inside, draw a solid black rectangle that spans the entire width of your movie. Make it about 40 pixels high. Set the Color Style of the MovieClip to Alpha at 30%.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/10.jpg" alt="Bar MovieClip" /></div>
<hr/>
<h2><span>Step 21:</span> Animate the Rolling Bar</h2>
<p>Create a new MovieClip called 'animatingBar' and place your <em>bar</em> clip inside. Create a short motion tween animation of the bar moving from the top of your movie to the bottom. This animation will loop to give us the rolling bar effect.</p>
<p>Place the animatingBar clip on the stage. Select it and add a blur filter. Unlink the X and Y blur settings and set the Blur Y to 20 and the Blur X to 0.</p>
<p>Set the blend mode to Overlay. This is similar to the Screen blend mode we used earlier, but not exactly the same.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/11.jpg" alt="AnimatingBar Blur Filter" /></div>
<hr/>
<h2><span>Step 22:</span> Create the Static Image</h2>
<p>Create a new Photoshop file the same size as your movie. Fill the background layer with neutral grey (#808080). Choose Filter > Noise > Add Noise...<br />
	Set the filter to 100%, Gaussian, Monochromatic.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/12.jpg" alt="Noise Filter Settings" /></div>
<p>Save the image as 'noise.jpg'. If you don't have Photoshop, you can get my 'noise.jpg' from the Source zip file.</p>
<hr/>
<h2><span>Step 23:</span> Animate the Static</h2>
<p>Import the <em>noise.jpg</em> image into your flash file. Create a new MovieClip called 'noise' and add the image to it. Create a new keyframe on frame 2 (F6) and rotate the image 180 degrees. Create another keyframe on frame 3 and flip the image horizontally (Modify > Transform > Flip Horizontal). Create a fourth keyframe on frame 4 and again rotate the image 180 degrees. We now have a 4 frame animation of flickering static.</p>
<p>You could also generate this noise effect using ActionScript, but that is beyond the scope of this tutorial.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/13.gif" alt="Animating Noise" /></div>
<hr/>
<h2><span>Step 24:</span> Add the Reflection</h2>
<p>Create a new MovieClip on the stage called 'shine'. Inside it draw a large oval that extends halfway above the top of your movie. Select the top portion of the oval and delete it. </p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/14.jpg" alt="Create Shine Oval" /></div>
<p>Change the fill to a linear gradient and set it so it blends from white 20% alpha at the top to white 5% alpha at the bottom. Grab the top of the shape and pull it up a little to give it a slight curve.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/076_rgbShift/Tutorial/15.jpg" alt="Color the Oval" /></div>
<hr/>
<h2><span>Step 25:</span> Fix Element Layering</h2>
<p>If you test your movie now you won't see any of the new graphics we just added because the RGB layers are being added on top of everything. To fix this go into the <em>Main</em> class and change this line:</p>
<pre name="code" class="javascript:firstline[13]">
addChild(rgb);
</pre>
<p>To this:</p>
<pre name="code" class="javascript:firstline[13]">
addChildAt(rgb, 0);
</pre>
<p>That adds the RGBShift object at the lowest level of <a href="http://active.tutsplus.com/tutorials/actionscript/as3-101the-display-list/">the display list</a>, below all the other graphics.</p>
<hr/>
<h2>Conclusion</h2>
<p>This tutorial is meant to be a starting place, not a final solution. Now that you have the RGB channels separated and animating individually there are a lot of different things you can do with this technique. The effect would look really nice if it were combined with the static distortion technique from my <a href="http://active.tutsplus.com/tutorials/effects/create-a-static-distortion-effect-using-the-displacement-map-filter/">earlier tutorial</a>.</p>
<p>As always, post a comment and let me know what you think. Good luck! </p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/create-a-retro-crt-distortion-effect-using-rgb-shifting/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Create 3D Effects With the Stardust Particle Engine</title>
		<link>http://active.tutsplus.com/tutorials/effects/create-3d-effects-with-the-stardust-particle-engine/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/create-3d-effects-with-the-stardust-particle-engine/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 12:00:51 +0000</pubDate>
		<dc:creator>Allen Chou</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3323</guid>
		<description><![CDATA[In my previous tutorial Shoot Out Stars with the Stardust Particle Engine, I explained the basic workflow of Stardust. This time, we&#8217;ll take things further and examine a couple of techniques for creating true 3D particle effects!


Introduction

We&#8217;ll begin with a demonstration of how to use the Stardust&#8217;s native 3D engine. Then, I&#8217;ll show you how [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous tutorial <a href="http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/">Shoot Out Stars with the Stardust Particle Engine</a>, I explained the basic workflow of Stardust. This time, we&#8217;ll take things further and examine a couple of techniques for creating true 3D particle effects!</p>
<p><span id="more-3323"></span></p>
<hr/>
<h2>Introduction</h2>
<p>
We&#8217;ll begin with a demonstration of how to use the <a href="http://code.google.com/p/stardust-particle-engine/">Stardust&#8217;s</a> native 3D engine. Then, I&#8217;ll show you how to get Stardust to work with Papervision3D; we&#8217;ll be creating 3D particle effects with Papervision3D&#8217;s Particles class and DisplayObject3D class.
</p>
<hr/>
<h2>Previously&#8230;</h2>
<p>
We&#8217;re going to pick up where we left off in the <a href="http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/"/>first tutorial</a>. Last time we created star and circle particles shooting out from a point, growing to a maximum size and then shrinking to nothing, while moving gradually slower over time (called a damping effect). This time, we&#8217;ll do the same thing, but in 3D. Instead of the particles moving out in a circle, they&#8217;ll move out in a sphere.
</p>
<hr/>
<h2><span>Step 1:</span> Create a New Flash Document</h2>
<p>
Just as <a href="http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/">before</a>, first create a new Flash document with dimensions of 640&#215;400, a frame rate of 60fps, and a dark background (I used a dark blue gradient).
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/075_stardust3D/Tutorial/1.jpg"/></div>
<hr/>
<h2><span>Step 2:</span> Draw the Particles</h2>
<p>
Draw a star and a white circle, then convert them to symbols, separately. These are the two symbols we are going to use as particles later. Name the star symbol &#8220;Star&#8221; and circle symbol &#8220;Circle&#8221;, exported for ActionScript with the same class names.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/075_stardust3D/Tutorial/2.jpg"/></div>
<p>(If you&#8217;re not much of an artist, you can download the source at the top of the page and use my symbols from the library of my FLA.)</p>
<hr/>
<h2><span>Step 3:</span> Create the Pause Button</h2>
<p>
Click <em>Window > Components</em> to bring up the Components Panel, then drag a Button from the User Interface folder onto the stage. Set the label to &#8220;Pause&#8221; and name it &#8220;pause_btn&#8221;. We are going to use this button to pause the 3D particle effects, thereby allowing users to spin the camera around in order to get a better taste of the 3D environment.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/075_stardust3D/Tutorial/3.jpg"/></div>
<hr/>
<h2><span>Step 4:</span> Create the Document Class</h2>
<p>
Create a new document class and name it StarParticles3D.
</p>
<pre name="code" class="javascript">
package {
	import flash.display.Sprite;

	public class StarParticles3D extends Sprite {

		public function StarParticles() {

		}
	}
}
</pre>
<p>Not sure how to use a document class? <a href="http://active.tutsplus.com/tutorials/actionscript/quick-tip-how-to-use-a-document-class-in-flash/">Read this Quick Tip.</a></p>
<hr/>
<h2>3D Initializers and Actions</h2>
<p>
The three main packages in Stardust are:
</p>
<ul>
<li>
<em>idv.cjcat.stardust.common</em>: contains general elements for both 2D and 3D particle effects.
</li>
<li>
<em>idv.cjcat.stardust.twoD</em>: contains specific elements for 2D particle effects.
</li>
<li>
<em>idv.cjcat.stardust.threeD</em>: contains specific elements for 3D particle effects.
</li>
</ul>
<p>
In the previous tutorial we used initializers and actions from the common and twoD packages. In this tutorial, we&#8217;ll still be using elements from the common package, but not from the twoD package. Instead, we will use elements from the threeD package.
</p>
<p>The class structure of the threeD package is pretty much the same as in the twoD package, except that the elements have an extra dimension. A 3D element possesses the same name as its 2D counterpart, but its name ends with &#8220;3D&#8221;. For example, the <em>Move3D</em> action in the 3D package updates particle positions in 3D space according to the velocities, just like its 2D counterpart in the 2D package, the <em>Move</em> action.
</p>
<hr/>
<h2><span>Step 5:</span> Extend the Emitter</h2>
<p>
Create a new AS file called <em>StarEmitter.as</em>; inside it, create a new class <em>StarEmitter</em>, which extends the Emitter3D class:
</p>
<pre name="code" class="javascript">
package {
	import idv.cjcat.stardust.threeD.emitters.Emitter3D;	//don't forget to import this!

	public class StarEmitter extends Emitter3D {

		public function StarEmitter(clock:Clock) {
			//pass the clock object to the superclass's constructor
			super(clock);
		}
	}
}
</pre>
<p>Remember the Clock parameter? It&#8217;s used to control the rate of particle creation. We need to include it in the constructor function, so that we can pass a Clock to it later.</p>
<p>
Since we are allowing users to pause the particle effects, we&#8217;re going to pack all the actions into a single CompositeAction object, which is essentially a group of actions. By deactivating this single composite action, we can &#8220;turn off&#8221; all the underlying actions. Declare a variable for a composite action in the emitter class. We&#8217;ll access this variable in the document class, so it needs to be public:
</p>
<pre name="code" class="javascript">
public var pausibleActions:CompositeAction;
</pre>
<hr/>
<h2><span>Step 6:</span> Declare the Particle Constants</h2>
<p>
Declare constants that will be used as particle parameters in the emitter class. We already covered the purpose of these constants in the previous tutorial. Most of the names are self-explanatory. These go inside the class but outside the constructor function. Feel free to come back here later and alter the numbers to see the effects.
</p>
<pre name="code" class="javascript">
private static const LIFE_AVG:Number = 30;
private static const LIFE_VAR:Number = 10;
private static const SCALE_AVG:Number = 1;
private static const SCALE_VAR:Number = 0.4;
private static const GROWING_TIME:Number = 5;
private static const SHRINKING_TIME:Number = 10;
private static const SPEED_AVG:Number = 30;
private static const SPEED_VAR:Number = 10;
private static const OMEGA_AVG:Number = 0;
private static const OMEGA_VAR:Number = 5;
private static const DAMPING:Number = 0.1;
</pre>
<hr/>
<h2><span>Step 7:</span> The Switch Initializer for Particle Display Objects</h2>
<p>
In the previous tutorial I demonstrated how to use the SwitchInitializer to create particles with different display objects. I was using the DisplayObjectClass initializer, which initializes particle appearance with display Objects. That was for 2D particle effects; here we are going to use its 3D counterpart, the DisplayObject3D initializer.</p>
<p>Add the following code to the emitter&#8217;s constructor function:</p>
<pre name="code" class="javascript">
//switch initializers for star and circle particles
var doc1:DisplayObjectClass3D = new DisplayObjectClass3D(Star);
var doc2:DisplayObjectClass3D = new DisplayObjectClass3D(Circle);
var si:SwitchInitializer = new SwitchInitializer([doc1, doc2], [1, 1]);
addInitializer(si);
</pre>
<hr/>
<h2><span>Step 8:</span> Add the Remaining Initializers</h2>
<p>
Same as the previous tutorial; add the other initializers shown below. Note that some of them have similar names to those in the previous tutorial, but end in &#8220;3D&#8221;.
</p>
<ul>
<li>
The Position3D initializer initializes particle positions. Just as its 2D counterpart, the Position initializer, it accepts one constructor parameter, a zone object. However, this time it does not accept a Zone object, which represents a 2D zone; instead, it accepts a Zone3D object, representing a zone in 3D space. The SinglePoint3D class extends the Zone3D class and is the 3D version of the SinglePoint class.
</li>
<li>
The same goes for the Velocity3D class. The SphereShell class is essentially the 3D version of the SectorZone class. Here we set the center of the sphere shell to (0, 0, 0), average radius to SPEED_AVG, and radius variation to SPEED_VAR.
</li>
<li>
The Rotation3D and Omega3D initializers work exactly the same as their 2D counterparts, Rotation and Omega. However, there is one little difference about the constructor parameters: they accept three Random objects instead of one. That is because now, in 3D space, there are three axes of rotation, so they require three random rotation values for these axes. In this example we are creating &#8220;2D billboards&#8221; in 3D space (i.e. flat objects), so only the rotation for the Z axis is apparent; that&#8217;s why the first two parameters, Random objects for the X and Y axes, are assigned with null values.
</li>
</ul>
<p>This code goes in the StarEmitter&#8217;s constructor function:</p>
<pre name="code" class="javascript">
addInitializer(new Life(new UniformRandom(LIFE_AVG, LIFE_VAR)));
addInitializer(new Scale(new UniformRandom(SCALE_AVG, SCALE_VAR)));
addInitializer(new Position3D(new SinglePoint3D()));
addInitializer(new Velocity3D(new SphereShell(0, 0, 0, SPEED_AVG, SPEED_VAR)));
addInitializer(new Rotation3D(null, null, new UniformRandom(0, 180)));
addInitializer(new Omega3D(null, null, new UniformRandom(OMEGA_AVG, OMEGA_VAR)));
</pre>
<hr/>
<h2><span>Step 9:</span> Add the Actions</h2>
<p>
Create a composite action, and add some actions to it. Then add this composite action to the emitter; this will make the particles perform the actions. You&#8217;ve seen these actions in the previous tutorial (some of them in 2D version), so I won&#8217;t explain them all over again. Again, this code goes in the StarEmitter&#8217;s constructor function:
</p>
<pre name="code" class="javascript">
pausibleActions = new CompositeAction();
pausibleActions.addAction(new Age());
pausibleActions.addAction(new DeathLife());
pausibleActions.addAction(new Move3D());
pausibleActions.addAction(new Spin3D());
pausibleActions.addAction(new Damping3D(DAMPING));
pausibleActions.addAction(new ScaleCurve(GROWING_TIME, SHRINKING_TIME));
addAction(pausibleActions);
</pre>
<hr/>
<h2><span>Step 10:</span> Back to The Document Class</h2>
<p>
All right, we&#8217;re done with the emitter. Now it&#8217;s time to build our document class.
</p>
<p>
First, declare constants for the orbiting camera&#8217;s radius, the camera distance from the origin and the emitter&#8217;s rate:
</p>
<pre name="code" class="javascript">
private static const CAMERA_RADIUS:Number = 250;
private static const PARTICLE_RATE:Number = 0.5;
</pre>
<p>(As before, consts go inside the class but outside the constructor function.)</p>
<p>
Then, declare variables for an emitter, a steady clock and a DisplayObjectRenderer3D (in the same place as the consts):
</p>
<pre name="code" class="javascript">
private var emitter:StarEmitter;
private var clock:SteadyClock;
private var renderer:DisplayObjectRenderer3D;
</pre>
<p>
In the constructor, initialize the clock, emitter and renderer. Also, set the initial camera&#8217;s position and direction, making it look at the origin:
</p>
<pre name="code" class="javascript">
//create the clock and emitter
clock = new SteadyClock(PARTICLE_RATE);
emitter = new StarEmitter(clock);	//we can do this because we gave StarEmitter's constructor a clock parameter

//create the renderer and its container sprite
var container:Sprite = new Sprite();
container.x = 320, container.y = 200;
renderer =  new DisplayObjectRenderer3D(container);
renderer.addEmitter(emitter);

//add the container to the stage
addChild(container);
//add the pause button again so that it is on top of the container
addChild(pause_btn);

//set the camera's initial position and direction
renderer.camera.position.set(0, 0, -CAMERA_RADIUS);
renderer.camera.direction.set(0, 0, CAMERA_RADIUS);
</pre>
<hr/>
<h2><span>Step 11:</span> Program the Pause</h2>
<p>
Create a handler function in the document class to handle the click event of the pause button:
</p>
<pre name="code" class="javascript">
private function togglePause(e:MouseEvent):void {
	if (e.target.label == "Pause") {
		e.target.label = "Resume";
		clock.ticksPerCall = 0;		//stop the clock
		emitter.pausibleActions.active = false;	//deactivate the emitter's actions
	} else {
		e.target.label = "Pause";
		clock.ticksPerCall = PARTICLE_RATE;		//restart the clock
		emitter.pausibleActions.active = true;	//reactivate the emitter's actions
	}
}
</pre>
<p>
..then register the listener for the pause button, in the constructor function:
</p>
<pre name="code" class="javascript">
pause_btn.addEventListener(MouseEvent.CLICK, togglePause);
</pre>
<hr/>
<h2><span>Step 12:</span> The Main Loop</h2>
<p>
Create a handler for the ENTER_FRAME event. This is our main loop. It updates the camera&#8217;s position by calling the updateCamera() method (which we will code in a minute) and calls the emitter&#8217;s step() method, which keeps the particle effects running:
</p>
<pre name="code" class="javascript">
private function mainLoop(e:Event):void {
	updateCamera();
	emitter.step();
}
</pre>
<p>
Again, register a listener in the constructor:
</p>
<pre name="code" class="javascript">
addEventListener(Event.ENTER_FRAME, mainLoop);
</pre>
<hr/>
<h2><span>Step 13:</span> Update the Camera&#8217;s Position</h2>
<p>
Now define the updateCamera() method called in the previous step. This is used to move the camera in 3D space depending on the mouse&#8217;s position. (If you&#8217;d like more information on how it works check out <a href="http://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates">this Wikipedia article</a>.)</p>
<p>The magic numbers used to generate theta and phi are just the result of trial and error; feel free to try your own equations.</p>
<pre name="code" class="javascript">
private function updateCamera():void {
	var theta:Number = 0.02 * (mouseX - 320);
	var phi:Number = 0.02 * (mouseY - 200);
	phi = StardustMath.clamp(phi, -StardustMath.HALF_PI, StardustMath.HALF_PI);

	var x:Number = CAMERA_RADIUS * Math.cos(theta) * Math.cos(phi);
	var y:Number = CAMERA_RADIUS * Math.sin(phi);
	var z:Number = CAMERA_RADIUS * Math.sin(theta) * Math.cos(phi);
	renderer.camera.position.set(x, y, z);
	renderer.camera.direction.set(-x, -y, -z);
}
</pre>
<p>Note that I used the StardustMath.clamp() method; this makes sure the phi value is kept between positive and negative half PI.</p>
<hr/>
<h2><span>Milestone:</span> Native Stardust Engine Complete</h2>
<p>
Okay, we&#8217;re done! That&#8217;s all we need to do to get a 3D emitter working with Stardust&#8217;s native 3D engine. Let&#8217;s look at the result. You can click the pause button to pause the particle effect, and move the mouse around to orbit the camera:</p>
<div class="download_wrap">
<div class="big_btn">
		<a href="http://activetuts.s3.cdn.plus.org/tuts/075_stardust3D/Preview/Stardust Native 3D Engine/StarParticles3D.html" rel="external"><span>Demo</span> <small>View It Online</small></a>
	</div>
</div>
<p>If you&#8217;d like to see the full source code, look in the folder called &#8220;01 &#8211; Stardust Native 3D Engine&#8221; in the Source.</p>
<hr/>
<h2>Time for Papervision3D</h2>
<p>
To switch from Stardust&#8217;s native 3D engine to Papervision3D is easy. We&#8217;ll just have to use a different renderer and display object initializer.
</p>
<p>(Never used Papervision3D before? Take a look at <a href="http://active.tutsplus.com/tutorials/3d/journey-to-the-next-dimension-with-pv3d-and-funny-glasses-part-1/">this beginner&#8217;s tutorial</a>.)</p>
<p>
First we&#8217;ll use Papervision3D&#8217;s Particles class. You might not be familiar with this; I&#8217;ll show you how to use the more common DisplayObject3D class later.
</p>
<hr/>
<h2><span>Step 14:</span> Change the Display Object Initializer</h2>
<p>
Change the following code in the emitter class:
</p>
<pre name="code" class="javascript">
var doc1:DisplayObjectClass3D = new DisplayObjectClass3D(Star);
var doc2:DisplayObjectClass3D = new DisplayObjectClass3D(Circle);
</pre>
<p>to this:</p>
<pre name="code" class="javascript">
var mat1:MovieParticleMaterial = new MovieParticleMaterial(new Star());
var mat2:MovieParticleMaterial = new MovieParticleMaterial(new Circle());
var doc1:PV3DParticle = new PV3DParticle([mat1]);
var doc2:PV3DParticle = new PV3DParticle([mat2]);
</pre>
<p>
As you may already know, the MovieParticleMaterial class allows us to use display objects as particles&#8217; appearance in Papervision3D. We create a Star and Circle instance to be used as particle material. The PV3DParticle initializer takes the place of the DisplayObjectClass3D initializer; its constructor accepts an array of parameters, which will all be added to a Particles object.
</p>
<p>
This is all we have to do regarding the emitter. Next we&#8217;ll modify the document class.
</p>
<hr/>
<h2><span>Step 15:</span> Set Up the Papervision3D Environment</h2>
<p>
The target container for our renderer is no longer a Sprite object. Instead, we are going to create particles in a Particles object. We&#8217;ll have to switch the renderer&#8217;s type from DisplayObjectRenderer3D to PV3DParticleRenderer.
</p>
<p>
Declare the following variables for Papervision3D-related objects:
</p>
<pre name="code" class="javascript">
private var scene:SceneObject3D;
private var particles:Particles;
private var camera:Camera3D;
private var origin:DisplayObject3D;
private var renderEngine:BasicRenderEngine;
private var viewport:Viewport3D;
</pre>
<p>
The code in the document class&#8217;s constructor is now:
</p>
<pre name="code" class="javascript">
initPV3D();		//this is new!

clock = new SteadyClock(PARTICLE_RATE);
emitter = new StarEmitter(clock);

renderer =  new PV3DParticleRenderer(particles);	//this is new!
renderer.addEmitter(emitter);

pause_btn.addEventListener(MouseEvent.CLICK, togglePause);
addEventListener(Event.ENTER_FRAME, mainLoop);
</pre>
<p>
The initPV3D() method sets up the Papervision3D Environment. Here&#8217;s the code:
</p>
<pre name="code" class="javascript">
private function initPV3D():void {

	//create the scene
	scene = new SceneObject3D();

	//create the Particles object
	particles = new Particles();

	//create the camera and initialize its position
	camera = new Camera3D();
	camera.position.x = 0;
	camera.position.y = 0;
	camera.position.z = -CAMERA_RADIUS;

	//create a DO3D representing the origin
	origin = new DisplayObject3D();
	origin.x = origin.y = origin.z = 0;

	//point the camera to the origin
	camera.target = origin;

	scene.addChild(origin);
	scene.addChild(particles);

	//create the render engine and viewport
	renderEngine = new BasicRenderEngine();
	viewport = new Viewport3D(640, 400);

	//add the viewport to the stage
	addChild(viewport);
	//add the pause button again so that it is on top of the viewport
	addChild(pause_btn);
}
</pre>
<hr/>
<h2><span>Step 16:</span> The New Main Loop</h2>
<p>
Now Stardust only updates the 3D objects&#8217; properties; Papervision3D&#8217;s render engine is taking over the responsibility of rendering. This is what our new main loop looks like:
</p>
<pre name="code" class="javascript">
private function mainLoop(e:Event):void {
	updateCamera();
	emitter.step();
	renderEngine.renderScene(scene, camera, viewport);	//this is new!
}
</pre>
<hr/>
<h2><span>Step 17:</span> Updating the Camera</h2>
<p>
Now that we are using Papervision3D&#8217;s camera, we&#8217;ll also have to modify the updateCamera() method:
</p>
<pre name="code" class="javascript">
private function updateCamera():void {
	var theta:Number = 0.02 * (mouseX - 320);
	var phi:Number = 0.02 * (mouseY - 200);
	phi = StardustMath.clamp(phi, -StardustMath.HALF_PI, StardustMath.HALF_PI);

	var x:Number = CAMERA_RADIUS * Math.cos(theta) * Math.cos(phi);
	var y:Number = -CAMERA_RADIUS * Math.sin(phi);	//note this is negative now
	var z:Number = CAMERA_RADIUS * Math.sin(theta) * Math.cos(phi);
	camera.x = x;	//we update each of the x, y, z properties of PV3D's camera separately
	camera.y = y;
	camera.z = z;
}
</pre>
<hr/>
<h2><span>Milestone:</span> Papervision3D with Particles Completed</h2>
<p>
Okay, we have successfully switched from Stardust&#8217;s native 3D engine to Papervision3D. Now let&#8217;s check out the result. Note the pixelation effect on the particles. That is because Papervision3D first draws vector objects into bitmaps before using them as particle materials.
</p>
<div class="download_wrap">
<div class="big_btn">
		<a href="http://activetuts.s3.amazonaws.com/tuts/075_stardust3D/Preview/Papervision3D Particles/StarParticles3D.html" rel="external"><span>Demo</span> <small>View It Online</small></a>
	</div>
</div>
<p>You can find all the source code for this in the &#8220;02 &#8211; Papervision3D Particles&#8221; folder.</p>
<hr/>
<h2>Papervision3D&#8217;s DisplayObject3D Class</h2>
<p>
So far, we have been working with &#8220;2D billboards&#8221; &#8211; flat objects, like paper. It&#8217;s possible to create &#8220;real&#8221; 3D particle objects, like Papervision3D&#8217;s DisplayObject3D objects. We&#8217;re just going to have to use another initializer. Now let&#8217;s get down to the final part of this tutorial. We will create red and blue cube particles.
</p>
<hr/>
<h2><span>Step 18:</span> Change the Display Object Initializer, Again</h2>
<p>
We&#8217;re going to change the initializer concerning the particle appearance for the last time.
</p>
<p>
Before that, declare a LightObject3D variable in the emitter class. We are going to use the FlatShadeMaterial for the DisplayObject3D objects, which require a light source. Also, declare the following constants &#8211; we&#8217;ll use these as parameters for the FlastShadeMaterial, and for determining the cubes&#8217; sizes:
</p>
<pre name="code" class="javascript">
public var light:LightObject3D;

private static const LIGHT_COLOR_1:uint = 0xCC3300;
private static const LIGHT_COLOR_2:uint = 0x006699;
private static const AMBIENT_COLOR_1:uint = 0x881100;
private static const AMBIENT_COLOR_2:uint = 0x002244;
private static const CUBE_SIZE:Number = 15;
</pre>
<p>
Now change the following code in the emitter class:
</p>
<pre name="code" class="javascript">
var mat1:MovieParticleMaterial = new MovieParticleMaterial(new Star());
var mat2:MovieParticleMaterial = new MovieParticleMaterial(new Circle());
var doc1:PV3DParticle = new PV3DParticle([mat1]);
var doc2:PV3DParticle = new PV3DParticle([mat2]);
</pre>
<p>to this:</p>
<pre name="code" class="javascript">
light = new LightObject3D();
var mat1:FlatShadeMaterial = new FlatShadeMaterial(light, LIGHT_COLOR_1, AMBIENT_COLOR_1);
var mat2:FlatShadeMaterial = new FlatShadeMaterial(light, LIGHT_COLOR_2, AMBIENT_COLOR_2);
var matList1:MaterialsList = new MaterialsList({all:mat1});
var matList2:MaterialsList = new MaterialsList({all:mat2});
var params1:Array = [matList1, CUBE_SIZE, CUBE_SIZE, CUBE_SIZE];
var params2:Array = [matList2, CUBE_SIZE, CUBE_SIZE, CUBE_SIZE];
var doc1:PV3DDisplayObject3DClass = new PV3DDisplayObject3DClass(Cube, params1);
var doc2:PV3DDisplayObject3DClass = new PV3DDisplayObject3DClass(Cube, params2);
</pre>
<p>
The new particle appearance will be initialized as red and blue 3D cubes. The first constructor parameter for the PV3DDisplayObject3DClass initializer is the class we wish to instantiate for the particles (so here, it is the Cube class) and the second parameter is an array of constructor parameters for this Cube class.
</p>
<hr/>
<h2><span>Step 19:</span> The Three Axes of Rotation</h2>
<p>
Previously, because we were working with &#8220;2D billboards&#8221;, only the rotation about the Z axis mattered. Now that we are working with true 3D objects, we need to pass three Random object references to the Rotation3D and Omega3D constructors, one for each axis.
</p>
<p>
Change the following code in the emitter class:
</p>
<pre name="code" class="javascript">
addInitializer(new Rotation3D(null, null, new UniformRandom(0, 180)));
addInitializer(new Omega3D(null, null, new UniformRandom(OMEGA_AVG, OMEGA_VAR)));
</pre>
<p>
to this:
</p>
<pre name="code" class="javascript">
var rotationRandom:UniformRandom = new UniformRandom(0, 180);
var omegaRandom:UniformRandom = new UniformRandom(OMEGA_AVG, OMEGA_VAR);
addInitializer(new Rotation3D(rotationRandom, rotationRandom, rotationRandom));
addInitializer(new Omega3D(omegaRandom, omegaRandom, omegaRandom));
</pre>
<hr/>
<h2><span>Step 20:</span> Modify the Document Class</h2>
<p>
This time, instead of using a Particles object as our particle container, we&#8217;re using a DisplayObject3D as the container. Declare a variable for this container in the document class:
</p>
<pre name="code" class="javascript">
private var container:DisplayObject3D;
</pre>
<p>
Also, we&#8217;ll need another type of renderer for creating particles in the new container. Change the renderer&#8217;s type from PV3DParticleRenderer to PV3DDisplayObject3DRenderer. The code in the document class&#8217;s constructor should now look like this:
</p>
<pre name="code" class="javascript">
initPV3D();

clock = new SteadyClock(PARTICLE_RATE);
emitter = new StarEmitter(clock);

renderer =  new PV3DDisplayObject3DRenderer(container);	 //this has changed!
renderer.addEmitter(emitter);

pause_btn.addEventListener(MouseEvent.CLICK, togglePause);
addEventListener(Event.ENTER_FRAME, mainLoop);
</pre>
<hr/>
<h2><span>Step 21:</span> Modify the initPV3D() Method</h2>
<p>
In the initPV3D() function, we now need to initialize the container variable and add it to the scene. Add these two lines to the end of that function:
</p>
<pre name="code" class="javascript">
container = new DisplayObject3D();
scene.addChild(container);
</pre>
<hr/>
<h2><span>Step 22:</span> Modify the updateCamera() Method</h2>
<p>
In the updateCamera() method, we wish to make the light follow the camera, so we&#8217;ll have an illusion that the light always &#8220;shoots&#8221; out from our eyes. Change the following code:
</p>
<pre name="code" class="javascript">
camera.x = x;
camera.y = y;
camera.z = z;
</pre>
<p>to this:</p>
<pre name="code" class="javascript">
emitter.light.x = camera.x = x;
emitter.light.y = camera.y = y;
emitter.light.z = camera.z = z;
</pre>
<p>Now the light source is always at the same point as the camera.</p>
<hr/>
<h2><span>Milestone:</span> Papervision3D with DisplayObject3D Completed</h2>
<p>
Yep, we&#8217;re finally done with this tutorial. No more coding. Let&#8217;s take a look at our final result, with fancy red and blue 3D cubes!
</p>
<div class="download_wrap">
<div class="big_btn">
		<a href="http://activetuts.s3.cdn.plus.org/tuts/075_stardust3D/Preview/Papervision3D DisplayObject3D/StarParticles3D.html" rel="external"><span>Demo</span> <small>View It Online</small></a>
	</div>
</div>
<p>The source code for this can be found in the &#8220;Papervision3D DisplayObject3D&#8221; folder.</p>
<hr/>
<h2>Conclusion</h2>
<p>
The workflow for creating 3D particle effects with Stardust is pretty much the same as that for 2D effects. You just choose a different set of initializers, actions, and renderers. Stardust also supports other 3D engines, including <a href="http://code.google.com/p/zedbox/">ZedBox</a> and <a href="http://code.google.com/p/nd3d/">ND3D</a>. The usage is almost the same. You&#8217;ll just have to use a different set of initializers and renderers. You may even extend the Initializer, Action, and Renderer classes to work with whichever 3D engines you like!
</p>
<p>Now you&#8217;ve got the basics, why not go back to the consts created in Step 6 and play with them to see the effects?</p>
<p>
I hope this tutorial helps you understand Stardust more and makes you more familiar and comfortable with Stardust&#8217;s workflow. Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/create-3d-effects-with-the-stardust-particle-engine/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Manipulate Visual Effects With the ColorMatrixFilter and ConvolutionFilter</title>
		<link>http://active.tutsplus.com/tutorials/effects/manipulate-visual-effects-with-the-colormatrixfilter-and-convolutionfilter/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/manipulate-visual-effects-with-the-colormatrixfilter-and-convolutionfilter/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 12:00:35 +0000</pubDate>
		<dc:creator>Martin Christov</dc:creator>
				<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3221</guid>
		<description><![CDATA[<img src="http://activetuts.s3.amazonaws.com/tuts/070_effectsTester/Preview/preview.jpg" alt="Visual Effects With the ColorMatrixFilter and ConvolutionFilter">]]></description>
			<content:encoded><![CDATA[<p>The ColorMatrixFilter and ConvolutionFilter can be used to visually transform your Flash objects. In this article, I&#8217;ll show you how easy they are to manipulate, using a cool tool I built for simple experimentation.</p>
<p><span id="more-3221"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Preview/Archive.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Preview/EffectsTester.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Introduction</h2>
<p>Have you guys ever experimented with Flash&#8217;s ColorMatrix and Convolution filters? I was digging around in a quest to find some interesting stuff you can do with Flash and I bumped into them. Experimenting with them can deliver some awesome results.</p>
<p>I&#8217;ve written an <a href="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Preview/EffectsTester.html" target="_blank">EffectsTester</a> to make it easy to experiment with them. Check out these camshots I took while playing around with it:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-2.jpg" alt="Andy Warhol eat your heart out." /></div>
<p>Now, if you find that interesting, let me walk you through what these two filters are all about.</p>
<h2>The Color Matrix Filter</h2>
<p><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/filters/ColorMatrixFilter.html">The Color Matrix Filter</a> is used to manipulate the color of a display object.</p>
<p>Let me explain the exact calculation performed by the ColorMatrixFilter. Every pixel in an image is a mixture of red, green, and blue. These <em>primary colors</em>, when combined, can make any other color:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-3.jpg" alt="Image from Wikimedia Commons. Thanks to Mike Horvath and jacobolus." /></p>
<p>Image from Wikimedia Commons. Thanks to Mike Horvath and jacobolus.</p>
</div>
<p>The amount of red in a pixel can vary from zero (no red at all) to 255. Same for green and blue. So, from the image above, you can see that a pure yellow pixel has red = 255, and green = 255. White has red, green, and blue all set to 255. Black has all three set to zero.</p>
<p>The color matrix filter looks at each pixel in a source image and changes them based on how much red, blue, and green is in the pixel. You end up with a whole new image; the <em>destination image</em>.</p>
<h4>Here&#8217;s How it Works</h4>
<p>First, let&#8217;s concentrate on these three values:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-4.jpg" alt="" /></div>
<p>Let&#8217;s label these values a[0], a[1], and a[2] in turn. Now, think about just one single pixel in the entire source image (the one in the top-left corner will do). Let&#8217;s call the amount of red in that <em>srcR</em>, the amount of green <em>srcG</em> and the amount of blue <em>srcB</em>.</p>
<p>The question is: how much red will be in that pixel of the destination image, <em>destR</em>? Flash uses this calculation:</p>
<pre name="code" class="javascript">
destR = ( a[0] * srcR ) + ( a[1] * srcG ) + ( a[2] * srcB );
</pre>
<p>Here you can see that a[0] is 1, while a[1] and a[2] are both zero, so:</p>
<pre name="code" class="javascript">
destR =	( 1 * srcR ) + ( 0 * srcG ) + ( 0 * srcB );
//which means...
destR = srcR;
</pre>
<p>There&#8217;s no change! But what if we changed a[0] to zero and a[1] to 1? Then:</p>
<pre name="code" class="javascript">
destR =	( 0 * srcR ) + ( 1 * srcG ) + ( 0 * srcB );
//which means...
destR = srcG;
</pre>
<p>&#8230;the amount of red in the destination pixel would be equal to the amount of <em>green</em> in the source pixel! Furthermore, if you changed the second row to read <em>&#8220;1 0 0&#8243;</em>, then the amount of green in the destination pixel would be equal to the amount of red in the source pixel; you would have swapped them over and your orange fish would turn into green ones:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-5.jpg" alt="Red fish" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-6.jpg" alt="Green fish" /></div>
<p>You&#8217;re probably wondering about the <em>A</em> column and row and about the <em>Offset</em> column. Well, A stands for alpha, which means transparency. The A values have much the same effect as the R G B values, but since none of these  sample images are transparent, it&#8217;s hard to demonstrate. The Offset column lets you simply increase or decrease the amount of red, blue, or green in the destination pixel: type -255 into the R row&#8217;s Offset column and you&#8217;ll see that there is no longer any red in the image.</p>
<h4>Experiment</h4>
<p>I realize it&#8217;s tricky to understand this just from reading about it, so we&#8217;re going to look at some cool example effects. That&#8217;s much more fun, anyway. But first, for the curious, here&#8217;s the actual mathematical formula Flash uses:</p>
<pre name="code" class="javascript">
destR = ( a[0]  * srcR ) + ( a[1]  * srcG ) + ( a[2]  * srcB ) + ( a[3]  * srcA ) + a[4];
destG = ( a[5]  * srcR ) + ( a[6]  * srcG ) + ( a[7]  * srcB ) + ( a[8]  * srcA ) + a[9];
destB = ( a[10] * srcR ) + ( a[11] * srcG ) + ( a[12] * srcB ) + ( a[13] * srcA ) + a[14];
destA = ( a[15] * srcR ) + ( a[16] * srcG ) + ( a[17] * srcB ) + ( a[18] * srcA ) + a[19];
</pre>
<p>(Each of the values you see in the 5&#215;4 matrix can vary between -255 and 255.)</p>
<p>Take a look at the &#8220;Color Chart&#8221; sample image:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-7.jpg" alt="" /></div>
<p>Now, let&#8217;s say you want to remove all red color from the picture. Simply set all the values in the R row to zero:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-8.jpg" alt="" /></div>
<p>This means:</p>
<pre name="code" class="javascript">
destR = ( 0 * srcR ) + ( 0 * srcG ) + ( 0 * srcB ) + ( 0 * srcA ) + 0;
//which means:
destR = 0 + 0 + 0 + 0 + 0;
//so:
destR = 0;
</pre>
<p>Now let&#8217;s say you want to add some more green where there was previously red. Put &#8220;1&#8243; at input 0&#215;1, so the G row reads &#8220;1 1 0 0 0&#8243;:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-9.jpg" alt="" /></div>
<p>Let&#8217;s now achieve something very strange by changing the G row to &#8220;0 -1 0 0 50&#8243;:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-10.jpg" alt="" /></div>
<p>What just happened? As an example, if at some random pixel you had green = 30, it was multiplied with &#8216;-1&#8242; and afterwards 50 was added, so the result would be: (30 * -1) + 50 = 20.</p>
<p>Therefore, a type of <em>threshold</em> is created: for each pixel with a green value greater than 50, its transformed pixel will be completely turned off. Why? Well, suppose the pixel&#8217;s green channel has a value of 51:</p>
<pre name="code" class="javascript">
destG = ( 0 * srcR ) + ( -1 * srcG ) + ( 0 * srcB ) + ( 0 * srcA ) + 50;
//remember srcG = 51:
destG = 0 + (-51) + 0 + 0 + 50;
//so:
destG = - 51 + 50;
//so:
destG = -1;
//but a pixel can't have a negative amount of green, so this is just set to zero:
destG = 0;
</pre>
<p>Now try this:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-11.jpg" alt="" /></div>
<p>All pixels with green values greater than 50 get turned off and those with green values below 50 have all three color channels increased. This allows you to see areas of the image that have only a very small amount of green, as with the fish image:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-12.jpg" alt="" />x</div>
<p>Here, only the pixels with an amount of green less than 50. The darker the pixel, the more green there is in the original image. That&#8217;s the basic principle anyway. I know it may seem complicated at first, but play with it and you&#8217;ll get it eventually <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h4>Grayscale</h4>
<p>OK, let&#8217;s go for something standard: a grayscale image. Change your matrix like so:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-13.jpg" alt="" /></div>
<p>You&#8217;ve got a grayscale. Nice <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-14.jpg" alt="" /></div>
<h4>Inverted Colors</h4>
<p>Let&#8217;s achieve another popular color state: Inverted Colors.</p>
<p>To invert the colors, we need to make it so that every pixel with a red value of 255 has a red value of zero, and vice-versa. Same for the other two colors. So we need to make Flash run code that looks like this:</p>
<pre name="code" class="javascript">
destR = 255 - srcR;
destG = 255 - srcG;
destB = 255 - srcB;
</pre>
<p>But that&#8217;s easy! All we have to do is set the matrix like this:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-15.jpg" alt="" /></div>
<p>Tada! Electric fish:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-16.jpg" alt="" /></div>
<h4>More Effects</h4>
<p>Most of the more exotic effects that can be achieved by the ColorMatrixFilter are done by setting a negative value for a color and a positive value for offset &#8211; or vice-versa. Put &#8220;-1&#8243; from 0&#215;3 to 2&#215;3 (the alphas) and 255 for offset of the alpha (4&#215;3).<br />
  Wow, now I know now how they made Terminator 2 <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Honestly, I am not really sure what I just did &#8211; calculations become really hard to track after a while.
</p>
<p>Although it&#8217;s possible to understand how the ColorMatrixFilter works from a mathematical point of view, realistically it&#8217;s going to remain a matter of playing around with it. You can never be exactly sure what is going to pop up when you put some specific values. That&#8217;s why I made this EffectsTester. So play around. Make yourself metallic green, or red, or colorless.</p>
<h4>Real World Application</h4>
<p>When you&#8217;ve got an effect you like, you can apply it to any DisplayObject (MovieClip, Sprite, Bitmap&#8230;) in your own code like this:</p>
<pre name="code" class="javascript">
//first import ColorMatrixFilter up at the top of your code:
import flash.filters.ColorMatrixFilter;

//...later on:
var filters:Array = new Array();
//for everything after " = new", copy and paste from the "Grab The Code" box of EffectsTester:
var cmf:ColorMatrixFilter = new ColorMatrixFilter(new Array(-1,0,0,0,255,0,-1,0,0,255,0,0,-1,0,255,0,0,0,1,0));
//the next two lines apply the filter to your display object:
filters.push( cmf );
myDisplayObject.filters = filters;
</pre>
<p>Now let&#8217;s look at the convolution filter.</p>
<h2>The Convolution Filter</h2>
<p>From Adobe&#8217;s <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/filters/ConvolutionFilter.html">class reference</a>:</p>
<blockquote><p>A convolution combines pixels in the input image with neighboring pixels to produce an image. A wide variety of image effects can be achieved through convolutions, including blurring, edge detection, sharpening, embossing, and beveling.</p></blockquote>
<p>The ConvolutionFilter loops through all pixels of a display object. For each of them, it uses the center value in the matrix as the value of the current pixel being manipulated. For example, in a 3 x 3 matrix, the center value is at (1, 1). It then multiplies the values from the matrix by the surrounding pixels and adds the resulting values for all pixels to get the value for the resulting center pixel.</p>
<p>Understanding the exact math beneath the Convolution matrix is worth a whole new article, so I won&#8217;t cover all this here. If you want to get into it, check out <a target="_blank" href="http://www.adobe.com/devnet/flash/articles/matrix_transformations_05.html" target="_blank">this post on adobe.com</a>.</p>
<p>However, a simple play around with the values will eventually give you all possible effects you can achieve. And it will be fun <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  So let&#8217;s see what can we do!</p>
<h4>Experiment</h4>
<p>The convolution filter uses a matrix, just like the color matrix filter. Again, the values vary between -255 and 255. And again, you achieve most of the interesting effects when combining negative values with positive ones.</p>
<p>Let me share with you my observations of how this thing works. Try increasing some random value from the matrix. Whichever you pick, it will lighten the picture; if you want the picture to stay at normal brightness, make sure the value of &#8220;divisor&#8221; is equal to the sum of all the values in the matrix.</p>
<p>Now if you try to lower a random value below zero while keeping at least one other above zero, you get something going on there. It affects your edges:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-17.jpg" alt="" /></div>
<p>Here is a nice one: want to look like a soldier? <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Try these values:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/070_effectsTester/Tutorial/-18.jpg" alt="" /></div>
<p>Now lower the &#8220;divisor&#8221; value to &#8220;-1&#8243; to become a soldier on a mission at night.</p>
<p>A lot of stuff can be achieved if you hold your mouse button a bit more <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Lower and raise some values to extremes. Don&#8217;t forget to adjust the &#8220;divisor&#8221; &#8211; it&#8217;s crucial. Enlarge your matrix. Make it 5&#215;5, for example.</p>
<h4>Real World Application</h4>
<p>To apply the effect in your own code, use the <em>filters</em> object, just as you did for the ColorMatrixFilter:</p>
<pre name="code" class="javascript">
//first import ConvolutionFilter up at the top of your code:
import flash.filters.ConvolutionFilter;

//...later on:
var filters:Array = new Array();
//for everything after " = new", copy and paste from the "Grab The Code" box of EffectsTester:
var cf:ConvolutionFilter = new ConvolutionFilter(3,3,new Array(1,0,-10,-2,3,1,6,1,-1),0);
//the next two lines apply the filter to your display object:
filters.push( cf );
myDisplayObject.filters = filters;
</pre>
<p>Finally: try combining both filters.</p>
<pre name="code" class="javascript">
//first import the filter classes up at the top of your code:
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;

//...later on:
var filters:Array = new Array();
//for everything after " = new", copy and paste from the "Grab The Code" box of EffectsTester:
var cmf:ColorMatrixFilter = new ColorMatrixFilter(new Array(-1,0,0,0,255,0,-1,0,0,255,0,0,-1,0,255,0,0,0,1,0));
var cf:ConvolutionFilter = new ConvolutionFilter(3,3,new Array(1,0,-10,-2,3,1,6,1,-1),0);

//the next three lines apply the filters to your display object:
filters.push( cf );
filters.push( cmf );
myDisplayObject.filters = filters;
</pre>
<p>Have fun playing with these filters and post any results you get in the comments! Thanks for reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/manipulate-visual-effects-with-the-colormatrixfilter-and-convolutionfilter/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Create a Pinball-Style Rolling Score Counter Class</title>
		<link>http://active.tutsplus.com/tutorials/effects/create-a-pinball-style-rolling-score-counter-class/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/create-a-pinball-style-rolling-score-counter-class/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 12:00:11 +0000</pubDate>
		<dc:creator>Cadin Batrack</dc:creator>
				<category><![CDATA[Effects]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3109</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Preview/previewIcon.jpg" alt="Create a Pinball-Style Rolling Score Counter Class">]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you&#8217;ll create a reusable Score class that counts up to the new total when points are added (instead of jumping up to the new score). We&#8217;ll cover graphics creation as well as code.</p>
<p><span id="more-3109"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/sourceFiles.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a>
</div>
<h3>Final Result Preview</h3>
<p>In some games when you gain points, you&#8217;ll see your score immediately jump to the new total. I think it&#8217;s much cooler if the score counts up one by one, so the player can &#8220;rack up points&#8221;. That&#8217;s what we&#8217;ll be making here.</p>
<p>Here&#8217;s an example of the score class in action:</p>
<div class="tutorial_image">
<object width="500" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/Preview.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/Preview.swf" /></object>
</div>
<p>The main idea behind this tutorial is to teach you how to program the &#8220;counting up&#8221; functionality, but I&#8217;ll also show you how to create the cool LED display seen in the preview. We&#8217;ll start by designing the numbers:</p>
<h2>Step 1: Set up Your Flash File</h2>
<p>Create a new Flash file (ActionScript 3.0). Your movie settings will vary depending on your game. For this demo I&#8217;m setting up my movie as 500&#215;300, black background, and 30 fps.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/1.jpg" alt="Flash file setup" /></div>
<h2>Step 2: Create the Digit Symbol</h2>
<p>Create a new Movie Clip symbol (Insert > New Symbol). Give this symbol the name &#8220;digit&#8221;.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/2.jpg" alt="TK" /></div>
<h2>Step 3: Create the Digit Text Field</h2>
<p>Inside the digit movie clip use the Text tool to add a number 0 to the symbol. I&#8217;m using a font called <a href="http://www.fontstock.net/717/digital-readout-upright.html">Digital Readout</a>, but any LED-style font should work.</p>
<p>Set the text size to 40 pt and make it a light amber/orange color (#F4C28B). Set the Paragraph Format to centered.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/3.jpg" alt="TK" /></div>
<h2>Step 4: Add Glows</h2>
<p>Add two separate glow filters to your text field. Set the color to red (#FF0000) for both and set the Strength of both to 200%.</p>
<p>Check the Inner Glow checkbox for one and set the Blur to 2px. Leave the other at 5px Blur.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/4.jpg" alt="TK" /></div>
<p>You can use a different color if you want (blue or green would both look cool). The trick in getting it to look realistic is to make the text color a little washed out and set the glows to a more saturated color. This makes it look like it&#8217;s emitting light.</p>
<h2>Step 5: Add More Numbers</h2>
<p>Create keyframes on frames 1-10 of the digit movie clip. An easy way to do this is to select frames 1-10 (click frame 1, then Shift-click frame 10) and press F6.</p>
<p>You should now have 10 frames, each with a keyframe with your glowing 0 text field. Go through each frame and change the numbers so you have the digits 0-9. Frame 1 will have &#8220;0&#8243;, frame 2 will have &#8220;1&#8243;, frame 3 will have &#8220;2&#8243;, etc.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/5.jpg" alt="TK" /></div>
<p>Name this layer &#8220;numbers&#8221;.</p>
<h2>Step 6: Add the LED Background</h2>
<p>We&#8217;ll now add an &#8220;off&#8221; state for the LED numbers, so you&#8217;ll be able to see the unlit segments of the LED display.</p>
<p>Copy your 8 digit (in frame 9). Create a new layer named &#8220;background&#8221;. With the new layer selected use Paste in Place (Edit > Paste in Place) to paste the 8 digit in the exact position as the one we copied.</p>
<p>Remove the glows from the new 8 digit and change its color to dark grey (#333333). Add a blur filter with the Blur set to 3px. Move this layer underneath the &#8220;numbers&#8221; layer.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/6.jpg" alt="TK" /></div>
<p>Now you can scrub through the frames and see how the unlit segments of the LED show behind each number.</p>
<h2>Step 7: Add the Stop Action</h2>
<p>Create another new layer named &#8220;actions&#8221;. Open the Actions Panel and add a stop() action on frame 1.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/7.jpg" alt="TK" /></div>
<p>This will keep the display showing &#8216;0&#8242; until we tell it otherwise.</p>
<h2>Step 8: Why Frames?</h2>
<p>Why are we manually putting each digit on its own frame instead of using a dynamic text field? Good question. </p>
<p>The main reason is that doing so makes it more flexible for updating the graphics later. If you wanted to change the design and use bitmaps for the numbers, or have each digit displayed in a different font or color this makes it easy to do that.</p>
<p>Also, if designers and developers are working together on a project it&#8217;s best to create things in a way that gives designers easy access to as much of the graphics as possible.<br />
I feel this setup does that more than using dynamic text.</p>
<h2>Step 9: Create the Score Movie Clip</h2>
<p>Create a new movie clip named &#8220;Score&#8221;. Check &#8216;Export for ActionScript&#8217; and set the class name to &#8220;Score&#8221; also.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/8.jpg" alt="TK" /></div>
<p>Drag the digit movie clip from the Library into the Score movie clip. Duplicate the digit clip (Edit > Duplicate) six times (so you have seven digits) and space them evenly.</p>
<p>Since we only have seven digits the maximum score we&#8217;ll be able to display is 9,999,999. If your game will need to accommodate higher scores add more digits accordingly.</p>
<p>Add a bit more space between every third digit to allow for comma separators.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/9.jpg" alt="TK" /></div>
<h2>Step 10: Name the Digit Clips</h2>
<p>Select the leftmost digit movie clip and give it the instance name &#8220;digit1&#8243;. Name the next one to the right &#8220;digit2&#8243;, then &#8220;digit3&#8243; and so on.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/10.jpg" alt="TK" /></div>
<h2>Step 11: Add Commas</h2>
<p>Create a new layer called &#8220;commas&#8221;.</p>
<p>The easiest way to get the commas to look exactly like the numbers is to go into one of the digit clips and copy one of the number text fields.<br />
Back inside the Score movie clip, paste the text field into the commas layer, and change the number to a comma. Duplicate it and move it as many times as you need.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/11.jpg" alt="TK" /></div>
<h2>Step 12: Add a Background</h2>
<p>For the Score background we&#8217;ll just add a simple rounded rectangle.</p>
<p>Create a new layer called &#8220;background&#8221; and place it behind the numbers and commas layers. Select the Rectangle Tool and Option-click (Alt-click) the stage. Make a rectangle 200px x 40px with 3px corners (make yours longer if you have more digits). Make the fill black and the stroke 1px grey (#666666).</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/12.jpg" alt="TK" /></div>
<p>For some reason Flash always distorts strokes on rounded rectangles. To get around this, select the stroke and choose Modify > Shape > Convert Lines to Fills. This converts the stroke from a line to a filled shape and it will no longer distort.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/13.jpg" alt="TK" /></div>
<p>If you think this is a total hack of a workaround for basic functionality that should have been fixed years ago, I urge you to <a href="https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform">contact Adobe and let them know</a>.</p>
<h2>Step 13: Add Shine</h2>
<p>What graphic would be complete without some iPhone-esque shine?</p>
<p>Create a new layer above everything else called &#8220;shine&#8221;. Add a new rounded rectangle, slightly smaller than the background one. This time give it no stroke and fill it with a white gradient from 20% Alpha to 0% Alpha.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/14.jpg" alt="TK" /></div>
<h2>Step 14: Create the Score Class</h2>
<p>Create a new Actionscript file named &#8220;Score.as&#8221;. Save it in the same directory as your main Flash file. Since the name of this class and the Export Class name of our Score movie clip are the same, Flash will automatically link them.</p>
<p>Add this code to the Score.as file:</p>
<pre name="code" class="javascript">
package {

	import flash.display.MovieClip;
	import flash.events.Event;

	public class Score extends MovieClip {

		// CONSTRUCTOR
		public function Score() {

		}

	}
}
</pre>
<p>This is just an empty shell of a class for now. We have to extend the MovieClip class since this class is linked to a movie clip in the library, so we also have to import the MovieClip class. We&#8217;ll be using the ENTER_FRAME event, so we import the Event class as well.</p>
<h2>Step 15: Add Variables and Constants</h2>
<p>Add these two lines to the Score class just above the constructor function.</p>
<pre name="code" class="javascript:firstline[8]">
private const SPEED:int = 1; // how fast to count
private const NUM_DIGITS:int = 7; // how many digits there are in the score
</pre>
<p>These are two constants &#8211; kind of like settings for the class.</p>
<ul>
<li>The first, SPEED, controls how fast the score counts. I have it set to count one by one, but if your game uses higher scores this might be too slow. You can change this to 5 or 10 or 50 to count up by those increments.</li>
<li>The second constant, NUM_DIGITS, defines how many digits we have in our Score movie clip. If you added more (or less) than 7 digits you&#8217;ll need to change this.</li>
</ul>
<p>Now let&#8217;s add a couple of variables. Put these just below the constants:</p>
<pre name="code" class="javascript:firstline[11]">
private var _totalScore:int = 0;
private var _displayScore:int= 0;
</pre>
<p>These variables will hold the two different versions of our score. &#8220;_totalScore&#8221; will be the actual score. &#8220;_displayScore&#8221; will be the number that is currently<br />
being shown on the LED display. If I add 50 to the score, the _totalScore will immediately be 50, but the _displayScore will be 1, then 2, then 3, until it reaches 50.</p>
<p>If you ever need to know the actual score (like to send to your high score boards) you&#8217;ll use _totalScore since _displayScore might not be accurate.</p>
<p>I&#8217;m using underscores at the beginning of the variable names to denote that these are private variables.</p>
<h2>Step 16: Add the <em>totalScore</em> Accessor Method</h2>
<p>So if _totalScore is a private variable, how will we access from outside the Score class? We&#8217;ll use an &#8220;accessor&#8221; or &#8220;getter&#8221; method.</p>
<p>Add this method below the constructor function:</p>
<pre name="code" class="javascript:firstline[19]">
// public accessor for totalScore
public function get totalScore():int {
	return _totalScore;
}
</pre>
<p>This method simply returns the value of the _totalScore variable. It gives us a way to access that value without having to expose it as a public variable.</p>
<h2>Step 17: Add the <em>add</em> Method</h2>
<p>We&#8217;ll need a way to add points to the score. Add this method:</p>
<pre name="code" class="javascript:firstline[24]">
// add an amount to the score
public function add(amount:int):void {
	_totalScore += amount;
	addEventListener(Event.ENTER_FRAME, updateScoreDisplay); // start the display counting up
}
</pre>
<p>This method accepts an integer &#8220;amount&#8221; which it adds to the _totalScore variable. The second line starts an ENTER_FRAME event that calls a method called updateScoreDisplay every frame. We&#8217;ll add that next.</p>
<h2>Step 18: Add the <em>updateScoreDisplay</em> Method</h2>
<p>Now add a the updateScoreDisplay method. This is where all of the cool counting-up functionality will happen. It needs to accept an Event since it&#8217;s getting called from an ENTER_FRAME event.</p>
<pre name="code" class="javascript:firstline[30]">
// this runs every frame to update the score
private function updateScoreDisplay(e:Event):void {

}
</pre>
<p>Now let&#8217;s add some functionality. The first thing this method will do is to increment the _displayScore variable by the amount we set in our SPEED constant:</p>
<pre name="code" class="javascript:firstline[33]">
// increment the display score by the speed amount
_displayScore += SPEED;
</pre>
<p>There&#8217;s a potential problem here though. What if our speed is set to 10 and we try to add 5 to the score? The displayScore will be higher than the totalScore. Let&#8217;s add a couple lines to fix that:</p>
<pre name="code" class="javascript:firstline[36]">
// make sure the display score is not higher than the actual score
if(_displayScore > _totalScore){
	_displayScore = _totalScore;
}
</pre>
<p>That checks if the displayScore is higher than the totalScore and if so, sets the displayScore to be equal to the totalScore.</p>
<p>Next we need to add the leading zeros to the score. We&#8217;ll do this by converting the displayScore to a String and adding zeros until the length equals the number of digits defined by the NUM_DIGITS constant:</p>
<pre name="code" class="javascript:firstline[41]">
var scoreStr:String = String(_displayScore); // cast displayScore as a String

// add leading zeros
while(scoreStr.length &lt; NUM_DIGITS){
	scoreStr = "0" + scoreStr;
}
</pre>
<p>Now to actually display the score we&#8217;re going to loop through each of our digit clips (remember we named then &#8220;digit1&#8243;, &#8220;digit2&#8243;, etc.) and use the corresponding number from the score string to set the frame number of the clip:</p>
<pre name="code" class="javascript:firstline[48]">
// loop through and update each digit
for (var i:int = 0; i &lt; NUM_DIGITS; i++) {
	var num = int(scoreStr.charAt(i));
	this["digit"+(i+1)].gotoAndStop(num+1);// set the digit mc to the right frame
}
</pre>
<p>The charAt method retrieves the character from a String at the specified position. This lets us go character by character through the score string.</p>
<p>The brackets in the next line allow us to dynamically create the clip name. The code, <em>this["digit"+(i+1)]</em> accesses the clip with the name &#8220;digit1&#8243; or &#8220;digit2&#8243;, etc., depending on the value of <em>i</em>.</p>
<p>We&#8217;re using &#8220;num+1&#8243; as the frame number because the frame numbers are offset by 1 from the digits they contain (frame 1 shows 0, frame 2 shows 1, etc.)</p>
<p>The last thing we need to do in this method is check to see if the displayScore and the totalScore are equal. If so, we can remove the listener and stop calling this method for now.</p>
<pre name="code" class="javascript:firstline[54]">
// if the display score is equal to the total score remove the enterframe event
if(_totalScore == _displayScore){
	removeEventListener(Event.ENTER_FRAME, updateScoreDisplay);
}
</pre>
<p>If you got lost anywhere in that step you can check out the source files to see the completed class.</p>
<h2>Step 19: The Score Class in Use</h2>
<p>To use this class drag the Score movie clip from the Library onto the Stage and give it the instance name &#8220;myScore&#8221;. You can add points to your score by using this line in your Document Class:</p>
<pre name="code" class="javascript">
myScore.add(50);
</pre>
<p>You can see an example of this in the source files. I&#8217;m adding to the score when the bumper buttons are clicked, but you&#8217;ll more likely be calling add() when events in your game occur.</p>
<p>If you need to know the player&#8217;s score you can get the totalScore by using:</p>
<pre name="code" class="javascript">
myScore.totalScore
</pre>
<p>This will call the accessor method and return the value of _totalScore.</p>
<h2>Conclusion</h2>
<p>You now have a reusable counting Score class that you can use in any of your games.</p>
<p>I think the LED look is cool, but you should definitely alter the design to fit the look of your game. Here are a couple ideas for different designs to get you started:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/062_scoreClass/Tutorial/15.jpg" alt="TK" /></div>
<p>Thanks for reading this tutorial. Let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/create-a-pinball-style-rolling-score-counter-class/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Introduction to QuickBox2D: Part 1</title>
		<link>http://active.tutsplus.com/tutorials/effects/introduction-to-quickbox2d-part-1/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/introduction-to-quickbox2d-part-1/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 12:00:19 +0000</pubDate>
		<dc:creator>Zevan Rosser</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2994</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/thumbnail.jpg" alt="Introduction to QuickBox2D: Part 1">]]></description>
			<content:encoded><![CDATA[<p>
	This tutorial will teach you the basics of the QuickBox2D library. 	After reading through the following steps, you&#8217;ll be able to create a wide variety of physics simulation effects. Over the course of this tutorial we&#8217;ll create a few small demos to familiarize you with QuickBox2D&#8217;s basic functionality.</p>
<p><span id="more-2994"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/source.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/example_1.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: A Little Background</h2>
<p>
	If you aren&#8217;t already aware, <a href="http://www.box2d.org/">Box2D</a> is a great physics library created by <a href="http://www.gphysics.com/" target="blank">Erin Catto</a>.<br />
	It was ported to AS3 by Matthew Bush and John Nesky.</p>
<p>
	<a href="http://actionsnippet.com/?page_id=1391">QuickBox2D</a> is a mini-library I created to work with <a href="http://sourceforge.net/projects/box2dflash/">Box2DFlashAS3</a>. 	The main purpose of this library is to significantly simplify instantiation of rigid bodies and provide a simple way to them bodies with custom graphics. </p>
<h2>Step 2: Download the Libraries</h2>
<p>In order to follow this tutorial you&#8217;ll need Box2DFlashAS3 version 2.0.2. You can download it at <a href="http://sourceforge.net/projects/box2dflash/files/" target="blank">sourceforge.net</a>. </p>
<div class="tutorial_image">
	  <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-2.gif" />
	</div>
<p><em>Be sure not to download 2.1a as it is still very much in an alpha state. Box2D 2.1 is still not out and the API is still undergoing<br />
	significant changes. When 2.1 is out of alpha, QuickBox2D will support it, but for the time being it will not work properly with QuickBox2D.</em></p>
<p>Next you need to download the latest version of QuickBox2D from <a href="http://actionsnippet.com/?page_id=1391" target="blank">actionsnippet.com</a>. </p>
<div class="tutorial_image">
	 <a href="http://actionsnippet.com/?page_id=1391" target="blank"><br />
	  <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-10.gif" /></a>
	</div>
<p>This tutorial will function with QuickBox2D 1.1 or greater.</p>
<h2>Step 3 : Set up the File</h2>
<p>
		Open Flash and create a new ActionScript 3.0 file.
		</p>
<div class="tutorial_image">
	      <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-3.gif" />
	    </div>
<p> Save your file and make sure that Box2D and QuickBox2D are either in your classpath, or directly next to your fla file.</p>
<div class="tutorial_image">
	      <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-4.gif" />
	    </div>
<h2>Step 4 : Create Your First Rigid Bodies</h2>
<p> We&#8217;ll be placing all our code on the first frame of the timeline, so open up your actions (option + F9) and paste the following code snippet:</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]

import com.actionsnippet.qbox.*;

var sim:QuickBox2D = new QuickBox2D(this);

sim.createStageWalls();

sim.addBox({x:3, y:3, width:1, height:1});
sim.addCircle({x:4, y:6, radius:1});

sim.start();
sim.mouseDrag()
		</pre>
<div class="tutorial_image">
	      <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-5.gif" />
	    </div>
<h2>Step 5 : Understanding the Code</h2>
<p>Go ahead and test your movie (command + enter). You should end up with a box and a circle rigid body that you can drag and throw around the stage.</p>
<p>After importing the library, we instantiate an instance of QuickBox2D. We pass a reference to the timeline into the QuickBox2D constructor, this causes all rigid bodies to be drawn to the main timeline. You can pass any MovieClip into the QuickBox2D constructor. We store our QuickBox2D instance in a variable called <strong>sim</strong> (short for simulation).</p>
<p>Next we call the <strong>createStageWalls()</strong> method. This draws boxes around the edges of the stage so that rigid bodies don&#8217;t fall off the screen. </p>
<p>On line 9 we create our first rigid body using the <strong>addBox()</strong> creation method. <strong>addBox()</strong> takes an <strong>Object</strong><br />
as its argument. This works like popular tweening engines, allowing you to enter a variable number of arguments in any order with easy to read syntax. In this case, we create a box with an <strong>x</strong> and <strong>y</strong> position of 3 meters and a <strong>width</strong> and <strong>height</strong> of 1 meter. <em>Those values may seem strange, but I&#8217;ll explain them shortly.</em></p>
<p>Next, we create a circle using the <strong>addCircle()</strong> method. This works pretty much the same way as the <strong>addBox()</strong> method. We use the params <strong>Object</strong> to tell QuickBox2D to position the circle at point (4,6) and we give the circle a radius of 1 meter.</p>
<p>To start the simulation we call <strong>start()</strong> and to allow dragging for the rigid bodies we call <strong>mouseDrag()</strong>.</p>
<p>The only tricky part with this code snippet is the coordinate system. It&#8217;s pretty obvious that our <strong>x</strong> and <strong>y</strong> values aren&#8217;t in pixels. Box2D uses meters instead of pixels. This takes a little getting used to, but after an hour or two you&#8217;ll have no trouble thinking in meters instead of pixels. It&#8217;s important to note that 1 meter is 30 pixels. We&#8217;ll see a little more about this later on when we get to skinning. </p>
<h2>Step 6 : Adding Density</h2>
<p>Let&#8217;s make this a little more interesting. Replace your previous <strong>addBox()</strong> and <strong>addCircle()</strong> calls with these:</p>
<pre name="code" class="javascript">
sim.addBox({x:4, y:3, width:1, height:1});
sim.addBox({x:3, y:6, width:4, height:0.25, density:0, angle:0.1});

sim.addCircle({x:3, y:10, radius:1});
sim.addCircle({x:8, y:10, radius:0.5});
</pre>
<p>Go ahead and test your movie. We&#8217;re already familiar with <strong>x, y, width, height </strong>and <strong>radius</strong>, but we added two more params:<br />
<strong>density</strong> and <strong>angle</strong>. Setting <strong>density</strong> to 0 causes Box2D to create a static rigid body. Static bodies don&#8217;t<br />
fall down or react to collisions with other rigid bodies. Setting density to other values controls how the mass of the rigid body is calculated. Try changing density to 100 and you&#8217;ll notice that the rectangle becomes <em>very</em> heavy.</p>
<p>Setting <strong>angle</strong> changes the starting rotation value for a rigid body. This value is in radians instead of degrees. I prefer working directly in radians, but if you don&#8217;t want to do that you can create a helper function to convert:</p>
<pre name="code" class="javascript">
// takes a degree value and converts it to radians
function radians(degs:Number):Number{
	return degs * Math.PI / 180;
}
</pre>
<h2>Step 7 : Take a Few Minutes to Create Something</h2>
<p>At this point I highly recommend taking five or ten minutes to create something simple. You already have a enough knowledge to create some pretty nice simulations&hellip; If you create something interesting, be sure to save it.</p>
<h2>Step 8 : Using What We&#8217;ve Learned</h2>
<p>
Now that you&#8217;re beginning to get a feel for things, clear your timeline code and replace it with this:
</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// make a heavy circle
sim.addCircle({x:3, y:3, radius:0.5, density:5});
// create a few platforms
sim.addBox({x:4, y:4, width:6, height:0.35, angle:0.1, density:0});
sim.addBox({x:9, y:6, width:6, height:0.35, angle:0.1, density:0});
sim.addBox({x:14, y:9, width:12, height:0.35, angle:-0.2, density:0});
sim.addBox({x:4, y:12, width:0.35, height:4, angle:-0.1, density:0});
sim.addBox({x:10, y:14, width:14, height:0.35, density:0});
// make 26 dominoes
for (var i:int = 0; i&lt;13; i++){
 sim.addBox({x:7 + i * 0.8, y:13, width:0.25, height:1.6});
 sim.addBox({x:8 + i * 0.8, y:18.7, width:0.25, height:1.6})
}
sim.start();
sim.mouseDrag();
</pre>
<p>
Go ahead and test your movie.</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/example_1.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/milestone.jpg" alt="" style="border:none"></a>
</div>
<div class="tutorial_image">
<p>  <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-6.gif" />
 </div>
<p>There&#8217;s nothing new happening in this example. We&#8217;re simply making use of <strong>x, y, width, height, radius</strong> and <strong>density</strong>.<br />
These few params will take you pretty far. We&#8217;re going to cover more params related to the behavior or rigid bodies in the second part of this tutorial, but if you feel like skipping ahead, a full list can be found in the <a href="http://actionsnippet.com/qb2d/docs/html/" target="blank">QuickBox2D Docs</a>.<br />
The params for <strong>addBox()</strong> can be found <a href="http://actionsnippet.com/qb2d/docs/html/com_actionsnippet_qbox_QuickBox2D.html#addBox">here</a>.</p>
<h2>Step 9 : Grouping Rigid Bodies</h2>
<p>
Box2D allows you to create compound shapes. This means taking circles, boxes and polygons and grouping them together to make more complex shapes.<br />
QuickBox2D vastly simplifies what you need to do to create compound shapes:
</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// store references to each part of the group
var circleA:QuickObject = sim.addCircle({x:0, y:0, radius:0.5});
var circleB:QuickObject = sim.addCircle({x:2, y:0, radius:0.5});
var middleBox:QuickObject = sim.addBox({x:1, y:0, width:1.5, height:0.5});
// create the group using the addGroup() method
sim.addGroup({objects:[circleA, circleB, middleBox], x:6, y:6});
sim.start();
sim.mouseDrag();
</pre>
<p>
Clear out your timeline code and replace it with what&#8217;s above. Go ahead and test your movie.</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/example_2.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/milestone.jpg" alt="" style="border:none"></a>
</div>
<p>All of the QuickBox2D creation methods (like <strong>addBox()</strong> and <strong>addCircle()</strong>) return QuickObject instances. QuickObjects are wrappers for the Box2D class instances that are necessary to create rigid bodies. When creating group objects, the first thing we need to do is store references to a few QuickObjects. We call these QuickObjects <strong>circleA, circleB</strong> and <strong>middleBox</strong>. Notice that <strong>x</strong> and <strong>y</strong><br />
coordinates for these are relative to (0,0) &#8211; this requirement is intended to simplify any positioning logic you need to do when placing the different parts of a group.</p>
<p>Now that we have our references, we can pass them as an array to the <strong>objects</strong> param of the <strong>addGroup()</strong> creation method. We then move the entire group to point (6,6). </p>
<h2>Step 10 : A More Complex Group</h2>
<p>With boxes and circles alone you can construct some pretty complicated group shapes. Clear out your timeline code and replace it with this:</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// create a circle
sim.addCircle({x:16, y:3, radius:1, density:0.2});
// create a bunch of boxes
var boxes:Array = [];
for (var i:int = 0; i&lt;20; i++){
	var h:Number = 1 - i / 20;
	boxes.push(sim.addBox({x:i, y:i * h, width:1, height:h}));
}
// group all the boxes together
sim.addGroup({objects:boxes, x:3, y:3});
sim.start();
sim.mouseDrag();
</pre>
<p>
Go ahead and test your movie.</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/example_3.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/milestone.jpg" alt="" style="border:none"></a>
</div>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-7.gif">
</div>
<h2>Step 11 : Coloring Rigid Bodies and Using setDefault()</h2>
<p>
There are a few params that you can use to change the colors and render style of QuickObjects. These are <strong>fillColor, fillAlpha, lineColor, lineAlpha</strong> and <strong>lineThickness</strong>. They should be pretty self-explanatory. Take a look at this:</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
sim.addCircle({x:3, y:3, radius:1,
			   fillColor:0xFF0000,
			   lineThickness:10,
			   lineColor:0xFFFF00});
sim.addCircle({x:6, y:3, radius:1,
			   fillColor:0xFF0000,
			   lineThickness:10,
			   lineColor:0xFFFF00});
sim.addCircle({x:9, y:3, radius:1,
			   fillColor:0x000022,
			   lineThickness:5,
			   lineColor:0x6666FF});
sim.addBox({x:12, y:4, width:2, height:2,
			   fillColor:0xFF0000,
			   lineThickness:10,
			   lineColor:0x00FF00});
sim.start();
sim.mouseDrag();
</pre>
<p>
Try this out on your timeline.</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/example_4.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/milestone.jpg" alt="" style="border:none"></a>
</div>
<div class="tutorial_image"> <img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-8.gif"></div>
<p>While this is easy to understand, you can see how dealing with these params can quickly become cumbersome. In the next step we&#8217;ll look at a way to get rid of some of this repetitive code.</p>
<h2>Step 12 : The setDefault() Method</h2>
<p>To get rid of repetitive looking code, QuickBox2D has a method called <strong>setDefault()</strong>. This method forces default values for all calls to creation methods. So you could simplify the previous example to look like this:</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
sim.setDefault({fillColor:0xFF0000, lineThickness:10, lineColor:0xFFFF00});
sim.addCircle({x:3, y:3, radius:1});
sim.addCircle({x:6, y:3, radius:1});
sim.addCircle({x:9, y:3, radius:1,
			   fillColor:0x000022,
			   lineThickness:5,
			   lineColor:0x6666FF});
sim.addBox({x:12, y:4, width:2, height:2, lineColor:0x00FF00});
sim.start();
sim.mouseDrag();
</pre>
<p>Go ahead and try this out in your timeline.</p>
<p>The <strong>setDefault()</strong> method isn&#8217;t limited to working with things like <strong>fillColor</strong> and <strong>lineThickness</strong>. It can be used in conjunction with <em>any</em> param. While I mostly find myself making use of <strong>setDefault()</strong> for render style and certain params related to joints, you <em>could</em> do something like this:</p>
<pre name="code" class="javascript">
sim.setDefault({fillColor:0xFF0000, lineThickness:10,
			   lineColor:0xFFFF00, y:3, radius:1});
sim.addCircle({x:3});
sim.addCircle({x:6});
sim.addCircle({x:9,
		   fillColor:0x000022,
		   lineThickness:5,
		   lineColor:0x6666FF});
</pre>
<p>This could quickly get confusing, so be careful when deciding to use <strong>setDefault()</strong> in this way.</p>
<h2>Step 13 : Skinning Rigid Bodies</h2>
<p>One of the main features of QuickBox2D is easy skinning of rigid bodies. Because skinning generally requires use of library assets, you&#8217;ll need to <a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/source.zip">download this source file</a>.</p>
<p>There are three MovieClips in the library, CircleFace, OddPizza and Mail. Each clip is exported for use with ActionScript. On the timeline you&#8217;ll find the following code:</p>
<pre name="code" class="javascript">
[SWF(width = 800, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
sim.addCircle({x:3, y:3, radius: 45 / 30, skin:CircleFace, scaleSkin:false});
sim.addCircle({x:6, y:3, radius:1, skin:OddPizza});
sim.addCircle({x:6, y:6, radius:0.5, skin:OddPizza});
sim.addCircle({x:6, y:10, radius:2, skin:OddPizza});
sim.addBox({x:12, y:3, width:3, height: 50 / 30, skin:Mail});
sim.addBox({x:18, y:3, width:3, height: 3, skin:Mail});
sim.start();
sim.mouseDrag();
</pre>
<p>
Go ahead and test the movie.</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/basic_skinning.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/milestone.jpg" alt="" style="border:none"></a>
</div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/051_quickBox2D/assets/image-9.gif"></div>
<p>In order to create custom skins, we make use of the <strong>skin</strong> param. In this example, we set all of our skin params to linkage classes from our library. By default, QuickBox2D will create an instance of this class and attempt to scale it to fit the rigid body. This is useful for simple shapes like circles and boxes, but for more complex skins, you may want to turn this feature off using the <strong>scaleSkin</strong> param. We do this on line 8 so that the CircleFace skin is used properly.</p>
<p>You&#8217;ll notice that for the radius we put 45 / 30 instead of 1.5. As mentioned earlier in this tutorial, 1 meter is 30 pixels, so to convert from pixels to meters we divide by 30. The circle in the CircleFace skin has a radius of 45 pixels so we&#8217;ve left the hard coded conversion in for clarity rather than writing 1.5.</p>
<p>Lines 10-12 create circles that make use of the OddPizza skin. The <strong>scaleSkin</strong> param is true by default, so each skin is automatically scaled<br />
according to the radius param. Lines 14 and 15 create boxes that are skinned with the Mail clip. </p>
<p>Over the past few months, more skinning features have been added at the request of developers making use of QuickBox2D. I use the techniques described above exclusively, but if you&#8217;re interested in seeing a few additional skinning techniques, have a look at <a href="http://actionsnippet.com/?p=2224" target="blank">this post on actionsnippet</a>. </p>
<h2>Step 14 : Further Reading</h2>
<p><a href="http://actionsnippet.com/?cat=113" target="blank">ActionSnippet QuickBox2D Posts</a> &#8211; There are a whole bunch of QuickBox2D examples on <a href="http://actionsnippet.com/">actionsnippet.com</a> in the form of posts. The earlier posts are significantly simpler than the newer ones. For that reason, I recommend going back a few pages and working your way up to some of the later posts. Nearly every aspect of QuickBox2D is covered in these examples.</p>
<p><a href="http://actionsnippet.com/qb2d/docs/html/index.html" target="blank">QuickBox2D Docs</a> &#8211; This is just the documentation for QuickBox2D. In some places it assumes basic Box2D knowledge.</p>
<p><a href="http://www.box2d.org/manual.html" target="blank">Box2D Manual</a> &#8211; An excellent resource that covers all aspects of Box2D. The C++<br />
syntax might scare you away&#8230; but if you replace arrows like this <strong>-&gt;</strong> with dot syntax and ignore asterisks <strong>*</strong>&hellip; you&#8217;ll find that you understand a good deal.</p>
<p><a href="http://www.linuxuser.at/elements/doc/box2d/index.htm">Box2D Docs</a> &#8211; Docs for all the C++ classes. I find this very useful for some of the techniques discussed in part 2 of this tutorial.</p>
<h2>Step 15 : What Next?</h2>
<p>
We&#8217;ve covered a lot of ground and we&#8217;ve only really scratched the surface. Below are summaries of the upcoming QuickBox2D tutorials:</p>
<p><strong>QuickBox2D Part 2</strong><br />
In the second part of this tutorial we will explore some of the more intermediate level features of QuickBox2D. We&#8217;ll look at how to create polygon rigid bodies. We&#8217;ll learn how to fine tune our simulation using additional param values such as <strong>restitution</strong>, <strong>linearDamping</strong> and <strong>angularDamping</strong>. We&#8217;ll discuss some powerful Box2D methods that are exposed by QuickBox2D and we&#8217;ll talk about FRIM (framerate independent motion).</p>
<p><strong>QuickBox2D Part 3</strong><br />
In the third part of this tutorial we will cover some advanced techniques. We&#8217;ll look at how QuickBox2D handles all of the different types of Box2D joints. We&#8217;ll also go over contact points and special types of collisions.</p>
<p>I hope you enjoyed reading this first part!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/introduction-to-quickbox2d-part-1/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Quick Tip: How to Create Perfect Alpha Reflections</title>
		<link>http://active.tutsplus.com/tutorials/effects/quick-tip-how-to-create-perfect-alpha-reflections/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/quick-tip-how-to-create-perfect-alpha-reflections/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 12:00:46 +0000</pubDate>
		<dc:creator>Bruno Crociquia</dc:creator>
				<category><![CDATA[Effects]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3046</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/preview/preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>2010 will see several changes here on Activetuts+, one of which you&#8217;ll see implemented across all the Tuts+ sites: <strong>Quick Tips</strong>. Quick Tips tuts will be short, informative, simple, effective and will demonstrate something achievable during your lunch break!</p>
<p><a href="http://active.tutsplus.com/author/bruno-crociquia/">Bruno</a> is kicking off the Quick Tips here at Activetuts+, with a great tip on creating perfect reflections. Got 5 minutes? Off you go then..</p>
<p><span id="more-3046"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/source.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a>
</div>
<h3>Final Result Preview</h3>
<p>Let&#8217;s take a look at what we&#8217;re aiming for here..</p>
<div class="tutorial_image">
<object width="500" height="440" data="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/alpha_reflection.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/alpha_reflection.swf" /></object>
</div>
<h2>Introduction</h2>
<p>This method allows you to take any kind of movieclips, even those containing video, and make a true reflection without worrying about the fading background.</p>
<h2>Step 1: Stage Setup</h2>
<p>Open up Flash and create a new Actionscript 3 FLA.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/1.jpg" width="600" alt="" /></div>
<h2>Step 2: Scene Setup</h2>
<p>Create the following layers:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/2.jpg" alt="" /></div>
<h2>Step 3: Object </h2>
<p>In the Objects layer create the movieclip that you want to reflect.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/3.jpg" alt="" /></div>
<h2>Step 4: Reflection </h2>
<p>Copy the movieclip from the Objects Layer and paste it in the Reflections layer, scale it vertically at -100%, that will make it flip vertically</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/4.jpg" alt="" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/5.jpg" alt="" /></div>
<h2>Step 5: Cache as Bitmap </h2>
<p>Check the cache as bitmap box.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/6.jpg" alt="" /></div>
<h2>Step 6: Instantiate </h2>
<p>Give it an instance name of &#8220;reflection_mc.&#8221;</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/7.jpg" alt="" /></div>
<h2>Step 7: Gradient </h2>
<p>Create a gradient filled rectangle with alpha.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/8.jpg" alt="" /></div>
<h2>Step 8: Mask </h2>
<p>Convert it to movieclip (F8) and give it an instance name of &#8220;mask_mc.&#8221;</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/9.jpg" alt="" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/10.jpg" alt="" /></div>
<h2>Step 9: Cache as Bitmap, Again </h2>
<p>Check the cache as bitmap box.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/6.jpg" alt="" /></div>
<h2>Step 10: Making Magic </h2>
<p>Select the actions layer and type:</p>
<pre name="code" class="javascript">
reflection_mc.mask = mask_mc
</pre>
<h2>Conclusion</h2>
<p>If you want you can add an alpha to the relfection_mc, I applied one of around 60%. Hope you liked this Quick Tip, thanks for reading!</p>
<div class="tutorial_image">
<object width="500" height="440" data="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/alpha_reflection.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/054_QTReflection/html/alpha_reflection.swf" /></object>
</div>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/quick-tip-how-to-create-perfect-alpha-reflections/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Shoot Out Stars with the Stardust Particle Engine</title>
		<link>http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 12:00:42 +0000</pubDate>
		<dc:creator>Allen Chou</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3010</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/preview.jpg" alt="Shoot Out Stars with the Stardust Particle Engine">]]></description>
			<content:encoded><![CDATA[<p>
In this tutorial I will introduce to you the <a href="http://code.google.com/p/stardust-particle-engine/">Stardust Particle Engine</a>. First I&#8217;m going to show you how to set up Stardust, and then I&#8217;ll cover the basic Stardust class responsibilities and how they collaborate together to make Stardust work as a whole.</p>
<p>Next, we will look at a Stardust&#8217;s general workflow and get down to creating a particle effect with stars shooting out from the mouse cursor; the stars will slow down gradually, grow larger after birth, and shrink when dying.</p>
<p>Finally, I&#8217;ll demonstrate the flexibility of Stardust by creating several variations from the already complete example, including using animated movie clips as particles, variable particle simulation timescale, and shooting out display objects of different classes from a single emitter.
</p>
<p><span id="more-3010"></span></p>
<p>
This tutorial is meant for people that are already familiar with ActionScript 3.0 object-oriented programming (OOP), so I&#8217;m assuming that you already know very well what classes, objects, inheritance, and interface mean. No problem with OOP? Then let&#8217;s go shoot some stars!
</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/src.rar"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/SWFs/MultipleDisplayClass/StarParticles.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Stardust Particle Engine</h2>
<p>
As its name suggests, Stardust is used for creating particle effects. If you&#8217;re an experienced ActionScripter, you might have created particle effects from scratch many times, and say &#8220;I&#8217;m totally cool with creating particle effects from scratch, so why would I need a particle engine anyway?&#8221; Well, Stardust is here to help you focus more on actual particle behavior design than worrying about the tedious underlying low-level stuff, such as memory management. Instead of writing code to take care of particle data, initializing and disposing resources, with Stardust, you get to skip these boring routines and just decide how you want your particles to behave.
</p>
<h2>Stardust Features</h2>
<p>
The class structure of Stardust was inspired by <a href="http://flintparticles.org/">FLiNT Particle System</a>, another ActionScript 3.0 particle engine. Thus, they share some similar basic features.
</p>
<ul>
<li>
<em>2D and 3D Particle Effects</em> &#8211; Stardust can be used to create both 2D and 3D particle effects. It has its own built-in 3D engine, and it also can be used to work in combination with other third-particle 3D engines, including <a href="http://code.google.com/p/zedbox/">ZedBox</a>, <a href="http://blog.papervision3d.org/"><a href="http://code.google.com/p/papervision3d/">Papervision3D</a>, and <a href="http://code.google.com/p/nd3d">ND3D</a>.
</li>
<li>
<em>High Extensibility</em> &#8211; Stardust provides a large set of particle behaviors and renderers at your disposal. If none of them fit your needs, you can always extend the base classes and create your own custom particle behaviors; also, you can create your own renderer to work with another 3D engine that is not supported by Stardust.
</li>
</ul>
<p>
In addition to these basic features, Stardust also provides several advanced features for experienced users.
</p>
<ul>
<li>
<em>Adjustable Simulation Timescale</em> &#8211; The timescale used for particle simulation can be dynamically adjusted during run-time. For instance, if you change the timescale to half of the original, the particle effect will be half as fast as normal speed; and if you tweak the timescale to twice the original, the particle effect is going to be simulated twice as fast as normal. This feature can come in handy when you are creating a game that has slow-motion effects: the particle effect can slow down to match your game engine&#8217;s speed, synchronizing with your game animation and graphics.
</li>
<li>
<em>XML Serialization</em> &#8211; You can transform your particle system into a file in XML format that can be stored on your hard drive, later loaded during run time and interpreted to reconstruct your orignal particle system. This is very useful when you&#8217;re working with a large project. Say you just want to size up your particles a little bit, so you tweak the parameters in the source code and recompile your entire Flash application, which might take a minute, or even over five minutes if your project is extremely huge. Is it worth it? Absolutely NO. That&#8217;s a total waste of time. Using the XML serialization feature to save your particle system in external XML files, you are separating parameters from the source code for the main application. So what you&#8217;ll have to do is simply open the XML file, change the parameter values, save it, and reopen your main application. That&#8217;s it! No recompilation is required at all. I would say this is the ideal way to work with large projects.
</li>
</ul>
<p>
When it comes to particle effects, it&#8217;s very important to handle massive particle data efficiently. Stardust makes heavy use of object pools and linked lists to enhance performance:
</p>
<ul>
<li>
<em>Object Pools</em> &#8211; Used objects are stored into a pool; later, if an object of the same type is required, Stardust doesn&#8217;t instantiate it immediately, but checks if there&#8217;s any object previously stored in the object pool left. If yes, Stardust simply takes out that object and uses it, instead of creating a whole new object. Usually particle effects involve a lot of object instantiation, which is CPU-consuming. By using object pools, Stardust greatly reduces the instantiation overhead.
</li>
<li>
<em>Linked Lists</em> &#8211; It&#8217;s very easy and tempting to store particle data into an array; however, in a case when particles are created and removed very frequently, a lot of array splicing takes place to remove dead particles. Array splicing is a CPU-consuming process, especially for long arrays. For a linked list, no matter how long the list is, it always takes the same short amount of time to splice out dead particles. From version 1.1, Stardust began to use linked lists internally to store particle data.
</li>
</ul>
<h2>Setting Up Stardust</h2>
<p>
Before we get down to actual coding, we&#8217;ll need to grab a copy of Stardust Particle Engine. It&#8217;s released under MIT license, which means it&#8217;s totally free of charge no matter if you want to use it in a commercial or non-commercial project.
</p>
<p>
Here&#8217;s the Stardust&#8217;s project homepage: <a href="http://code.google.com/p/stardust-particle-engine/">http://code.google.com/p/stardust-particle-engine/</a>
</p>
<p>
You can download Stardust here: <a href="http://code.google.com/p/stardust-particle-engine/downloads/list">http://code.google.com/p/stardust-particle-engine/downloads/list</a>
</p>
<p>
At the time of writing, the latest version that can be downloaded from the download list is 1.1.132 Beta. You can always grab the latest revision from the <a href="http://stardust-particle-engine.googlecode.com/svn/">SVN repository</a> (which might not be stable, however).
</p>
<p>
On the project homepage, you can also find more accessories like <a href="http://stardust-particle-engine.googlecode.com/svn/trunk/docs/index.html">API documentation</a> and a copy of <a href="http://stardust-particle-engine.googlecode.com/svn/trunk/manual/Stardust%20Particle%20Engine%20Manual.pdf">PDF manual</a>. There are even video tutorials on <a href="http://www.youtube.com/view_play_list?p=79300CF812C795F9">YouTube</a>.
</p>
<h2>Stardust Class Responsibilities</h2>
<p>
Here I&#8217;m going to briefly cover the Stardust core classes and their responsibilities.
</p>
<h4>StardustElement</h4>
<p>
This class is the superclass of all core classes, which defines properties and methods especially for XML serialization.
</p>
<h4>Random</h4>
<p>
Generally speaking, particle effects are all about controlling an amount of entities with similar but randomized appearance and behaviors. The Random class is for generating random numbers, which can be used in Stardust for randomizing particle properties. For instance, the UniformRandom class is a subclass of the Random class, and its name tells everything: the random number generated by a UniformRandom object is uniformly distributed, and I&#8217;ll be using this class in particular for the entire tutorial.
</p>
<h4>Zone</h4>
<p>
There are times when a one-dimensional random number is not enough. Sometimes we need two-dimensional random numbers, which are essentially pairs of random numbers, for properties like position and velocity. The Zone class is for generating two-dimensional random number pairs. This class models a random number pair as a random point in a 2D zone. For instance, the CircleZone generates random number pairs (x, y) from random points within a circular region. The Random and Zone classes are mainly used by the Initializer class, which will be covered later. The Zone3D class is the 3D counterpart of this class, for 3D particle effects.
</p>
<h4>Emitter</h4>
<p>
The Emitter class is basically where all the low-level stuff is encapsulated. An emitter initializes newly created particles before they are added into the simulation, updates particle properties in each main loop iteration, and removes dead particles from the simulation. The Emitter.step() method is what you want to invoke repeatedly in order to keep Stardust up and running.
</p>
<h4>Clock</h4>
<p>
The Clock class determines the rate of new particle creation for emitters. One Emitter object holds exactly one reference to a Clock object. At the beginning of each Emitter.step() method call, the emitter asks the clock object how many new particles it should create. Take the SteadyClock class for example, it tells emitters to create new particles at a constant rate.
</p>
<h4>Initializer</h4>
<p>
This class is for initializing newly created particles. An Initializer object needs to be added to an emitter for it to work. Basically, one Initializer subclass initializes just one particle property. For instance, the Mass initializer class initializes the mass of new particles. Some initializers accept a Random object as a constructor paramter for initializing particles with randomized values. The following code creates a Life initializer which initializes particle lives to values centered at 50 with variation of 10, namely between the range of 40 to 60.
</p>
<pre name="code" class="javascript">
new Life(new UniformRandom(50, 10));
</pre>
<h4>Action</h4>
<p>
Action objects update particle properties in each iteration of the main loop (the Emiter.step() method). For example, the Move action class updates particle positions according to velocity. An Action object must be added to an emitter for it to work.
</p>
<h2>General Stardust Workflow</h2>
<p>
Now that you know how the core classes collaborate together, let&#8217;s take a look at a general workflow for Stardust.
</p>
<p>
You start by creating an emitter. Use the Emitter2D class for 2D particle effects and the Emitter3D class for 3D effects.
</p>
<pre name="code" class="javascript">
var emitter:Emitter = new Emitter2D();
</pre>
<p>
To specify the rate of particle creation, we need a clock. This can either be set by the Emitter.clock property or by passing a clock as the first parameter to the emitter&#8217;s constructor.
</p>
<pre name="code" class="javascript">
//property approach
emitter.clock = new SteadyClock(1);

//constructor approach
var emitter:Emitter = new Emitter2D(new SteadyClock(1));
</pre>
<p>
Add initializers to the emitter through the Emitter.addInitializer() method.
</p>
<pre name="code" class="javascript">
emitter.addInitializer(new Life(new UniformRandom(50, 10)));
emitter.addInitializer(new Scale(new UniformRandom(1, 0.2)));
</pre>
<p>
Add actions to the emitter through the Emitter.addAction() method.
</p>
<pre name="code" class="javascript">
emitter.addAction(new Move());
emitter.addAction(new Spin());
</pre>
<p>
Create a renderer and add the emitter to the renderer through the Renderer.addEmitter() method.
</p>
<pre name="code" class="javascript">
var renderer:Renderer = new DisplayObjectRenderer(container); //"container" is our container sprite
renderer.addEmitter(emitter);
</pre>
<p>
Finally, repeatedly call the Emitter.step() method to keep the particle simulation going. You might want to use the enter-frame event or a timer to do this. In a single call of the Emitter.step() method, the clock determines how many new particles should be created, these new particles are initialized by initializers, all particles are updated by actions, dead particles are removed, and finally, the renderer renders the particle effect.
</p>
<pre name="code" class="javascript">
//enter-frame event approach
addEventListener(Event.ENTER_FRAME, mainLoop);

//timer approach
timer.addEventListener(TimerEvent.TIMER, mainLoop);
function mainLoop(e:Event):void {
	emitter.step();
}
</pre>
<p>
Alright. That&#8217;s pretty much all of it for Stardust primer. Now it&#8217;s time to open the Flash IDE and get your hands dirty.
</p>
<h2>Step 1: Create a New Flash Document</h2>
<p>
Create a new Flash document with a dimension of 640X400 a frame rate of 60fps, and a dark background. Here I made a dark-blue gradient background. By the way, Stardust works well with both Flash Player 9 and 10, so it&#8217;s okay no matter you&#8217;re using Flash CS3 or CS4. In this tutorial I&#8217;ll be using Flash CS3.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/1.jpg"/>
</div>
<h2>Step 2: Draw a Star</h2>
<p>
We&#8217;re creating a particle effect with stars, so we&#8217;ll need to draw a star and convert it to a symbol, exported for ActionScript of course. This symbol will be used later to render our particle effect. Name the symbol and the exported class &#8220;Star&#8221;.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/2.jpg"/>
</div>
<h2>Step 3: Create the Document Class</h2>
<p>
Create a new document class, and name it StarParticles.
</p>
<pre name="code" class="javascript">
package {
	import flash.display.Sprite;

	public class StarParticles extends Sprite {

		public function StarParticles() {

		}
	}
}
</pre>
<h2>Step 4: Extend the Emitter</h2>
<p>
As mentioned in the general workflow, the first step is to create an emitter. And the next step is adding initializers and actions to the emitter. While this can be done in the document class constructor, I strongly recommend that it be done in a separate Emitter subclass. It&#8217;s always better to separate the particle behavior design form the main program; by doing so, the code is much cleaner and easier to modify in the future, without being mixed up with the main program.
</p>
<p>
We are going to create a 2D particle effect, so the Emitter2D is the emitter class we&#8217;re going to extend. Extend the Emitter2D class and name it StarEmitter, since we are going to make it shoot out stars later. The Emitter constructor accepts a Clock parameter, so we&#8217;ll declare a constructor parameter to pass on a Clock object reference to the superclass&#8217;s constructor.
</p>
<pre name="code" class="javascript">
package {
	import idv.cjcat.stardust.twoD.emitters.Emitter2D;

	public class StarEmitter extends Emitter2D {

		public function StarEmitter(clock:Clock) {
			//pass on the clock object to the superclass's constructor
			super(clock);
		}
	}
}
</pre>
<h2>Step 5: Declare Constants</h2>
<p>
A better approach to create an emitter subclass is to declare particle parameters as static constants, grouped at a single place. So in case you want to tweak the parameters, you&#8217;ll always know where to find the declarations. The meaning of these constants will be explained later when they are used.
</p>
<pre name="code" class="javascript">
//average lifespan
private static const LIFE_AVG:Number = 30;

//lifespan variation
private static const LIFE_VAR:Number = 10;

//average scale
private static const SCALE_AVG:Number = 1;

//scale variation
private static const SCALE_VAR:Number = 0.4;

//scale growing time
private static const GROWING_TIME:Number = 5;

//scale shrinking time
private static const SHRINKING_TIME:Number = 10;

//average speed
private static const SPEED_AVG:Number = 10;

//speed variation
private static const SPEED_VAR:Number = 8;

//average omega (angular velocity)
private static const OMEGA_AVG:Number = 0;

//omega variation
private static const OMEGA_VAR:Number = 5;

//damping coefficient
private static const DAMPING:Number = 0.1;
</pre>
<h2>Step 6: Adding Initializers</h2>
<p>
Which initializers do we need to create our particle effect? Let&#8217;s take a look at the list below:
</p>
<ul>
<li>
<em>DisplayObjectClass</em> &#8211; This initializer assigns a specified display object to each particle, which will be used by a DisplayObjectRenderer to render particle effects. The constructor accepts a class reference to the display object class we wish to instantiate; for this tutorial, this class will be the Star class (symbol) we created in Step 2.
</li>
<li>
<em>Life</em> &#8211; This initializer assigns each particle a random life value. Later, we&#8217;ll add actions to the emitter to deplete this life value through time, and to mark a particle as dead if its life value reaches zero. A Random object is passed to the constructor, which will be used by this initializer to generate random value for particles&#8217; life. For most cases, the UniformRandom class is convenient and sufficient; the first parameter of the UniformRandom constructor is the center (or average) value of the random numbers generated, and the second is the radius (or variation). For instance, a UniformRandom object with center 20 and variation 5 generates random numbers within the [15, 25] range. Here we use the LIFE_AVG constant for the center value and LIFE_VAR for the radius.
</li>
<li>
<em>Scale</em> &#8211; Like the Life initializer, the Scale initializer initializes a particle&#8217;s scale to a random value, determined by a Random object passed to the initializer&#8217;s constructor. Here we use the SCALE_AVG constant for the center value and SCALE_VAR for the radius.
</li>
<li>
<em>Position</em> &#8211; This initializer assigns a particle a random position. Unlike the Life and Scale initializers, which need only 1D random numbers, the Position initializer requires 2D random number pair generators. As described in the Stardust Class Responsibilities section, the Zone class is exactly for this purpose. The Zone object passed to the initializer&#8217;s constructor is used to generate 2D random number pairs, which will be assigned to particles as position vectors. In this tutorial we&#8217;re going to make stars shoot out from a single point located at the mouse cursor, so we&#8217;ll use a SinglePoint class, which is a Zone subclass. In order to dynamically adjust the coordinate of this SinglePoint object from the document class, we need to expose a reference to this point object through a public property. This is what the &#8220;point&#8221; property is for.
</li>
<li>
<em>Velocity</em> &#8211; Same as the Position initializer, the Velocity initializer needs a Zone object to generate 2D random value pairs to initialize particle velocities. A 2D vector generated by the Zone object, which is the coordinate of a random point in the zone, is assigned to particles as their velocities. Here we use the LazySectorZone class that represents a sector region. A sector is a portion of a circle enclosed by two radii and two angles. For the LazySectorZone, the two angles are 0 and 360 by default, representing a full angle around a circle. The first constructor parameter of the LazySectorZone class is the average of the two radii, and the second is the variation of the radii. In this case, the average of the two radii represents the average speed, and the variation of radii represents variation of speed. Here we use the SPEED_AVG constant for the first parameter and SPEED_VAR for the second.
</li>
<li>
<em>Rotation</em> &#8211; The Rotation initializer initializes a particle&#8217;s rotation angle to a random value. And as some of the aforementioned initializers, the constructor accepts a Random object to generate a random value. Since we&#8217;d like to have particles with angles ranging from 0 to 360 degrees, we&#8217;ll use 0 as the center and 180 as the radius of the UniformRandom object.
</li>
<li>
<em>Omega</em> &#8211; Omega, as in most of the physics textbooks, means angular velocity. With that said, the purpose of this initializer is clear: it initializes a particle&#8217;s angular velocity to a random value, and the OMEGA_AVG constant is used as the center and OMEGA_VAR as the radius of the UniformRandom object.
</li>
</ul>
<p>
And here&#8217;s the code:
</p>
<pre name="code" class="javascript">
point = new SinglePoint();

addInitializer(new DisplayObjectClass(Star));
addInitializer(new Life(new UniformRandom(LIFE_AVG, LIFE_VAR)));
addInitializer(new Scale(new UniformRandom(SCALE_AVG, SCALE_VAR)));
addInitializer(new Position(point));
addInitializer(new Velocity(new LazySectorZone(SPEED_AVG, SPEED_VAR)));
addInitializer(new Rotation(new UniformRandom(0, 180)));
addInitializer(new Omega(new UniformRandom(OMEGA_AVG, OMEGA_VAR)));
</pre>
<h2>Step 7: Adding Actions</h2>
<p>
Okay, we&#8217;re done with the initializers. Now it&#8217;s time to add actions to the emitter. Below is a list of actions we need:
</p>
<ul>
<li>
<em>Age</em> &#8211; The Age action decreases a particle&#8217;s life value by 1 in each emitter step.
</li>
<li>
<em>DeathLife</em> &#8211; When a particle&#8217;s life value reaches zero, this action marks the particle as dead, changing its isDead property from false to true. At the end of an emitter step, dead particles are removed.
</li>
<li>
<em>Move</em> &#8211; Pretty much as its name suggests, the Move action updates particle positions according to their velocities.
</li>
<li>
<em>Spin</em> &#8211; Similar to the Move action, the Spin action updates a particle&#8217;s rotation angle according to the particle&#8217;s omega value (angular velocity).
</li>
<li>
<em>Damping</em> &#8211; This action multiplies a particle&#8217;s veloctiy with a factor within the range [0, 1], simulating damping effects and gradually slowing down particle. A factor of one means no damping at all: particles move freely as if there were no damping effect; a factor of zero means total damping: all particles cannot move a bit. This factor is determined by the &#8220;damping coefficient&#8221; through this formula: &#8220;factor = 1 &#8211; (damping coefficient)&#8221;. The parameter passed to the constructor is the damping coefficient; here we just want a little damping effect, so we use the value 0.1 for the coefficient.
</li>
<li>
<em>ScaleCurve</em> &#8211; The ScaleCurve action changes a particle&#8217;s scale according to its life value. It grows from an initial scale to a normal scale after birth, and fades to a final scale as it dies. Of course, a particle can also have an initial or final scale value that is larger than the normal scale; it just depends on personal choice. In many cases, we&#8217;d like particles to have an initial and final scale value of zero, which is the default value. The first parameter in the constructor stands for a particle&#8217;s growing time, and the second is the fading time; so we pass in the GROWING_TIME and SHRINKING_TIME constants as the first and second parameter, respectively. The growing time is 5, meaning a particle grows from zero scale to normal scale during its first 5 unit of lifespan; and the shrinking time is 15, which means a particle shrinks to zero scale at the last 15 unit of lifespan. Note that the transition is linear by default, but any easing fucntion can be used, specifically the easing equations created by Robert Penner. There&#8217;s another similar action called <em>AlphaCurve</em>, which works on alpha values in the same way.
</li>
</ul>
<p>
That&#8217;s it. Our emitter is done. Here&#8217;s the code for this emitter in its entirety, necessary import statements included.
</p>
<pre name="code" class="javascript">
package {
	import idv.cjcat.stardust.common.actions.Age;
	import idv.cjcat.stardust.common.actions.DeathLife;
	import idv.cjcat.stardust.common.actions.ScaleCurve;
	import idv.cjcat.stardust.common.clocks.Clock;
	import idv.cjcat.stardust.common.initializers.Life;
	import idv.cjcat.stardust.common.initializers.Scale;
	import idv.cjcat.stardust.common.math.UniformRandom;
	import idv.cjcat.stardust.twoD.actions.Damping;
	import idv.cjcat.stardust.twoD.actions.Move;
	import idv.cjcat.stardust.twoD.actions.Spin;
	import idv.cjcat.stardust.twoD.emitters.Emitter2D;
	import idv.cjcat.stardust.twoD.initializers.DisplayObjectClass;
	import idv.cjcat.stardust.twoD.initializers.Omega;
	import idv.cjcat.stardust.twoD.initializers.Position;
	import idv.cjcat.stardust.twoD.initializers.Rotation;
	import idv.cjcat.stardust.twoD.initializers.Velocity;
	import idv.cjcat.stardust.twoD.zones.LazySectorZone;
	import idv.cjcat.stardust.twoD.zones.SinglePoint;

	public class StarEmitter extends Emitter2D {

		/**
		 * Constants
		 */
		private static const LIFE_AVG:Number = 30;
		private static const LIFE_VAR:Number = 10;
		private static const SCALE_AVG:Number = 1;
		private static const SCALE_VAR:Number = 0.4;
		private static const GROWING_TIME:Number = 5;
		private static const SHRINKING_TIME:Number = 10;
		private static const SPEED_AVG:Number = 10;
		private static const SPEED_VAR:Number = 8;
		private static const OMEGA_AVG:Number = 0;
		private static const OMEGA_VAR:Number = 5;
		private static const DAMPING:Number = 0.1;

		public var point:SinglePoint;

		public function StarEmitter(clock:Clock) {
			super(clock);

			point = new SinglePoint();

			//initializers
			addInitializer(new DisplayObjectClass(Star));
			addInitializer(new Life(new UniformRandom(LIFE_AVG, LIFE_VAR)));
			addInitializer(new Scale(new UniformRandom(SCALE_AVG, SCALE_VAR)));
			addInitializer(new Position(point));
			addInitializer(new Velocity(new LazySectorZone(SPEED_AVG, SPEED_VAR)));
			addInitializer(new Rotation(new UniformRandom(0, 180)));
			addInitializer(new Omega(new UniformRandom(OMEGA_AVG, OMEGA_VAR)));

			//actions
			addAction(new Age());
			addAction(new DeathLife());
			addAction(new Move());
			addAction(new Spin());
			addAction(new Damping(DAMPING));
			addAction(new ScaleCurve(GROWING_TIME, SHRINKING_TIME));
		}
	}
}
</pre>
<h2>Step 8: Finish the Document Class</h2>
<p>
Now it&#8217;s time to go back to the document class and finish it up. Let&#8217;s take a look at the remaining tasks.
</p>
<ul>
<li>
<em>Create a StarEmitter instance</em> &#8211; We&#8217;re going to instantiate the StarEmitter class we just finished.
</li>
<li>
<em>Assign a Clock object to the emitter</em> &#8211; We want a steady rate of particle emission, so we&#8217;ll use the SteadyClock class. The parameter passed to the clock&#8217;s constructor is the rate of emission, or, in other words, the number of new particles created in each emitter step; a fractional rate of 0.5 means in each emitter step, there&#8217;s a 50% chance for a new particle to be created and 50% chance for no particle created.
</li>
<li>
<em>Create a Renderer</em> &#8211; To visualize the particle effect, we&#8217;ll going to need a renderer. The DisplayObjectRenderer should be used in conjunction with the DisplayObjectClass initializer: the initializer assigns a display object to each particle, and the renderer adds these display objects to a container&#8217;s display list, constantly updating them. Also, don&#8217;t forget to add the emitter to the renderer.
</li>
<li>
<em>Call the Main Loop Repeatly</em> &#8211; This last step keeps Stardust up and running. Here we&#8217;ll make use of the enter-frame event.
</li>
<p>
Below is the complete code for the document class, necessary import statements included.
</p>
</ul>
<pre name="code" class="javascript">
package {
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import idv.cjcat.stardust.common.clocks.SteadyClock;
	import idv.cjcat.stardust.common.renderers.Renderer;
	import idv.cjcat.stardust.twoD.renderers.DisplayObjectRenderer;

	public class StarParticles extends Sprite {

		private var emitter:StarEmitter;

		public function StarParticles() {
			//instantiate the StarEmitter
			emitter = new StarEmitter(new SteadyClock(0.5));

			//the container sprite
			var container:Sprite = new Sprite();

			//the renderer that renders the particle effect
			var renderer:Renderer =  new DisplayObjectRenderer(container);
			renderer.addEmitter(emitter);

			//add the container to the display list, above the background
			addChildAt(container, 1);

			//make use of the enter-frame event
			addEventListener(Event.ENTER_FRAME, mainLoop);
		}

		private function mainLoop(e:Event):void {
			//update the SinglePoint position to the mouse position
			emitter.point.x = mouseX;
			emitter.point.y = mouseY;

			//call the main loop
			emitter.step();
		}
	}
}
</pre>
<p>
Finally, we&#8217;re done! Now let&#8217;s take a look at the outcome. Press CTRL+ENTER in Flash to test the movie, and you&#8217;ll see the result.
</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/SWFs/Basic/StarParticles.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Variation 1: Animated Stars</h2>
<p>
We&#8217;re not done yet! Let&#8217;s do a few more variations. The first one is using animated movie clips for our particles.
</p>
<h2>Step 9: Create a Timeline Animation</h2>
<p>
This first variation is quite simple, not involving any extra coding. It&#8217;s as simple as creating a basic timeline animation. Edit the Star symbol in Flash IDE, create another key frame, and change the star&#8217;s color in this frame to red. This essentially causes the stars to blink between yellow and red. You might want to insert some more empty frames in between, since a frame rate of 60fps is too fast for a two-frame blinking.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/3.jpg"/>
</div>
<p>
Now test the movie and check the result. The blinking star effect looks cartoonish; this can be used for classic dizzy-star effects, which is commonly seen in cartoons.
</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/SWFs/AnimatedMovieClips/StarParticles.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Variation 2: Adjusting Timescale Dynamically</h2>
<p>
As I mentioned earlier, one of the Stardust feature is &#8220;adjustable simulation timescale&#8221;, which means the timescale used by Stardust for particle simulation can be dynamically adjusted. All is done by changing the Emitter.stepTimeInterval property, which is 1 by default. The following code snippet changes this value to 2, resulting in particles moving twice as fast and emitter creating new particles at double rate.
</p>
<pre name="code" class="javascript">
emitter.stepTimeInterval = 2;
</pre>
<p>
In this variation, we&#8217;ll create a slider on the stage and use it to dynamically adjust the simulation timescale.
</p>
<h2>Step 10: Create a Slider</h2>
<p>
Drag a Slider component out from the Components Panel to the stage. Name it &#8220;slider&#8221;.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/4.jpg"/>
</div>
<h2>Step 11: Setup Slider Parameters</h2>
<p>
We&#8217;d like to have the slider to slide between 0.5 and 2, which means we want our particle simulation to be at least half as fast as normal and at most twice at fast. Also, set &#8220;liveDragging&#8221; to true so we can see the update as we scrub the slider thumb.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/5.jpg"/>
</div>
<h2>Step 12: Slider Event Listener</h2>
<p>
Now we have to listen to the slider&#8217;s change event to dynamically change the simulation timescale. First import the SliderEvent class in the document class.
</p>
<pre name="code" class="javascript">
import fl.events.SliderEvent;
</pre>
<p>
And then listen to the slider&#8217;s change event in the document class constructor.
</p>
<pre name="code" class="javascript">
slider.addEventListener(SliderEvent.CHANGE, changeTimescale);
</pre>
<p>
Finally, change the simulation timescale in the listener. Add the following listener to the document class.
</p>
<pre name="code" class="javascript">
private function changeTimescale(e:SliderEvent):void {
	emitter.stepTimeInterval = slider.value;
}
</pre>
<p>
Let&#8217;s look at the result. Notice that as you scrub the slider&#8217;s thumb to the left, the particle simulation slows down, and if you scrub right the simulation goes faster.
</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/SWFs/DynamicTimescale/StarParticles.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Variation 3: Multiple Display Class</h2>
<p>
Stardust provides a special initializer called SwitchInitializer. Its constructor accepts two arrays as parameters; the first one is an array of initializers, and the second one, with the same length as the first, is an array of &#8220;weights&#8221;. Each time Stardust uses this initializer to initialize particles, one of the initializers in the first array is picked randomly to initialize the particles. The more weight an initializer has, the more likely it&#8217;ll be picked for initialization. In this variation, we&#8217;re going to make the emitter shoot out not only stars but also white circles.
</p>
<h2>Step 13: Draw a Circle</h2>
<p>
Draw a white circle, convert it to a symbol, exported for ActionScript, and name the symbol and the class &#8220;Circle&#8221;. This is the class we&#8217;ll use for the white circles.
</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/6.jpg"/>
</div>
<h2>Step 14: Create the Switch Initializer</h2>
<p>
Open the StarEmitter class, and delete the following line. This disables the DisplayObjectClass initializer we set up in the previous steps.
</p>
<pre name="code" class="javascript">
addInitializer(new DisplayObjectClass(Star));
</pre>
<p>
Now add the following code to the constructor. We&#8217;d like to have stars and circles to be emitted equally likely, so we&#8217;ll give them both a weight of 1.
</p>
<pre name="code" class="javascript">
//the initializer for stars
var doc1:DisplayObjectClass = new DisplayObjectClass(Star);

//the initializer for white circles
var doc2:DisplayObjectClass = new DisplayObjectClass(Circle);

//the switch initializer
var si:SwitchInitializer = new SwitchInitializer([doc1, doc2], [1, 1]);

//add the switch initializer to the emitter
addInitializer(si);
</pre>
<p>
Finally, test the movie. You can see both stars and circles are emitted out from the emitter, although angular velocity doens&#8217;t have much effect on circles.
</p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/053_starDust/SWFs/MultipleDisplayClass/StarParticles.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>End of Tutorial</h2>
<p>
This is the end of this tutorial. Thank you for reading! You might say it&#8217;s a whole lot of code just to create such simple effect, but hey, do you remember writing any code other than designing the particle&#8217;s behavior in high-level? In the future if you want to modify your code, would you like to see code like this:
</p>
<pre name="code" class="javascript">
particle.vx *= 0.9;
particle.vy *= 0.9;
particle.x += particle.vx * 2;
particle.y += particle.vy * 2;
</pre>
<p>
&#8230;or like this?
</p>
<pre name="code" class="javascript">
emitter.addAction(new Damping(0.1));
emitter.addAction(new Move());
emitter.stepTimeInterval = 2;
</pre>
<p>
Stardust is here to help you create particle effects at ease. Design particle behaviors in high-level, tell Stardust what to do, and let Stardust handle the low-level implementation for you!
</p>
<p>
I hope you have understood how Stardust works internally and are now familiar enough with the basic workflow. In the future, I&#8217;ll write more tutorials on custom initializers/actions/renderers, 3D particle effects, and XML serialization. Thank you again for reading this tutorial. Happy Stardusting!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/shoot-out-stars-with-the-stardust-particle-engine/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Creating Ripples in the Medici Fountain &#8211; Basix</title>
		<link>http://active.tutsplus.com/tutorials/effects/creating-ripples-in-the-medici-fountain/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/creating-ripples-in-the-medici-fountain/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 12:00:37 +0000</pubDate>
		<dc:creator>Tom Green</dc:creator>
				<category><![CDATA[Effects]]></category>
		<category><![CDATA[Basix]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2957</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/PreviewImage.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>You have to admit, when you use a product named Flash there is a tendency to get flashy and overdo it. The thing is the true art of the Flash designer lies not in producing overwhelming in-your-face presentations or effects. The true art lies in dialing the Flashiness Meter way back and realizing it is the <strong>art of subtlety</strong> that is important. Not the <strong>Flash</strong>.</p>
<p>Which brings us to the subject of this Beginner-level tutorial&hellip; doing water.</p>
<p><span id="more-2957"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/ExerciseFiles.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/preview.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<p>Before we get going let’s be perfectly clear with each other. There are several dozen ways to do what I am going to talk about in this tutorial. In fact, I fully expect to see the comments box at the end of this piece  become populated with a number of posts telling me, essentially, <strong>That ain’t the way I would do it.</strong> It most likely isn’t and I have no problem with that and expect it. In fact this tutorial is based upon an example <a href="http://www.leebrimelow.com/" target="_blank">Lee Brimelow</a>, a Flash Platform Evangelist for Adobe first showed me a couple of years ago. </p>
<p>Lee and I both share a remarkably similar outlook when it comes to working with ActionScript. Instead of staring at a blank Actions panel, we both think it is important that you, as a beginner, grab a code sample (much like we offer here)  and start playing with it. This way you learn what a lot of things do. Academics call this process, &#8220;scaffolding&#8221;, which is a fancy term for learning a basic skill and building your knowledge from it.</p>
<p>As I said,though, this is a beginner level tutorial designed to demonstrate some very interesting ActionScript that uses Displacement maps, filters and Perlin Noise to create water ripples. The whole point of this exercise, in fact, is to present some otherwise complex code and show you where you can have some fun with it. When code starts becoming fun, you are well on your way to full OOP glory. In fact, my associate here at Activetuts+, Cadin Batrack does just that with many of the techniques presented here in his tutorial <a href="http://active.tutsplus.com/tutorials/effects/create-a-static-distortion-effect-using-the-displacement-map-filter/">Create a Static Distortion Effect Using the Displacement Map Filter</a>. </p>
<p>Now that we understand each other, let’s get subtle and make some ripples.</p>
<h2>Step 1: Develop a Plan of Attack</h2>
<p>The image we will be using is a shot I took of the Medici Fountain in the Jardin du Luxembourg in Paris, France. The plan is to put that pool of water into motion using Flash.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/1.jpg" width="600" /></div>
<p>Why do we need a plan of attack? Flash doesn’t do water ripples. In this particular approach, you simply can’t select the water area using a selection tool in Flash and, using ActionScript, say,</strong> Jiggle this selection around.</strong></p>
<p>For Flash to <strong>jiggle a selection around</strong> you need to stick the image in a BitMapData object, shift the pixels in that object around using the DisplacementMapFilter and then apply some Perlin Noise to the filter to create the ripples. Before you do that you need to take a trip to Photoshop or Fireworks.</p>
<h2>Step 2: Mask out the Water</h2>
<p>This can be done in either Fireworks or Photoshop. The key is to duplicate the image and either mask out or remove the water in the masking layer. Save the file as either a .png or .psd image and quit. As you may have surmised the bottom, unmasked,  layer is critical to the success of this project.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/2.jpg" width="600" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/3.jpg" width="600" /></div>
<h2>Step 3: New Document</h2>
<p>Create a new Flash ActionScript 3 Document. Add two new layers named &#8220;Mask&#8221; and &#8220;actions&#8221;. Rename Layer 1 to &#8220;Image&#8221; and lock the &#8220;actions&#8221; layer. At this point I am going to do a bit of a branch because importing Photoshop and Fireworks images into Flash are two separate techniques.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/4.jpg" width="369" height="209" /></div>
<h2>Step 4: Import the Photoshop Image</h2>
<p>When the Import dialog box opens, select the Fountain layer and select Create movie clip for this layer. Don’t bother with the instance name we’ll do that once the layers hit the stage. When the file imports you will see the Mask layer is a bitmap and the Fountain layer is now a movieclip.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/5.jpg" width="600"/></div>
<h2>Step 5: Import the Fireworks CS4 Image</h2>
<p>When the Import dialog box opens be sure that Import as Flattened Bitmap is not selected. </p>
<p>Fireworks imports a .png that is nothing more than a placeholder. If you open the Firework Objects folder you will see the document is in its own folder- usually &#8220;Page One&#8221; &#8211; because Fireworks allows you to have multiple pages in one document. If you open that folder you will see the two bitmaps and a movieclip. Open the movieclip and set up the layers using the instructions from Step 3. Convert the Fountain layer to a movieclip.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/6.jpg" width="451" height="298" /></div>
<h2>Step 6: Fountain</h2>
<p>Select the Fountain movieclip on the timeline and give it the instance name of &#8220;photo&#8221;. Lock all three layers and save the file.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/048_perlinNoise/7.jpg" width="600"/></div>
<h2>Step 7: Wiring it up</h2>
<p>The code you are about to write is fairly simple. As I said earlier you can’t tell Flash to take a selection and make it jiggle. In the case of this code we are going to jiggle the  the pixels in the fountain movieclip. This requires you to :</p>
<ol>
<li>Create a virtual bitmap that holds the pixels to be jiggled.</li>
<li>Set the jiggle parameters using a DisplacementMapFilter.</li>
<li>Create some variables that provide the jiggle.</li>
<li>Apply the perlinNoise method to the fountain image to jiggle the pixels using the DisplacementMapFilter every time the playhead loops through the frame.</li>
</ol>
<p>If you are subtle, the jiggling looks like running water rather than a tsunami or a tar pit..</p>
<p>Let’s get started:</p>
<h2>Step 8: Code</h2>
<p>Enter the following code:</p>
<pre name="code" class="javascript">
var bmd:BitmapData = new BitmapData(800,535);
var dmf:DisplacementMapFilter = new DisplacementMapFilter(bmd, new Point(0,0),0,2,10,60);
</pre>
<p>We start by creating a BitmapData object that matches the size of the image to be manipulated. Remember, Flash is not exactly the brightest candle on the tree. It needs to be told what to do. In this case you are telling it to create a collection of pixels matching the dimensions of the image and stick them in an object named &#8220;bmd&#8221;.</p>
<p>Now that it has this &#8220;bmd thing&#8221; it needs to be told what to do with the pixels in the object. The next line does just that.<br />
  The DisplacementMapFilter uses the greyscale values of an RGB channel, including alpha, and uses them to distort an image (in this case a bunch of Bitmapdata pixels) based upon the values kicked out of the filter’s paramters. The parameters are as follows:</p>
<ul>
<li><strong>mapBitmap: </strong>In this case the bmd’s pixels will be used.</li>
<li><strong>mapPoint:</strong> This is the alignment point- 0,0 &#8211; for the placement of the bmd object.</li>
<li><strong>componentX: </strong> How far will the channel’s pixels be shifted along the X axis. In this case, they aren’t. You can also specify a Channel such as RED instead of a numeric value.</li>
<li><strong>componentY:</strong>  The channel will be moved down 2 pixels on the Y axis. The really neat thing about these X and Y values is they can actually be used for different channels of the bmd object. For instance you could have the red channel  control the X axis displacement and the blue channel control the Y axis displacement.</li>
<li><strong>scaleX: </strong> We are going to scale the pixels along the X axis by 10%.  Just keep in mind that the bigger the number, the bigger the displacement which sort of explains the Tsunami and Tar Pit references earlier.</li>
<li><strong>scaleY:</strong>  The pixels will be scaled by 60% on the Y axis.</li>
</ul>
<p>There are three other parameters you can add but aren’t needed here. They are:</p>
<ul>
<li><strong>mode:</strong> These are strings that determine how pixels that go off of the edge are handled. Wrap pulls in pixels from the opposite side of the image, Clamp repeats pixels at the edge. Ignore simple uses the source pixel color and Color uses the color and alpha values specified.</li>
<li><strong>Color:</strong> Use this when you need to specify a mode. This one specifies the color, expressed as a number, to be used for pixels that go off the edge.</li>
<li><strong>Alpha:</strong> Used when you use a mode and the number &#8211; between 0.0 and 1.0 &#8211; is used to determine the transparency of the pixels that go off the edge.</li>
</ul>
<h2>Step 9: Variables</h2>
<p>Create the variables to be used in creating the ripple effect:</p>
<pre name="code" class="javascript">
  var pt1:Point = new Point(0,0);
  var pt2: Point = new Point(0,0);
  var perlinOffset:Array =  [pt1,pt2];
</pre>
<h2>Step 10: Create the Event</h2>
<pre name="code" class="javascript">
addEventListener(Event.ENTER_FRAME,loopIt);
</pre>
<p>We need this to make the water jiggle. This occurs thanks to the Displacment filter altering the values in its Point() parameter at the same rate as your movie. In my case the frame rate is set to 30 fps meaning the values will change 30 times per second.</p>
<h2>Step 11: LoopIt</h2>
<p>Write the loopIt function:</p>
<pre name="code" class="javascript">
  function loopIt (evt:Event) :void{
  perlinOffset[0].x += 0.5;
  perlinOffset[1].y += 0.1;
  bmd.perlinNoise(400,5,3,2,false,false,2,true,perlinOffset);
  photo.filters = [dmf];
};</pre>
<p>The first two lines set the values used by <em>Point() </em>parameter in the DisplacementMapFilter, as the playhead loops the x and y values increment. The values I chose were the result of a lot of testing until I achieved the effect I wanted.</p>
<p>The third line applies the perlinNoise method to the bitmap object created in line 1 of the code. Let’s go through the parameters:</p>
<p>The first two numbers are the <em>baseX</em> and <em>baseY</em> values &#8211; 400, 5 &#8211; which determine the frequency of the noise on the x and y axes. The lower the number the more detailed the noise will be. As a rule of thumb the baseX number can be set to match the width of the image. I found 800 to be a bit much so I dialed it down to 400. The difference in detail was negligible. </p>
<p>The third number, 3, is the <em>numOctave</em> parameter. The higher the number the more detailed will be the random noise. The downside is a hit on processing power and a potential speed decrease in the effect. This wasn’t destined for the web so 3 seems to work just fine. Using a value of 1 really didn’t move the pixels all that much. The next number,2, is the<em> randomSeed </em>parameter.</p>
<p>The two Boolean values are are the <em>stitch</em> and <em>fractalNoise</em> parameters. A true value for stitch smooths the edges of any tiling that may occur &#8211; not needed here. The fractalNoise value determines whether the noise will be fractal noise (true) or turbulence (false).  The false value &#8211; turbulence &#8211; is suited for water effects such as ripples or fire.</p>
<p>The next value, 2, is the <em>channelOptions</em> parameter. This value determines in which of the four color channels the noise will be applied.</p>
<p>The Boolean value, false, is the <em>greyScale</em> parameter. Had I used false the color channel specified in the channelOptions parameter would be used to generate the noise. Using true tells Flash that I want to use the greyscale .
</p>
<p>The final parameter,<em>perlinOffse</em>t, is the array of Points to be used  to offset the noise in each octave of the effect.</p>
<p>The final line &#8211; photo.filters = [dmf]; &#8211; applies the displacement filter, with the Perlin Noise, to the image in the photo instance.</p>
<h2>Step 12: Finish up</h2>
<p>Save the movie and test it.</p>
<h2>Conclusion:</h2>
<p>In this beginner-level tutorial I walked you through the use of ActionScript to create rippling water in a fountain in Paris. As you can see there wasn&#8217;t all that much code involved and much of it was fairly uncomplicated.</p>
<p>What is really important to you, as you start exploring ActionScript and Flash is to clearly understand that most code values are either numbers or Boolean values. What you need to do is to be unafraid to play &quot;What if &#8230; &quot; games. These are the games where you wonder,&quot;What if I changed this number, what would happen?&quot; In fact, feel free to play around with all the numbers in the DisplacemantmapFilter and perlinNoise(). You can get some rather fascinating affects ranging from the oooze of a Tar Pit to the water looking like there is an earthquake under way. </p>
<p>Have some fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/creating-ripples-in-the-medici-fountain/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Create a Static Distortion Effect Using the Displacement Map Filter</title>
		<link>http://active.tutsplus.com/tutorials/effects/create-a-static-distortion-effect-using-the-displacement-map-filter/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/create-a-static-distortion-effect-using-the-displacement-map-filter/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 12:00:00 +0000</pubDate>
		<dc:creator>Cadin Batrack</dc:creator>
				<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2914</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Preview/previewIcon.jpg" alt="Create a Static Distortion Effect Using the Displacement Map Filter">]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you&#8217;ll learn how to use AS3&#8217;s DisplacementMapFilter class to create a reusable static distortion effect for button rollovers.</p>
<p><span id="more-2914"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/sourceFiles.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a>
</div>
<h3>Final Result Preview</h3>
<p>Let&#8217;s take a look at the final result we will be working towards:</p>
<div class="tutorial_image">
<object width="500" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/Preview.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/Preview.swf" /></object>
</div>
<h2>Step 1: About Displacement Mapping</h2>
<p>A displacement map works by using the color values from one image to alter the position of pixels in another image. This effect is often used to make a flat graphic &#8216;wrap&#8217; around a dimensional image. We&#8217;re going to use it here to distort a button so it looks like it&#8217;s receiving static interference.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/1.jpg" alt="displacement example" /></div>
<p>You can read more about displacement mapping <a target="_blank" href="http://en.wikipedia.org/wiki/Displacement_mapping">here</a>.</p>
<h2>Step 2: Set up Your Flash File</h2>
<p>Create a new Flash file (ActionScript 3).</p>
<p>Your movie settings will vary depending on your game. For this demo I&#8217;m setting up my movie as 500&#215;300, black background, and 30 fps.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/2.jpg" alt="Flash file setup" /></div>
<h2>Step 3: Create a Simple Button</h2>
<p>Create a new Button symbol on the stage (Insert > New Symbol). Design the 4 states for your button. The exact design should be something that matches your game. Something glowy and semi-transparent works well with this effect.<br />
I used a font called <a target="_blank" href="http://www.veer.com/products/typedetail.aspx?image=AMT0000008">Genetrix Square</a> for mine, but you should use something that matches the look of your game.</p>
<p>Give your button an instance name of &#8216;button1&#8242;.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/3.jpg" alt="button properties" /></div>
<h2>Step 4: Test</h2>
<p>If you save and test your movie (Control > Test Movie) now you should see your button on the stage responding to the mouse with the rollover states you designed. Like this:</p>
<div class="tutorial_image">
<object width="500" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone1.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone1.swf" /></object>
</div>
<h2>Step 5: Create the JitteryButton Class</h2>
<p>We need to add custom functionality to our button. We&#8217;ll accomplish this by creating a new custom class and putting our simple button inside it.</p>
<p>Create a new ActionScript file named &#8216;JitteryButton.as&#8217;. Save this file in the same directory as your main Flash file. Add this code to create the wrapper for our button:</p>
<pre name="code" class="javascript">
package {

	import flash.display.Sprite;
	import flash.display.SimpleButton;

	public class JitteryButton extends Sprite {

		private var myButton:SimpleButton; // holds the reference to our simple button

		// CLASS CONSTRUCTOR
		public function JitteryButton(button:SimpleButton) {
			myButton = button; // the button on the stage gets passed in
		}

}
</pre>
<p>All this code does so far is accept the simple button and store a reference to it. We&#8217;ll add more functionality later.</p>
<h2>Step 6: Create the Game Class</h2>
<p>Create a new ActionScript file named &#8216;Game.as&#8217;. This will be the document class for our movie. Save it in the same directory as the main Flash file.</p>
<p>This code will add our custom button wrapper around the button on the stage:</p>
<pre name="code" class="javascript">
package {
	import flash.display.MovieClip;

	public class Game extends MovieClip {

		private var startButton:JitteryButton;

		// CLASS CONSTRUCTOR
		public function Game() {
			// create the jittery button from the simple button on the stage
			startButton = new JitteryButton(button1);

			// add the new button to the stage
			addChild(startButton);
		}

	}

}
</pre>
<p>This code creates a new instance of our custom JitteryButton class and passes it the button on the stage (&#8216;button1&#8242;).</p>
<p>Of course your document class will end up looking much different since it will have the code for your game in it. Here we&#8217;re just concerned with the code for our button.</p>
<p>Back inside your Flash file set the document class to &#8216;Game&#8217;. Remember, you don&#8217;t include the file extension here.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/4.jpg" alt="set the document class" /></div>
<h2>Step 7: Test Again</h2>
<p>If you save and test your movie again at this point you should see exactly the same thing as when we tested in Step 4. The only difference is that now our code is set up to be able to add our custom behavior.</p>
<h2>Step 8: Create the Displacement Map Image </h2>
<p>We&#8217;ll now create the image of the static pattern that we&#8217;ll use to distort our button graphic.</p>
<p>Open Photoshop and create a new image filled with neutral grey (#808080). The image should be slightly wider than your button and about 3 or 4 times as high. My button is 277&#215;56, and my image is 310&#215;220.</p>
<p>We&#8217;re starting with a neutral grey because that won&#8217;t effect our image.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/5.jpg" alt="create a new image" /></div>
<h2>Step 9: Add Noise</h2>
<p>We&#8217;ll now add a little bit of noise to our image. This won&#8217;t be very noticeable in our static effect, but it gives it a bit of extra shimmer. You can skip this step if you like.
</p>
<p>
Duplicate the background layer and name the new layer &#8216;Noise&#8217;. You should now have 2 layers filled with neutral grey. Select the new Noise layer and choose Filter > Noise > Add Noise. Set <em>Amount</em> to 120% and <em>Distribution</em> to Uniform. Check <em>Monochromatic.</em></p>
<p>Hit OK.</p>
<p>Set the &#8216;Noise&#8217; layer to 10% opacity.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/6.jpg" alt="add noise to the Noise layer" /></div>
<h2>Step 10: Add Lines</h2>
<p>Create a new layer called &#8216;Lines&#8217;. Now use a 1px pencil brush to add some horizontal black and grey lines to the image.</p>
<p>Remember how these lines will effect our image: anything darker than neutral will shift our image in one direction and anything lighter will shift it in the other.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/7.jpg" alt="draw horizontal lines" /></div>
<h2>Step 11: Save the Displacement Map Image</h2>
<p>Choose File > Save for Web &amp; Devices and save your image as an 8 color gif named &#8217;staticMap.gif&#8217;.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/8.jpg" alt="save for web" /></div>
<h2>Step 12: </h2>
<p>Back in Flash, import the &#8217;staticMap.gif&#8217; to your library (File > Import > Import to Library&#8230;). Open the linkage properties, check <em>Export for ActionScript</em>, and set the Class name to &#8216;StaticMap&#8217;.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/9.jpg" alt="import the image" /></div>
<p>We can now reference this image in our code by using the StaticMap class name.</p>
<h2>Step 13: Create the Displacement Map Filter</h2>
<p>Add this function to your JitteryButton class:</p>
<pre name="code" class="javascript">
// create the displacement map filter
private function createDMFilter():DisplacementMapFilter {

	var mapBitmap:BitmapData = new StaticMap(0,0); // use the bitmap data from our StaticMap image
	var mapPoint:Point       = new Point(0, 0);  // position of the StaticMap image in relation to our button
	var channels:uint        = BitmapDataChannel.RED; // which color to use for displacement
	var componentX:uint      = channels;
	var componentY:uint      = channels;
	var scaleX:Number        = 5; // the amount of horizontal shift
	var scaleY:Number        = 1; // the amount of vertical shift
	var mode:String          = DisplacementMapFilterMode.COLOR;
	var color:uint           = 0;
	var alpha:Number         = 0;

	return new DisplacementMapFilter(
					mapBitmap,
					mapPoint,
					componentX,
					componentY,
					scaleX,
					scaleY,
					mode,
					color,
					alpha	);

}
</pre>
<p>This function simply creates the Displacement Map Filter using the BitmapData from our StaticMap image. This doesn&#8217;t need to be in it&#8217;s own function, I&#8217;m just doing it for clarity.</p>
<p>In order for it to work we&#8217;ll need to import these classes at the top of our JitteryButton class:</p>
<pre name="code" class="javascript">
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.filters.DisplacementMapFilter;
import flash.filters.DisplacementMapFilterMode;
import flash.geom.Point;
</pre>
<p>(You can learn more about the DisplacementMapFilter class in the <a target="_blank" href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/filters/DisplacementMapFilter.html">AS3 documentation</a>)</p>
<h2>Step 14: Apply the Filter</h2>
<p>We&#8217;ll now create a variable to hold the filter. We apply it to the button by setting the button&#8217;s &#8216;filters&#8217; property to an array that contains our filter.</p>
<p>Here&#8217;s the JitteryButton class so far (lines 18 and 25 are new):</p>
<pre name="code" class="javascript">
package {

	import flash.display.Sprite;
	import flash.display.SimpleButton;
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.filters.DisplacementMapFilter;
	import flash.filters.DisplacementMapFilterMode;
	import flash.geom.Point;

	import caurina.transitions.Tweener;

	public class JitteryButton extends Sprite{

		private var myButton:SimpleButton;

		//create a variable to hold the displacement map filter
		private var dmFilter:DisplacementMapFilter = createDMFilter();

		// CLASS CONSTRUCTOR
		public function JitteryButton(button:SimpleButton) {
			myButton = button;

			// apply the filter to the button
			myButton.filters = new Array(dmFilter);
		}

		// create the displacement map filter
		private function createDMFilter():DisplacementMapFilter {

			var mapBitmap:BitmapData = new StaticMap(0,0); // use the bitmap data from our StaticMap image
			var mapPoint:Point       = new Point(0, 0);  // this is the position of the StaticMap image in relation to our button
			var channels:uint        = BitmapDataChannel.RED; // which color to use for displacement
			var componentX:uint      = channels;
			var componentY:uint      = channels;
			var scaleX:Number        = 5; // the amount of horizontal shift
			var scaleY:Number        = 1; // the amount of vertical shift
			var mode:String          = DisplacementMapFilterMode.COLOR;
			var color:uint           = 0;
			var alpha:Number         = 0;

			return new DisplacementMapFilter(
							mapBitmap,
							mapPoint,
							componentX,
							componentY,
							scaleX,
							scaleY,
							mode,
							color,
							alpha	);

		}

	}
}
</pre>
<h2>Step 15: Test Again</h2>
<p>If we save and test the file now we can see the displacement map filter being applied to our button:</p>
<div class="tutorial_image">
<object width="500" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone2.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone2.swf" /></object>
</div>
<p>You can see how the horizontal lines we drew in the StaticMap are shifting the pixels in our button left and right. The amount of the shift is dependent on the darkness of the lines in the image and the scaleX setting in our Displacement Map Filter.</p>
<p>Unfortunately, the static isn&#8217;t animating so it looks pretty lame. Let&#8217;s fix that now&#8230;</p>
<h2>Step 16: Add the randRange Function</h2>
<p>This is a simple function that returns a random integer within a specified range:</p>
<pre name="code" class="javascript">
	// returns a random number between the specified range (inclusive)
	private function randRange(min:int, max:int):int {
	    var randomNum:int = Math.floor(Math.random() * (max - min + 1)) + min;
	    return randomNum;
	}
</pre>
<p>I find it makes it a little easier to generate random values. We&#8217;ll be randomizing a few different values for our static effect so it will come in handy.</p>
<p>Add it to your JitteryButton class.</p>
<h2>Step 17: Animate the Displacement Map Filter</h2>
<p>There are a couple of ways we can animate the static effect. The first will be to alter the amount of horizontal shift applied to our button. This is done through the scaleX property of the DisplacementMapFilter.</p>
<p>We can also animate the position of the StaticMap image in relation to our button. This will ensure that the same areas of the button aren&#8217;t always getting shifted.</p>
<p>To animate the effect we&#8217;ll add a function called &#8216;displayStatic&#8217; that gets called every frame to update these two properties of the filter. Add this function to your JitteryButton class:</p>
<pre name="code" class="javascript">
// called on ENTER_FRAME
private function displayStatic(e:Event):void {
	dmFilter.scaleX = randRange(fuzzMin, fuzzMax);
	dmFilter.mapPoint = new Point(0, randRange(0, -160));
	myButton.filters = new Array(dmFilter);
}
</pre>
<p>The first line of this function randomizes the amount of horizontal shifting to a value between the variables fuzzMin and fuzzMax. Add these two variables to your JitteryButton class:</p>
<pre name="code" class="javascript">
	private var fuzzMin:int = 0;
	private var fuzzMax:int = 2;
</pre>
<p>The second line of the displayStatic function randomizes the Y position of the StaticMap in relation to our button. We already told the filter to use our StaticMap image so we just need to update the position.</p>
<p>The third line just re-applies the filter to our button.</p>
<p>The last thing we need to do to get this animating is to add the ENTER_FRAME event listener. Add this line to the JitteryButton constructor function:</p>
<pre name="code" class="javascript">
// start displaying the static effect
addEventListener(Event.ENTER_FRAME, displayStatic);
</pre>
<p>And don&#8217;t forget to import the Event class at the top of the JitteryButton file:</p>
<pre name="code" class="javascript">
import flash.events.Event;
</pre>
<h2>Step 18: Test Again</h2>
<p>If you save and test the movie now you&#8217;ll see the effect is making our button shimmer and jump:</p>
<div class="tutorial_image">
<object width="500" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone3.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/milestone3.swf" /></object>
</div>
<p>That&#8217;s pretty cool, but we want the effect to react to the mouse as well. Onward&#8230;</p>
<h2>Step 19: Adjust the Intensity of the Effect</h2>
<p>We&#8217;ll now add two functions to adjust the intensity of the jitter effect. We&#8217;ll call the effect we currently have Low intensity so we&#8217;ll add a setting for Medium and High intensity. Add these functions to your JitteryButton class:</p>
<pre name="code" class="javascript">
// increase the intensity of the static to MEDIUM
private function setStaticMedium(e:MouseEvent = null):void {
	fuzzMin = 2;
	fuzzMax = 6;
	staticLength = randRange(8, 12);
}

// increase the intensity of the static to HIGH
private function setStaticHigh(e:MouseEvent = null):void {
	fuzzMin = 12;
	fuzzMax = 25;
	staticLength = 12;
}
</pre>
<p>You can see that we&#8217;re adjusting the intensity by setting the values of the fuzzMin and fuzzMax variables. This way our displayStatic function will use these new values when it sets the horizontal shift of the filter.</p>
<p>We also added a variable called staticLength. We&#8217;ll use this to set how long the more intense effect should last (the number of frames) before returning to low intensity. Add this variable to your JitteryButton class and modify your displayStatic function like so:</p>
<pre name="code" class="javascript">
private var staticLength:int;

// called on ENTER_FRAME
private function displayStatic(e:Event):void {
	dmFilter.scaleX = randRange(fuzzMin, fuzzMax);
	dmFilter.mapPoint = new Point(0, randRange(0, -160));
	myButton.filters = new Array(dmFilter);

	staticLength--;

	if(staticLength <= 0){
		fuzzMin = 0;
		fuzzMax = 2;
	}
}
</pre>
<p>This new code decrements the staticLength variable and resets fuzzMin and fuzzMax to the low intensity values once the value of staticLength reaches zero.</p>
<h2>Step 20: Set up the Button Rollover Handlers</h2>
<p>To make our button react to the mouse we need to add two mouse event listeners and an event handler function for each.</p>
<p>Add the mouse listeners in the constructor function of your JitteryButton class:</p>
<pre name="code" class="javascript">
// add the rollover event listeners to the button
myButton.addEventListener(MouseEvent.ROLL_OVER, onButtonRollOver);
myButton.addEventListener(MouseEvent.ROLL_OUT, onButtonRollOut);
</pre>
<p>Now create the two event handlers that are referenced in those two new lines. These also go in the JitteryButton class:</p>
<pre name="code" class="javascript">
// called on button ROLL_OVER
private function onButtonRollOver(e:MouseEvent):void {
	setStaticHigh();
}

// called on button ROLL_OUT
private function onButtonRollOut(e:MouseEvent):void {
	setStaticMedium();
}
</pre>
<p>To make this all work we'll have to import the MouseEvent class at the top of our JitteryButton file:</p>
<pre name="code" class="javascript">
import flash.events.MouseEvent;
</pre>
<p>Now when our button detects a ROLL_OVER event it will call the event handler which in turn calls our setStaticHigh function. This function increases the values of fuzzMin and fuzzMax (used for setting the horizontal shift) for the duration specified by the staticLength variable.</p>
<h2>Step 21: Add the Scale Effect</h2>
<p>We could stop here. Our effect is animating nicely and reacts to the mouse rollovers. I still feel like something is missing here though. Let's add a little scaling effect.</p>
<p>You'll need to <a href="http://tweener.googlecode.com/files/tweener_1_33_74_as3.zip">download the Tweener Library</a> for this step if you don't already have it. Place the 'caurina' folder in your project directory and import the Tweener classes at the top of your JitteryButton file:</p>
<pre name="code" class="javascript">
import caurina.transitions.Tweener;
</pre>
<p>Tweener allows us to add some nice scaling effects with only a couple lines of code. We can add one line to each of our rollover event handlers:</p>
<pre name="code" class="javascript">
// called on button ROLL_OVER
private function onButtonRollOver(e:MouseEvent):void {
	Tweener.addTween(myButton, {scaleX: 1.1, time: .5, transition: "easeOutElastic"});
	setStaticHigh();
}

// called on button ROLL_OOUT
private function onButtonRollOut(e:MouseEvent):void {
	Tweener.addTween(myButton, {scaleX: 1, time: .5, transition: "easeOutElastic"});
	setStaticMedium();
}
</pre>
<p>Here we're adding an animation to the rollover handler that scales the button's scaleX property to 110% over .5 seconds. We're using an elastic transition type to give it that bouncy feel. In the rollout handler we're doing the same thing in reverse, scaling it back to 100%.</p>
<p>You can learn more about how to use Tweener in the <a target="_blank" href="http://hosted.zeh.com.br/tweener/docs/en-us/">Tweener documentation</a>.</p>
<h2>Step 22: Add Sound</h2>
<p>The last thing we need to do make this effect complete is to add some sound. I made my sound effect in Garage Band. You can make your own or try to find one online.</p>
<p>Once you have one you like, import it into your library and set the linkage to export as 'StaticSound'.</p>
<p>To add it to our JitteryButton we first need to import the Sound class:</p>
<pre name="code" class="javascript">
import flash.media.Sound;
</pre>
<p>Then we'll initialize it (add this line just before the constructor function):</p>
<pre name="code" class="javascript">
private var staticSound:Sound = new StaticSound();
</pre>
<p>Inside the rollover handler we'll tell the sound to play:</p>
<pre name="code" class="javascript">
// called on button ROLL_OVER
private function onButtonRollOver(e:MouseEvent):void {
	Tweener.addTween(myButton, {scaleX: 1.1, time: .5, transition: "easeOutElastic"});
	setStaticHigh();
	staticSound.play();
}
</pre>
<p>Now we're good to go. Test your movie and everything should be working. If your button or sound isn't working right check the source files to see my completed JitteryButton class.</p>
<h2>Step 23: Add More Buttons</h2>
<p>The cool thing about building this effect as a separate class that wraps our button is that we can easily reuse it on other buttons.</p>
<p>If you want to add more buttons to your game menu just create a new button and add it to the stage. Give it the instance name 'button2'. Then inside your document class (the 'Game.as' file) create a new JitteryButton and pass it the new button. Here's how that might look:</p>
<pre name="code" class="javascript">
package {
	import flash.display.MovieClip;

	public class Game extends MovieClip {

		private var startButton:JitteryButton;
		private var menuButton:JitteryButton;

		// CLASS CONSTRUCTOR
		public function Game() {
			// create the jittery buttons from the simple buttons on the stage
			startButton = new JitteryButton(button1);
			addChild(startButton);

			// adding a new button is easy!
			menuButton = new JitteryButton(button2);
			addChild(menuButton);
		}

	}

}
</pre>
<h2>Conclusion</h2>
<p>You will almost certainly need to change this code a bit to get it to fit into the structure of your game. Hopefully this tutorial will give you a good starting point though.</p>
<p>If you want to change the look of this effect you can try using different types of images for your StaticMap graphic, and adjusting the values for fuzzMin and fuzzMax.</p>
<p>This is my first tutorial so let me know if there's anything I can do better next time. Thanks for reading!</p>
<div class="tutorial_image">
<object width="550" height="300" data="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/Final.swf" type="application/x-shockwave-flash"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/045_displacementMapButton/Tutorial/Final.swf" /></object>
</div>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/create-a-static-distortion-effect-using-the-displacement-map-filter/feed/</wfw:commentRss>
		<slash:comments>58</slash:comments>
		</item>
		<item>
		<title>Creating a Four-State Button With the Flash Timeline and ActionScript 3.0</title>
		<link>http://active.tutsplus.com/tutorials/effects/creating-a-four-state-button-with-the-flash-timeline-and-actionscript-3-0/</link>
		<comments>http://active.tutsplus.com/tutorials/effects/creating-a-four-state-button-with-the-flash-timeline-and-actionscript-3-0/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 12:00:20 +0000</pubDate>
		<dc:creator>Gary Horsman</dc:creator>
				<category><![CDATA[Effects]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2622</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/preview.jpg" alt="Creating a Four-State Button With the Flash Timeline and ActionScript 3.0">]]></description>
			<content:encoded><![CDATA[<p>This tutorial came about after looking online for help with the very same topic. A lot of people seem to be asking the same question, but it was hard to find a neatly packaged set of instructions to follow.</p>
<p>So, like any decent netizen, I cobbled together this article, gaining inspiration from a couple of other blogs and using experience from some trial and error on my own. And now I offer it to you, hoping this will end your own search.</p>
<p><span id="more-2622"></span>  </p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/src.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/preview.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<p>This tutorial uses Flash CS4 in combination with ActionScript 3.0, but you can apply these principles in Flash CS3. It presumes you already have a pretty good handle on creating animations in the timeline and a fair understanding of how to apply ActionScript to the timeline.</p>
<p>The aim is to have a navigation button in the form of a tab, tucked away to the side, for stepping backwards through an image presentation. I want it to slide open, change color and display its label. When the user clicks on it, it will navigate back one slide. If the user mouses out before clicking on it, it will slide back to its original position and color.</p>
<p><em>Note: remember to save often to avoid starting from scratch should something go wrong.</em></p>
<h2>Limits of the Button Symbol</h2>
<p>Flash gives you the ability to create a button symbol, but it&#8217;s limited to three states: <em>Up, Over</em> and <em>Down</em>. There is also <em>Hit</em> which defines the interactive area around the button. This is fine for most uses of a simple button. In fact, this button symbol is actually a member of the <em>SimpleButton</em> class. But what if you want to change the appearance of the button or animate it when the user mouses over and then mouses away without clicking? In that case, you will need a fourth state called <em>Out</em>.</p>
<p>The built-in button symbol sadly doesn&#8217;t have an out state.</p>
<p>Here&#8217;s the takeaway: any symbol, like a graphic symbol or a movie clip symbol, can become a button. You just need to apply the proper ActionScript. In this tutorial, a movie clip will be turned into a button with four states.</p>
<h2>Step 1: Storyboard or Sketch the Button</h2>
<p>It will make your life a lot easier if you already have a clear visual idea of how your button will behave in each of the four states. Sketch it out on paper or use Illustrator or Photoshop to prototype the visual elements which can in turn be imported into Flash. This is a bit of work up front, but it&#8217;s a lot better than working blind and having to go back and fix something because the concept wasn&#8217;t thought through logically.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/1.jpg" alt="Step 1" name="imgStep1" width="600" height="301" id="imgStep1" />
</div>
<h2>Step 2: Set Up the Document</h2>
<p>Create a new document and choose <em>Flash File (ActionScript 3.0)</em>. Set up the stage with the proper size and background color.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/2.jpg" alt="Step 2" name="imgStep2" width="600" height="429" id="imgStep2" />
</div>
<h2>Step 3: Create an Empty Movie Clip Symbol</h2>
<p>Instead of creating a button symbol, we&#8217;ll create a new movie clip symbol. Press Control-F8 (Command-F8 on a Mac) or choose Insert &gt; New Symbol from the menu. We&#8217;ll call it &#8220;four state button&#8221;.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/3.jpg" alt="Step 3" name="imgStep3" width="600" height="194" id="imgStep3" />
</div>
<h2>Step 4: Add an Actions Layer</h2>
<p>In the &#8220;four state button&#8221; movie clip, add a new layer and call it &#8220;actions&#8221;.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/4.jpg" alt="Step 4" name="imgStep4" width="600" height="244" id="imgStep4" />
</div>
<h2>Step 5: Add Labels for the Four States</h2>
<p>Create another layer and call it &#8220;labels&#8221;. Insert four blank keyframes at roughly equal intervals just enough so that you can leave enough room to read each label. Here I&#8217;ve put them at 20 frame intervals. Give label names of <em>up, over, down</em> and <em>out</em> in the Properties panel. These will be your button states.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/5.jpg" alt="Step 5" name="imgStep5" width="600" height="244" id="imgStep5" />
</div>
<h2>Step 6: Create Action Keyframes</h2>
<p>Add keyframes in the actions layer which correspond to the four states in the labels layer.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/6.jpg" alt="Step 6" name="imgStep6" width="600" height="244" id="imgStep6" />
</div>
<h2>Step 7: Add Stop Actions</h2>
<p>For each blank keyframe in the actions layer, add <em>this.stop()</em>; in the ActionScript Editor. This will make sure that the movie clip doesn&#8217;t play through to other button states.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/7.jpg" alt="Step 7" name="imgStep7" width="600" height="253" id="imgStep7" />
</div>
<h2>Step 8: The Up State</h2>
<p>Create a new movie clip symbol by pressing Control-F8 (Command-F8 on a Mac) or choose Insert &gt; New Symbol from the menu and call it &#8220;up animation&#8221;.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/8.jpg" alt="Step 8" name="imgStep8" width="600" height="244" id="imgStep8" />
</div>
<h2>Step 9: Up State Graphic</h2>
<p>For the button, draw a green box in one layer and add a white arrow in a layer above. Make sure it&#8217;s registered in the top left corner. As this is static, there&#8217;s no need for a series of frames for animation, but you always have the flexibility should you decide to animate it, such as a box that fades up into view.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/9.jpg" alt="Step 9" name="imgStep9" width="600" height="322" id="imgStep9" />
</div>
<h2>Step 10: Add a Stop Action</h2>
<p>Create a new layer and call it &#8220;actions&#8221;. Make sure it&#8217;s at the top. Select the blank keyframe and add <em>this.stop();</em> to the ActionScript Editor. It&#8217;s not completely necessary in this case since it&#8217;s just a static image, but it&#8217;s good practice to keep each state from looping.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/10.jpg" alt="Step 10" name="imgStep10" width="600" height="390" id="imgStep10" />
</div>
<h2>Step 11: Define the Hit Area</h2>
<p>The one thing missing from the button symbol editing mode that you don&#8217;t have with movie clips is a special frame reserved for the hit area. This would define the boundaries where mouse events occur like clicks and hovers. Create a new layer and call it &#8220;hit area&#8221;.</p>
<p>Draw a shape on the layer and set its alpha value to 0 in the Properties panel, making it invisible. This hit area will be as large as the button when it&#8217;s fully extended. <em>Note: If you have an animated sequence, make sure the hit area frames span the entire length of the animation.</em></p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/11.jpg" alt="Step 11" name="imgStep11" width="600" height="530" id="imgStep11" />
</div>
<h2>Step 12: Instantiate the up state movie clip</h2>
<p>Create a new layer in the <em>four state button</em> movie clip symbol called <em>button   states.</em> Drag an instance of the <em>up animation</em> symbol from the   Library panel and into the <em>four state button</em> movie clip symbol editing   area in the <em>button states</em> layer. Make sure its X and Y coordinates   are set to 0. Insert a frame at frame 20.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/12.jpg" alt="Step 12" name="imgStep12" width="600" height="330" id="imgStep12" />
</div>
<h2>Step 13: The Over State</h2>
<p>Press Control-F8 (Command-F8 on a Mac) or choose Insert &gt; New Symbol from the menu and choose Movie Clip. We&#8217;ll call it &#8220;over animation&#8221;.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/13.jpg" alt="Step 13" name="imgStep13" width="600" height="223" id="imgStep13" />
</div>
<h2>Step 14: Shape Tween Animation</h2>
<p>Return to the &#8220;up animation&#8221; movie clip, click on the green button and copy it. Return to the &#8220;over animation&#8221; movie clip and add a new layer called &#8220;button morph&#8221;. Right-click to paste the green button in place in the blank keyframe.</p>
<p>Create another blank keyframe at frame 20 and right-click to paste in place again. With this shape, increase its width and change its color to orange. It should be the same size as the hit area created in Step 10. Select the entire range of frames and right-click to create a shape tween.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/14.jpg" alt="Step 14" name="imgStep14" width="600" height="425" id="imgStep14" />
</div>
<h2>Step 15: Fade up the Label</h2>
<p>To add a button label, create a new layer called &#8220;text appear&#8221; and use the type tool to create a static text object, in this case, PREVIOUS in a blank keyframe.</p>
<p>Right-click to insert a frame at frame 20. Select a frame in the layer and right-click to create a motion tween. I want the label to fade up starting in the middle of the animation, so I&#8217;ll go to the motion editor and create keyframes in the middle and at the end, making three keyframes. The first keyframe will add a color effect with an alpha of 0% and the last two will have an alpha of 100%.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/15.jpg" alt="Step 15" name="imgStep15" width="600" height="456" id="imgStep15" />
</div>
<h2>Step 16: Define the Hit Area</h2>
<p>Add a new layer called &#8220;hit area&#8221;. You can select the longer orange shape from the end of the shape tween, copy it and paste it in place into a blank keyframe on the &#8220;hit area&#8221; layer. Select it and give it an alpha value of 0% in the Properties panel. Insert a frame at frame 20 to make the hit area span the entire animation.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/16.jpg" alt="Step 16" name="imgStep16" width="600" height="511" id="imgStep16" />
</div>
<h2>Step 17: Add a Stop Action</h2>
<p>Add a new layer at the top and call it &#8220;actions&#8221;. Add a blank keyframe at frame 20 and add a <em>this.stop();</em> action in the actions panel. This will prevent the animation from looping.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/17.jpg" alt="Step 17" name="imgStep17" width="600" height="507" id="imgStep17" />
</div>
<h2>Step 18: Instantiate the Over State</h2>
<p>Return to the &#8220;four state button&#8221; movie clip. Insert a blank keyframe in frame 21 on the button states layer and drag an instance of the <em>over animation</em> movie clip from the Library. Make sure its coordinates are set to 0. Insert a frame at frame 40.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/18.jpg" alt="Step 18" name="imgStep18" width="600" height="302" id="imgStep18" />
</div>
<h2>Step 19: The Down State</h2>
<p>Create a new graphic symbol by pressing Control-F8 (Command-F8 on a Mac) or choose Insert &gt; New Symbol from the menu and call it &#8220;down graphic&#8221;. There is no explicit animation required since it will only be displayed instantaneously when the mouse button is being clicked.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/19.jpg" alt="Step 19" name="imgStep19" width="600" height="205" id="imgStep19" />
</div>
<h2>Step 20: Down State Graphic</h2>
<p>For this state, all that is required, optionally, is to change the color of the fully extended button. You can copy and paste in place the orange box as well as the PREVIOUS label from the &#8220;over animation&#8221; movie clip in their respective layers. Change the orange box to red. Only one frame is required, there is no need for a hit area as the button covers the full area. And, since it&#8217;s a graphic symbol, no <em>stop();</em> action is needed.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/20.jpg" alt="Step 20" name="imgStep20" width="600" height="332" id="imgStep20" />
</div>
<h2>Step 21: Instantiate the Down State Graphic</h2>
<p>Return to the &#8220;four state button&#8221; movie clip. Insert a blank keyframe in frame 41 on the &#8220;button states&#8221; layer and drag an instance of the &#8220;down graphic&#8221; symbol from the Library. Make sure its coordinates are set to 0. Insert a frame at frame 60.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/21.jpg" alt="Step 21" name="imgStep21" width="600" height="322" id="imgStep21" />
</div>
<h2>Step 22: The Out State</h2>
<p>Press Control-F8 (Command-F8 on a Mac) or choose Insert &gt; New Symbol from the menu and choose Movie Clip. We&#8217;ll call it &#8220;out animation&#8221;.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/22.jpg" alt="Step 22" name="imgStep22" width="600" height="205" id="imgStep22" />
</div>
<h2>Step 23: Reverse the Shape Tween</h2>
<p>The out state will essentially be a reversed version of the over state. Return to the &#8220;over animation&#8221; movie clip and copy the shape tween frames, then come back to the &#8220;out animation&#8221;, create a layer called &#8220;button morph&#8221; and paste the frames into the blank keyframe. Then select all the frames in that layer and choose  Modify &gt; Timeline &gt; Reverse Frames  from the menu.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/23.jpg" alt="Step 23" name="imgStep23" width="600" height="355" id="imgStep23" />
</div>
<h2>Step 24: Fade Out the Label</h2>
<p>Return to the &#8220;over animation&#8221; movie clip and copy the PREVIOUS text object, then go back to the &#8220;out animation&#8221;, create a new layer called &#8220;text disappear&#8221; and paste in place.</p>
<p>Insert a frame at frame 20 then select the range of frames and create a motion tween. You will do the reverse of the motion tween created in Step 15 and create keyframes in the middle and at the end in the Motion Editor, but the first and middle keyframes will have an alpha of 100% while the last keyframe will have an alpha of 0%.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/24.jpg" alt="Step 24" name="imgStep24" width="600" height="465" id="imgStep24" />
</div>
<h2>Step 25: Add the Arrow</h2>
<p>To return the appearance of the button to its original up state, add a layer called &#8220;arrow&#8221; and place a keyframe in frame 20, leaving the first 19 frames blank. Copy the arrow from the &#8220;up animation&#8221; and paste in place back in the &#8220;out animation&#8221; in that last keyframe.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/25.jpg" alt="Step 25" name="imgStep25" width="600" height="399" id="imgStep25" />
</div>
<h2>Step 26: Define the Hit Area</h2>
<p>Again, we need to create a new layer called &#8220;hit area&#8221; and place a box large enough to cover the full size of the extended button. Give it an alpha of 0 to make it invisible.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/26.jpg" width="600" height="586" alt="Step 26" />
</div>
<h2>Step 27: Add a Stop Action</h2>
<p>Again, to keep the &#8220;out animation&#8221; from looping, we need to add a layer called &#8220;actions&#8221;, put a blank keyframe in frame 20 and add a <em>this.stop();</em> action in the Actions panel.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/27.jpg" alt="Step 27" name="imgStep27" width="600" height="422" id="imgStep27" />
</div>
<h2>Step 28: Instantiate the Out State</h2>
<p>Return to the &#8220;four state button&#8221; movie clip. Insert a blank keyframe in frame 61 on the &#8220;button states&#8221; layer and drag an instance of the &#8220;out animation&#8221; symbol from the Library. Make sure its coordinates are set to 0. Insert a frame at frame 80.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/28.jpg" alt="Step 28" name="imgStep28" width="600" height="511" id="imgStep28" />
</div>
<h2>Step 29: Add Event Listeners</h2>
<p>Now comes the ActionScript to make it all work. To detect mouse events like clicks and hovers, we need to add event listeners.</p>
<p>Click on the first keyframe of the actions layer in the &#8220;four state button&#8221; movie clip where we first added a stop action and open the Actions panel. We will add event listeners as shown below to detect a mouse ROLL_OVER, a MOUSE_UP (when the mouse button is released) and a MOUSE_DOWN (when the mouse button is pressed).</p>
<p>We use the ROLL_OVER event instead of the MOUSE_OVER event because of how it treats the child elements of the movie clip in context with the parent movie clip which is more suitable for this setup. We add false, 0, true to the parameters as a good practice to mark these listeners for garbage collection for when they&#8217;re no longer needed.</p>
<pre class="javascript" name="code">
this.addEventListener(MouseEvent.ROLL_OVER, onMouseRollover, false, 0, true);

this.addEventListener(MouseEvent.MOUSE_UP, onMouseClick, false, 0, true);

this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownButton, false, 0, true);
</pre>
<h2>Step 30: Toggling Functions</h2>
<p>For each event listener, a function will be called. Each function essentially advances the timeline to the appropriate state within the four state button movie clip and plays that section by referring to the label name.</p>
<p>You&#8217;ll notice there&#8217;s no event listener created for a MOUSE_OUT event. Instead of creating a standalone event listener, we will simply use the ROLL_OVER event to call up a function which will in turn remove its own event listener and add a new event listener for a ROLL_OUT event. In this setup, a ROLL_OUT event will work better than a MOUSE_OUT event.</p>
<p>The same goes for the opposite, where a ROLL_OUT event removes its own listener and reinstates the event listener for a ROLL_OVER event. By toggling these rollovers and rollouts, we keep the code clean and free from potential conflicts.</p>
<pre class="javascript" name="code">
function onMouseRollover(e:MouseEvent):void {       e.target.gotoAndPlay("over");
		this.removeEventListener(MouseEvent.ROLL_OVER, onMouseRollover);
		this.addEventListener(MouseEvent.ROLL_OUT, onMouseRollout, false, 0, true);
	}

function onMouseRollout(e:MouseEvent):void {
		e.target.gotoAndPlay("out");
		this.removeEventListener(MouseEvent.ROLL_OUT, onMouseRollout);
		this.addEventListener(MouseEvent.ROLL_OVER, onMouseRollover, false, 0, true);
	}   </pre>
<h2>Step 31: onMouseDownButton Function</h2>
<p>To play the down state, create a function that corresponds to the MOUSE_DOWN event set up by the event listener.</p>
<pre class="javascript" name="code">
function onMouseDownButton(e:MouseEvent):void {
e.target.gotoAndPlay(&quot;down&quot;);
}</pre>
<h2>Step 32: onMouseClick Function</h2>
<p>Finally, we need to actually tell the button what to do when it&#8217;s clicked. Add a function that corresponds to the MOUSE_UP event. A MOUSE_UP event is essentially the same thing as the last part of a CLICK event (down, then up).</p>
<p>For test purposes, I created a web link in a URL variable (in this case, to Adobe&#8217;s website) then added the navigateToURL() method to the function so that I could verify that it&#8217;s working. However, you can substitute this method with a call to navigate to another frame label, number or scene using <em>gotoAndPlay</em> or any other method you prefer.</p>
<pre class="javascript" name="code">
var linkToAdobe:URLRequest = new URLRequest("http://www.adobe.com");

function onMouseClick(e:MouseEvent):void {       e.target.gotoAndPlay("up");
		navigateToURL(linkToAdobe); // you can substitute this with any other method or function
	}</pre>
<h2>Step 33: Instantiate the Button</h2>
<p>The four state button is now ready to be used. Return to the main timeline and drag the four state button movie clip symbol to the stage on its own layer. A substitute background is added on another layer to better see the effect in context with other elements on the stage.</p>
<div class="tutorial_image">
<img src="http://activetuts.s3.cdn.plus.org/tuts/024_fourStateButton/images/33.jpg" alt="Step 33" name="imgStep33" width="600" height="400" id="imgStep33" />
</div>
<h2>Step 34. Test the Movie</h2>
<p>Make sure the file is saved and press Control-Enter (Command-Enter on a Mac) to test the movie.</p>
<h2>Acknowledgements</h2>
<p>Much thanks goes to Alex at Sanctified Studios for inspiring the original idea to <a href="http://www.sanctifiedstudios.com/portfolio" title="Link to Sanctified Studios" target="_blank">use a movie clip as a button</a> and to Dominic Gelineau of Zedia Flash Blog for showing the <a href="http://www.zedia.net/2008/the-right-way-to-do-rollover-event-in-as3/" title="Link to Zedia Flash Bog" target="_blank">best way to create rollovers and rollouts in ActionScript 3.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/effects/creating-a-four-state-button-with-the-flash-timeline-and-actionscript-3-0/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.780 seconds -->
