<?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>orangeSPLoTCH &#187; Tutorials</title>
	<atom:link href="http://orangesplotch.com/blog/categories/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://orangesplotch.com/blog</link>
	<description>Web developing in the middle of the night.</description>
	<lastBuildDate>Wed, 25 Aug 2010 11:45:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1-alpha</generator>
		<item>
		<title>Flash Tutorial: Eyes Following the Mouse</title>
		<link>http://orangesplotch.com/blog/flash-tutorial-eyes-following-the-mouse/</link>
		<comments>http://orangesplotch.com/blog/flash-tutorial-eyes-following-the-mouse/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 13:59:25 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[eye-roll]]></category>
		<category><![CDATA[eyes]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[motion]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=158</guid>
		<description><![CDATA[Have you ever seen those paintings where the eyes are always looking at you no matter where you stand. Well, sorry, this tutorial won't teach you anything about painting. This simple Flash tutorial goes over how to make a pair of eyes follow the mouse using Actionscript.]]></description>
			<content:encoded><![CDATA[<p class="intro">Have you ever seen those paintings where the eyes are always looking at you no matter where you stand. Well, sorry, this tutorial won&#8217;t teach you anything about painting. This simple Flash tutorial goes over how to make a pair of eyes follow the mouse using Actionscript.</p>
<p><a href="#rollingeyes-source">Jump straight to the source code</a> if you&#8217;d like to skip the details.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="500" height="196" class="align-right bordered">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2009/04/rollingeyes.swf" />
      <param name="wmode" value="transparent" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2009/04/rollingeyes.swf" width="500" height="196" wmode="transparent">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h3>The eye</h3>
<p>First you need to create three <code>Sprites</code> for each eye. The pupil, the eye, and the mask for the pupil. The mask for the pupil needs to be identical in shape to the part of the eye where the pupil shows. In my case, the eye and the mask for the eye are identical circles. To make things easier on yourself, the registration point for both the pupil and the eye should be located at the center of each.</p>
<p>For this tutorial, I&#8217;ll be doing everything in basic Actionscript. However, you are free to use images or <code>MovieClip</code>s for your eyes. In fact I&#8217;d encourage it, as that will look way better than my goofy circle eyes.</p>
<p class="note">I&#8217;m not going to bother pasting my eyeball creation and placement Actionscript here, since it isn&#8217;t important to the tutorial. If you really want to see it, just <a href="#rollingeyes-source">download the source code</a> at the bottom of the article.</a></p>
<p>So now that you have your eye, pupil and mask, place them on the screen wherever you want. Make sure you mask the pupils with the mask object. Otherwise you&#8217;ll have some weird floating pupil effect. Again, I&#8217;m doing all of this in the Actionscript, but you are free to manually place everything on the stage. That&#8217;s actually the easier way to do it, since you can see exactly where they are going. </p>
<h3>It follows me everywhere I go</h3>
<p>Ok, enough talk about making and placing eyeballs on the stage. The real reason you are reading this is to see how to get your eyes to follow the mouse. As I said before, the code is really simple. </p>
<p>First calculate the offset between the mouse position and your eye. In this case I have two eyes, so I created the <code>_focalPoint</code> object to compare against. My <code>_focalPoint</code> is located right between the two eyes. This allows both eyes to move together in uniform instead of getting cross-eyed in the middle. The following code goes in your <code>EnterFrame</code> handler function.</p>
<pre>// calculate mouse offset
var distx:Number = mouseX - _focalPoint.x;
var disty:Number = mouseY - _focalPoint.y;</pre>
<p>Finally we reposition the pupils based on this offset. You will notice that we are scaling down <code>distx</code> and <code>disty</code>. This is so the eyes don&#8217;t move so far that they are no longer visible. I am using a factor of 25. You may need to change this depending on how wide or thin your stage is and where you position the eyes. Experiment a little to get it just right.</p>
<pre>// set the eyes according to the mouse offset
_pupil1.x = _eye1.x + (distx / 25);
_pupil1.y = _eye1.y + (disty / 25);
_pupil2.x = _eye2.x + (distx / 25);
_pupil2.y = _eye2.y + (disty / 25);</pre>
<p>Because we set the registration point of both the eye and the pupil Sprites, we can use the eye <code>.x</code> and <code>.y</code> properties to place the pupil. This makes the code a lot cleaner as you can see.</p>
<p>And there you go. Nice rolling eyes going everywhere your mouse goes. Like I said, it&#8217;s a very easy effect to make once you know how to do it. No complex trig. No fancy classes. Just plain simple Actionscript.</p>
<h3>Eye Following Downloads</h3>
<ul id="rollingeyes-source" class="downloads">
<li><a title="Download the source file used in this tutorial." type="zip" href="http://orangesplotch.com/files/RollingEyes.zip">Rolling Eyes Actionscript 3.0 source file.</a></li>
</ul>
<p>If you have any questions, please let me know either in the comments below or through the <a href="http://orangesplotch.com/contact/">contact form</a>. I&#8217;d love to see what you guys come up with this. So go set your mouse following eyeballs free. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-tutorial-eyes-following-the-mouse/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tutorial: Polar Coordinate Plotting in Actionscript</title>
		<link>http://orangesplotch.com/blog/tutorial-polar-coordinate-plotting-in-actionscript/</link>
		<comments>http://orangesplotch.com/blog/tutorial-polar-coordinate-plotting-in-actionscript/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 14:52:26 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[polar coordinates]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=102</guid>
		<description><![CDATA[If you are trying to generate effects in a circular pattern, like a planet's orbit then polar coordinates are the way to go. Here's a brief discussion on the topic of polar coordinate plotting inFlash to create some very cool rotating effects without a lot of effort.]]></description>
			<content:encoded><![CDATA[<p class="intro">A long, long time ago someone requested that I post a tutorial based on some polar coordinate experiments I was doing. I think it&#8217;s about time to get this post published.<br />As usual, if you are just interested in the code, you can <a href="#polarcoordinate-downloads">skip straight to the source</a>.</p>
<h3>Polar Coordinate Basics</h3>
<p>In Flash, like most other graphics applications, elements are positioned using the Cartesian coordinate system. While you may not be familiar with the name, you are probably familiar with the way it works. Location coordinates are set using x and y positions. &#8220;x&#8221; represents a horizontal offset from the origin <em>(top left corner of the screen)</em>, and &#8220;y&#8221; represents the vertical offset from the origin.</p>
<p>The polar coordinate system also uses two values, r and θ (theta). &#8220;r&#8221; is the radial distance from the origin, and &#8220;θ&#8221; is the angular offset from 0 <em>(a line going straight up from the origin)</em>. The following image shows the differences between the two coordinate systems.</p>
<p><img src="http://orangesplotch.com/blog/wp-content/uploads/2009/03/polar-coordinates.png" alt="Plotting a point using cartesian and polar coordinates." title="Cartesian vs. Polar Coordinates" width="380" height="150" class="bordered" /></p>
<p>That&#8217;s all the explaining of the two coordinate systems that I&#8217;ll waste your time with here. If you&#8217;d like to learn more about them, you can consult Wikipedia.</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Polar_coordinate_system">http://en.wikipedia.org/wiki/Polar_coordinate_system</a></li>
<li><a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system">http://en.wikipedia.org/wiki/Cartesian_coordinate_system</a></li>
<ul>
<p>So why do we care? When positioning things in Flash, it is usually easier to use the default Cartesian (x, y) system. However, for positioning objects that rotate around a fixed point, the Polar Coordinate system is much more efficient.</p>
<p>For example, here are two ways to move an object in a circle around the screen. One uses Cartesian coordinates and one uses Polar coordinates.</p>
<pre>// Cartesian coordinate circle
obj.x = radius * cos(t);
obj.y = radius * sin(t);
t += increment;

// Polar coordinate circle
obj.theta += increment;</pre>
<p>As you can see the code is much simpler in the Polar coordinate example. We didn&#8217;t have to deal with cos or sin, and we only had to change one value of the object (θ) since the radius of the circle doesn&#8217;t change. Are you convinced?</p>
<p>Unfortunately Flash does not directly support Polar coordinate plotting. It&#8217;s an easy problem to get around, though. For my work, I&#8217;ve created an Actionscript class derived from the Sprite class which adds Polar coordinate functionality. I call it PolarSprite. How&#8217;s that for creative! I&#8217;m not going to pretend that I&#8217;m the first person to have done this, or that my class is the most elegant/efficient one out there. But it works great for me.</p>
<h3>How to go Polar</h3>
<p>I&#8217;m not going to go into the details of my PolarSprite class. You can look at the source code if you really want to see how it works. However, I will quickly show you the translation from polar coordinates (r, θ) to Cartesian coordinates (x, y).</p>
<pre>x = offset_x + r * Math.cos( theta );
y = offset_y + r * Math.sin( theta );</pre>
<p>The offsets are used to set the origin of the polar coordinate somewhere away from the top left corner of the screen. Usually, you want the center of the rotation to be in the center of the screen when you have an object orbiting around in a circle.</p>
<h3>Experimenting in Polar</h3>
<p>Now that you know how to translate from the Polar coordinate frame into the Cartesian, the real fun begins. Here is some example AS3 code using the PolarSprite class to make an object move in a simple circle.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="500" height="180">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/07/polarcircle.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/07/polarcircle.swf" width="500" height="180" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<pre>public function PolarCircle(){
  // create and initialize the animation
  inc = 0.1; // how much to rotate each frame
  hero = new PolarSprite();
  hero.SetOrigin(250, 50);
  hero.r = 50; // radius of the circle animation
  hero.addChild(new BigHero()); // BigHero is the flying guy graphic
  hero.addEventListener(Event.ENTER_FRAME, this.Rotate);
  addChild(hero);
}

private function Rotate(event:Event):void {
  // rotate the image in a circle
  hero.theta += inc;
}</pre>
<p>And there you go. Flying, polar-coordinate Flash fun. For all my talking, it really isn&#8217;t that complicated to do. In a later post I&#8217;ll go over ways to get some really cool variations in your animations, but for now, here&#8217;s a little teaser.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_2" width="500" height="180" class="align-right">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2009/04/polarexample1.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2009/04/polarexample1.swf" width="500" height="180" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h3>Polar Source</h3>
<p>Here are the source files for your downloading pleasure. Feel free to use them however you&#8217;d like. And if you really want to make my day, send me a link so I can check out your work. Enjoy!</p>
<ul id="polarcoordinate-downloads" class="downloads">
<li><a title="Download the source files used in this tutorial." type="zip" href="http://orangesplotch.com/files/PolarCoordinateExamples.zip">Polar Coordinate Actionscript 3.0 source files.</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/tutorial-polar-coordinate-plotting-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WordPress Media Plugin Tutorial 1: Custom media tabs</title>
		<link>http://orangesplotch.com/blog/wordpress-media-plugin-tutorial-1-custom-media-tabs/</link>
		<comments>http://orangesplotch.com/blog/wordpress-media-plugin-tutorial-1-custom-media-tabs/#comments</comments>
		<pubDate>Thu, 29 May 2008 15:31:47 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[media]]></category>
		<category><![CDATA[media library]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[series]]></category>
		<category><![CDATA[wordpress 2.5]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=98</guid>
		<description><![CDATA[The first part in the WordPress 2.5 Media API tutorial series. This article discusses how to customize the tabs available in the WordPress media library using hooks made available in the latest WordPress release.]]></description>
			<content:encoded><![CDATA[<p class="intro">This is the first tutorial in a series covering the media hooks available in the WordPress 2.5 API. This article shows how to add a custom media tab to WordPress&#8217;s built in media library. We&#8217;ll be using the WordPress API to do this, so no code hacks are required. All examples are based on<a href="http://wordpress.org/extend/plugins/swfobj/"> the SwfObj plugin</a> I developed. Feel free to <a href="http://wordpress.org/extend/plugins/swfobj/download/">download SwfObj</a> as a reference.</p>
<h3>WordPress hooks</h3>
<p>WordPress has conveniently added hooks to its core code, allowing developers the ability to modify content and add functionality without having to hack WordPress source files.  These include filters and actions. For these tutorials we will be using both the &#8216;<code>add_filter</code>&#8216; and &#8216;<code>add_action</code>&#8216; functions.</p>
<p>If you are unfamiliar with WordPress&#8217;s hooks, I&#8217;d recommend <a href="http://codex.wordpress.org/Plugin_API">reading their API documentation first</a>.</p>
<h3>Creating a media tab</h3>
<p>When viewing media in WordPress&#8217;s media library, there are tabs for images, video, and audio. I am going to add a &#8220;Flash&#8221; tab to the list. You can add whatever media tab you require.</p>
<p><a href="http://orangesplotch.com/blog/wp-content/uploads/2008/05/swfobj_ss1.png"><img class="alignnone size-full wp-image-96" title="A screenshot of the Media Library showing the Flash tab" src="http://orangesplotch.com/blog/wp-content/uploads/2008/05/swfobj_ss1.png" alt="\" width="400" height="171" /></a></p>
<p><strong>Adding file type categories is actually quite easy to do.</strong> To add a tab, you first need to know the MIME type of your category. Flash files (<code>.swf</code> files) use the &#8216;<code>application/x-shockwave-flash</code>&#8216;  MIME type. If you don&#8217;t happen to know the MIME type for your files, upload one using the WordPress media button. Once it is uploaded, WordPress displays its type right under the file name.</p>
<p>The WordPress hook to add a category tab to your library is the &#8216;<code>post_mime_types</code>&#8216; filter. WordPress uses an array called <code>$post_mime_types</code> to store all of the MIME types it lists in the Media Library. To add a new media type, you simply need to add it to this array. The following code adds a &#8220;Flash&#8221; media category that lists all .swf files in the library.</p>
<pre>function modify_post_mime_types($post_mime_types) {
    $post_mime_types['application/x-shockwave-flash'] = array('Flash', 'Manage Flash', 'Flash (%s)');
    return $post_mime_types;
}

add_filter('post_mime_types', 'modify_post_mime_types');</pre>
<p>The array that is stored in the new <code>$post_mime_types</code> entry holds the following values</p>
<ol>
<li>The title of the media type <em>(&#8216;Flash&#8217;)</em>.</li>
<li>The title to display when viewing this category in the Media Library <em>(&#8216;Manage Flash&#8217;)</em>.</li>
<li>And the title to put on the tab in the Media Library <em>(&#8216;Flash (%s)&#8217;)</em>. The <code>%s</code> is replaced by the number of items in this category.</li>
</ol>
<h3>Extras</h3>
<p>WordPress allows you to add both general and specific MIME types. You can add an &#8216;<code>application</code>&#8216; type which will show all objects whose MIME type starts with &#8216;<code>application/</code>&#8216;. To only show a specific file type, use the full MIME type, such as &#8216;<code>application/x-shockwave-flash</code>&#8216;. Make sure if you are declaring something specific, that you use the full MIME type, not just the value after the &#8216;<code>/</code>&#8216;.</p>
<p>Here are a few file types you may be interested in.</p>
<ul>
<li>PNG: <code>image/png</code></li>
<li>PDF: <code>application/pdf</code></li>
<li>ZIP: <code>application/zip</code></li>
</ul>
<p>You can also remove media types from the list if you&#8217;d like. To do this, use the <code>unset</code> function. Here is an example that removes the &#8216;audio&#8217; category from the Media Library.</p>
<pre>function modify_post_mime_types($post_mime_types) {
    unset ($post_mime_types['audio']);
    return $post_mime_types;
}</pre>
<p>And there you have it. Total control over the media types listed in WordPress using the WordPress API. In future posts we&#8217;ll discuss how to customize uploading, editing and embedding media into your posts. Please post any comments or questions you have. </p>
<p class="aside">If anyone has a better name for the &#8220;WordPress 2.5 Media API tutorial series&#8221; please let me know. That&#8217;s a monster to type out.</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/wordpress-media-plugin-tutorial-1-custom-media-tabs/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>WordPress Media API tutorial series</title>
		<link>http://orangesplotch.com/blog/wordpress-media-api-tutorial-series/</link>
		<comments>http://orangesplotch.com/blog/wordpress-media-api-tutorial-series/#comments</comments>
		<pubDate>Wed, 28 May 2008 00:45:14 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[media]]></category>
		<category><![CDATA[media library]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[series]]></category>
		<category><![CDATA[wordpress 2.5]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=99</guid>
		<description><![CDATA[While developing the SwfObj WordPress plugin, I realized there is a large gap in documentation on WordPress media library API. In an attempt to help fill in that gap a little, I am developing a tutorial series based on the API hooks I used to develop SwfObj.]]></description>
			<content:encoded><![CDATA[<p class="intro">Recently I developed the <a href="http://orangesplotch.com/blog/swfobj/">SwfObj WordPress plugin</a>. This required using several newly available WordPress media hooks. Unfortunately, few of these are documented and it took a lot of trial and error to get things working. In the hopes of helping other developers save a few hours, I&#8217;m putting together a series of tutorials based on what I learned.</p>
<h3>Coming Soon to a Feed near you</h3>
<p>The plan is to make these short and simple. Each one will highlight one or two API hooks available in WordPress and how they work. The first in this series will be released later this week. If you are interested, <a href="http://orangesplotch.com/blog/feed/">subscribe to the feed</a> and you&#8217;ll be ready to go. Or just check in later this week</p>
<p>If you have any questions or requests, please let me know.  Feedback will drive the development of future articles. And as always, <a href="http://orangesplotch.com/freelunch">donations are very much appreciated</a>.</p>
<p class="aside">I am also looking for sponsors of this series if anyone is interested. All the articles will be published freely here irregardless of whether I get any funding. It doesn&#8217;t hurt to ask, <em>I hope</em>.<br />If interested, <a href="http://orangesplotch.com/contact/">contact me for terms</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/wordpress-media-api-tutorial-series/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Actionscript Tutorial: Starry Night</title>
		<link>http://orangesplotch.com/blog/actionscript-tutorial-starry-night/</link>
		<comments>http://orangesplotch.com/blog/actionscript-tutorial-starry-night/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 14:11:27 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[actionscript 3.0]]></category>
		<category><![CDATA[night sky]]></category>
		<category><![CDATA[star]]></category>
		<category><![CDATA[twinkle]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=28</guid>
		<description><![CDATA[This is a very basic Actionscript tutorial that will show you how to make a sky full of twinkling stars. Everything for this tutorial will be done in Actionscript, using Actionscript 3.0. If you're interested, jump on in and check it out.]]></description>
			<content:encoded><![CDATA[<p class="intro">This is a very basic Actionscript tutorial that will show you how to make a sky full of twinkling stars. Everything for this tutorial will be done in Actionscript, using Actionscript 3.0. It is targeted at novices, but hopefully pros and newbies alike can get something from it. Make a wish on the first star you see and maybe your dreams will come true.</p>
<h3>The first star I see tonight</h3>
<p>First we need to make our black sky. This is going to be a black rectangle that covers the entire area of the <code>Stage</code>. We&#8217;ll draw this using a Sprite, which is a type of object that can hold graphics, such as black rectangles. Here is how simple it is to make night.</p>
<pre>bg = new Sprite();
bg.graphics.beginFill(0);
bg.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
addChild(bg);</pre>
<p>The last line adds the <code>bg</code> <code>Sprite</code> to the <code>Stage</code>. This is what triggers the Flash player to actually render the object. Until you put this line in, <code>bg</code> is invisible.</p>
<p>Next we are going to need to draw a star. The stars are just tiny circles, so there isn&#8217;t too much to drawing them. Make the star by creating a new <code>Sprite</code>, drawing a white circle in it with a 2 pixel radius, positioning it, then adding it to the <code>Stage</code> so it will be displayed. I&#8217;ve made the positioning random so every time you run it, your star will be in a different place. The following Actionscript is all we need to dynamically draw our star.</p>
<pre>var star:Sprite = new Sprite();
star.graphics.beginFill(0xFFFFFF);
star.graphics.drawCircle(0, 0, 2);
star.x = Math.random() * stage.stageWidth;
star.y = Math.random() * stage.stageHeight;
addChild(star);</pre>
<p class="note">In all of the following examples, you can click on the image to regenerate it.</p>
<p>Here is the resulting dynamically created star.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_3" width="500" height="90">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/lonestar.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/lonestar.swf" width="500" height="90" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h3>The Milky Way</h3>
<p>One star is nice and all, but what we really want is a whole sky full of stars. The Universe has bajillions of stars, but for this tutorial we&#8217;ll just make 100. The nice thing about doing this in Actionscript is that we can make 200 stars just as easily. All you need to do is change one number in the code.</p>
<p>To make lots of stars, we put the star creation in a for loop and run it as many times as we want stars. It may surprise you just how easy it is to make lots of stars now that we know how to make just one. Here&#8217;s the code with just two extra lines.</p>
<pre><strong>for (var i:Number = 0; i&lt;100; ++i) {</strong>
    var star:Sprite = new Sprite();
    star.graphics.beginFill(0xFFFFFF);
    star.graphics.drawCircle(0, 0, 2);
    star.x = Math.random() * stage.stageWidth;
    star.y = Math.random() * stage.stageHeight;
    addChild(star);
<strong>}</strong></pre>
<p>And you&#8217;ve got a starry sky.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_4" width="500" height="90">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/starrynight_samesize.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/starrynight_samesize.swf" width="500" height="90" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>Now they say variety is the spice of life, but all of these stars are exactly the same, just in a different location. What we want to do now is make them all different sizes. I am going to vary mine between a radius of 0.25 and 1.5, but you can feel free to make yours whatever size you want. Changing the size of the stars to be random is again, very easy. We just need to change one line of code.</p>
<pre>for (var i:Number = 0; i&lt;100; ++i) {
    var star:Sprite = new Sprite();
    star.graphics.beginFill(0xFFFFFF);
    star.graphics.drawCircle(0, 0, <strong>((Math.random() * 1.25) + 0.25)</strong>);
    star.x = Math.random() * stage.stageWidth;
    star.y = Math.random() * stage.stageHeight;
    addChild(star);
}</pre>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_5" width="500" height="90">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/starrynight_notwinkle.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/starrynight_notwinkle.swf" width="500" height="90" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h3>Twinkle, twinkle little star</h3>
<p>To make this starry sky even better, you can add a little twinkle effect. I&#8217;ve been playing around with this quite a bit to try and get just the right effect. You want them to flicker, but not too much. It is a sweet spot between not being able to notice the twinkle, to it being way too obvious and annoying.</p>
<p>The effect is by adding an <code>ENTER_FRAME</code> event handler to each star <code>Sprite</code>. The <code>ENTER_FRAME </code>event handler is a function that is called every frame of your movie. To make the stars twinkle I randomly change their their <code>alpha</code> and size very subtly. Also, I keep the value within a certain limit so that the stars don&#8217;t disappear on me. Play around with the effect on your own to find your sweet spot.</p>
<pre>public function Twinkle(event:Event):void {
    // get the current star to tweak
    var _self:Sprite = Sprite(event.currentTarget);

    // change the alpha and size of the star
    _self.alpha += Math.random() * 0.02 - 0.01;
    _self.scaleX = _self.alpha * 0.5 + 0.5;
    _self.scaleY = _self.alpha * 0.5 + 0.5;

    // do some bounds checking
    if (_self.alpha &lt; 0.5) _self.alpha = 0.5;
    if (_self.alpha &gt; 1) _self.alpha = 1;
}</pre>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_6" width="500" height="196">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/constellation.swf" />
      <param name="allowfullscreen" value="true" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/constellation.swf" width="500" height="196" allowfullscreen="true" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h3>To infinity and beyond</h3>
<p>You can use this wherever you want to throw some stars into a scene. If you don&#8217;t want the stars, or the night sky to cover the entire stage, simply change the bounds from the stage.stageWidth and stage.stageHeight to whatever you want them to be. Or put other elements on top of this, like mountains, or a cityscape or whatever you feel like. The possibilities are as numberless as the stars <em>(sorry, that was really pathetic)</em>.</p>
<p>Feel free to download the full source files used to make this. Included is a bonus full screen enabled version.<strong> Now that&#8217;s exciting!</strong></p>
<ul id="starrynight-downloads" class="downloads">
<li><a title="Download the source files used in this tutorial." type="zip" href="http://orangesplotch.com/files/starrynight.zip">Starry Night Actionscript 3.0 source files.</a></li>
</ul>
<p class="aside">And that&#8217;s the end of our tutorial. Hope you enjoyed your stay. Feel free to <a href="#discussion">leave any comments or questions</a> you have. <strong>Thanks!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/actionscript-tutorial-starry-night/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Flash Tutorial: Elastic Object Follower</title>
		<link>http://orangesplotch.com/blog/flash-tutorial-elastic-object-follower/</link>
		<comments>http://orangesplotch.com/blog/flash-tutorial-elastic-object-follower/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 14:55:04 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[elastic]]></category>
		<category><![CDATA[follow the leader]]></category>
		<category><![CDATA[momentum]]></category>
		<category><![CDATA[mouse]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/?p=29</guid>
		<description><![CDATA[Finally, a new Flash tutorial. In this article, we'll explore how to make one object follow another around like a little puppy dog. This tutorial includes both Actionscript 3.0 and Actionscript 2.0 versions. So if you always wanted to make more followers, now you can.]]></description>
			<content:encoded><![CDATA[<p class="intro">In this tutorial I will show you how to make one object follow another object in Flash. Then I&#8217;ll show you how to make the effect more elastic. It&#8217;s up to you to figure out an application for it. I use it a lot to get things to follow the mouse around.</p>
<p>The following scripts are written in Actionscript 3.0. However, I&#8217;ve also included a .fla done in Flash 8 in for anyone who wants to see it in Actionscript 2.0. If you just want the files, feel free to <a href="#elasticfollower-downloads">jump down and download them now</a>.</p>
<h3>We&#8217;re following the leader!</h3>
<p>So first we need to get one object to follow the other object around. Having a two year old son and a dog, I have a lot of experience with things following you. In these examples, the object follows the mouse pointer.</p>
<p>Getting an object to follow the mouse is fairly simple in Flash. In fact, you can just use the <code>startDrag()</code> function, but that sticks the object to the mouse. We&#8217;d like it to follow at a distance, so we&#8217;ll need to make our own function to do that. This function will be an <code>EnterFrame</code> event handler.</p>
<p class="note">Rather than documenting the entire script here, I&#8217;ll just focus on where the real action is. The full Actionscript files are available for download at the end of the article.</p>
<pre>private function FollowMouse(event:Event):void {
    // follow the mouse, but not too closely
    distx = follower.x - mouseX;
    disty = follower.y - mouseY;
    follower.x -= distx / 10;
    follower.y -= disty / 10;
}</pre>
<p>Basically, all we do here is figure out how far away the follower object is from the mouse. Then we move the object a certain amount closer. Here we are moving 10% closer each frame. And here is the resulting mouse following effect.</p>
<div class="object-wrapper">
<p class="title">Mouse Follower</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_7" width="500" height="196">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/follow.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/follow.swf" width="500" height="196" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

</div>
<h3>Now add some elasticity</h3>
<p>Now that the object is following, let&#8217;s add a little personality to the effect. I know when my son is following me around, he rarely makes a straight path directly to me, nor is he always able to stop once he&#8217;s caught up.</p>
<p>Rather than directly moving towards the mouse, we&#8217;ll use momentum to insert some elasticity to the objects response. This makes it appear that the object is attached to the mouse by a rubber band. And it is surprisingly easy to do.</p>
<pre>private function FollowMouse(event:Event):void {
    // follow the mouse in a more elastic way
    // by using momentum
    distx = follower.x - mouseX;
    disty = follower.y - mouseY;
    momentumx -= distx / 3;
    momentumy -= disty / 3;

    // dampen the momentum a little
    momentumx *= 0.75;
    momentumy *= 0.75;

    // go get that mouse!
    follower.x += momentumx;
    follower.y += momentumy;
}</pre>
<p>You will notice that we had to dampen the momentum a little. This keeps it from bouncing indefinitely off the screen. The number you use here needs to be between <code>0.0</code> and <code>1.0</code>. Anything else and you&#8217;ll have flubber that shoots off the screen, never to return.</p>
<p>The closer this value is to <code>1.0</code>, the faster your object will move and the more it will swing around. The closer it is to <code>0.0</code>, the slower it will move and the less it will overshoot its target. Experiment with it a bit to get the effect you want. You can also speed or slow the object by changing the number that you divide the distance by when adjusting the momentum.</p>
<div class="object-wrapper">
<p class="title">Elastic Mouse Follower</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_8" width="500" height="196">
      <param name="movie" value="http://orangesplotch.com/blog/wp-content/uploads/2008/04/elasticfollow.swf" />
      <param name="wmode" value="opaque" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://orangesplotch.com/blog/wp-content/uploads/2008/04/elasticfollow.swf" width="500" height="196" wmode="opaque">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

</div>
<h3>Follow another object</h3>
<p>So now you can follow the mouse. What about when you want to follow something else? That&#8217;s what makes this script so simple, just replace <code>mouseX</code> and <code>mouseY</code> with the <code>x</code> and <code>y</code> of the object you want to follow and you are set.</p>
<pre>distx = follower.x - leader.x;
disty = follower.y - leader.y;</pre>
<h3>Download the fun</h3>
<ul id="elasticfollower-downloads" class="downloads">
<li><a title="Download the source files used in this tutorial." type="zip" href="http://orangesplotch.com/files/FollowTutorial.zip">Elastic mouse follower Actionscript 3.0 source files.</a></li>
<li><a title="Download the Flash 8 version of this tutorial." type="zip" href="http://orangesplotch.com/files/ElasticFollower.fla.zip">Elastic follower in Flash 8 form <em>(Actionscript 2.0)</em>.</a></li>
</ul>
<p class="aside">Please feel free to leave any comments or questions you may have about this tutorial. That&#8217;s what the comments are all about.</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-tutorial-elastic-object-follower/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Flash Race Car Tutorial: Part 1</title>
		<link>http://orangesplotch.com/blog/flash-race-car-tutorial-part-1/</link>
		<comments>http://orangesplotch.com/blog/flash-race-car-tutorial-part-1/#comments</comments>
		<pubDate>Sat, 01 Dec 2007 08:33:21 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[keyboard]]></category>
		<category><![CDATA[keyboard control]]></category>
		<category><![CDATA[momentum]]></category>
		<category><![CDATA[race]]></category>
		<category><![CDATA[racecar]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/flash-race-car-tutorial-part-1/</guid>
		<description><![CDATA[This Flash tutorial will teaches the basics of making a keyboard controlled racecar in Flash. Lots of great stuff on moving an object around the screen with the keyboard. You could apply this to a spaceship, a gorilla or whatever else you want to control.]]></description>
			<content:encoded><![CDATA[<p class="intro">
This tutorial will teach you the basics of making a keyboard controlled racecar in Flash. You could apply this to a spaceship, a gorilla or whatever else you want to control with your keyboard.
</p>
<h3>Making a car</h3>
<p>I&#8217;ll leave all of the making the car fun up to you. Design it however you want. Mine is going to be a rectangle. Not very aerodynamic, but it will do the trick. Be sure to set the Actionscript Class name of the car to &#8220;Racecar&#8221; and check the &#8220;Export for Actionscript&#8221; box in the <code>Properties</code> menu.</p>
<h3>Start your engines</h3>
<p class="note error"><strong>Attention Flash MX 2004 users!</strong> Flash Player 8 has a bug that causes it to not catch key releases correctly if more than one key is pressed simultaneously. The problem is fixed in later versions of the player, so while you will see it if you test your movie in Flash MX 2004, web users probably won&#8217;t encounter the problem.</p>
<p>The first step is to set up the car&#8217;s controls. To allow keyboard buttons to control the car, we need to create a <code>KeyListener</code> object. The <code>KeyListener</code> catches key press and release events similar to the way Flash <code>Button</code> object catches the mouse press and release events. When a key is pressed or released the <code>KeyListener</code> will see that event and show us what key the action happened on. We will program the listener to only pay attention to the arrow keys and call the appropriate function on our car when one is pressed or released.</p>
<p>We are setting up the <code>KeyListener</code> to alert us when the control keys are pressed and when they are released. For instance, when the <code>UP</code> arrow key is pressed, the car will accelerate until it is release. By listening for both the <code>Press</code> action and the <code>Release</code> action we will be able to control the car. I won&#8217;t bore you too much with all of the details of how the <code>KeyListener</code> works. Instead I&#8217;ll throw you the code and let you see it yourself.</p>
<p class="note">When I&#8217;m debugging <code>KeyListener</code>s, I usually put <code>trace</code> statements in my code to make sure the right functions are linked to the right keys. Add <code>trace</code> statements when you are first writing up the code to save yourself a lot of headaches.</p>
<pre class="Actionscript">
// Create key listener
var keyListener:Object = new Object();
keyListener.onKeyDown = function () {
  switch ( Key.getCode() ) {
	case Key.UP:
		_root.mainCar.ForwardOn();
		break;
	case Key.DOWN:
		_root.mainCar.ReverseOn();
		break;
	case Key.RIGHT:
		_root.mainCar.RightTurnOn();
		break;
	case Key.LEFT:
		_root.mainCar.LeftTurnOn();
		break;
  }
}
keyListener.onKeyUp = function () {
  switch ( Key.getCode() ) {
	case Key.UP:
		_root.mainCar.ForwardOff();
		break;
	case Key.DOWN:
		_root.mainCar.ReverseOff();
		break;
	case Key.RIGHT:
		_root.mainCar.RightTurnOff();
		break;
	case Key.LEFT:
		_root.mainCar.LeftTurnOff();
		break;
  }
}
Key.addListener(keyListener);
</pre>
<h3>Let&#8217;s burn some rubber</h3>
<p>Now that we have a car and some controls, let&#8217;s get that car moving!</p>
<p>To run everything, we will be writing <em>(or copying)</em> the <code>Racecar Class</code>. Everything the car does will be controlled by this class.</p>
<p>To start out, I&#8217;m going to just throw a bunch of code at you. This code sets up the <code>Racecar</code> class as an extension of the <code>MovieClip</code> class. All we are doing here is setting a bunch of variables to be used later and defining the functions we used in the <code>KeyListener</code> earlier.</p>
<pre>
class Racecar extends MovieClip {

	private static var MASS_CONST:Number = 10;
	private static var MIN_SPIN:Number   = 1;
	private static var MAX_TORQUE:Number = 1;

	private var maxaccel:Number;      // px. per frame. squared
	private var drag:Number;          // ratio
	private var turnRadius:Number;    // px

	private var _turn:Number;         // 1, 0, -1
	private var _accel:Number;        // 1, 0, -1
	private var vel:flash.geom.Point; // px. per frame
	private var heading:Number;       // radians
	private var spin:Number;          // radians per frame

	// Initialize all the car variables
	function Racecar() {
		// car characteristics
		this.maxaccel   = 1;
		this.turnRadius = 100;
		this.drag       = 0.05;

		// state info
		this.vel = new flash.geom.Point(0, 0);
		this.heading = 0;
		this.spin    = 0;
		this._accel  = 0;
		this._turn   = 0;

		this.onEnterFrame = Update;
	}

	// Updates car state
	private function Update() {
		// *** We'll discuss this function later
	}

	/// - - - - - - - - - - - - - - ///
	///    CAR CONTROL FUNCTIONS    ///
	/// - - - - - - - - - - - - - - ///

	// Forward and reverse
	public function ForwardOn() {
		this._accel = 1;
	}
	public function ForwardOff() {
		this._accel = 0;
	}
	public function ReverseOn() {
		this._accel = -1;
	}
	public function ReverseOff() {
		this._accel = 0;
	}

	// Left and right turn
	public function RightTurnOn() {
		this._turn = 1;
	}
	public function RightTurnOff() {
		this._turn = 0;
	}
	public function LeftTurnOn() {
		this._turn = -1;
	}
	public function LeftTurnOff() {
		this._turn = 0;
	}

}
</pre>
<p>As you can see, the control functions are pretty simple. They just set the <code>_accel</code> and <code>_turn</code> variables. Rather than bore you with the details of this chunk of code, I wanted to jump straight into the most important part, the <code>Update</code> function. If there is anything here that is confusing to you, or that you&#8217;d like explained, feel free to <a href="#comment">post a comment</a> or <a href="http://orangesplotch.com/contact/" title="Send an email to mattc">send me an email</a>. Hopefully it will all make sense once you see the full code. Each part of the <code>Update</code> function will be explained in detail. Hopefully I don&#8217;t bore you to death.</p>
<p> The first step is to get the car&#8217;s heading in radians. All of the <code>Math</code> functions in Flash use radians, but the <code>_rotation</code> property is in degrees.</p>
<pre>
// get the heading
this.heading = Math.PI / 180 * this._rotation;
</pre>
<p>The next thing we&#8217;ll do is update the car&#8217;s velocity. First, I apply drag to the car. If the car is not accelerating it will slowly come to a stop. The larger the value of <code>drag</code>, the faster the car loses speed. It only takes a little drag to slow the car down, so don&#8217;t set that value too high.</p>
<p>Also, if the car is accelerating, we increase the velocity in the direction it is pointing. The <code>sin</code> and <code>cos</code> of the car&#8217;s <code>heading</code> calculates how much of the acceleration should be applied to the <code>x</code> and <code>y</code> direction. The <code>_accel</code> is set by the car control functions and determines whether we are accelerating forward or reverse. The <code>maxaccel</code> variable is how fast the car accelerates. Again, a small value goes a long way here. Set this too high and your car will shoot off the screen. The most important thing is to get your <code>+</code> and <code>-</code> signs right. Otherwise the car will have some interesting behavior.</p>
<pre>
// Add drag
this.vel.x *= (1 - this.drag);
this.vel.y *= (1 - this.drag);

// Add acceleration
this.vel.x += Math.sin( this.heading ) * this._accel * this.maxaccel;
this.vel.y -= Math.cos( this.heading ) * this._accel * this.maxaccel;
</pre>
<p>The trickiest part of this code is getting the car to turn. A car turns based on how fast it is moving. If it isn&#8217;t moving at all, it isn&#8217;t going to turn. The faster you go, the faster it turns. We&#8217;ll have to calculate how fast the car turns based on how fast it is moving.</p>
<p>Real cars can turn at varying rates depending on how much you crank the steering wheel. To simplify things, this car will only turn at a fixed rate. We &#8220;turn&#8221; the car by changing its rotation. Based on the speed of the car and the direction it is turning, we&#8217;ll rotate it. Here is the code that does it. Notice the <code>turnRadius</code> variable. The smaller this number is, the sharper the turn the car will make.</p>
<pre>
var velMag:Number = Math.sqrt(this.vel.x * this.vel.x + this.vel.y * this.vel.y);
this.spin  = velMag / this.turnRadius * this._turn;
var newHeading:Number       = this.heading + this.spin;
</pre>
<p>Just pointing the car in the right direction isn&#8217;t enough, though. We also have to change it&#8217;s velocity to match. I&#8217;ve added an additional feature that allows the car to spin-out if it is turning too fast.</p>
<p>First we calculate how much the velocity will change to get the car moving in the direction it is pointed. I&#8217;m calling this value torque. Next we check the magnitude of this torque against a maximum value. If it is greater than the maximum torque allowed, we limit it. This results in the car spinning out. And finally we modify the velocity by the torque.</p>
<p class="note">If you don&#8217;t want your car to spin out, simply remove the code in the <code>if</code> statement or set <code>MAX_TORQUE</code> very high.</p>
<pre>
// calculate torque (turning the car changes the direction it travels)
var torque:flash.geom.Point = new flash.geom.Point(0,0);
torque.x =  Math.sin(newHeading) * velMag - this.vel.x;
torque.y = -Math.cos(newHeading) * velMag - this.vel.y;
var torqueMag = Math.sqrt(Math.pow(torque.x,2) + Math.pow(torque.y,2));

// limit torque, so the car will "spin out" if turning too fast
if (torqueMag > MAX_TORQUE) {
	torque.x = MAX_TORQUE * torque.x / torqueMag;
	torque.y = MAX_TORQUE * torque.y / torqueMag;
}

// apply torque to velocity
this.vel.x += torque.x;
this.vel.y += torque.y;
</pre>
<p>And finally we update the car&#8217;s position and heading. Not much here, we just set the <code>_x</code>, <code>_y</code>, and <code>_rotation</code> values based on the calculations above.</p>
<pre>
// update position and heading
this._x       += this.vel.x;
this._y       += this.vel.y;
this.heading   = newHeading;
this._rotation = this.heading * 180 / Math.PI;
</pre>
<p>And there you have it! A keyboard controlled car of your very own. It might not be as cool as that remote control car that the neighbor has, but this one never runs out of batteries.</p>
<div class="object-wrapper">
<p class="title">Keyboard Controlled Racecar</p>
<p><object type="application/x-shockwave-flash" data="http://orangesplotch.com/media/flash/tutorials/racecar1.swf" height="400" width="500"><param name="movie" value="http://orangesplotch.com/media/flash/tutorials/racecar1.swf"><img alt="The Flash plugin is required to view this example." src="/media/images/site/noflash.gif" height="100" width="100"><br />
</object>
</div>
<p>Feel free to download the full project and play around with the Actionscript files. The best way to learn this stuff is to jump in and experiment, so go for it. I hope you found this tutorial helpful. Any feedback you have on this or any of my other tutorials is welcome. <strong>Thanks for stopping by!</strong></p>
<ul class="downloads" id="racecar-download">
<li><a href="http://orangesplotch.com/files/Racecar1.zip" type="zip" title="Download the Racecar Tutorial project files.">Racecar Tutorial Project Files.</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-race-car-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Flash Hyperspace Star Field Tutorial</title>
		<link>http://orangesplotch.com/blog/flash-hyperspace-star-field-tutorial/</link>
		<comments>http://orangesplotch.com/blog/flash-hyperspace-star-field-tutorial/#comments</comments>
		<pubDate>Wed, 20 Jun 2007 17:44:21 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[star]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/flash-hyperspace-star-field-tutorial/</guid>
		<description><![CDATA[This Flash tutorial shows you how to create an effect of flying through particles, similar to the "warp speed" effect in Star Trek. The particles can be any MovieClip object you want, stars, dancing bananas, etc.]]></description>
			<content:encoded><![CDATA[<p class="intro">
In this Flash tutorial we are going to make a nice &#8220;star field&#8221; effect. All you Star Trek junkies could call it the &#8220;warp speed effect&#8221;. Use it for all your flying-through-particles needs. Are you ready to <strong>get your nerd on</strong>!
</p>
<div class="object-wrapper">
<p class="title">Hyperspace Star Field</p>
<p><object type="application/x-shockwave-flash" data="http://orangesplotch.com/media/flash/tutorials/star.swf" height="300" width="400"><param name="movie" value="http://orangesplotch.com/media/flash/tutorials/star.swf"><img alt="The Flash plugin is required to view this example." src="/media/images/site/noflash.gif" height="100" width="100"><br />
</object>
</div>
<p>The effect is done using two functions, <code>AddStar</code> and <code>FlyingStar</code>. I&#8217;ll explain everything in detail in this article. If you&#8217;d rather jump into the code and play, <a href="#starfield-download">skip to the end</a> and download the project.</p>
<p>The first step is setting a few control parameters. The following variables control our hyperspace travel effect. I&#8217;ve tried to comment thoroughly, so everything should be self explanatory.</p>
<pre class="actionscript">
// star control variables
var initVel:Number     = 7; // the starting speed of the star in pixels
var accel:Number       = 1.1; // the star's acceleration off the Stage
var alphaChange:Number = 10; // the fade in rate

// myInterval controls how quickly stars are added to the Stage
// the smaller the number, the more stars you'll have
var myInterval:Object  = setInterval(AddStar, 10); 

// maxOffset is the distance from center stage to a corner
// it is used to calculate the size of the star when it is "born"
var maxOffset:Number   = Math.sqrt(Math.pow((Stage.width/2),2) + Math.pow((Stage.height/2),2));

var i:Number           = 0; // star index

// create a container for all of our new stars
this.createEmptyMovieClip("universe_mc", 10);
</pre>
<h3>A star is born</h3>
<p>The <code>AddStar</code> function places a star on the Stage and sets it up for flying. For this to work, you need a <code>MovieClip</code> called &#8220;star&#8221; set to <code>Export For ActionScript</code> in your library.</p>
<p class="note">The star can be whatever you want it to be, a dot, a smiley face, a dancing banana. You&#8217;re the boss.</p>
<p>As you can see in the code, we first attach the star to the <code>universe_mc</code> MovieClip that we made earlier. Next we place it randomly on the Stage by setting its <code>_x</code> and <code>_y</code>. I also wanted the stars to fade in, so I set the <code>_alpha</code> to zero here.</p>
<p>Once the star is placed, we need to figure out how big to make it and what direction to send it flying off the Stage. The size is based on how close it is to the center of the stage. The stars that show up in front of you will look bigger than ones that appear farther out to the edges. That&#8217;s a personal choice, feel free to resize your stars however you like.</p>
<p>Figuring out the direction the stars should fly is the trickiest part of this script. You&#8217;ll need to pull out your old trig book, or copy the code below. Basically we calculate the angle between the vertical axis and the line from the star to Stage center. Using that angle we calculate the star&#8217;s velocity in the <code>_x</code> and <code>_y</code> directions. The stars will now travel in a straight line away from the center of the Stage.</p>
<p class="note">Having the stars fly away from the center of the Stage is key to this effect, so make sure you get it right. Everything else just adds to the effect.</p>
<p>The final line in this block sets the star&#8217;s <code>onEnterFrame</code> to the <code>FlyingStar</code> function. This function controls the motion of the star. We&#8217;ll talk more about it next.</p>
<pre>
function AddStar() {
	// a star is born
	var curStar:MovieClip = universe_mc.attachMovie("star", "star_"+i, i);
	++i;

	// initialize the baby star
	curStar._x     = Math.random() * Stage.width;
	curStar._y     = Math.random() * Stage.height;
	curStar._alpha = 0;

	// calculate which angle star will fly
	// the angle is based on the position of the star from
	// the center of the stage.
	var xOffset:Number     = curStar._x - (Stage.width/2);
	var yOffset:Number     = curStar._y - (Stage.height/2);
	var totalOffset:Number = Math.sqrt( xOffset*xOffset + yOffset*yOffset );
	var velAngle:Number    = Math.atan2(yOffset, xOffset);
	curStar._xVel = initVel * Math.cos( velAngle );
	curStar._yVel = initVel * Math.sin( velAngle );
	curStar._xscale = (maxOffset - totalOffset)/7;
	curStar._yscale = (maxOffset - totalOffset)/7;

	// fly away little star
	curStar.onEnterFrame = FlyingStar;
}
</pre>
<h3>Wish upon a flying star</h3>
<p>We&#8217;ve done all the hard work of placing our star and figuring out its velocity. Now all that&#8217;s left is to send it flying. The <code>FlyingStar</code> function will shoot our stars on their merry way. Again, I&#8217;ll step through this function for you and explain how it works.</p>
<p>The first part of the <code>FlyingStar</code> moves the position of the star based on the x and y velocities we calculated earlier. To make it look like we&#8217;re really flying, we increase the speed of the star on each frame. This makes it accelerate off the page. To do the initial fade in, we increase the <code>_alpha</code> each frame until it is at 100.</p>
<p class="note">If you wanted to get really fancy, you could also add a blur value to the star as it approached the edge of the Stage. I&#8217;ll leave that to you to figure out on your own. If you get stumped, just <a href="http://orangesplotch.com/contact/">shoot me an email</a>.</p>
<p>Finally we check to see if the star has flown off the Stage. If it has, we remove it from the movie. Not doing this will allow the movie to use more and more memory with each star, eventually bogging down the whole computer. When you are dynamically adding infinite numbers of MovieClips to a movie, be sure to be deleting them just as fast.</p>
<pre>
function FlyingStar () : Void {
	// move the star
	this._x += this._xVel;
	this._y += this._yVel;

	// accelerate the star
	this._xVel *= accel;
	this._yVel *= accel;

	// fade the star in
	if (this._alpha < 100) this._alpha += alphaChange;
	else this._alpha = 100;

	// check if the star has left the stage
	// if it has, remove it so you don't hog memory
	if (  (this._x < -this._width) ||
		  (this._x > (Stage.width + this._width)) ||
		  (this._y < -this._height) ||
		  (this._y > (Stage.height + this._height))  ) {
		this.removeMovieClip();
	}
}
</pre>
<h3>Warp speed ahead</h3>
<p>Now you have everything you need to fly through space. Change variables we set up at the beginning to get different effects. Feel free to experiment all you want. If you really screw something up, just delete it all and start again. If only the real universe were so simple.</p>
<ul class="downloads" id="starfield-download">
<li><a href="http://orangesplotch.com/files/FlyingStars.zip" type="zip" title="Download the project files to make your flying universe.">Download the Hyperspace Project Files.</a></li>
</ul>
<p>This project is published under the <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>. Feel free to use it however you like. I always appreciate links back. If you have any problems with the scripts, please let me know.</p>
<p class="aside">Please post links to any Flash movies you&#8217;ve made using this tutorial. I&#8217;d love to see how it gets used <strong>in the wild</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-hyperspace-star-field-tutorial/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Flash Momentum Tutorial</title>
		<link>http://orangesplotch.com/blog/flash-momentum-tutorial/</link>
		<comments>http://orangesplotch.com/blog/flash-momentum-tutorial/#comments</comments>
		<pubDate>Tue, 24 Apr 2007 22:40:39 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[momentum]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/flash-momentum-tutorial/</guid>
		<description><![CDATA[This tutorial will show you how to make items in Flash "throwable" using Actionscript. So if you like throwing things around, this is the tutorial for you.]]></description>
			<content:encoded><![CDATA[<p class="intro">
This tutorial will show you how to make items in Flash &#8220;throwable&#8221; using Actionscript. So if you like throwing things around, this is the tutorial for you.
</p>
<h3><code>startDrag</code> Woes</h3>
<p>As you probably know, Flash comes with a great predefined function <code>startDrag</code>. This makes dragging things around the screen very easy. However, once you call the function <code>stopDrag</code>, the object stops <strong>dead in its tracks</strong>. If you wanted the object to maintain its motion once <code>stopDrag</code> is called, you will need to add some extra code to your objects.</p>
<h3>Get the motion</h3>
<p>The first step in maintaining an object&#8217;s motion is figuring out what that motion is and saving it. To do this we simply need to save the objects location from the last frame, and then subtract that from the current frame&#8217;s location. This gives us the object&#8217;s velocity.</p>
<p>As an example of what I mean, I&#8217;ve written the following handlers for a ball <code>MovieClip</code>. The key point to be aware of is that I am saving the position of the clip so I can use it to calculate the velocity. We only need to execute this code when the object is not being dragged. The velocity won&#8217;t be changing once it is released. To keep the object moving once it is released, we simply add the velocity values to its current position.</p>
<p class="note">You can get some pretty annoying behavior if you don&#8217;t include <code>releaseOutside</code> in the events that trigger the <code>stopDrag</code>. This is because the mouse moves before the object does, making it possible to let go of the mouse when the object isn&#8217;t under it.</p>
<pre>
onClipEvent(load) {
	// initialize the variables needed to calculate and store momentum
	this.lastFramePosition = new Object();
	this.velocity = new Object();

	this.lastFramePosition.x = this._x;
	this.lastFramePosition.y = this._y;
	this.velocity.x = 0;
	this.velocity.y = 0;
	this.isDragging = false;
}

onClipEvent(enterFrame) {
	if (this.isDragging) {
		// calculate and save the object's velocity
		this.velocity.x = this._x - this.lastFramePosition.x;
		this.velocity.y = this._y - this.lastFramePosition.y;

		// save the current location to the lastFramePosition
		this.lastFramePosition.x = this._x;
		this.lastFramePosition.y = this._y;
	}
	else {
		// the object is not being dragged, so keep it moving
		this._x += this.velocity.x;
		this._y += this.velocity.y;
	}
}

// Make the object draggable
on(press) {
	this.startDrag();
	this.isDragging = true;
}

on(release, releaseOutside) {
	this.stopDrag();
	this.isDragging = false;
}
</pre>
<div class="object-wrapper">
<p class="title">Throw-able Ball</p>
<p><object width="350" height="200" type="application/x-shockwave-flash" data="http://orangesplotch.com/media/flash/tutorials/momentum-nodamping.swf"><param name="movie" value="http://orangesplotch.com/media/flash/tutorials/momentum-nodamping.swf" /><img width="100" height="100" alt="The Flash plugin is required to view this example." src="/media/images/site/noflash.gif" /><br />
</object>
</div>
<h3>Damping and Limiting</h3>
<p>As you can see, the ball can get moving pretty <strong>fast</strong> and shows no signs of slowing down ever. Perhaps this is how you want the ball to behave. For most applications, however, you will probably want to limit the object&#8217;s speed to within reason. You may also want the object to slow down over time. The rest of this tutorial will address these two features.</p>
<p>To limit the speed of the ball, we use a little trig. Don&#8217;t be afraid of the <strong>math</strong>, I&#8217;ve already worked it out here for you. Those of you who like math can probably figure out what&#8217;s going on pretty easily. Those of you who hate it can just copy the code.</p>
<pre>
// limit the velocity to MAX_SPEED
if ( Math.sqrt(Math.pow(this.velocity.x,2) + Math.pow(this.velocity.y,2)) > MAX_SPEED ) {
	velAng = Math.atan2( this.velocity.y, this.velocity.x );
	this.velocity.x = MAX_SPEED * Math.cos( velAng );
	this.velocity.y = MAX_SPEED * Math.sin( velAng );
}
</pre>
<p>And finally we&#8217;ll slow the object down over time. To slow the object down, we simply multiply the velocity by a number less than zero each frame. You could get the same effect by dividing the velocity by a number greater than zero. As you can see in the code, it doesn&#8217;t take much to slow the ball down.</p>
<pre>
DAMPING_FACTOR = 0.98;

// slow down the ball by the DAMPING_FACTOR
this.velocity.x *= DAMPING_FACTOR;
this.velocity.y *= DAMPING_FACTOR;
</pre>
<div class="object-wrapper">
<p class="title">Throw-able Ball with Limiting and Damping</p>
<p><object width="350" height="200" type="application/x-shockwave-flash" data="http://orangesplotch.com/media/flash/tutorials/momentum-withdamping.swf"><param name="movie" value="http://orangesplotch.com/media/flash/tutorials/momentum-withdamping.swf" /><img width="100" height="100" alt="The Flash plugin is required to view this example." src="/media/images/site/noflash.gif" /><br />
</object>
</div>
<h3>The End</h3>
<p>And there you have it. Your very own <strong>throw-able Flash object</strong>. To make things easier, I&#8217;ve placed all of the code into the <code>MomentumObject</code> class for anyone to use. Simply link this class to any <code>MovieClip</code> you want and it will be automatically throw-able.</p>
<ul class="downloads">
<li><a href="http://orangesplotch.com/files/MomentumObject.as" title="Download the MomentumObject class file to use however you want." type="text">MomentumObject.as</a></li>
<li><a href="http://orangesplotch.com/files/MomentumProject.zip" title="Download the project files to see how it all works." type="zip">MomentumProject.zip</a></li>
</ul>
<p class="aside">As I am pretty new to this whole tutorial thing, I would love to hear any feedback you might have on this. Was this useful for you? What can I do better? Feel free to <a href="#commentform">leave a comment</a> or <a href="http://orangesplotch.com/contact/">send me an email</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-momentum-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flash Bouncing Ball Tutorial</title>
		<link>http://orangesplotch.com/blog/flash-bouncing-ball-tutorial/</link>
		<comments>http://orangesplotch.com/blog/flash-bouncing-ball-tutorial/#comments</comments>
		<pubDate>Sun, 07 Jan 2007 07:12:44 +0000</pubDate>
		<dc:creator>mattc</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[ball]]></category>
		<category><![CDATA[bounce]]></category>

		<guid isPermaLink="false">http://orangesplotch.com/blog/flash-bouncing-ball-tutorial/</guid>
		<description><![CDATA[Enjoy the thrill of a rubber ball in Flash. Oh, boy! This is a basic bouncy ball tutorial for anyone interested in learning a little Actionscript.]]></description>
			<content:encoded><![CDATA[<p class="intro">To make things a little more fun around here, I have put together a bouncing ball tutorial for Flash. Just like the previous tutorial, this one will be done primarily in Actionscript. Ready, go!</p>
<h3>Find a ball</h3>
<p>The first thing we&#8217;ll need is a ball. Start out with a plain circle. Using Flash&#8217;s very useful gradient tools, we can make our ball more realistic. First create the gradient. For the best results, don&#8217;t place your darkest shade at the end. Instead place it near the end and at the end of the gradient place a slightly lighter shade to represent reflections off of the floor. <strong>Play around</strong> with it until you get something you like. Use the Paint-bucket tool to paint your circle, placing the center near the top of the ball and to one side for the best effect.</p>
<p class="note">The trick to a realistic gradient is to keep it subtle. It is tempting to go from really dark to really light, but in reality things only have that kind of contrast if they are directly in a spotlight.</p>
<p><img class="bordered align-right" src="http://orangesplotch.com/media/images/tutorials/ball-gradient.png" alt="Adding a gradient to the ball." /></p>
<p>To finish it off we need to convert our ball to a movie clip. Select the ball, then select <code>Modify &gt; Convert to Symbol</code>. In the window that comes up give it a name, select <code>Type: Movie Clip</code> and click <code>OK</code>. And now you have a ball.</p>
<h3>Add some bounce</h3>
<p>Now that we have a nice ball, it&#8217;s time to <strong>add some motion</strong>. I usually write all of the actions on the actual object to start with. Later I move them to their own Actionscript file. So select the ball <code>MovieClip</code> on your screen and open the Actionscript editor panel.</p>
<p>Before things start moving, we need to initialize a few variables. The <code>Load</code> event is perfect for initializing. These variables when we use them later, for now here&#8217;s the code.</p>
<pre class="actionscript">onClipEvent(load) {
	this._freefall        = true;
	this._momentumY       = 0;
	this._accelerationY   = 2.0;
	this._floorElasticity = 0.75;
	this._floorY          = 190;
	this._bounceThreshold = 3;
}</pre>
<p>All of the interesting stuff happens in the <code>EnterFrame</code> handler. To start with, we want the ball to fall down. We also want it to accelerate as it falls. So <strong>we increment</strong> the <code>_y</code> value by a variable, <code>_momentumY</code> and then we increase <code>_momentumY</code> by the <code>_accelerationY</code>.</p>
<pre>  this._y += this._momentumY;
  this._momentumY += this._accelerationY;</pre>
<p>A ball falling forever into the vast depths of <strong>outer space</strong> off our screen isn&#8217;t too interesting. Let&#8217;s have it hit a floor at the bottom. To do that, we just add an <code>if</code> statement to see if it has hit solid ground. When it meets the ground we want it to reverse direction. Also, to keep it from bouncing forever, the ground needs to absorb a percentage of its momentum in the process. The ball jiggles indefinitely at the end, so I added the <code>_bounceThreshold</code> to the equation to <strong>bring it to rest</strong>. Here is what the code looks like.</p>
<pre>// bounce it off the floor if it has hit it
if (this._y &gt; this._floorY) {
	this._y = this._floorY; // this prevents the ball from getting stuck in the floor
	this._momentumY = -(this._momentumY * this._floorElasticity) + this._bounceThreshold;

	// keep the ball from jiggling infinitely
	if (Math.abs(this._momentumY) &lt;= this._bounceThreshold) {
		this._momentumY = 0;
	}
}</pre>
<div class="object-wrapper">
<p class="title">Bouncy Ball</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="350" height="200" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://orangesplotch.com/media/flash/tutorials/ball-nodrag.swf" /><embed type="application/x-shockwave-flash" width="350" height="200" src="http://orangesplotch.com/media/flash/tutorials/ball-nodrag.swf"></embed></object></p>
</div>
<h3>Go Play!</h3>
<p>A ball <strong>isn&#8217;t any fun</strong> unless you can pick it up, so let&#8217;s make this ball a little more interactive. Adding the following <code>Press</code> and <code>Release</code> handlers let&#8217;s you pick up the ball and drop it wherever you want. You also need to wrap the <code>EnterFrame</code> contents in an <code>if</code> statement so the ball doesn&#8217;t keep falling while you&#8217;re holding it. Here is the final code.</p>
<pre>on(press) {
	this._freefall  = false;
	this._momentumY = 0;
	this.startDrag(false);
}

on(release, releaseOutside) {
	this._freefall = true;
	this.stopDrag();
}

onClipEvent(load) {
	this._freefall        = true;
	this._momentumY       = 0;
	this._accelerationY   = 2.0;
	this._floorElasticity = 0.75;
	this._floorY          = 190;
	this._bounceThreshold = 3;
}

onClipEvent(enterFrame) {
	if (this._freefall) {
		this._y         += this._momentumY;
		this._momentumY += this._accelerationY;

		// bounce it off the floor if it has hit it
		if (this._y &gt; this._floorY) {
			this._y = this._floorY;
			this._momentumY = -(this._momentumY * this._floorElasticity) + this._bounceThreshold;

			// keep it from jiggling infinitely
			if (Math.abs(this._momentumY) &lt;= this._bounceThreshold) {
				this._momentumY = 0;
			}
		}
	}
}</pre>
<p>And now you have a bouncing ball. Go have some fun, just don&#8217;t go throwing it through the neighbor&#8217;s window. Try changing some of the initial variable values to see what happens. If you want a <strong>flubber ball</strong> that gets higher with each bounce, make the <code>_elasticity</code> &gt; 1.</p>
<div class="object-wrapper">
<p class="title">Bouncy Ball</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="350" height="200" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://orangesplotch.com/media/flash/tutorials/ball.swf" /><embed type="application/x-shockwave-flash" width="350" height="200" src="http://orangesplotch.com/media/flash/tutorials/ball.swf"></embed></object></p>
</div>
<ul class="download">
<li><a type="zip" href="http://orangesplotch.com/files/bouncyball.zip">Download the Bouncing Ball Project.</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://orangesplotch.com/blog/flash-bouncing-ball-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
