<?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>Абструс! &#187; accelerometer</title>
	<atom:link href="http://www.abstrys.com/tag/accelerometer/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.abstrys.com</link>
	<description>Writing, game development, and other enigmatic esoterica.</description>
	<lastBuildDate>Tue, 12 Apr 2011 17:14:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Porting Sparkles from Zune HD to Windows Phone 7</title>
		<link>http://www.abstrys.com/2010/05/porting-sparkles-from-zune-hd-to-windows-phone-7/</link>
		<comments>http://www.abstrys.com/2010/05/porting-sparkles-from-zune-hd-to-windows-phone-7/#comments</comments>
		<pubDate>Mon, 24 May 2010 19:34:54 +0000</pubDate>
		<dc:creator>Eron</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[accelerometer]]></category>
		<category><![CDATA[input]]></category>
		<category><![CDATA[multitouch]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[XNA Game Studio 4]]></category>
		<category><![CDATA[Zune HD]]></category>

		<guid isPermaLink="false">http://www.abstrys.com/?p=72</guid>
		<description><![CDATA[InputToy (also known as &#8220;Sparkles&#8221;) started as an application designed to demonstrate programming touch and accelerometer input on the Zune HD with XNA Game Studio 3.1. However, when the XNA Game Studio 4 Community Technical Preview (CTP) was released with support for the upcoming Windows Phone 7, including a built-in emulator, I felt that porting [...]]]></description>
			<content:encoded><![CDATA[<p>InputToy (also known as &#8220;Sparkles&#8221;) started as an application designed to demonstrate programming touch and accelerometer input on the Zune HD with XNA Game Studio 3.1. However, when the XNA Game Studio 4 Community Technical Preview (CTP) was released with support for the upcoming Windows Phone 7, including a built-in emulator, I felt that porting the application to Windows Phone was the next logical step.</p>
<p>This tutorial will provide step-by-step instructions on porting an application from the Zune HD to Windows Phone, using the existing Zune HD Sparkles application (InputToyZuneHD) as an example.  The full source code for that version can be <a href="http://www.abstrys.com/files/source/InputToyZuneHD.zip">downloaded here</a>.</p>
<p><span id="more-72"></span></p>
<p style="padding-left: 30px;"><strong>Important Notes:</strong></p>
<ul>
<li>This article is written about pre-released technology.  It is likely that some of the features, the API, and the products mentioned here will change before final release.  I will attempt to keep this article up-to-date, but no guarantees can be made of the accuracy of this material when compared to the final (future) product.</li>
<li>Since the Windows Phone emulator doesn&#8217;t include accelerometer support, you&#8217;ll need to wait for actual Windows Phone 7 devices to become available to actually see that part of the code in action, but you can certainly work with touch input right now using the emulator.</li>
</ul>
<h2>Prerequisites</h2>
<p>This tutorial assumes that you&#8217;ve already created an application for Zune HD using the steps in the first set of tutorials. If you haven&#8217;t, you may want to at least read through <a href="http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-1/" target="_blank">Making the Zune HD Sparkle with XNA Game Studio 3.1 &#8211; Part 1</a> and <a href="http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-2/" target="_blank">Part 2</a>.</p>
<p>Before you begin, you&#8217;ll also need the following:</p>
<ul>
<li>The <a href="http://creators.xna.com/en-US/downloads" target="_blank">XNA Game Studio 4 Community Technical Preview</a>.</li>
<li>The <a href="http://www.abstrys.com/files/source/InputToyZuneHD.zip">InputToy code for the Zune HD</a>.  If you have an existing project to work from, you can begin from there.  Otherwise, download the code, unpack it, and follow along.</li>
</ul>
<p>For reference, the full source code for the finished application for  Windows Phone 7 can be <a href="../files/source/InputToyWP7.zip">downloaded  here</a>.</p>
<h2>Converting a Zune HD project to Windows Phone 7</h2>
<p>The first thing you&#8217;ll need to do is create a new Windows Phone game project and copy the source files into it. Call the project <strong>InputToyWP7</strong>. I won&#8217;t go into this process in detail here, since there&#8217;s already an article in the <a href="http://msdn.microsoft.com/en-us/library/bb200104(v=XNAGameStudio.40).aspx" target="_blank">XNA Game Studio 4 documentation</a> about how to do exactly that, called <a href="http://msdn.microsoft.com/en-us/library/ff604985(v=XNAGameStudio.40).aspx" target="_blank">Migrating from Zune to Windows Phone</a>.  It&#8217;s a great guide—trust me, I wrote it!</p>
<p>The source files you will need to copy from the old project are:</p>
<ul>
<li>Game1.cs</li>
<li>Instructions.cs</li>
<li>Menu.cs</li>
</ul>
<p>Copy these into the <em>InputToyWP7</em> directory in your Visual Studio 2010 project.</p>
<p>You&#8217;ll also notice that there&#8217;s an <em>InputToyWP7Content</em> directory in your project, as well. A major difference between the way XNA Game Studio 3.1 and 4.0 behave is that content projects are now full projects alongside the code project, and not in a sub-directory within the code project&#8217;s directory.</p>
<p>From the old project&#8217;s <em>Content</em> directory, copy the following files into the new project&#8217;s <em>InputToyWP7Content</em> directory:</p>
<ul>
<li>btnHelp.png</li>
<li>btnPause.png</li>
<li>btnPlay.png</li>
<li>Flare.png</li>
<li>Instructions.png</li>
</ul>
<p>Once all these files have been added to your projects, you&#8217;ll be ready to proceed with the code modification necessary to get the application running on the WP7 emulator supplied with the XNA GS 4 CTP (wow, three <a href="http://foldoc.org/tla" target="_blank">TLAs</a> in a row!).</p>
<h2>Modifying the game code for Windows Phone</h2>
<h3>Screen dimensions</h3>
<p>The original Zune HD version of this application was written for the Zune HD&#8217;s native screen resolution of 272 x 480.  Windows Phone 7, however, sports a native resolution of 480 x 800.  At some point, the Windows Phone emulator may support the built-in hardware scaling that is planned for the phone, but for now, it supports only the standard 480 x 800 resolution.</p>
<p>In anticipation of being able to set my screen dimensions to be equal to the Zune HD&#8217;s resolution—therefore preserving the original look of my application—I&#8217;m going to set the screen dimensions in a Vector2 that I can easily change in the future.  Add the following member to the <strong>Game1 </strong>class:</p>
<pre><strong><span style="color: #008000;">Vector2 screenDimensions = new Vector2(480, 800);</span></strong></pre>
<p>Now, in the game&#8217;s constructor, we&#8217;ll set the <strong>GraphicsDeviceManager</strong>&#8216;s <strong>PreferredBackBufferWidth</strong> and <strong>PreferredBackBufferHeight</strong> to these dimensions.  We&#8217;ll also set <strong>IsFullScreen</strong> to <em><strong>true</strong></em>.  Add the following code to Game1&#8242;s constructor:</p>
<pre>// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromSeconds(1/30.0);

<strong><span style="color: #008000;">// This makes use of the built-in hardware scaler to work with our original (Zune HD) resolution
graphics.PreferredBackBufferWidth = (int)screenDimensions.X;
graphics.PreferredBackBufferHeight = (int)screenDimensions.Y;

// use the whole screen
graphics.IsFullScreen = true;</span></strong></pre>
<p>Another neat thing that we&#8217;ll get for free is an <em>automatic translation</em> of touchscreen coordinates from WP7&#8242;s native resolution to the resolution that we set for the backbuffer, so we can count on having the same touch coordinates (272 x 480) that we did for Zune HD. This isn&#8217;t an issue now, since we&#8217;re using 480 x 800 resolution, but it&#8217;s nice to know that no additional code changes will be needed when using automatic backbuffer scaling.</p>
<p>Speaking of touch input&#8230; we&#8217;ll now modify our touch input code so it works with GS4.  Thankfully, there won&#8217;t be much to do.</p>
<h3>Changing the touch input code for XNA Game Studio 4</h3>
<p>One difference between XNA GS 3.1 and 4.0 is how the touch input classes are referenced.  In XNA GS 4, they are now inside their own assembly.  To make our old code work with XNA GS 4, we&#8217;ll need to add a new reference to <strong>Microsoft.Xna.Framework.Input.Touch</strong> to the top of <em>Game1.cs</em>:</p>
<pre>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
<span style="color: #008000;"><strong>using Microsoft.Xna.Framework.Input.Touch;</strong></span>
using Microsoft.Xna.Framework.Media;</pre>
<p>You&#8217;ll also need to make sure that <strong>Microsoft.Xna.Framework.Input.Touch</strong> is  also referenced by your project itself:  Click on the <strong>References </strong>node in  your InputToy source project, and make sure it contains <strong>Microsoft.Xna.Framework.Input.Touch</strong> in the list.  If it doesn&#8217;t, right click the <strong>References </strong>node and  click <strong>Add Reference&#8230;</strong>, then select it from the list and click <strong>OK</strong> to add it to your project.</p>
<p>That&#8217;s it!  Aside from this change, we don&#8217;t need to do anything extra to our code to support touch input on WP7.  As mentioned before, due to the magic of hardware scaling, all our touch input code from the Zune HD version of the application will continue to work fine.</p>
<h3>Changing the accelerometer code for Windows Phone</h3>
<p>This is where things get interesting.  Accelerometers are <em>not</em> supported by XNA GS 4, as they were for Zune HD on XNA GS 3.1.  To work with the accelerometer on Windows Phone, you need to add the <strong>Microsoft.Devices.Sensors</strong> assembly to the project, which is, thankfully, included with the XNA GS 4 CTP you downloaded as a prerequisite.  Add the following line to the using statements at the beginning of Game1.cs (I added it after the <em>using Microsoft.Xna.Framework.Media</em> line):</p>
<pre><strong><span style="color: #008000;">using Microsoft.Devices.Sensors;</span></strong>
</pre>
<p>You&#8217;ll also need to make sure that <strong>Microsoft.Devices.Sensors</strong> is also referenced by your project, as you did for <strong>Microsoft.Xna.Framework.Input.Touch</strong>.</p>
<p><strong>Microsoft.Devices.Sensors</strong> is not an XNA GS assembly—it&#8217;s supplied by Silverlight—and doesn&#8217;t follow the usual programming patterns used with XNA Game Studio.  There&#8217;s no polling for input as there was with <strong>Accelerometer.GetState</strong> in GS 3.1.</p>
<p>Instead, we&#8217;ll be using the <strong>AccelerometerSensor</strong> class in <strong>Microsoft.Devices.Sensors</strong>.  We&#8217;ll also define an event handler that will be called when the <strong>ReadingChanged</strong> event is raised.</p>
<p>First, add the following members to the <strong>Game1</strong> class:</p>
<pre>...
List&lt;Sparkle&gt; sparkles;
Instructions instructions;
Menu menu;
<strong><span style="color: #008000;">bool accelActive = false;
AccelerometerSensor accelSensor;
Vector3 accelReading = new Vector3();</span></strong></pre>
<p>First, we have a boolean value that we&#8217;ll use to keep track of whether the accelerometer is <em>active</em> or not.  Next is a member to hold the AccelerometerSensor object, and finally is a Vector3 that we&#8217;ll use to hold the X, Y, and Z values returned by the accelerometer.</p>
<p>Next, we&#8217;ll add the following code to Game1&#8242;s constructor:</p>
<pre>// This makes use of the built-in hardware scaler to work with our original (Zune HD) resolution
graphics.PreferredBackBufferWidth = (int)screenDimensions.X;
graphics.PreferredBackBufferHeight = (int)screenDimensions.Y;

// use the whole screen
graphics.IsFullScreen = true;

<strong><span style="color: #008000;">accelSensor = new AccelerometerSensor();

// Add the accelerometer event handler to the accelerometer sensor.
accelSensor.ReadingChanged +=
   new EventHandler&lt;AccelerometerReadingAsyncEventArgs&gt;(AccelerometerReadingChanged);

// Start the accelerometer
try
{
   accelSensor.Start();
   accelActive = true;
}
catch (AccelerometerStartFailedException e)
{
   // the accelerometer couldn't be started.  No fun!
   accelActive = false;
}</span></strong></pre>
<p>After creating an instance of the <strong>AccelerometerSensor</strong>, we add the event handler to handle the <strong>ReadingChanged</strong> event.  It will be called <strong>AccelerometerReadingChanged</strong>, and takes an <strong>AccelerometerReadingAsyncEventArgs </strong>argument. We&#8217;ll define this handler in a short while.</p>
<p>For now, notice that we also have to <strong>Start</strong> the accelerometer, and that this call can fail with an <strong>AccelerometerFailedException</strong>.  If it does, we simply set <strong>accelActive</strong> to <strong>false</strong>.</p>
<p>In this case, we&#8217;ll have the accelerometer active during the entire run of the program.  In your own games, you may want to turn off the accelerometer when its not being used.  This can improve performance, since there will be no need to receive or respond to <strong>ReadingChanged</strong>.</p>
<p>Instead, we&#8217;ll just turn off the accelerometer when the program shuts down.  Add the following lines to <strong>UnloadContent</strong>, which is called as the game is exiting:</p>
<pre>protected override void UnloadContent()
{
   // Unload any non ContentManager content here
<span style="color: #008000;"><strong>   // Stop the accelerometer if it's active.
   if (accelActive)
   {
      try
      {
         accelSensor.Stop();
      }
      catch (AccelerometerStopFailedException e)
      {
         // the accelerometer couldn't be stopped now.
      }
   }</strong>
</span>}</pre>
<p>Now, lets revisit the <strong>ReadingChanged </strong>event handler.  We called it <strong>AccelerometerReadingChanged</strong>, but didn&#8217;t actually define the method.  We&#8217;ll do so now.  Add the following method to the Game1 class:</p>
<pre><strong><span style="color: #008000;">public void AccelerometerReadingChanged(object sender, AccelerometerReadingAsyncEventArgs e)
{
   accelReading.X = (float)e.Value.Value.X;
   accelReading.Y = (float)e.Value.Value.Y;
   accelReading.Z = (float)e.Value.Value.Z;
}</span></strong></pre>
<p>There isn&#8217;t much to it: this method simply gets the X, Y, and Z values from the <strong>AccelerometerReadingAsyncEventArgs</strong> object, and saves them in the Vector3 that we defined earlier.</p>
<p>Now, all we need to do is make use of this data.  We actually had code that did this for our Zune HD version of the application, and we&#8217;ll reuse that code.</p>
<p>In Game1&#8242;s Update method, <em>remove </em>the lines that were used to get the accelerometer state, since these are no longer used.  Remove these lines:</p>
<pre><span style="color: #ff0000;"><strong>// grab the accelerometer state.  This will be used for sparkle
// movement.
AccelerometerState accelState = Accelerometer.GetState();</strong></span></pre>
<p>Later in Update, there&#8217;s code that sets the particle speed based on the value in the <strong>accelState</strong> variable.  Find it, and modify the code (modified bits are in <strong><span style="color: #008000;">green</span></strong>, as usual) so that it looks like this:</p>
<pre><strong><span style="color: #008000;">if (accelActive)
{</span></strong>
   // accelerate the sparkle depending on accelerometer
   // action.
   s.speed.X += <span style="color: #008000;"><strong>accelReading.X</strong></span> * ACCELFACTOR;
   s.speed.Y += <span style="color: #008000;"><strong>-accelReading.Y</strong></span> * ACCELFACTOR;

   // move the sparkle based on its speed.
   s.position.X += s.speed.X * etms;
   s.position.Y += s.speed.Y * etms;
   s.rotation += s.speed.Length() * ACCELFACTOR * etms;
<span style="color: #008000;"><strong>}</strong></span></pre>
<p>The only changes we had to make were to make use of the <strong>accelActive </strong>value that tells us the accelerometer has been made active (by calling <strong>Start</strong>), and switching out the <strong>accelState</strong> variable that we removed earlier with our <strong>accelReading</strong> class member.</p>
<p>That&#8217;s it!  Though modifying the accelerometer code was a little more work than it took to modify the touch code, it didn&#8217;t take much more than defining a single event handler and adding the code to instantiate, start, and stop the <strong>AccelerometerSensor</strong>.</p>
<p>You should now be able to build the application and, once you get your hands on a Windows Phone 7 device, be able to see it behave just like it did for Zune HD.  For now, however, you can at least play with the touch portions of the application in the Windows Phone 7 emulator:</p>
<p><a href="http://www.abstrys.com/wp-content/uploads/2010/05/InputToyWP7.png"><img class="aligncenter size-full wp-image-97" title="InputToyWP7" src="http://www.abstrys.com/wp-content/uploads/2010/05/InputToyWP7.png" alt="" width="300" height="522" /></a></p>
<p>As before, please let me know if you have any questions or comments regarding this tutorial, or if you&#8217;d like to see articles covering other subjects.  I hope you enjoyed it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.abstrys.com/2010/05/porting-sparkles-from-zune-hd-to-windows-phone-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making the Zune HD Sparkle with XNA Game Studio 3.1 &#8211; Part 1</title>
		<link>http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-1/</link>
		<comments>http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-1/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 08:40:47 +0000</pubDate>
		<dc:creator>Eron</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[accelerometer]]></category>
		<category><![CDATA[input]]></category>
		<category><![CDATA[touch]]></category>
		<category><![CDATA[XNA Game Studio Docs & Resources]]></category>
		<category><![CDATA[Zune HD]]></category>

		<guid isPermaLink="false">http://www.abstrys.com/?p=5</guid>
		<description><![CDATA[Introduction This article explores using XNA Game Studio to access the two primary forms of user input on the Zune HD: the multitouch screen, and the accelerometer. We&#8217;ll do this by building a small demo that allows the user to create sparkles by touching the screen, and to move them around by tilting the device. Over the course [...]]]></description>
			<content:encoded><![CDATA[<div id="Intro">
<h2>Introduction</h2>
<p><img class="alignright" src="http://www.abstrys.com/files/images/InputToy-Part1.png" alt="" width="200" height="264" />This article explores using XNA Game Studio to access the two primary forms of user input on the Zune HD: the multitouch screen, and the accelerometer. We&#8217;ll do this by building a small demo that allows the user to create sparkles by touching the screen, and to move them around by tilting the device.</p>
<p>Over the course of this tutorial, the following subjects will be covered:</p>
<ul>
<li>Multitouch input</li>
<li>Accelerometer input</li>
<li>Animating blended sprites</li>
<li>A simple UI  (in part two)</li>
</ul>
<p>I won&#8217;t be going over how to create a new XNA game project, nor will I describe how to add textures using the Content Pipeline. I assume that the reader has read enough about Game Studio to know how to do these things already. If you haven&#8217;t, I suggest downloading XNA Game Studio (a link is provided below) and going through the <a href="http://msdn.microsoft.com/en-us/library/bb203893.aspx">first tutorial</a> provided in the Game Studio documentation.</p>
<p><span id="more-5"></span></p>
<p>The full sample, including source code, images, and VS2008 project files, can be <a href="http://www.abstrys.com/files/source/InputToyZuneHD.zip">downloaded here</a>. Unless you want to make your own textures while following along with the tutorial, you&#8217;ll at least want to grab the images from the zip archive.</p>
</div>
<div id="Prereqs">
<h2>Prerequisites</h2>
<p><em>This is a Zune HD tutorial</em>: although some parts of the tutorial apply to all XNA Game Studio projects in general, much of the content here will apply only to devices that support both accelerometer and multi-touch input with XNA Game Studio 3.1. At the moment, that list begins and ends with the Zune HD. If you don&#8217;t already have a Zune HD, I&#8217;d recommend borrowing one from a friend, purchasing one, or sticking with Xbox 360 and Windows programming for now.</p>
<p>In addition to having access to a Zune HD, you&#8217;ll need the following software installed:</p>
<ul>
<li><em>Visual Studio 2008</em> &#8211; If you don&#8217;t already have Visual Studio 2008 Professional, you can download <a href="http://www.microsoft.com/express/Downloads/#2008-Visual-CS">Visual Studio 2008 Express edition</a>.</li>
<li><em>XNA Game Studio 3.1</em> &#8211; Available from the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=80782277-D584-42D2-8024-893FCD9D3E82">Microsoft Download Center</a>.</li>
<li><em>XNA Game Studio 3.1 Zune Extensions</em> &#8211; Also available from the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=48F7BA37-8BA7-4D16-8873-0B7F83EF77F9">Microsoft Download Center</a>.</li>
</ul>
<p>As I mentioned in the Introduction, you&#8217;ll also need an understanding of the basics of building an XNA Game Studio application.</p>
</div>
<div id="S1">
<h2>First Steps</h2>
<p>To begin, open Visual Studio 2008 and create a new XNA Game Studio project for Zune. Call it whatever you like. I called this project &#8220;InputToyZuneHD&#8221;.</p>
<p>Then, add some images to the project that we&#8217;ll be using. For now, all you&#8217;ll need is Flare.png, which contains the sparkle image. It looks like this:</p>
<p><img style="background: black;" src="http://www.abstrys.com/files/images/Flare.png" alt="The sparkle image" /><br />
Make sure the Asset Name in the <strong>Properties</strong> pane is &#8220;Flare&#8221; and the <strong>Build Action</strong> is &#8221;Compile&#8221;. We&#8217;re now ready to add some code to the project!</p>
</div>
<div id="AddingSparkles">
<h2>Adding Sparkles</h2>
<p>Open the file &#8220;Game1.cs&#8221; in your project, and right at the top of the <strong>Game1 </strong>class, add the following code:</p>
<pre>public class Game1 : Microsoft.Xna.Framework.Game
{
<span style="color: #008000;">    </span><strong><span style="color: #008000;">static Random random = new Random();
    class Sparkle
    {
        public Vector2 position;
        public Vector2 speed;
        public float rotation; // in radians
        public Color color;
        public long birthtime;

        public Sparkle(float x, float y, long time)
        {
            position = new Vector2(x, y);
            rotation = (float)(random.NextDouble() * 2.0 * Math.PI);
            color = Color.White;
            birthtime = time;
        }</span>
    <span style="color: #008000;">}</span></strong>
...</pre>
<p>First, we&#8217;re just setting up the random number generator, which we&#8217;ll be using when setting up sparkle rotation. Then, we create a class to hold information about each sparkle: its position, speed, rotation, color (which will be used to fade the sparkles), and birthtime (also used for fading).</p>
<p>Then, we&#8217;ll create a constructor that takes a position in screen coordinates (x,y), and a birthtime. We&#8217;re using the same image for all of the sparkles, so there&#8217;s no need to save any image-specific data in the sparkle class.</p>
<p>Notice that we use a random rotation for each sparkle when it&#8217;s created. This helps, since we&#8217;re using the same image, from keeping every sparkle look exactly like the others when it appears. <strong>Random.NextDouble</strong> produces a number between zero and one, so by multiplying it by 2*PI, we can get a random rotation in radians.</p>
<p>Next, we define some constants that will be used to fade sparkles. We&#8217;ll define a maximum lifetime for each sparkle, the maximum number of sparkles allowed on the screen at once, an acceleration factor for sparkle movement, and a factor to control how quickly the sparkles will fade out.</p>
<p>Add this code beneath the definition of the <strong>Sparkle</strong> class:</p>
<pre><span style="color: #008000;"><strong>const int SPARKLELIFE = 4000; // ticks
const int MAXSPARKLES = 100; // maximum number of sparkles, for performance tuning.
const float ACCELFACTOR = 0.01f;
const float FADEFACTOR = 255.0f / SPARKLELIFE;</strong></span></pre>
<p>We&#8217;ll now add a few variables to the class to hold the sparkle data. In <strong>Game1</strong>&#8216;s class data section, where the <em>graphics</em> and <em>spriteBatch </em>members are declared, add new data members called <em>flareImage</em>, <em>flareOffset</em>, and <em>sparkles</em>, as shown:</p>
<pre>GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
<span style="color: #008000;"><strong>Texture2D flareImage;
Vector2 flareOffset;
List&lt;Sparkle&gt; sparkles;</strong></span></pre>
</div>
<div id="LoadingSparkles">
<h2>Loading the Sparkle Image</h2>
<p>There&#8217;s one last thing we&#8217;ll need to do before creating and drawing sparkles, and that&#8217;s loading the sparkle image into the <strong>Texture2D</strong> that we&#8217;ve declared for it.</p>
<p>In <strong>Game1.LoadContent</strong>, add lines to load the flare image and set the flare offset:</p>
<pre>// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);<span style="color: #008000;">
<strong>flareImage = this.Content.Load&lt;Texture2D&gt;("Flare");
flareOffset = new Vector2(
    flareImage.Width * 0.5f, flareImage.Height * 0.5f);</strong></span></pre>
<p>The <em>flareOffset</em> will be used to rotate the sparkles, and is set to the middle of the sparkle texture.</p>
</div>
<div id="CreatingSparkles">
<h2>Creating Sparkles with Touch</h2>
<p>Now, let&#8217;s add some code that uses touch to create sparkles. We&#8217;ll allow the user to touch the screen to create a sparkle, or to create many sparkles by touching multiple points at the same time or by dragging a touch-point.</p>
<p>All of the code in this section will go into <strong>Game1.Update</strong>.</p>
<p>First, we&#8217;ll get the total game time as a <em>long</em>. The <strong>GameTime</strong> structure that&#8217;s passed to <strong>Update</strong> contains a number of members for different timing purposes. Since the sparkle birth-time is something that we&#8217;ll be tracking starting from the beginning of app launch, we&#8217;ll use the <strong>TotalGameTime</strong> member to get a timestamp for sparkle creation. This will allow us to fade the sparkles out over time, and to remove them from the list once they&#8217;ve faded.</p>
<p>To add a sparkle to a location touched on the screen, we&#8217;ll get the <strong>TouchCollection</strong> that contains all of the touch points (represented by the <strong>TouchLocation</strong> structure) that are active (either <strong>Pressed</strong> or <strong>Moved</strong>) this  frame. Iterating through the list and adding sparkes at the <strong>TouchLocation.Position</strong> points is simple, as shown in the following code:</p>
<p>Add the following code to <strong>Update</strong>:</p>
<pre>// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
   this.Exit();
}

<strong><span style="color: #008000;">long ttms = (long)gameTime.TotalGameTime.TotalMilliseconds;
<span style="color: #008000;">
</span></span><span style="color: #008000;">// Process touch events
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
      // add sparkles based on the touch location
      sparkles.Add(new Sparkle(tl.Position.X,
               tl.Position.Y, ttms));
}</span></strong>
</pre>
<p>We call <strong>TouchPanel.GetState</strong> to get the <strong>TouchCollection</strong>, and then simply iterate through each <strong>TouchLocation</strong>, passing the X and Y locations and the timestamp to <strong>Sparkle</strong>&#8216;s constructor to add a new sparkle to the list.</p>
<p>We now have the code to add sparkles, but there&#8217;s still a problem that we need to solve: if you simply continue to add sparkles, you&#8217;ll soon have many thousands of sparkles on the list, which could really drag down your framerate.</p>
<p>To keep the frame-rate up, we should limit the number of objects that are being updated and drawn each frame. We&#8217;ll impose a limit, represented by <em>MAXSPARKLES</em>, on the number of sparkles that can be in the list at once, by removing sparkles from the beginning of the list if there are too many sparkles in existence. Right after adding a new sparkle, add code to remove the sparkles:</p>
<pre>foreach (TouchLocation tl in touchCollection)
{
   // add sparkles based on the touch location
    sparkles.Add(new Sparkle(tl.Position.X,
             tl.Position.Y, ttms));
<span style="color: #008000;">
<strong>   // if there are too many sparkles, remove from the head.
   if (sparkles.Count &gt; MAXSPARKLES)
   {
      sparkles.RemoveAt(0);
   }</strong></span>
}
</pre>
<p><strong>Note:</strong> The sparkles are removed from the front of the list since these are the oldest sparkles: new sparkles are always added at the end. It would be quite unexpected (in other words, it would seem like a bug) from the user&#8217;s point-of-view if just-created sparkles suddenly disappeared!</p>
</div>
<div id="DrawingSparkles">
<h2>Drawing the Sparkles</h2>
<p>We now have the ability to add sparkles to our world, but unless we draw them on the screen, nobody (but you) will know they exist!</p>
<p>Drawing the sparkles on the screen is a simple matter of iterating through the list we&#8217;ve created, and drawing the Flare image at the location of each sparkle. In <strong>Game1.Draw</strong>, add the following code:</p>
<pre>protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(<span style="color: #008000;"><strong>Color.Black</strong></span>);
<span style="color: #008000;">    <strong>spriteBatch.Begin();
    // draw the sparkles
    foreach(Sparkle s in sparkles)
    {
        // when drawing with a specified origin, the origin affects
        // both the rotation and position parameters.
        spriteBatch.Draw(
            flareImage, s.position, null, s.color, s.rotation,
            flareOffset, 1.0f, SpriteEffects.None, 0);
    }
    spriteBatch.End();
<span style="color: #000000;">...</span></strong></span></pre>
<p>There are a number of <strong>SpriteBatch.Draw</strong> overloads provided in Game Studio, but we&#8217;ll use the version shown above since we&#8217;ll eventually want to change the color and rotation of each sparkle. For now, the color will always be <strong>Color.White </strong>and the rotation will always be zero.</p>
<p>The default template code for an XNA Game Studio game clears the screen to <strong>Color.CornflowerBlue</strong>. While this is a good color to use for debugging purposes, I&#8217;ve designed the sparkle image to look best on a black background. The clear color was changed to <strong>Color.Black</strong> to complement this.</p>
<p>If you&#8217;d like, compile and run the application on your Zune HD. You should be able to draw sparkles on the screen with your fingertips, and watch them disappear as you pass the MAXSPARKLES threshhold.</p>
</div>
<div id="FadingSparkles">
<h2>Fading the Sparkles</h2>
<p>Although the above code removes sparkles from the list if there are too many, it&#8217;s likely that the user will notice sparkles suddenly vanishing from the display. It&#8217;s much nicer if we fade them out, so the user feels that the eventual dissapearance of the sparkle is natural within the design of the world we&#8217;re creating.</p>
<p>To do this, we&#8217;ll make use of the sparkle&#8217;s timestamp, comparing it to the current timestamp to fade the sparkle depending on its age. We&#8217;ll place this code directly after the code, entered in the previous section, that creates the sparkles in the Update method.</p>
<pre><span style="color: #008000;"><strong>// update the sparkles. We count from the end of the list in case
// we need to remove a sparkle (without upsetting the order).
for (int i = sparkles.Count - 1; i &gt;= 0; i--)
{
    Sparkle s = sparkles[i];
    if ((ttms - s.birthtime) &gt; SPARKLELIFE)
    {
        sparkles.RemoveAt(i);
        continue;
    }
    else
    {
        // fade the sparkle a bit, depending on its age.
        s.color.A = (byte)(255.0f - (ttms - s.birthtime) * FADEFACTOR);
    }
}</strong></span></pre>
<p>If the sparkle has passed the end of its lifetime, it&#8217;s removed from the list.</p>
<p>Rebuild and deploy your updated application. You should now see the sparkles fading!</p>
</div>
<div id="AddingMotion">
<h2>Adding Motion with the Accelerometer</h2>
<p>We&#8217;ll now use the Zune HD&#8217;s accelerometer to move the sparkles around on the screen, and add a little speed-based rotation to the sparkles to make them more interesting.</p>
<p>To do this, directly after the total game time calculation, get the elapsed game time in milliseconds, and then get the accelerometer state as shown:</p>
<pre>long ttms = (long)gameTime.TotalGameTime.TotalMilliseconds;

<span style="color: #008000;"><strong>// elapsed time will be used in updating movement
float etms = gameTime.ElapsedGameTime.Milliseconds;
</strong></span>
<span style="color: #008000;"><strong>// grab the accelerometer state.  This will be used for sparkle
// movement.</strong>
</span><span style="color: #008000;"><strong>AccelerometerState accelState = Accelerometer.GetState();</strong></span></pre>
<p>The elapsed game time will be used during sparkle movement. Since I&#8217;m only interested in the elapsed time since the last frame, and I&#8217;m not ever expecting this to be more than a second, I use only <strong>ElapsedGameTime.Milliseconds</strong>.</p>
<p>Next, inside the loop used to update the sparkles, right below the code to fade the sparkles, add the following lines:</p>
<pre>// fade the sparkle a bit, depending on its age.
s.color.A = (byte)(255.0f - (ttms - s.birthtime) * FADEFACTOR);

<span style="color: #008000;"><strong>// accelerate the sparkle depending on accelerometer action.
s.speed.X += accelState.Acceleration.X * ACCELFACTOR;
s.speed.Y += -accelState.Acceleration.Y * ACCELFACTOR;

// move the sparkle based on its speed.
s.position.X += s.speed.X * etms;
s.position.Y += s.speed.Y * etms;
s.rotation += s.speed.Length() * ACCELFACTOR * etms;</strong></span></pre>
<p>We&#8217;re adding speed to each sparkle based on the current state of the accelerometer, and then updating its position based on its speed. Additionally, we&#8217;re adding a bit of rotation depending on the magnitude of the resulting speed vector. As simple as it is, the effect looks fairly nice.</p>
<p>No changes are needed to the drawing code. Once you rebuild and deploy, you should now see the sparkles moving as you tilt the device.</p>
</div>
<div id="Next">
<h2>What&#8217;s Next?</h2>
<p>The Sparkle application is fairly complete, but for a user who doesn&#8217;t know how it works, it might seem a bit mystifying: unless you touch the screen once it starts, you only see a black screen.</p>
<p>It would be nice to have some instructions pop up as the application starts, and perhaps a way to &#8220;freeze&#8221; the sparkle fading so that the user has more time to play with the sparkles as they slide around the screen.</p>
<p>In the next part of the tutorial, I&#8217;ll add a GUI that consists of an instructions screen and a menu that appears at the bottom of the screen.</p>
<p><strong>Continue with</strong>: <a href="http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-2/" target="_self">Making the Zune HD Sparkle with XNA Game Studio 3.1 &#8211; Part 2</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.abstrys.com/2010/02/making-the-zune-hd-sparkle-with-xna-game-studio-3-1-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

