<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts</link>
    <language>en</language>
    <pubDate>Mon, 20 May 2013 04:00:36 GMT</pubDate>
    <lastBuildDate>Mon, 20 May 2013 04:00:36 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>18</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Intro to XNA Part 3: More Sound and adding Text</title>
      <description><![CDATA[
<p></p>
<p>In this article, The ZMan walks through the steps required to&nbsp;add some more sound effects and text output&nbsp;to&nbsp;TinyTennis, a Pong clone.<br>
The ZMan (Andy Dunn)<br>
<a href="http://www.thezbuffer.com/">TheZBuffer.com</a></p>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free (<a href="http://msdn2.microsoft.com/en-us/xna/bb219592.aspx">Creators Club membership</a> required to deploy to Xbox, additional cost applies)</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualcsharp/download/">Visual C# Express
</a>, <a href="http://msdn.com/xna/">XNA Game Studio Express</a></span></div>
<div class="entry_details"><strong>Hardware: </strong>Xbox360<span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download:</b> <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=294299">
Starting point C# code</a>, <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=304187">
Final C# code</a></div>
<div class="entry_details">&nbsp;</div>
<p>Welcome to part&nbsp;3 of the introduction to XNA series.&nbsp;<a href="http://blogs.msdn.com/coding4fun/archive/2007/03/23/1938626.aspx">Last time</a> you converted the TinyTennis sample to&nbsp;run on the Xbox 360 and added the sound effects back in.&nbsp;This time I will
 cover some more audio effects and also add the scores back in as well as explain some of the background behind XACT and font rendering in the XNA Framework.
</p>
<p>Before you go any further I need to explain how XNA works on the Xbox 360. Microsoft created a version of the .Net compact framework that runs on the Xbox 360, as well as Xbox versions of the XNA assemblies. To get these assemblies onto your Xbox 360 and
 enable deployment of XNA framework requires that you join the <a href="http://msdn2.microsoft.com/en-us/xna/bb219592.aspx">
Creators Club</a>&nbsp;which has a cost associated. The changes you will make for this article will work on the PC too, but you will not be able to play on the Xbox 360 without this. Microsoft have provided a video to help you get this installed:
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=63E75972-4AD0-4CB2-B214-2CA4D7AB9E41">
Getting Started with the XNA Creators Club</a>. </p>
<p>Note that XNA Game Studio Express&nbsp;has an upgrade. The 1.0 Refresh was released on April 24th 2007. The code for this and future columns will be based on the updated version so if you have not already upgraded then go and
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=12ADCD12-7A7B-4413-A0AF-FF87242A78DE&amp;displaylang=en">
download now</a>.&nbsp;Then read about the <a href="http://blogs.msdn.com/xna/archive/2007/03/08/announcing-the-xna-game-studio-express-update.aspx">
new features</a> and <a href="http://www.thezbuffer.com/articles/486.aspx">check out the API changes</a>.
</p>
<h3>One Quick Audio Fix</h3>
<p>There's an interesting bug in the build from last time which is hard to reproduce. Occasionally the code will crash with a InstancePlayLimitException. The reason for this is due to a) the default options in XACT and b) a possible bug in the XNA Framework.
 The bug occurs when the ball bounces twice very close together like when the bat is near the top or bottom of the screen. The reason is that the default sound settings in XACT limit each cue to play a single instance. If the cue is called a second time and
 the first is still playing then XACT should just not play the second sound. However the XNA framework sees this as something that requires an exception to be thrown. You can see the discussion about this item in the
<a href="http://forums.xna.com/thread/7394.aspx">XNA Audio forums</a>. </p>
<p>To fix this you should change the sound cue to allow multiple instances. Open up the .xap project from the project folder and open the sound bank window and make the following changes.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image07.png"><img height="174" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb5.png" width="409"></a>
</p>
<p>Now you can have as many instances of the beep sound playing as you want. </p>
<h3>Changing the pitch of the sound</h3>
<p>If you followed the sound tutorial from last time you would probably be thinking &quot;wow, that's a LOT of work compared to calling the .Net SoundPlayer class&quot;. Instead of 2-3 lines of code you had to create special files in a tool, package those files in your
 project and after all of that it was still more lines of code to play the sound. The only obvious advantage is that you can play more than one sound at a time.</p>
<p>So I would like to show you one of the cool things you can do using XACT - changing the pitch of the sound as the ball bouncing speeds up. In the past the audio designer would have had to describe the effect to the developer, the developer would have to
 get a sound library or write code to do the sound manipulation and each change would have had several iterations before everyone was happy. With XACT the sound designer has all of the control and the only thing the developer has to do is pass in a single variable.</p>
<p>First, open up the XACT project that you created last time. Don't forget to use the version of the XACT editor that is in the XNA Game Studio Express folder. Since XACT often changes with the DirectX SDK you need to use the one which is compatible.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image011.png"><img height="200" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb7.png" width="352"></a>
</p>
<p>When the Variable Settings dialog appears all you need to do is rename the variable to BallSpeed.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image021.png"><img height="291" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb11.png" width="819"></a>
</p>
<p>You have just created a variable which will be visible from your code. When you change the value of that variable you want it to have an effect on the sound. To create the effect you need to create an
<a href="http://msdn2.microsoft.com/en-us/library/bb172307.aspx">RPC Preset</a>. RPC in this case stands for Runtime Parameter Control and allows you to manipulate the cues based on an input value. Create the RPC Preset by right clicking the node in the project
 tree:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image022.png"><img height="148" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb12.png" width="266"></a>
</p>
<p>For now ignore the dialog that appears I will get back to that in a moment. Right click the RPC Preset node that just created and rename it to BallSpeedEffect.</p>
<p>To associate a sound with an RPC preset you must drag and drop the sound onto the preset.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image025.png"><img height="143" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb15.png" width="442"></a></p>
<p>You should see that the BallSpeedEffect dialog box now shows 'beep' at the top. While you are looking at the dialog change the Parameter to Sound::Pitch&nbsp;- because we want to change the pitch based on the speed - and the Variable to BallSpeed - which is what
 we will pass in to the program.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image029.png"><img height="135" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb17.png" width="502"></a>
</p>
<p>Now the question you need to ask yourself is 'how do I want the pitch to vary based on the input variable?'. Since XACT is a sound designers tool it allows you to set this relationship in great detail. But to know if you have it right means you have to be
 able to listen to the sound. The architecture of XACT means that you cannot play sounds directly from the tool but you have to run a separate auditioning application before the 'Play' buttons will work. You can find the XACT Auditioning Utility in the same
 place as you found the XACT editor in the Game Studio Express folder.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image033.png"><img height="175" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb19.png" width="229"></a>
</p>
<p>When you run this tool you will just see a console window appear. Minimize it and forget it's there.</p>
<p>Now you can use the control buttons on the top of the dialog to audition the beep sound.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image037.png"><img height="177" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb21.png" width="378"></a>
</p>
<p>Right now all you will hear is the normal beep that you heard in the game. But now comes the fun part. Press the 'repeat' button and then the 'play' button so that you hear the beep repeatedly. Then in the section below you can move the black dots up and
 down to represent the curve that relates the input variable to the output variable. You can drag the dotted line left and right to simulate passing in different values to the BallSpeed variable and you will hear the effect in real time. This diagram is made
 from multiple screen shots (should be obvious since there are 3 mouse pointers) but you should get the general idea.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image040.png"><img height="249" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb22.png" width="487" border="0"></a>
</p>
<p>I have created a curve where an input of 0 will drop the pitch by a factor of 8 and an input of 100 will raise the pitch by a factor of 8. You can add points to the curve, make flat parts - whatever you want.</p>
<p>So the work in XACT is done. Save the project and open the C# solution file.</p>
<p>Firstly you need to speed the ball up when it bounces off each bat. In Ball.cs add the following 2 lines of code:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="rem">//Bounce off the bats</span>
<span class="kwrd">if</span> ((Velocity.X &lt; 0 &amp;&amp; collision(_player1))
    || (Velocity.X &gt; 0 &amp;&amp; collision(_player2)))
{
    <span class="rem">//The ball speeds up with each bat bounce</span>
    Velocity.X = Velocity.X * 1.05f;
    Velocity.Y = Velocity.Y * 1.05f;</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>Finally you need to translate the ball velocity into a variable in the range 0-100 to pass into XACT. The code to play the sound changes a little too.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> playBounceSound()
 {
     <span class="rem">//Calculate a variable in the range 0-100 to pass to the sound engine</span>
     <span class="kwrd">float</span> ballSpeed = (<span class="kwrd">float</span>)Math.Max(Math.Min(((Math.Abs(Velocity.X) &#43; Math.Abs(Velocity.Y)) /2.0  - _initialSpeed)/4 , 100f), 0f);

     Cue _beep = TinyTennis.soundbank.GetCue(<span class="str">&quot;beep&quot;</span>);
     _beep.SetVariable(<span class="str">&quot;BallSpeed&quot;</span>, ballSpeed);
     _beep.Play();
 }</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>&nbsp;</p>
<p>Run the app and listen to the pitch of the bounce increase as the ball speed increases.</p>
<h3>Adding the Scores</h3>
<p>I'm sure many of you are&nbsp;wondering why its taken this long to add the scores back into the game, after all displaying some text is usually
<a href="http://www.roesler-ac.de/wolfram/hello.htm">the first program people write</a> in any new&nbsp;computer language or framework. The big problem is (or rather WAS) the lack of text support in the XNA Framework. Text rendering on windows is done using the
<a href="http://www.microsoft.com/typography/default.mspx">Truetype font system</a> which is part of
<a href="http://msdn2.microsoft.com/en-us/library/ms536795.aspx">GDI</a> and exposed to managed developers through the
<a href="http://msdn2.microsoft.com/en-us/library/system.drawing.aspx">System.Drawing</a> APIs. If you have used
<a href="http://msdn2.microsoft.com/en-us/library/bb173961.aspx">D3DXFont</a> from native DirectX or its
<a href="http://msdn2.microsoft.com/en-us/library/bb296709.aspx">managed wrapper</a> then you would be forgiven for thinking that DirectX also understands fonts. In reality the D3DX code uses GDI to render the requested font into a bitmap which is then used
 by DirectX to render the text. In the case of the <a href="http://msdn2.microsoft.com/en-us/library/bb206236.aspx">
Text3D sample</a> GDI is also used to get the outline description of the font and&nbsp;create a 3d model from that data.&nbsp;Since the DirectX we know and love only runs on windows, having a dependency on GDI is not an issue. However whatever the core OS of the Xbox
 is (its not something Microsoft make public) it certainly doesn't have any Truetype or GDI support - its just not something professional game developers need and the Xbox 360 is a specifically focused piece of hardware. This would make the font parts of D3DX
 very hard to implement and, in fact, D3DX is also not supported on the Xbox 360 version of DirectX.</p>
<p>This left the XNA Framework team with a dilemma - how can you support fonts on both Windows and Xbox 360 given that only one platform has the font rendering technology. For the first version they did not have time to implement a solution but within weeks
 several 3rd parties provided solutions such as bitmap based <a href="http://www.nuclex.org/news/2007/01/16/xna-font-rendering-component">
Nuclex Fonts</a>&nbsp;and <a href="http://www.ziggyware.com/readarticle.php?article_id=44">
XNA Font Creator</a>&nbsp;and&nbsp;vector based <a href="http://blogs.msdn.com/manders/archive/2007/01/12/stroke-based-text-rendering-in-xna.aspx">
stroke based fonts</a>. The bitmaps versions do a similar job to the D3DX implementation, except they create the texture either in the compilation process or in a separate tool that you have to run before you run your application. Eventually Microsoft released
 a <a href="http://creators.xna.com/Headlines/developmentaspx/archive/2007/02/13/Font-Sample.aspx">
Font Sample</a> themselves which created a content pipeline add in to create the bitmap font at compile time. In the Game Studio Express refresh they included font support in the base product. It works in a very similar manner to the previously release font
 sample and integrates into the SpriteBatch API that you have used in previous columns.</p>
<p>So after that history lesson how do we actually add the scores to TinyTennis? Thankfully the XNA Framework guys have made it very easy.</p>
<p>&nbsp;</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image044.png"><img height="383" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image0_thumb24.png" width="640"></a>
</p>
<p>Start by adding a new item to your project. From the dialog choose the new Sprite Font item and call it PongScore. After you have created it you will see an XML file appear that describes the font you want to make.</p>
<p>Change the name to the name of the font you want to use, the size and the style. In addition since you only need 0-9 you can tell Game Studio Express to only use&nbsp;characters 48-57. Your XML file should look similar to this: (I've removed the comments for
 size here)</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">    <span class="kwrd">&lt;</span><span class="html">FontName</span><span class="kwrd">&gt;</span>Comic Sans MS<span class="kwrd">&lt;/</span><span class="html">FontName</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">Size</span><span class="kwrd">&gt;</span>48<span class="kwrd">&lt;/</span><span class="html">Size</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">Spacing</span><span class="kwrd">&gt;</span>2<span class="kwrd">&lt;/</span><span class="html">Spacing</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">Style</span><span class="kwrd">&gt;</span>Bold<span class="kwrd">&lt;/</span><span class="html">Style</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">CharacterRegions</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">CharacterRegion</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Start</span><span class="kwrd">&gt;</span>&amp;#48;<span class="kwrd">&lt;/</span><span class="html">Start</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">End</span><span class="kwrd">&gt;</span>&amp;#57;<span class="kwrd">&lt;/</span><span class="html">End</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">CharacterRegion</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">CharacterRegions</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>After you have saved it don't forget to drag and drop the PongScore.spritefont into the TinyTennis360 project too.
</p>
<p>To draw the font you use a SpriteBatch - which we already have around from drawing the bats and ball - and a SpriteFont. Declare the SpriteFont at the class level in TinyTennis.cs</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> SpriteFont _font;
</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>Load the font in LoadGraphicsContent()</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">if</span> (loadAllContent)
{
....
    _font = content.Load&lt;SpriteFont&gt;(<span class="str">&quot;PongScore&quot;</span>);
....
}
</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>and draw it with the new DrawText overload in the Draw() function</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="rem">//Draw the scores</span>
SpriteBatch.Begin();
SpriteBatch.DrawString(_font, gameState.Player1Score.ToString(), <span class="kwrd">new</span> Vector2(300, 30), Color.Red);
SpriteBatch.DrawString(_font, gameState.Player2Score.ToString(), <span class="kwrd">new</span> Vector2(470, 30), Color.Green);
SpriteBatch.End();
</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>Notice the color overloads to give each player a different color score. </p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image046.png"><img height="186" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/2307521/image045.png" width="240" border="0"></a>
</p>
<p>That's all for this time folks.... please send me feedback if you have any ideas, find bugs, or have requests about which bits of XNA you would like tutorials for.
</p>
<p>&nbsp; </p>
<p>The ZMan runs the #1 Managed DirectX &amp; XNA&nbsp;community website <a href="http://www.TheZBuffer.com">
http://www.TheZBuffer.com</a>.&nbsp;If you have a question for the ZMan that you would like to se answered in a future column then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>.</p>
<p>Copyright © 2007 ZBuffer Games, LLC</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:a864530364d441bab9919e7600d43c7e">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-3-More-Sound-and-adding-Text</comments>
      <itunes:summary>
 
In this article, The ZMan walks through the steps required to&amp;nbsp;add some more sound effects and text output&amp;nbsp;to&amp;nbsp;TinyTennis, a Pong clone.
The ZMan (Andy Dunn)
TheZBuffer.com 
Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free (Creators Club membership required to deploy to Xbox, additional cost applies)
Software: Visual C# Express
, XNA Game Studio Express
Hardware: Xbox360
Download: 
Starting point C# code, 
Final C# code
&amp;nbsp;
Welcome to part&amp;nbsp;3 of the introduction to XNA series.&amp;nbsp;Last time you converted the TinyTennis sample to&amp;nbsp;run on the Xbox 360 and added the sound effects back in.&amp;nbsp;This time I will
 cover some more audio effects and also add the scores back in as well as explain some of the background behind XACT and font rendering in the XNA Framework.
 
Before you go any further I need to explain how XNA works on the Xbox 360. Microsoft created a version of the .Net compact framework that runs on the Xbox 360, as well as Xbox versions of the XNA assemblies. To get these assemblies onto your Xbox 360 and
 enable deployment of XNA framework requires that you join the 
Creators Club&amp;nbsp;which has a cost associated. The changes you will make for this article will work on the PC too, but you will not be able to play on the Xbox 360 without this. Microsoft have provided a video to help you get this installed:

Getting Started with the XNA Creators Club.  
Note that XNA Game Studio Express&amp;nbsp;has an upgrade. The 1.0 Refresh was released on April 24th 2007. The code for this and future columns will be based on the updated version so if you have not already upgraded then go and

download now.&amp;nbsp;Then read about the 
new features and check out the API changes.
 
One Quick Audio Fix
There&#39;s an interesting bug in the build from last time which is hard to reproduce. Occasionally the code will crash with a InstancePlayLimitException. The reason for this is due to a) the default options in XACT and b) a possible bug in the XNA Frame</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-3-More-Sound-and-adding-Text</link>
      <pubDate>Sat, 28 Apr 2007 00:11:29 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-3-More-Sound-and-adding-Text</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/2307521_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/2307521_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-3-More-Sound-and-adding-Text/RSS</wfw:commentRss>
      <category>Gaming</category>
    </item>
  <item>
      <title>Intro to XNA Part 2: Running Tiny Tennis on the Xbox 360</title>
      <description><![CDATA[
<p>In this article, The ZMan walks through the final steps required to get TinyTennis, a Pong clone, running on your Xbox 360.<br>
The ZMan (Andy Dunn)<br>
<a href="http://www.thezbuffer.com/">TheZBuffer.com</a></p>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free (<a href="http://msdn2.microsoft.com/en-us/xna/bb219592.aspx">Creators Club membership</a> required to deploy to Xbox, additional cost applies)</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualcsharp/download/">Visual C# Express
</a>, <a href="http://msdn.com/xna/">XNA Game Studio Express</a></span></div>
<div class="entry_details"><strong>Hardware: </strong>Xbox360<span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download:</b> <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=265223">
Starting point C# code</a>, <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=294299">
Final C# code</a></div>
<div class="entry_details">&nbsp;</div>
<p>Welcome to part 2 of the introduction to XNA series.&nbsp;<a href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">Last time</a> we converted the TinyTennis sample to use the XNA framework&nbsp;for rendering and keyboard input. However at the time&nbsp;that
 article was written deployment was not available on the Xbox 360. In this article you will make additional changes to the project to enable the game to be deployed and played on your Xbox 360.
</p>
<p>Before you go any further I need to explain how XNA works on the Xbox 360. Microsoft created a version of the .Net compact framework that runs on the Xbox 360, as well as Xbox versions of the XNA assemblies. To get these assemblies onto your Xbox 360 and
 enable deployment of XNA framework requires that you join the <a href="http://msdn2.microsoft.com/en-us/xna/bb219592.aspx">
Creators Club</a>&nbsp;which has a cost associated. The changes you will make for this article will work on the PC too, but you will not be able to play on the Xbox 360 without this. Microsoft have provided a video to help you get this installed:
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=63E75972-4AD0-4CB2-B214-2CA4D7AB9E41">
Getting Started with the XNA Creators Club</a> </p>
<p>Some people have asked why I am using such a simple game for these articles. My reasoning is that I do not want to introduce many new things at the same time. TinyTennis is a very simple game and the GDI version has been on MSDN for a long time now and is
 well documented so I do not need much explanation. Future articles will use more advanced code such as the SpaceWar starter kit.
</p>
<h3></h3>
<h3>Errata for part 1</h3>
<p>Firstly an update to <a href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">
part 1</a>. In the rush to get the article out at launch date I converted all the GDI PointF structs into XNA Point structs. This meant that everything was stored as integers rather than floating point values. The rounding is not noticeable in a game this simple,
 but it was incorrect. The correct thing to do was convert to XNA Vector2 structs and this has been corrected in
<a href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">the article</a> and the
<a href="http://channel9.msdn.com/ShowPost.aspx?PostID=265223">code for part 1</a>.
</p>
<h3>Making it work with Gamepads</h3>
<p>Those of you with an Xbox 360 will notice that there is no keyboard so controlling the paddles will be a problem. In fact the Xbox 360 does support a standard USB keyboard if you plug one in, its just that very few games look for this input device so there
 is little point in coding for it and certainly no point in mandating it. All Xbox 360 games of course work with the gamepads and TinyTennis will be no exception.
</p>
<p>Xbox 360 gamepads work on the PC as well as on the Xbox. If you have wired controllers you can just plug them in to a vacant USB port and let Windows download the drivers. If you have wireless controllers then you need to buy the wireless controller adapter
 for windows. Note that the charging pack looks like it has a USB connection but that is purely to take electricity to charge the controller - it won't allow you to use the controller on Windows. In addition since the XNA framework only supports the XInput
 API you can <strong>ONLY</strong> use controllers that support this API. In general right now this is Xbox 360 controllers. Any older controllers rely on the DirectInput API which is not available in the XNA framework.
</p>
<p>Reading the gamepad is as simple as reading the keyboard in XNA. You simple get the current state of a particular gamepad using the PlayerIndex enumeration (one, two, three or four corresponding to the players) and then read strongly named properties from
 the gamepad. </p>
<p>Firstly you need to know which player controls each bat so add a PlayerIndex field to bat.cs and modify the constructor to take a PlayerIndex:</p>
<p>&nbsp;</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> PlayerIndex _playerIndex;</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>&nbsp;</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">public</span> Bat(<span class="kwrd">int</span> x, Keys up, Keys down, <span class="kwrd">float</span> minPosition, <span class="kwrd">float</span> maxPosition, PlayerIndex playerIndex)
    : <span class="kwrd">base</span>()
{
    initialize(x, minPosition, maxPosition);

    <span class="rem">//Keys to control this sprite </span>
    _upKey = up;
    _downKey = down;

    _playerIndex = playerIndex;
    _isHuman = <span class="kwrd">true</span>;
}
</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>When the bat is created in the constructor of TinyTennis.cs you need to pass in the correct PlayerIndex for each bat (note player 2 is the commented out line)</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="rem">//Create the bat Sprites - they need the keyboard controls and the gameplay area limits</span>
_player1 = <span class="kwrd">new</span> Bat(30, Keys.Q, Keys.A, 0, Window.ClientBounds.Height, PlayerIndex.One);

<span class="rem">//use this line for a second human player</span>
<span class="rem">//_player2 = new Bat(Window.ClientBounds.Width - 30 - Bat.Width, Keys.P, Keys.L, 0, Window.ClientBounds.Height, PlayerIndex.Two);</span>
</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>Finally change the humanMove function in bat.cs to read the gamepad state for the correct gamepad.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> humanMove()
{
    KeyboardState keyState = Keyboard.GetState();
    GamePadState padState = GamePad.GetState(_playerIndex);

    <span class="kwrd">double</span> velocity = 0.0;
    <span class="rem">//Set the velocity of the sprite based on which keys are pressed</span>
    <span class="kwrd">if</span> (keyState.IsKeyDown(_upKey) || padState.DPad.Up == ButtonState.Pressed)
    {
        velocity &#43;= -_speed;
    }
    <span class="kwrd">if</span> (keyState.IsKeyDown(_downKey) || padState.DPad.Down == ButtonState.Pressed)
    {
        velocity &#43;= _speed;
    }
    Velocity.Y = (<span class="kwrd">int</span>)velocity;
}</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>&nbsp;</p>
<h3>Replacing Windows Sound with XACT</h3>
<p>TinyTennis only has one sound for when the ball bounces. The code currently uses the SoundPlayer class from System.Media. Unfortunately System.Media is one of the assemblies which is not availalbe in the version of the .Net framework on the Xbox 360. The
 only audio API available on the Xbox is called XACT and its exposed in the Microsoft.Xna.Framework.Audio namespace in the XNA framework.</p>
<p>In addition to being the name of the API, XACT also contains a fairly complex sound management tool. In AAA titles the sound guy on the team uses XACT to create a bank of sounds that the programmer can simply play by referring to a 'cue'. The idea behind
 it is to separate the work the audio guy does away from the programmer in the same way as a 3D modeling tool allows an artist to work away from the programmer. If this sounds too complex just to play the bounce sound then you are right - XACT is overkill for
 this. But its the only way to play sounds at the moment, and thankfully you do not need to learn very much XACT to be able to play a WAV file.</p>
<p>Start by running the XACT tool from the start menu. Note that you <strong>MUST</strong> use the version of XACT that ships with XNA Game Studio Express and not one that you may find in a DirectX SDK. The file formats for XACT projects changes almost every
 SDK release and the XNA framework only understands the one it was shipped with. Also note that if you are running on Vista you should
<a href="http://letskilldave.com/archive/2007/02/08/Getting-XNA-Game-Studio-Express-to-run-in-Windows-Vista.aspx">
follow the instructions on Dave's blog</a> to get it to work, and also set it to run as Admin. A future release of XNA Game Studio Express will make everything compatible with Vista.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image01.png"><img height="152" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0.png" width="240" border="0"></a></p>
<p>You will see the XACT window:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image02.png"><img height="480" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb.png" width="572" border="0"></a>
</p>
<p>For TinyTennis you do not need to understand most of this. However there are 2 concepts you need to grasp:</p>
<ol>
<li>Wavebank: This contains the raw sound files </li><li>Soundbank: This contains the 'cues' that you, as the programmer, will play.</li></ol>
<p>In the case of TinyTennis the 'cue' will just play the raw sound file but XACT gives an audio engineer a lot more flexibility than that such as merging multiple sound files, changing the pitch and volume and applying reverb effects.</p>
<p>Create a new wavebank and soundbank by right clicking and selecting New</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image05.png"><img height="98" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb1.png" width="393" border="0"></a>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image09.png">
<img height="77" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb3.png" width="280" border="0"></a>
</p>
<p>You will now see the wavebank and the soundbank windows appear. Add the beep.wav from the project directory by right clicking the wavebank window and selecting Insert Wave Files. In Windows XP you can drag and drop from Windows Explorer into the wavebank
 window.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image012.png"><img height="415" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb4.png" width="407" border="0"></a>
</p>
<p>Then drag the beep from the wave bank window into the top half of the sound bank window (the Sound Name section). Then drag the 'beep' sound into the lower half of the sound bank window (the Cue Name) section. You will end up with something that looks like
 this:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image015.png"><img height="506" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb5.png" width="494" border="0"></a>
</p>
<p>What you have done is created an XACT cue that plays a sound which just contains a single wave file.</p>
<p>Now save the XACT project as TinyTennis.xap in the project folder.</p>
<p>XNA Game Studio Express understands .xap files and will compile&nbsp;correct Windows&nbsp;or Xbox 360 versions when the project is compiled. So the only remaining thing to do is add the .xap to the project. Simple browse and add. Since the .xap file knows which .wav
 files are required you do not need to explicitly reference beep.wav any more so it can be 'excluded from project' (Do not use 'delete' as that will actually remove the file from disc and the .xap file references it).</p>
<p>Playing the sound is a little more complex that the 2 lines of code required with the SoundPlayer class but its much more flexible. For a start you can have more than one sound playing at a time which is not possible with SoundPlayer.</p>
<p>The XACT sound engine needs to be initialized when the game starts up so add the following declarations to TinyTennis.cs (note this was called Game1.cs in part1&nbsp;- I have renamed it for obvious reasons)</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> AudioEngine engine;
<span class="kwrd">private</span> <span class="kwrd">static</span> WaveBank wavebank;
<span class="kwrd">public</span> <span class="kwrd">static</span> SoundBank soundbank;</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>and then initialize the engine inside the Initialize() function</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Initialize()
{
    engine = <span class="kwrd">new</span> AudioEngine(<span class="str">@&quot;tinytennis.xgs&quot;</span>);
    wavebank = <span class="kwrd">new</span> WaveBank(engine, <span class="str">@&quot;wave bank.xwb&quot;</span>);
    soundbank = <span class="kwrd">new</span> SoundBank(engine, <span class="str">@&quot;sound bank.xsb&quot;</span>);</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>In ball.cs&nbsp;you can remove the&nbsp;using statement for&nbsp;System.Media and add in Microsoft.Xna.Framework.Audio. Then remove all of the places that _beep and SoundPlayer are used.</p>
<p>To play the sound using XACT is a single line replacement inside PlayBounceSound()</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> playBounceSound()
{
    TinyTennis.soundbank.PlayCue(<span class="str">&quot;beep&quot;</span>);
}</pre>
<style type="text/css">
<!--
.csharpcode-wrapper, .csharpcode-wrapper 
	{background-color:#f4f4f4;
	border:solid 1px gray;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	margin:20px 0px 10px 0px;
	max-height:200px;
	overflow:auto;
	padding:4px 4px 4px 4px;
	width:97.5%}
.csharpcode-wrapper 
	{border-style:none;
	margin:0px 0px 0px 0px;
	overflow:visible;
	padding:0px 0px 0px 0px}
.csharpcode, .csharpcode .csharpcode .alt
	{background-color:#f4f4f4;
	border-style:none;
	color:black;
	font-family:consolas,'Courier New',courier,monospace;
	font-size:8pt;
	line-height:12pt;
	overflow:visible;
	padding:0px 0px 0px 0px;
	width:100%}
.csharpcode 
	{margin:0em}
.csharpcode .alt
	{background-color:white}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .html
	{color:#800000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .lnum
	{color:#606060}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .rem
	{color:#008000}
.csharpcode .str
	{color:#006080}
-->
</style></div>
<p>&nbsp;Compile and run and after all of that hard work you should be back exactly where you started, with the ball playing a beep sound when it bounces.</p>
<h3>Running TinyTennis on the Xbox 360</h3>
<p>Game Studio Express requires you to have separate projects for Windows and Xbox 360 development. For almost all XNA framework projects the source code is identical between the two versions - any slight differences can be handled using #if XBOX - so maintaining
 2 code trees is almost always more trouble than it is worth. The easiest way to get round this is to create both projects in the same directory so that they can share files in a simple manner. You will still have to remember to add a file to both projects
 when you make a new file but that is a simple drag and drop operation. </p>
<p>Firstly create an empty <strong>Xbox 360&nbsp;Game</strong> project somewhere on your hard drive - its a temporary location so anywhere will do. Then using windows explorer copy the .csproj file into the TinyTennisXNA folder and add it to your solution as a second
 project. It will complain about the source files that are missing but that doesn't matter as we will add our own.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image018.png"><img height="211" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb6.png" width="348" border="0"></a>
</p>
<p>Rename the project to TinyTennis360, remove Game1.cs and then drag and drop all the files from TinyTennisXNA into TinyTennis360 - from within the solution explorer. Even though the files are in the same directory they will get added to the new project. Now
 if you modify bat.cs in one project it automatically gets updated in the other project too. The only thing you have to do to keep in sync is remember to drag and drop any new files if you add them to one of the projects.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image024.png"><img height="504" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb8.png" width="246" border="0"></a>
</p>
<p>Now when you compile it will compile both projects. If you only want to compile the windows or the Xbox one you can select it from the platform drop down on the men bar
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image027.png"><img height="116" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1938626/image0_thumb9.png" width="326" border="0"></a>
</p>
<p>Also remember that now you have 2 projects you need to remember to set the right one to be the startup project by right clicking the project file. You will get confused when it tries to run the Xbox project and deploy when you really wanted to debug the
 windows one. </p>
<p>Now that everything compiles its time to deploy it to the Xbox. Rather than explain how to do it in words and pictures I recommend you take a look at the second half of the
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=63E75972-4AD0-4CB2-B214-2CA4D7AB9E41">
Getting Started with the XNA Creators Club</a>&nbsp;video. If you fast forward to 6:02 you can see a demo of how to create the connection between Game Studio Express and your 360 and how to put your Xbox in receive mode. Once that is done you just hit f5 in Game
 Studio Express and the game will be deployed and run. Depending on what screen resolution you have set on your Xbox the paddles may not appear in the expected place, but the game is still playable. To quit the game on the Xbox 360 press the 'back' button on
 gamepad 1. </p>
<p>&nbsp; </p>
<p>Next time I will cover some additional features for the Xbox version and add the scores back in.
</p>
<p>&nbsp; </p>
<p>The ZMan runs the #1 Managed DirectX &amp; XNA&nbsp;community website <a href="http://www.TheZBuffer.com">
http://www.TheZBuffer.com</a>.&nbsp;If you have a question for the ZMan that you would like to se answered in a future column then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>.</p>
<p>Copyright © 2007 ZBuffer Games, LLC</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:aeb5fb29d50f4830b5ce9e7600d4e142">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-2-Running-Tiny-Tennis-on-the-Xbox-360</comments>
      <itunes:summary>
In this article, The ZMan walks through the final steps required to get TinyTennis, a Pong clone, running on your Xbox 360.
The ZMan (Andy Dunn)
TheZBuffer.com 
Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free (Creators Club membership required to deploy to Xbox, additional cost applies)
Software: Visual C# Express
, XNA Game Studio Express
Hardware: Xbox360
Download: 
Starting point C# code, 
Final C# code
&amp;nbsp;
Welcome to part 2 of the introduction to XNA series.&amp;nbsp;Last time we converted the TinyTennis sample to use the XNA framework&amp;nbsp;for rendering and keyboard input. However at the time&amp;nbsp;that
 article was written deployment was not available on the Xbox 360. In this article you will make additional changes to the project to enable the game to be deployed and played on your Xbox 360.
 
Before you go any further I need to explain how XNA works on the Xbox 360. Microsoft created a version of the .Net compact framework that runs on the Xbox 360, as well as Xbox versions of the XNA assemblies. To get these assemblies onto your Xbox 360 and
 enable deployment of XNA framework requires that you join the 
Creators Club&amp;nbsp;which has a cost associated. The changes you will make for this article will work on the PC too, but you will not be able to play on the Xbox 360 without this. Microsoft have provided a video to help you get this installed:

Getting Started with the XNA Creators Club  
Some people have asked why I am using such a simple game for these articles. My reasoning is that I do not want to introduce many new things at the same time. TinyTennis is a very simple game and the GDI version has been on MSDN for a long time now and is
 well documented so I do not need much explanation. Future articles will use more advanced code such as the SpaceWar starter kit.
 

Errata for part 1
Firstly an update to 
part 1. In the rush to get the article out at launch date I converted all the GDI PointF structs into XNA Point structs. This meant that everythin</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-2-Running-Tiny-Tennis-on-the-Xbox-360</link>
      <pubDate>Fri, 23 Mar 2007 15:26:34 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-2-Running-Tiny-Tennis-on-the-Xbox-360</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1938626_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1938626_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-2-Running-Tiny-Tennis-on-the-Xbox-360/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>arcade</category>
    </item>
  <item>
      <title>2D Game Primer (Visual C#)</title>
      <description><![CDATA[
<p>&nbsp;</p>
<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article is the first part of the Upgrade Your Game series of tutorials. It walks you through the basics of how 2D games work using Visual C#</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">Andy Dunn - The Z-Man</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z-Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a>,</span></div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<p><strong></strong>&nbsp;</p>
<p><strong>Visual&nbsp;C# Upgrade Your Game Series</strong></p>
<ul>
<li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727608.aspx">2D Game Primer</a>
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916355.aspx">Tiny Tennis</a>&nbsp;(note:<a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">Tiny Tennis using XNA</a> available)
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916430.aspx">Space Blitz</a>&nbsp;
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/11/09/1044573.aspx">Crusader</a></li></ul>
<p>&nbsp;</p>
<p><strong></strong></p>
<h3>Introduction</h3>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdnprod/directx/">Microsoft DirectX</a>. </p>
<p>When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today's top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
</p>
<p>This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h3>2D Game Development Concepts</h3>
<p><strong>The Game Loop</strong></p>
<p>Window Forms and ASP applications are often called &quot;event-driven&quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that kind of application. </p>
<p>Games, on the other hand, are generally not sitting doing nothing all the time. Even if the end user is not pressing a key or a button on the gamepad, the game must animate characters, perform AI functions, and play sounds and many other things depending
 on the game. You've probably done some of these background type tasks in Windows Forms applications using timer controls or background threads. But in general these don't scale to the computer game scenario, where there are multiple animations and multiple
 background tasks all happening at very different intervals. </p>
<p>The solution that most games use (and by &quot;most games&quot; I mean everything right up to the top-selling Xbox 360 titles) is usually called the &quot;game loop.&quot; In pseudo code it looks something like this:
</p>
<pre><code>    While (game is running)
        Check for input
        Update all objects in the game 
        Draw all objects in the game</code></pre>
<p>This might explain one reason why games almost always use 100% of your CPU even if they don't appear to be doing much. The faster your computer is, the faster this loop will run and the smoother the animation and the synchronization will be.
</p>
<p>There is one slight problem with running a tight loop like that, at least in Windows. If you don't allow Windows to check for and process Windows messages and events, your application will be marked as &quot;Not responding&quot; by the operating system. You might
 have seen this in your applications if you have a loop that runs for a long time. You might also have solved it by putting a call to DoEvents into the loop, which allows Windows to process the events. This can work reasonably well if you know the loop will
 end eventually, but in this case the loop is the entire game and you need a better way.
</p>
<p>The method I have chosen to use for these games is NOT the most efficient (for a full discussion on this under Managed DirectX see the
<a href="http://www.thezbuffer.com/articles/185.aspx">MDX Game Loop FAQ</a>), but it is the simplest, and none of the games covered here needs the more complex method.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> TinyTennis_Paint(<span class="kwrd">object</span> sender, PaintEventArgs e)
{
    <span class="rem">//Work out how long since we were last here</span>
    <span class="kwrd">in</span> seconds
    <span class="kwrd">double</span> gameTime = _timer.ElapsedMilliseconds / 1000.0;
    <span class="kwrd">double</span> elapsedTime = gameTime - _lastTime;
    _lastTime = gameTime;
    _frameCounter&#43;&#43;;
 
    <span class="rem">//Perform any animation</span>

    <span class="rem">//Draw the game objects</span>
 
   <span class="rem">//Force the next Paint()</span>
    <span class="kwrd">this</span>.Invalidate();
}
</pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h5><strong></strong>&nbsp;</h5>
<strong>Sprites<br>
</strong><a href="http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29">Sprites</a> are two-dimensional images that appear in a video game. Sometimes they are static images, but in general they are the building blocks for animation. They either move
 around the screen or change the image at regular intervals, giving a &quot;flip book&quot; kind of animation; or they do both, giving you characters like Mario and Donkey Kong that can move around the screen running and jumping. &nbsp; Positioning a Sprite<br>
Just like Windows Forms controls, sprites are placed at an x,y position on the form. 0,0 is the top left and ClientSize.Width, ClientSize.Height is the bottom right. Just like Windows Forms controls, sprites have a height and width too.
<p>However, unlike Windows Forms controls, sprites are primarily designed to move and animate, often hundreds of times per second, to get the smoothest animation possible. So while a sprite can only be drawn at an integer x,y position, its ACTUAL position at
 a subsecond point in time could be 1.45, 12.67. It's important to remember this position so that the animation doesn't get choppy. A sprite position is stored using a floating-point Point structure PointF rather than the integer-based Point structure like
 Windows Forms controls. This means you can store the subpixel accuracy and then just convert to integer screen positions when you draw them.
<strong>Vectors<br>
</strong>The more game programming you do, the more you will come across the term &quot;vector.&quot; Though I've avoided the term in this series for the sake of simplicity, it's worth noting that the concepts are used when the positions of the sprites are updated for
 animation. </p>
<p>Simply put, a vector is just an offset. So a vector of (4,2) means that from some start point you move 4 units in the x-axis and 2 in the y-axis.
</p>
<p>You will see positions referred to as vectors. In this case, a position of (4,2) means an offset of (4,2) from the origin.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1727608/2dprimer1.png">
</p>
<p>Vectors can be added together, so (4,2) &#43; (2,4) gives you a total offset of (6,6).
</p>
<p>Vectors can have negative components, so (-2,1) means move 2 units to the left on the x-axis and 1 unit down on the y-axis.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1727608/2dprimer2.png">
</p>
<p>All of these concepts are used when moving a sprite around the screen. <strong>
</strong>&nbsp; <strong>Moving a Sprite<br>
</strong>Sprites move with a certain velocity. Velocity is different from speed because velocity also contains information about the direction. For example, you could tell me you are driving at 60 mph, and I would guess that in one hour you would be 60 miles
 from the start point. But if you were driving round in a circle, that would not be the case. If I told you my velocity was 60 mph due east, then I would know for sure where you would end up.
</p>
<p>Since your position is an x, y value you can store your velocity as another two-component vector (s, t): s is how fast you want to move on the x-axis, and t is how fast you want to move on the y-axis. If you add them together: (x,y) &#43; (s,t) = (x&#43;s, y&#43;t),
 you get the new position of the sprite. </p>
<p><b>Example: </b>Sprite is at (4,10) and has a speed of (1,0). (1,0) means the sprite will move right in the x direction only. (4,10) &#43; (1,0) = (5,10). If you repeat this addition every second, then the sprite will move 1 pixel per second across the screen.
 You can see that any direction and speed can be represented just by changing the s, t values in that vector.
</p>
<h5><strong>Time-Based Animation</strong></h5>
<p>Imagine a sprite that starts at x=0 and is moving to the right with a velocity of &#43;10. If you walk through the game loop above, the sprite would have &#43;10 added to its position each time the sprite was updated and would move from x=0 to x={some bigger number}
 where {some bigger number} is 10 times the number of times the loop has been run. But the question is, exactly how fast would it move? Well, it depends on how fast the loop runs, which depends on how fast your computer is running. This would mean that on your
 top-of-the-line gaming rig the sprite could cross the screen in half a second, but on your parents' four-year-old &quot;we only use it for e-mail&quot; computer it could take two seconds. Obviously this isn't something that is desirable in a computer game.
</p>
<p>To fix this you need to think about what velocity really is. What does that &#43;10 mean? Velocity is a measure of distance over a period of time, so you cannot think of the &#43;1 as just a distance; it's really &#43;1 pixel in some time that you need to define. So
 each time round the loop, you just need to know how long it's been since the last update and scale the movement by that time.
</p>
<p>A sprite that has a velocity of &#43;10 actually means you move &#43;10 pixels per second. So if it's been half a second since the last frame, multiply that by the velocity and move 5 pixels. In reality the time between frames is fractions of a second. So on your
 fast gaming rig, where the loop runs very fast, the sprite will move with subpixel accuracy for some very smooth animation. On your parents' computer, where the loop only runs 5 times per second, the sprite will move 2 pixels each frame, but after 10 seconds
 the sprite will be in exactly the same place as it is on your computer. </p>
<p>The code will look something like this (notice that for accuracy elapsedTime is a double and therefore needs to be cast down to a float to match the PointF structure):
</p>
<pre><code></code></pre>
<pre class="csharpcode">    <span class="rem">//Move the sprite based on the velocity</span>
    Location.X &#43;= Velocity.X * (<span class="kwrd">float</span>)elapsedTime;
    Location.Y &#43;= Velocity.Y * (<span class="kwrd">float</span>)elapsedTime;
</pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The loop timings I mentioned here are very exaggerated — on most computers the loop will be running hundreds or thousands of times per second, meaning that your animations will be very smooth and accurate.
</p>
<h5>Sprite bounds</h5>
<p>There are two ways to represent the rectangle containing the sprite: </p>
<ol>
<li>X, Y, Height, Width </li><li>X, Y of top left corner and X, Y of bottom right corner </li></ol>
<p>Whilst both of these are valid, you must usually find the first one in use. It's easier to update just one corner as the sprite moves around and calculate the other corner when it's needed. For tasks like collisions- and bounds-checking you need to calculate
 the bottom-right corner, so you will see X&#43;Width and Y&#43;Height as a very commonly used formula in games.
</p>
<h5><strong></strong>&nbsp;</h5>
<strong>Simple Collision Detection<br>
</strong>Collisions are a vital part of almost any game — they restrict where an object can move, whether an object has taken damage, and so forth.
<p>Simple collisions can be described in terms of the positions and size of the sprites and the regions they need to collide with. Since everything is rectangular in this case, there is no need for any more complex collisions that need to be determined at the
 pixel level. All the collisions can be checked for by looking to see if the rectangles overlap or if the coordinates are outside of a certain range. Checking for rectangle overlap is
<a href="http://www.tekpool.com/?p=23">quite simple</a>. </p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> collide()
{
<span class="kwrd">  return</span> ! ( sprite1.Location.X &gt; sprite2.Location.X &#43; sprite2.Size.Width
    || sprite1.Location.X &#43; sprite1.Size.Width  &lt; sprite2.Location.X
    || sprite1.Location.Y &gt; sprite2.Location.Y &#43; sprite2.Size.Height
    || sprite1.Location.Y &#43; sprite1.Size.Height &lt; sprite2.Location.Y);
}
</pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:b45a7cdaab6c4c47879d9e7600d5c536">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</comments>
      <itunes:summary>
&amp;nbsp; 




&amp;nbsp;
This article is the first part of the Upgrade Your Game series of tutorials. It walks you through the basics of how 2D games work using Visual C#



Andy Dunn - The Z-Man
The Z-Buffer

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions,





&amp;nbsp; 
&amp;nbsp; 
Visual&amp;nbsp;C# Upgrade Your Game Series 

2D Game Primer
Tiny Tennis&amp;nbsp;(note:Tiny Tennis using XNA available)
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp; 
 
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today&#39;s top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
 
This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
Help on the menu bar, and then clicking Contents, Index, or 
Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
 
2D Game Development Concepts
The Game Loop 
Window Forms and ASP applications are often called &amp;quot;event-driven&amp;quot; applications — they sit doing nothing for most of the time waiting for an externa</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</link>
      <pubDate>Tue, 20 Feb 2007 13:31:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1727608_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1727608_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>25</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C/RSS</wfw:commentRss>
    </item>
  <item>
      <title>2D Game Primer (Visual Basic)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article is the first part of Upgrade Your Game series of tutorials. It walks you through the basics of how 2D games work using Visual Basic</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">Andy Dunn - The Z-Man</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z-Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a>,</span></div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<p><strong></strong>&nbsp;</p>
<p><strong>Visual Basic Upgrade Your Game Series</strong></p>
<ul>
<li><a class="" href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1727545">2D Game Primer</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916341">Tiny Tennis</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916405">Space Blitz</a>&nbsp;
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1044549">Crusader</a></li></ul>
<p><strong></strong>&nbsp;</p>
<p><strong>Introduction<br>
</strong>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and
 builds on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.com/directx">Microsoft DirectX</a>. </p>
<p>When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today's top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
</p>
<p>This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
</p>
<p><strong>Note</strong>: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking Help on the menu bar, and then clicking
 Contents, Index, or Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h3>&nbsp;</h3>
<h3>2D Game Development Concepts </h3>
<p><strong>The Game Loop </strong></p>
<p>Window Forms and ASP applications are often called &quot;event-driven&quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that kind of application. </p>
<p>Games, on the other hand, are generally not sitting doing nothing all the time. Even if the end user is not pressing a key or a button on the gamepad, the game must animate characters, perform AI functions, and play sounds and many other things depending
 on the game. You've probably done some of these background type tasks in Windows Forms applications using timer controls or background threads. But in general these don't scale to the computer game scenario, where there are multiple animations and multiple
 background tasks all happening at very different intervals. </p>
<p>The solution that most games use (and by &quot;most games&quot; I mean everything right up to the top-selling Xbox 360 titles) is usually called the &quot;game loop.&quot; In pseudo code it looks something like this:
</p>
<blockquote>
<p>While (game is running) <br>
Check for input<br>
Update all objects in the game<br>
Draw all objects in the game</p>
</blockquote>
<p><br>
This might explain one reason why games almost always use 100% of your CPU even if they don't appear to be doing much. The faster your computer is, the faster this loop will run and the smoother the animation and the synchronization will be.
</p>
<p>There is one slight problem with running a tight loop like that, at least in Windows. If you don't allow Windows to check for and process Windows messages and events, your application will be marked as &quot;Not responding&quot; by the operating system. You might
 have seen this in your applications if you have a loop that runs for a long time. You might also have solved it by putting a call to DoEvents into the loop, which allows Windows to process the events. This can work reasonably well if you know the loop will
 end eventually, but in this case the loop is the entire game and you need a better way.
</p>
<p>The method I have chosen to use for these games is NOT the most efficient (for a full discussion on this under Managed DirectX see the
<a href="http://www.thezbuffer.com/articles/185.aspx">MDX Game Loop FAQ</a>), but it is the simplest, and none of the games covered here needs the more complex method.
</p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> TinyTennis_Paint(<span class="kwrd">ByVal</span> sender <span class="kwrd">As</span> <span class="kwrd">Object</span>, <span class="kwrd">ByVal</span> e <span class="kwrd">As</span> PaintEventArgs) <span class="kwrd">Handles</span> <span class="kwrd">MyBase</span>.Paint
<span class="rem">  'Perform any animation here</span>
<span class="rem">  'Draw the game objects here</span>
<span class="rem">  'Force the next Paint()</span>
<span class="kwrd">  Me</span>.Invalidate()
<span class="kwrd">End</span> <span class="kwrd">Sub</span> </pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><strong>Sprites</strong><br>
<a href="http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29">Sprites</a> are two-dimensional images that appear in a video game. Sometimes they are static images, but in general they are the building blocks for animation. They either move around the
 screen or change the image at regular intervals, giving a &quot;flip book&quot; kind of animation; or they do both, giving you characters like Mario and Donkey Kong that can move around the screen running and jumping.
</p>
<p><strong>Positioning a Sprite</strong><br>
Just like Windows Forms controls, sprites are placed at an x,y position on the form. 0,0 is the top left and ClientSize.Width, ClientSize.Height is the bottom right. Just like Windows Forms controls, sprites have a height and width too.
</p>
<p>However, unlike Windows Forms controls, sprites are primarily designed to move and animate, often hundreds of times per second, to get the smoothest animation possible. So while a sprite can only be drawn at an integer x,y position, its ACTUAL position at
 a subsecond point in time could be 1.45, 12.67. It's important to remember this position so that the animation doesn't get choppy. A sprite position is stored using a floating-point Point structure PointF rather than the integer-based Point structure like
 Windows Forms controls. This means you can store the subpixel accuracy and then just convert to integer screen positions when you draw them.
</p>
<p><strong>Vectors</strong><br>
The more game programming you do, the more you will come across the term &quot;vector.&quot; Though I've avoided the term in this series for the sake of simplicity, it's worth noting that the concepts are used when the positions of the sprites are updated for animation.
</p>
<p>Simply put, a vector is just an offset. So a vector of (4,2) means that from some start point you move 4 units in the x-axis and 2 in the y-axis.
</p>
<p>You will see positions referred to as vectors. In this case, a position of (4,2) means an offset of (4,2) from the origin.
</p>
<p><strong><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1727545/2dprimer1.png">
</strong></p>
<p>Vectors can be added together, so (4,2) &#43; (2,4) gives you a total offset of (6,6).
</p>
<p>Vectors can have negative components, so (-2,1) means move 2 units to the left on the x-axis and 1 unit down on the y-axis.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1727545/2dprimer2.png">
</p>
<p>All of these concepts are used when moving a sprite around the screen. </p>
<p><strong>Moving a Sprite</strong><br>
Sprites move with a certain velocity. Velocity is different from speed because velocity also contains information about the direction. For example, you could tell me you are driving at 60 mph, and I would guess that in one hour you would be 60 miles from the
 start point. But if you were driving round in a circle, that would not be the case. If I told you my velocity was 60 mph due east, then I would know for sure where you would end up.
</p>
<p>Since your position is an x, y value you can store your velocity as another two-component vector (s, t): s is how fast you want to move on the x-axis, and t is how fast you want to move on the y-axis. If you add them together: (x,y) &#43; (s,t) = (x&#43;s, y&#43;t),
 you get the new position of the sprite. </p>
<p><strong>Example</strong>: Sprite is at (4,10) and has a speed of (1,0). (1,0) means the sprite will move right in the x direction only. (4,10) &#43; (1,0) = (5,10). If you repeat this addition every second, then the sprite will move 1 pixel per second across
 the screen. You can see that any direction and speed can be represented just by changing the s, t values in that vector.
</p>
<p><strong>Time-Based Animation</strong><br>
Imagine a sprite that starts at x=0 and is moving to the right with a velocity of &#43;10. If you walk through the game loop above, the sprite would have &#43;10 added to its position each time the sprite was updated and would move from x=0 to x={some bigger number}
 where {some bigger number} is 10 times the number of times the loop has been run. But the question is, exactly how fast would it move? Well, it depends on how fast the loop runs, which depends on how fast your computer is running. This would mean that on your
 top-of-the-line gaming rig the sprite could cross the screen in half a second, but on your parents' four-year-old &quot;we only use it for e-mail&quot; computer it could take two seconds. Obviously this isn't something that is desirable in a computer game.
</p>
<p>To fix this you need to think about what velocity really is. What does that &#43;10 mean? Velocity is a measure of distance over a period of time, so you cannot think of the &#43;1 as just a distance; it's really &#43;1 pixel in some time that you need to define. So
 each time round the loop, you just need to know how long it's been since the last update and scale the movement by that time.
</p>
<p>A sprite that has a velocity of &#43;10 actually means you move &#43;10 pixels per second. So if it's been half a second since the last frame, multiply that by the velocity and move 5 pixels. In reality the time between frames is fractions of a second. So on your
 fast gaming rig, where the loop runs very fast, the sprite will move with subpixel accuracy for some very smooth animation. On your parents' computer, where the loop only runs 5 times per second, the sprite will move 2 pixels each frame, but after 10 seconds
 the sprite will be in exactly the same place as it is on your computer. </p>
<p>The code will look something like this (notice that for accuracy elapsedTime is a double and therefore needs to be cast down to a float to match the PointF structure):
</p>
<pre class="csharpcode"><span class="rem">'Move the sprite based on the velocity</span>
Location.X &#43;= Velocity.X * <span class="kwrd">CSng</span>(elapsedTime)
Location.Y &#43;= Velocity.Y * <span class="kwrd">CSng</span>(elapsedTime) </pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The loop timings I mentioned here are very exaggerated — on most computers the loop will be running hundreds or thousands of times per second, meaning that your animations will be very smooth and accurate.
</p>
<p><strong>Sprite bounds</strong><br>
There are two ways to represent the rectangle containing the sprite: </p>
<ol>
<li>X, Y, Height, Width </li><li>X, Y of top left corner and X, Y of bottom right corner <br>
</li></ol>
<p>Whilst both of these are valid, you must usually find the first one in use. It's easier to update just one corner as the sprite moves around and calculate the other corner when it's needed. For tasks like collisions- and bounds-checking you need to calculate
 the bottom-right corner, so you will see X&#43;Width and Y&#43;Height as a very commonly used formula in games.
</p>
<p><strong>Simple Collision Detection</strong><br>
Collisions are a vital part of almost any game — they restrict where an object can move, whether an object has taken damage, and so forth.
</p>
<p>Simple collisions can be described in terms of the positions and size of the sprites and the regions they need to collide with. Since everything is rectangular in this case, there is no need for any more complex collisions that need to be determined at the
 pixel level. All the collisions can be checked for by looking to see if the rectangles overlap or if the coordinates are outside of a certain range. Checking for rectangle overlap is
<a href="http://www.tekpool.com/?p=23">quite simple</a>. </p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Function</span> collide() <span class="kwrd">As</span> <span class="kwrd">Boolean</span>
<span class="kwrd">  Return</span> <span class="kwrd">Not</span> (Sprite1.Location.X &gt; Sprite2.Location.X &#43; Sprite2.Size.Width <span class="kwrd">OrElse</span> _
  Sprite1.Location.X &#43; Sprite1.Size.Width &lt; Sprite2.Location.X <span class="kwrd">OrElse</span> _
  Sprite1.Location.Y &gt; Sprite2.Location.Y &#43; Sprite2.Size.Height <span class="kwrd">OrElse</span> _
  Sprite1.Location.Y &#43; Sprite1.Size.Height &lt; Sprite2.Location.Y)
<span class="kwrd">End</span> <span class="kwrd">Function</span> </pre>
<style type="text/css">
<!--
.csharpcode
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{margin:0em;
	width:100%;
	background-color:#f4f4f4}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>This code uses an efficient algorithm for determining if the two rectangles overlap. It checks the bounds of both rectangles to determine whether they DON'T overlap and then negates the result. For example, the first line checks whether the left-hand edge
 of sprite 1 is to the right of the right-hand edge of sprite 2. If it is, then obviously they cannot overlap. The next three lines check the other three edges.
</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:ac4fa210ac6e41ae9cb49e7600d5d286">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</comments>
      <itunes:summary>



&amp;nbsp;
This article is the first part of Upgrade Your Game series of tutorials. It walks you through the basics of how 2D games work using Visual Basic



Andy Dunn - The Z-Man
The Z-Buffer

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions,





&amp;nbsp; 
&amp;nbsp; 
Visual Basic Upgrade Your Game Series 

2D Game Primer
Tiny Tennis
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp; 
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and
 builds on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today&#39;s top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
 
This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking Help on the menu bar, and then clicking
 Contents, Index, or Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
 
&amp;nbsp;
2D Game Development Concepts 
The Game Loop  
Window Forms and ASP applications are often called &amp;quot;event-driven&amp;quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</link>
      <pubDate>Tue, 20 Feb 2007 13:24:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1727545_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1727545_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>15</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Intro to XNA Part 1: Building Tiny Tennis</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" colspan="2"><span class="entry_description">In this article, the ZMan walks through creating Tiny Tennis, a Pong clone, using the XNA Framework</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The ZMan</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">TheZbuffer.com</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualcsharp/download/">Visual C# Express
</a>, <a href="http://msdn.com/xna/">XNA Game Studio Express</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b><a href="http://channel9.msdn.com/ShowPost.aspx?PostID=265223">Download</a>
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>December 11th... a day that we all hope will go down in history as the start of a new generation of hobbyist game developers. Today
<a href="http://msdn.com/xna">XNA Game Studio Express</a> launches. It's not the first platform to allow home developers access to console development but its is the first one to be fully sanctioned and supported and running on a retail console.
</p>
<p>So where do you start? XNA Game Studio Express is going to interest people who have no game development experience at all so starting with some simple games is a good idea. You may have seen the 3 games I did for MSDN for their Upgrade Your Game promotion
 - <a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916355.aspx">
Tiny Tennis</a>, <a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916430.aspx">
Space Blitz</a> and <a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/11/09/1044573.aspx">
Crusader</a>. For this series of articles I will walk you through simple XNA applications using as much code from these starter kits as possible. The original tutorials and screencasts will walk you through the game logic and these articles will add in the
 XNA know how.</p>
<p>Firstly a couple of points:</p>
<ol>
<li>Even The ZMan didn't have access to the retail XBox 360 release before today so for the first part I will only cover the PC. Watch for part 2 to add in the things needed to run on the 360 and go into more detail.
</li><li>XNA only supports Visual C# Express so although the original games were in Visual Basic, this series will be only in C#
</li><li>You need to ensure you have <a href="http://msdn.microsoft.com/vstudio/express/visualcsharp/">
C# Express</a> and <a href="http://msdn.microsoft.com/xna">XNA Game Studio Express</a> installed. If you have problems installing or running then ask in the
<a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=882&amp;SiteID=1">XNA Game Studio Express Forum</a>.
</li></ol>
<h1>Making a new XNA game</h1>
<p>Installing XNA Game Studio Express adds several new project types to C# Express:</p>
<p><img title="New Project" height="469" alt="New Project" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/NewProject4.png" width="681">
</p>
<p>The SpaceWar projects are complete games for the xbox and the windows platforms - they have all the source code, graphics and sound and
<a href="http://letskilldave.com/archive/2006/11/14/Show-me-your-Spacewar-mods_21002100_.aspx">
Microsoft absolutely want you to use this</a> to make your own games as well as learn about making simple 2d and 3d games.</p>
<p>The Windows Game and Xbox Game projects are for writing games on those 2 platforms and the Game Library projects are for making
<span>reusable </span>components that are easy to use within the XNA game projects.</p>
<p>For this tutorial start with the Windows Game project. Once you have selected it you can
<span>immediately </span>run the project and see a <span>wonderful </span>cornflower blue, blank screen. (It is widely speculated that cornflower blue is Tom Miller's
<span>favorite </span>color).</p>
<p>Now we need to add the project files from the Tiny Tennis sample. Select Add Files by right clicking the project and then browse to the Tiny Tennis solution and add the following files:</p>
<p><img title="Add Exiisting Item" height="346" alt="Add Exiisting Item" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/AddFiles5.png" width="529">
</p>
<h1>Converting the Game</h1>
<p>There are going to be a LOT of errors right now because Tiny Tennis relies heavily on Windows.Forms and System.Drawing neither of which are available when writing an XNA application that you eventually want to run on the Xbox 360 because the Xbox 360 does
 not support those libraries. So initially there are several big changes to make.
</p>
<p>Game1.cs is the main XNA game file. It contains the initializer for the game as well as several methods that are called automatically for the game. If you have been through the tutorials for the Express games you will see that the games are designed to be
 continually updated. As fast as possible the keyboard is read, the positions are updated and the screen is redrawn. This is exactly the same method used in XNA so it is very simple for us to use the same logic.</p>
<p>You need to copy sections of code from the tennis.cs file into the game1.cs. </p>
<p>Firstly the declarations:</p>
<div class="code">private Bat _player1;<br>
private Bat _player2;<br>
private Ball _ball;<br>
private GameState gameState; </div>
<p>Then the constructor which goes into the end of the Game1 constructor.</p>
<div class="code">gameState = new GameState();<br>
<br>
//Create&nbsp;the&nbsp;bat&nbsp;Sprites&nbsp;-&nbsp;they&nbsp;need&nbsp;the&nbsp;keyboard&nbsp;controls&nbsp;and&nbsp;the&nbsp;gameplay&nbsp;area&nbsp;limits<br>
_player1 = new Bat(player1Bat,&nbsp;30,&nbsp;Keys.Q,&nbsp;Keys.A,&nbsp;0, ClientSize.Height);<br>
<br>
//use&nbsp;this&nbsp;line&nbsp;for&nbsp;a&nbsp;second&nbsp;human&nbsp;player<br>
//_player2&nbsp;=&nbsp;new&nbsp;Bat(player2Bat,&nbsp;ClientSize.Width&nbsp;-&nbsp;30&nbsp;-&nbsp;Bat.Width,&nbsp;Keys.P,&nbsp;Keys.L,&nbsp;0,&nbsp;ClientSize.Height);<br>
<br>
//use&nbsp;this&nbsp;line&nbsp;for&nbsp;a&nbsp;computer&nbsp;player<br>
_player2 = new Bat(player2Bat, ClientSize.Width - 30 - Bat.Width, &nbsp;0, ClientSize.Height);<br>
<br>
//Create&nbsp;the&nbsp;ball&nbsp;sprite.&nbsp;It&nbsp;needs&nbsp;the&nbsp;gameplay&nbsp;area&nbsp;limits&nbsp;and&nbsp;references&nbsp;to&nbsp;the&nbsp;bats&nbsp;to&nbsp;be&nbsp;able&nbsp;to&nbsp;check&nbsp;for&nbsp;collisions<br>
_ball = new Ball(ballControl,&nbsp;0,&nbsp;ClientSize.Width,&nbsp;0,&nbsp;ClientSize.Height,&nbsp;_player1,&nbsp;_player2,&nbsp;gameState);<br>
<br>
//Connect&nbsp;the&nbsp;AI&nbsp;player&nbsp;with&nbsp;the&nbsp;ball<br>
_player2.Ball&nbsp;= _ball; </div>
<p>The TinyTennis_Paint code gets moved into the Draw method in Game1.cs. The Draw method is continually called by the XNA Game class and this is where you should draw your graphics.</p>
<div class="code">//Perform any animation<br>
_player1.Update(gameTime, elapsedTime);<br>
_player2.Update(gameTime, elapsedTime);<br>
_ball.Update(gameTime, elapsedTime);<br>
<br>
//Draw the scores<br>
player1Score.Text = gameState.Player1Score.ToString();<br>
player1Score.Refresh();<br>
player2Score.Text = gameState.Player2Score.ToString();<br>
player2Score.Refresh();<br>
<br>
//and the game objects<br>
_player1.Draw();<br>
_player2.Draw();<br>
_ball.Draw(); </div>
<p>Notice that I have not copied across any of the timer/stopwatch code. XNA provides its own timer logic so that is not needed. Since XNA does not support Windows forms, it does not support KeyUp and KeyDown events so the code for those is of no use to us.
 You can now remove TinyTennis.cs from the project.</p>
<p>Now to fix up the errors. If you hit compile and walk through them one by one you will fix them in the following order:</p>
<ul>
<li>The first thing to do is remove all the 'using' statements that mention Windows.Forms and System.Drawing. If you try to compile these will be the first errors on the list.
</li><li>PointF in System.Drawing is replaced by Vector2 in Microsoft.XNA.Framework. If you change the type to Vector2 you can use the intellisense feature of C# express to add in the new using statement.<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/using8.png"><img height="90" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/using_thumb6.png" width="341" border="0"></a> &nbsp;
</li><li>There is no SizeF type in XNA. Since it is just a pair of values you can reuse Vector2 type so change SizeF to Vector2. Change the Width property to X and the Height
</li><li>Color in System.Drawing is replaced by Color in Microsoft.XNA.Framework. For most of these errors you just need to add the correct using statement with intellisense.
</li><li>In TinyTennis I used windows controls to do the rendering. Since this is not possible in XNA all references to the Control type need to be removed
<ul>
<li>in ball.cs and bat.cs remove the parameters in the constructor that refer to Control
</li><li>ControlSprite is a wrapper around Sprite that draws using windows controls. Since we no longer have windows controls we can remove ControlSprite from the project and just use the Sprite implementation
</li><li>Now that ControlSprite is missing Ball and Bat should be changed to inherit directly from Sprite
</li><li>In game1.cs remove the Control parameters from the new Bat() and new Ball() lines in the constructor
</li></ul>
</li><li>Keys is now found in Microsoft.Xna.Framework.Input so needs the correct using statement
</li><li>ClientSize from Windows.Forms becomes Window.ClientBounds from Microsoft.Xna.Framework
</li><li>In the WindowsForms version of TinyTennis I tracked the game time myself. This code is redundant in XNA and is removed
<span>because </span>the Game class passes in gametime to the Draw() function. So replace the elapsedTime property with gameTime.ElapsedGameTime.TotalSeconds and the gameTime parameter with gameTime.TotalGameTime.TotalSeconds<br>
<div class="code">//Perform any animation<br>
_player1.Update(gameTime.TotalGameTime.TotalSeconds, gameTime.ElapsedGameTime.TotalSeconds);<br>
_player2.Update(gameTime.TotalGameTime.TotalSeconds, gameTime.ElapsedGameTime.TotalSeconds);<br>
_ball.Update(gameTime.TotalGameTime.TotalSeconds, gameTime.ElapsedGameTime.TotalSeconds);
</div>
</li><li>There is no easy way to draw text to the screen in XNA. So for this article I am simply going to avoid the subject until there is time to go into it in more detail. Comment out the lines that display the score. You can use the ctrl-K-C keypress to easily
 to this. ctrl-K-U reverses it<br>
<div class="code">//Draw the scores<br>
//player1Score.Text = gameState.Player1Score.ToString();<br>
//player1Score.Refresh();<br>
//player2Score.Text = gameState.Player2Score.ToString();<br>
//player2Score.Refresh(); </div>
</li><li>Since the Point type uses integers in XNA there are some parameters to change to int from float and the calculations need to have their results cast into (int). For example:<br>
<div class="code">public virtual void Update(double gameTime, double elapsedTime)<br>
{<br>
&nbsp; &nbsp; //Move the sprite based on the velocity<br>
&nbsp; &nbsp; Location.X &#43;= (int)(Velocity.X * (float)elapsedTime);<br>
&nbsp; &nbsp; Location.Y &#43;= (int)(Velocity.Y * (float)elapsedTime);<br>
} </div>
</li></ul>
<p>So you should now have a project that compiles. However when it runs you will see a runtime error about a missing sound file - copy the WAV file from the original project and add it to the project and set the properties to copy the file to the output directory.
 Now the project should compile and run but nothing will appear on the screen. This is to be expected since the previous version used windows forms to do the rendering.</p>
<h1>Using XNA to Render</h1>
<p>The simplest way to draw anything in XNA is using the SpriteBatch class. This uses your graphics card to draw 2d rectangular areas on the screen. Since Tiny Tennis uses rectangles this is perfect. The
<span>SpriteBatch </span>allows you to set the location and size of the rectangle - however it expects a graphic file to be used as the thing to draw. For TinyTennis a graphic file which is all white will work perfectly. I created a small graphic file using
 Windows Paint and added it to the project.</p>
<p>If you look at the file properties after you add the bitmap you will see another addition that XNA Game Studio Express adds. Image files are now a recognized project item. This is what you may have heard of as the content pipeline. It allows game content
 to be created and checked at compile time and the content to be treated as part of the game rather than some external files.</p>
<p><img height="209" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/tennis4.png" width="278"> &nbsp;</p>
<p>For the most part you don't need to change or even look at the properties window. Make a note of the Asset name - this is how you will be able to refer to it in code. It defaults to the name of the file without the type extension.</p>
<p>Rendering involves 2 steps - loading the graphic and then using it to draw.</p>
<p>Loading the graphic is done in the Game1.cs class. Using the already declared reference to the content
<span>pipeline </span>it requires a simple declaration:</p>
<div class="code">public static Texture2D SpriteTexture; </div>
<p>&nbsp; and a single line of code in the LoadGraphicsContent function:</p>
<div class="code">protected override void LoadGraphicsContent(bool loadAllContent)<br>
{<br>
&nbsp; &nbsp; if (loadAllContent)<br>
&nbsp; &nbsp; {<br>
&nbsp; &nbsp; &nbsp; &nbsp; spriteTexture = content.Load&lt;Texture2D&gt;(&quot;whitePixel&quot;);<br>
&nbsp; &nbsp; }<br>
} </div>
<p>To draw the sprite you need a sprite batch object for this simple application its easiest to just create a single SpriteBatch and make it static so that the bats and balls can share it.
</p>
<div class="code">public static SpriteBatch SpriteBatch; </div>
<p>And create it in the initialize function.</p>
<div class="code">SpriteBatch = new SpriteBatch(this.graphics.GraphicsDevice); </div>
<p>Drawing with SpriteBatch has many overloads - however to draw a rectangle uses the simplest overload which simple stretches the white pixel to a rectangle of the required size and color in sprite.cs</p>
<div class="code">public virtual void Draw()<br>
{<br>
&nbsp; &nbsp; Game1.SpriteBatch.Begin();<br>
&nbsp; &nbsp; Game1.SpriteBatch.Draw(Game1.SpriteTexture, new Rectangle((int)(Location.X &#43; .5f), (int)(Location.Y &#43;.5f), (int)Size.X, (int)Size.Y), Color.White);<br>
&nbsp; &nbsp; Game1.SpriteBatch.End();<br>
} </div>
<p>Now if you run the game you will see the bats and balls on the screen. The final thing is to add the new keyboard code. Since there is no events in XNA you need to simply check each time around the game loop if the key is up or down, Just like everything
 else in XNA this is a few simple lines of code. Replace the humanMove() function in bat.cs with the following:</p>
<p>private void humanMove() <br>
{&nbsp;&nbsp;&nbsp;&nbsp; </p>
<blockquote>
<p>KeyboardState keyState = Keyboard.GetState(); <br>
double velocity = 0.0; &nbsp; &nbsp; <br>
//Set the velocity of the sprite based on which keys are pressed &nbsp; &nbsp; <br>
if (keyState.IsKeyDown(_upKey)) &nbsp; &nbsp; <br>
{ &nbsp; &nbsp; &nbsp; &nbsp; velocity &#43;= -_speed; &nbsp; &nbsp; } &nbsp; &nbsp;<br>
<br>
if (keyState.IsKeyDown(_downKey)) &nbsp; &nbsp; <br>
{ &nbsp; &nbsp; &nbsp; &nbsp; velocity &#43;= _speed; &nbsp; &nbsp; } &nbsp; <br>
&nbsp; <br>
Velocity.Y = (int)velocity; </p>
</blockquote>
<p>} </p>
<h1></h1>
<p><img height="316" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1256876/tennis4.png" width="403">
</p>
<p>Now you can play the game. The keys Q and A control the bat on the left and the bat on the right uses some rudimentary AI.</p>
<h1>Running on the Xbox</h1>
<p>As I mentioned earlier running on the Xbox is something I will cover in the next article. But I'm sure you want to try so here are some pointers:</p>
<ul>
<li>There is no keyboard on the xbox so you will need to <span>replace </span>the key press code with reading the xbox controller instead
</li><li>Sound on the xbox is done using XACT so the SoundPlayer class is not available. You need to create an XACT project and add the .wav file to that
</li></ul>
<p>Take a look at the SpaceWar sample for examples of ow to do both of these things - or just wait till next week.</p>
<p>&nbsp;</p>
<p>The code in this article uses <a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">
Visual C#&nbsp;2005 Express Edition</a> and the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A">
October 2005 DirectX SDK</a></p>
<p>The ZMan is here to solve your XNA Game Studio Express and Managed DirectX programming problems. If you have a question for the ZMan then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>.</p>
<p><b>Credits:</b></p>
<p>Thanks to </p>
<ul>
<li><a href="mailto:web@carlosag.net">Carlos Aguilar</a> for the <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">
code colorizer</a> </li></ul>
<p>Copyright © 2006 TheZBuffer.com</p>
<p>The ZMan runs the #1 Managed DirectX community website <a href="http://www.thezbuffer.com/">
http://www.thezbuffer.com</a>. </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:db5142556b8b45c5a06c9e7600d73ea4">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-1-Building-Tiny-Tennis</comments>
      <itunes:summary>



In this article, the ZMan walks through creating Tiny Tennis, a Pong clone, using the XNA Framework



The ZMan
TheZbuffer.com

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual C# Express
, XNA Game Studio Express
Hardware: 
Download: Download








December 11th... a day that we all hope will go down in history as the start of a new generation of hobbyist game developers. Today
XNA Game Studio Express launches. It&#39;s not the first platform to allow home developers access to console development but its is the first one to be fully sanctioned and supported and running on a retail console.
 
So where do you start? XNA Game Studio Express is going to interest people who have no game development experience at all so starting with some simple games is a good idea. You may have seen the 3 games I did for MSDN for their Upgrade Your Game promotion
 - 
Tiny Tennis, 
Space Blitz and 
Crusader. For this series of articles I will walk you through simple XNA applications using as much code from these starter kits as possible. The original tutorials and screencasts will walk you through the game logic and these articles will add in the
 XNA know how. 
Firstly a couple of points: 

Even The ZMan didn&#39;t have access to the retail XBox 360 release before today so for the first part I will only cover the PC. Watch for part 2 to add in the things needed to run on the 360 and go into more detail.
XNA only supports Visual C# Express so although the original games were in Visual Basic, this series will be only in C#
You need to ensure you have 
C# Express and XNA Game Studio Express installed. If you have problems installing or running then ask in the
XNA Game Studio Express Forum.

Making a new XNA game
Installing XNA Game Studio Express adds several new project types to C# Express: 

 
The SpaceWar projects are complete games for the xbox and the windows platforms - they have all the source code, graphics and sound and

Microsoft absolutely want you to use th</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-1-Building-Tiny-Tennis</link>
      <pubDate>Mon, 11 Dec 2006 04:27:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-1-Building-Tiny-Tennis</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1256876_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1256876_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>15</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Intro-to-XNA-Part-1-Building-Tiny-Tennis/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>arcade</category>
    </item>
  <item>
      <title>Upgrade Your Game: Crusader (C#)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">Welcome to the Upgrade Your Game series of tutorials. In this article, we will develop a role-playing game Crusader!!!</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b><a href="http://download.microsoft.com/download/0/7/8/078f6de6-4b20-47a3-9a94-dbf3a0131ca0/crusader.vsi">Download</a>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044573/crusader1.png"></a>
</p>
<p>&nbsp;</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv"><img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044573/media6.jpg"></a>
<a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv">
Download Video</a></p>
<p><b>Visual&nbsp;C# Upgrade Your Game Series</b></p>
<ul>
<li><a href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727608.aspx">2D Game Primer</a>
</li><li><a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916355.aspx">Tiny Tennis</a>&nbsp;(note:<a href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">Tiny Tennis using XNA</a> available)
</li><li><a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916430.aspx">Space Blitz</a>&nbsp;
</li><li><a href="http://blogs.msdn.com/coding4fun/archive/2006/11/09/1044573.aspx">Crusader</a><br>
&nbsp;</li></ul>
<h2>Introduction</h2>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://blogs.msdn.com/directx/">Microsoft DirectX</a>.</p>
<p>Not all games are real-time action games. Role-playing games (RPGs) are generally slower paced and involve more thinking. Usually there's no penalty if you turn your attention to something else for a few moments. Many, many, many years ago,
<a href="http://en.wikipedia.org/wiki/Dungeon_%28computer_game%29">sometime in the 1970s</a>, RPGs were played using text or graphics made up from text. Since we're no longer in the 1970s, we can do a little better than that using the sprites from the previous
 games.</p>
<p>For the fourth and final game, I will be creating a tile-based role-playing game. These days, role-playing games have as good graphics and special effects as any first person shooter. But the origins of graphical role-playing games are tile-based games such
 as the early <a href="http://en.wikipedia.org/wiki/Final_Fantasy_VI">Final Fantasy</a> and
<a href="http://en.wikipedia.org/wiki/Ultima">Ultima</a> games. Because this is a beginner series with limited code, I cannot create even games as complex as those early works; however, I can give you most of the techniques you will need to put together similar-looking
 games. After that, it's really just up to your imagination.</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.</p>
<h2>Getting Started <br>
</h2>
<h3>Building and Running Crusader</h3>
<p>Once your project is loaded into the Visual C# environment, you can compile and run the program in one step.
</p>
<p>To build and run Crusader: </p>
<ul>
<li>Press F5 to build and start the game under the debugger. </li></ul>
<p>The game launches and you can use the arrow keys to control the hero and press P to use magic potions. Find the keys to open the doors and kill the wizard who has captured the princess.</p>
<h2>Files </h2>
<table border="1" rules="all" width="595" frame="box" cols="2">
<tbody>
<tr valign="top">
<td width="50%"><b>File</b></td>
<td width="50%"><b>Use</b></td>
</tr>
<tr valign="top">
<td width="50%">Area.cs</td>
<td width="50%">Represents an 8 x 8 area of the world. Each area stores a set of tiles and current state of any dynamic objects. In addition, it stores connectivity information about which areas surround it.</td>
</tr>
<tr valign="top">
<td width="50%">BitmapCache.cs</td>
<td width="50%">A static class that stores bitmaps in a cache. This is used by the Sprite class to save on memory and loading time by reusing bitmaps.</td>
</tr>
<tr valign="top">
<td width="50%">Crusader.cs</td>
<td width="50%">The main display form. Other than UI initialization and keyboard events, little gameplay code is performed in here. Most code calls into GameState.</td>
</tr>
<tr valign="top">
<td width="50%">GameObject.cs</td>
<td width="50%">Abstract base class that represents an object that requires updating and drawing once per frame.</td>
</tr>
<tr valign="top">
<td width="50%">GameState.cs</td>
<td width="50%">Stores the current state of the game and controls all gameplay.</td>
</tr>
<tr valign="top">
<td width="50%">MapTile.cs</td>
<td width="50%">Stores an individual tile. Each tile has a background sprite and an optional transparent sprite in the foreground. In addition, for dynamic sprites such as monsters, we store the current state of that monster, for example, Health.</td>
</tr>
<tr valign="top">
<td width="50%">Sounds.cs</td>
<td width="50%">A static class that plays any of the game sounds.</td>
</tr>
<tr valign="top">
<td width="50%">Tile.cs</td>
<td width="50%">Represents a tile from the data file.</td>
</tr>
<tr valign="top">
<td width="50%">World.cs</td>
<td width="50%">The world is a collection of Areas. This class handles reading of the tile and map files and any gameplay related to the world.</td>
</tr>
</tbody>
</table>
<br>
<h2>Game Development Concepts </h2>
<p>If you are new to 2D game development, check out the <a href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727608.aspx">
2D Game Primer (C#)</a>.</p>
<h3>Tile-based Games</h3>
<p>Tile-based games get their name from the way the graphics are built up. Instead of having a single graphic for each area in the game, the area is built up from several small tiles. So there is one tile for grass, another with a tree, and another with a brick
 wall. By combining these squares like a patchwork quilt, you can make a huge number of different-looking levels from a small number of graphics. Take a look at the tiles.bmp<b>
</b>in the GameData folder to get an idea of what the tiles look like for this game.</p>
<p>I asked the artist to cover three themes: </p>
<ol>
<li>Outdoor — grass, trees, and paths. <br>
</li><li>Castles — walls, floor, and decorations. <br>
</li><li>Dungeon — different walls and floor. </li></ol>
<p>I asked him to create all the sections needed to make paths that connect in any direction, so there are 11 different combinations for each one. In addition, he created three doors of differing colors with both open and closed positions. The doors are themed
 to fit into the castle wall.</p>
<p>You will also see that this file includes tiles for all of the in-game objects. These are not drawn as part of the tile-based background but instead are layered over the top of the tiles depending on the location of the item in the game.</p>
<h3>Extracting Sprites and Animation from Sprite Sheets</h3>
<p>It's far more efficient to load all of the graphics in one go rather then having many different files as I did in Space Blitz. As you have already seen, the graphics for this game are all in one file. Well, actually they are in two. I asked the artist to
 put the multi-frame animations in a second file, so that we could control the layout without having to fit them around the other tiles. Take a look at animations.bmp.</p>
<p>The Sprite class currently loads its own bitmap with a file name, which is not really very efficient either; in SpaceBlitz you loaded the same bitmap multiple times each time it was used. To improve this, I added a constructor that takes an already loaded
 bitmap and just stores the reference to it. Now multiple sprites can share the same bitmap. This doesn't make sense for sprites that you want to change (like the bases in SpaceBlitz), but those are the exception to the rule.</p>
<p>So how does the sprite know which bit of the large bitmap it should draw? In the same constructor, you pass a rectangle structure that describes the top, left, height, and width of the region you wish to extract. When the sprite is drawn it uses this to
 draw only the relevant part. The function also takes the number of frames of animation within that rectangle and automatically subdivides the rectangles to extract the correct frame into the _frames collection.</p>
<b></b>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">public</span> Sprite(GameState gameState, <span class="kwrd">float</span> x, <span class="kwrd">float</span> y, Bitmap bitmap, Rectangle rectangle, <span class="kwrd">int</span> numberAnimationFrames)<br>{<br>    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; numberAnimationFrames; i&#43;&#43;)<br>    {<br>        _frames.Add(bitmap);<br> <br>        <span class="rem">//Set the location and use the height and width from the 1st frame</span><br>        initialize(gameState, x, y, rectangle.Width / <br>            numberAnimationFrames, rectangle.Height);<br> <br>        _rectangle.Add(<span class="kwrd">new</span> Rectangle(rectangle.X &#43; i * rectangle.Width / <br>            numberAnimationFrames, rectangle.Y, <br>        rectangle.Width / numberAnimationFrames, rectangle.Height));<br>    }<br>}<br> <br><span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Draw(Graphics graphics)<br>{<br>    graphics.DrawImage(_frames[CurrentFrame], outputRect,<br>        _rectangle[CurrentFrame].X, _rectangle[CurrentFrame].Y, <br>        _rectangle[CurrentFrame].Width, _rectangle[CurrentFrame].Height, <br>        GraphicsUnit.Pixel);<br>}</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h3>Using Color Key to Make Sprites Transparent</h3>
<p>If the game objects were drawn over the top of the tiles in the same way that all of the other sprites are drawn, they would look like this:</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044573/crusader2.png"></p>
<p>In SpaceBlitz, all of the aliens were actually being drawn inside a black box (try changing the form background color and running the game). Since the game background was black, you could not see this. That was fine for SpaceBlitz but obviously isn't suitable
 for Crusader. The technique used is called Color Key and it's the same one used in movies to put actors in front of a green screen into a sci-fi setting. It's more often called
<a href="http://blogs.msdn.com/ControlPanel/Blogs/%20http://en.wikipedia.org/wiki/Chroma_key%20">
chroma key</a>. The general idea is that you do not draw a pixel where it is a certain color. I requested the artist choose an RGB color that he was not using in the artwork and set the backgrounds to that color. He chose (75, 75, 75), which is the dark grey
 you see in the image above. When you ask GDI to draw the shape, you tell it which color to remove and all the magic is done for you giving this corrected image:</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044573/crusader3.png"></p>
<p>The code is just a few lines of modification to the sprite drawing routine: colorKey is Color.ToArgb(75, 75, 75).</p>
<b></b>
<p><b>Visual C#</b></p>
<pre class="csharpcode"><span class="rem">//Set the color key for this sprite;</span><br>_attributes= <span class="kwrd">new</span> ImageAttributes();<br>_attributes.SetColorKey(_colorKey, _colorKey);<br> ...<br>graphics.DrawImage(_frames[CurrentFrame], outputRect,<br>    _rectangle[CurrentFrame].X, _rectangle[CurrentFrame].Y,<br>    _rectangle[CurrentFrame].Width, _rectangle[CurrentFrame].Height, <br>    GraphicsUnit.Pixel, _attributes);</pre>
<h3>Data Driven Map Architecture</h3>
<p>Describing what goes where in a game like this makes much more sense in a data file than inside the code. This means that some aspects of the game are very easy for you to change without even recompiling.</p>
<p>There are two data files that drive most of the look and feel of the game. Things like how the doors open, how the monsters fight, and what happens when you pick things up are, for this sample, hard-coded in the code. But there's no reason why you couldn't
 change the data files to make them even more descriptive and then drive the game from the new files. You could debate file formats and how they are laid out forever, so find something that works for your game and stick to it. To keep down the amount of code,
 the error checking is minimal. For a game that is designed to be modded by the end users, this is something that would have to be improved
</p>
<p><b>Tilelookups.csv</b></p>
<p>This file describes all of the tiles and sprites in the game. It's a comma delimited format that contains the following information:
</p>
<ul>
<li>Name: text name of the item.<br>
</li><li>Shortcut: an abbreviated lookup. This value must be unique and for background tiles must be a single character.<br>
</li><li>Path to bitmap: the bitmap this tile comes from.<br>
</li><li>X<b>:</b> the x count into the tile sheet. 1 is the 1st column. Assumes that the tiles are all the same size.<br>
</li><li>Y: the y count into the tile sheet. 1 is the 1st row. Assumes that the tiles are all the same size.<br>
</li><li>Transparent: Y or N (not case sensitive); if Y the (75, 75, 75) will be color-keyed out.<br>
</li><li>Number of frames: how many frames of animation. The frames must be laid out from left to right with X,Y being frame 0.<br>
</li><li>Traversable: Open or Block (not case sensitive); if Block then the hero cannot pass.<br>
</li><li>Special: For doors and keys this is the color, for characters this is the default health.</li></ul>
<p>Example:</p>
<pre><code>        DoorGreenOpen,G,Door,gamedata\tiles.bmp,5,1,N,1,Open,Green</code></pre>
<p><b>Map.txt</b></p>
<p>This file describes the set of 8 x 8 areas that make up the world. There is a single blank line between each area.
</p>
<ul>
<li>line 1: name of the area (must be unique).<br>
</li><li>line 2: the area you move to when you go North or —<br>
</li><li>line 3: the area you move to when you go East or —<br>
</li><li>line 4: the area you move to when you go South or —<br>
</li><li>line 5: the area you move to when you go West or —<br>
</li><li>lines 6-13: an 8 x 8 grid made up of the shortcut characters from tilelookups.csv.<br>
</li><li>lines 13 onwards: x,y,shortcut. A list of objects and their x,y position in the area; x and y are zero based.<br>
</li><li>final blank line:</li></ul>
<p>Example:</p>
<pre><code>start<br>-<br>forest1<br>-<br>-<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;<br>&gt;.&gt;.....<br>&gt;...^...<br>&gt;....ccc<br>^.^.....<br>^^......<br>&gt;..&gt;....<br>&gt;&gt;^&gt;&gt;&gt;&gt;&gt;<br>1,1,kbr<br>1,6,pot<br>3,1,arm<br>4,1,att<br>4,6,tro<br>5,6,tro<br>6,6,tro<br></code></pre>
<h3>Character Development and Gameplay</h3>
<p>One thing that distinguishes RPGs from other kinds of games is that usually the story is very relevant to the plot rather than being a poor excuse for why the character is about to do something very unlikely. In addition, you usually take the character from
 a low start point to some high point in the game by changing or improving the way that character works. You have probably heard of games with levels, hit points, strength, agility, and more, though different games refer to these differently. The more advanced
 the game gets, the more of these there are to track and the more effect they have in different parts of the game.
</p>
<p>Given the limited space for these games, I chose to have a very simple but often heard story. The princess has been captured by the forces of evil (in this case a wizard since that's what the artist drew) and it is your job to rescue her. The story plays
 out in three settings: an outdoor area, a dungeon, and a castle. Each has a distinct look and type of monster to fight.
</p>
<p>The characters' attributes are: </p>
<ul>
<li>Health, which should stay above 0 and is replenished by food items. <br>
</li><li>Experience, which is earned by killing monsters and gives attack and armor bonuses at certain levels.
<br>
</li><li>Attack rating, which increases your damage and ability to hit.<br>
</li><li>Armor rating, which decreases the ability of others to hit you.<br>
</li><li>Potions, which do damage to all visible monsters.<br>
</li><li>Keys, which are the ones are you holding. </li></ul>
<p>All of these attributes and the code to manipulate them can be found in the GameState or the World classes. There is too much to list here but spend some time looking through to see how the world works. Searching for &quot;Health,&quot; for example, will show you
 all the places that the health points are increased or decreased.</p>
<h2>Extending Crusader</h2>
<ul>
<li>Since most of the game is data driven, open up the maps in Notepad and make some of your own.
<br>
</li><li>Change all of the graphics to make a space themed game. <br>
</li><li>Game too hard or too easy? Change the rules of the game in the code. Give each monster its own attack and armor rating. Let the monsters attack back with magic.
<br>
</li><li>Make the monsters move toward you. You should be able to reuse some of the hero animation code but you will need to implement some path-finding algorithms to avoid obstacles.</li></ul>
<h2>Online Resources</h2>
<ul>
<li>Discuss this Starter Kit in <a href="http://channel9.msdn.com/ShowForum.aspx?ForumID=16">
Channel 9's Techoff forum</a>.<br>
</li><li><a href="http://lab.msdn.microsoft.com/ProductFeedback/">Provide feedback on this documentation.</a><br>
</li><li>Check out <a href="http://blogs.msdn.com/coding4fun/gamedevelopment/default.aspx">
Game Development on Coding4Fun</a>.<br>
<br>
</li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:078dd0d1eadd4ae49e749e7600d8a86e">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-C</comments>
      <itunes:summary>



&amp;nbsp;
Welcome to the Upgrade Your Game series of tutorials. In this article, we will develop a role-playing game Crusader!!!



The Z-man Andy Dunn
The Z Buffer

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware: 
Download: Download






&amp;nbsp; 

 
&amp;nbsp; 


Download Video 
Visual&amp;nbsp;C# Upgrade Your Game Series 

2D Game Primer
Tiny Tennis&amp;nbsp;(note:Tiny Tennis using XNA available)
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp;
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX. 
Not all games are real-time action games. Role-playing games (RPGs) are generally slower paced and involve more thinking. Usually there&#39;s no penalty if you turn your attention to something else for a few moments. Many, many, many years ago,
sometime in the 1970s, RPGs were played using text or graphics made up from text. Since we&#39;re no longer in the 1970s, we can do a little better than that using the sprites from the previous
 games. 
For the fourth and final game, I will be creating a tile-based role-playing game. These days, role-playing games have as good graphics and special effects as any first person shooter. But the origins of graphical role-playing games are tile-based games such
 as the early Final Fantasy and
Ultima games. Because this is a beginner series with limited code, I cannot create even games as complex as those early works; however, I can give you most of the techniques you will need to put together similar-looking
 games. After that, it&#39;s really just up to your imagination. 
Note: This documentation assumes that you have a basic knowledge of programming concepts and </itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-C</link>
      <pubDate>Thu, 09 Nov 2006 14:31:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-C</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1044573_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1044573_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>11</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-C/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Upgrade Your Game: Crusader (Visual Basic)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">Welcome to the Upgrade Your Game series of tutorials. In this article, we will develop a role-playing game Crusader!!!</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b><a href="http://download.microsoft.com/download/2/d/1/2d1afc02-08ea-46d5-88e0-bbe2036b92f9/crusader.vsi">Download</a>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1044573"></a>&nbsp;</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044549/crusader1.png"></a>
</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv"><img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044549/media6.jpg"></a>
<a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/crusader.wmv">
Download Video</a> </p>
<p><strong>Visual Basic Upgrade Your Game Series</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1727545">2D Game Primer</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916341">Tiny Tennis</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916405">Space Blitz</a>&nbsp;
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1044549">Crusader</a></li></ul>
<h2>Introduction</h2>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://blogs.msdn.com/directx/">Microsoft DirectX</a>.</p>
<p>Not all games are real-time action games. Role-playing games (RPGs) are generally slower paced and involve more thinking. Usually there's no penalty if you turn your attention to something else for a few moments. Many, many, many years ago,
<a href="http://en.wikipedia.org/wiki/Dungeon_%28computer_game%29">sometime in the 1970s</a>, RPGs were played using text or graphics made up from text. Since we're no longer in the 1970s, we can do a little better than that using the sprites from the previous
 games.</p>
<p>For the third and final game, I will be creating a tile-based role-playing game. These days, role-playing games have as good graphics and special effects as any first person shooter. But the origins of graphical role-playing games are tile-based games such
 as the early <a href="http://en.wikipedia.org/wiki/Final_Fantasy_VI">Final Fantasy</a> and
<a href="http://en.wikipedia.org/wiki/Ultima">Ultima</a> games. Because this is a beginner series with limited code, I cannot create even games as complex as those early works; however, I can give you most of the techniques you will need to put together similar-looking
 games. After that, it's really just up to your imagination.</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.</p>
<h2>Getting Started&nbsp;</h2>
<h3>Building and Running Crusader</h3>
<p>Once your project is loaded into the Visual Basic environment, you can compile and run the program in one step.
</p>
<p>To build and run Crusader:</p>
<ul>
<li>Press F5 to build and start the game under the debugger. </li></ul>
<p>The game launches and you can use the arrow keys to control the hero and press P to use magic potions. Find the keys to open the doors and kill the wizard who has captured the princess.</p>
<h2>Files </h2>
<table border="1" rules="all" width="595" frame="box" cols="2">
<tbody>
<tr valign="top">
<td width="50%"><b>File</b></td>
<td width="50%"><b>Use</b></td>
</tr>
<tr valign="top">
<td width="50%">Area.cs</td>
<td width="50%">Represents an 8 x 8 area of the world. Each area stores a set of tiles and current state of any dynamic objects. In addition, it stores connectivity information about which areas surround it.</td>
</tr>
<tr valign="top">
<td width="50%">BitmapCache.cs</td>
<td width="50%">A static class that stores bitmaps in a cache. This is used by the Sprite class to save on memory and loading time by reusing bitmaps.</td>
</tr>
<tr valign="top">
<td width="50%">Crusader.cs</td>
<td width="50%">The main display form. Other than UI initialization and keyboard events, little gameplay code is performed in here. Most code calls into GameState.</td>
</tr>
<tr valign="top">
<td width="50%">GameObject.cs</td>
<td width="50%">Abstract base class that represents an object that requires updating and drawing once per frame.</td>
</tr>
<tr valign="top">
<td width="50%">GameState.cs</td>
<td width="50%">Stores the current state of the game and controls all gameplay.</td>
</tr>
<tr valign="top">
<td width="50%">MapTile.cs</td>
<td width="50%">Stores an individual tile. Each tile has a background sprite and an optional transparent sprite in the foreground. In addition, for dynamic sprites such as monsters, we store the current state of that monster, for example, Health.</td>
</tr>
<tr valign="top">
<td width="50%">Sounds.cs</td>
<td width="50%">A static class that plays any of the game sounds.</td>
</tr>
<tr valign="top">
<td width="50%">Tile.cs</td>
<td width="50%">Represents a tile from the data file.</td>
</tr>
<tr valign="top">
<td width="50%">World.cs</td>
<td width="50%">The world is a collection of Areas. This class handles reading of the tile and map files and any gameplay related to the world.</td>
</tr>
</tbody>
</table>
<br>
<h2>Game Development Concepts </h2>
<p>If you are new to 2D game development, check out the <a href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727545.aspx">
2D Game Primer (Visual Basic)</a>.</p>
<h3>Tile-based Games</h3>
<p>Tile-based games get their name from the way the graphics are built up. Instead of having a single graphic for each area in the game, the area is built up from several small tiles. So there is one tile for grass, another with a tree, and another with a brick
 wall. By combining these squares like a patchwork quilt, you can make a huge number of different-looking levels from a small number of graphics. Take a look at the tiles.bmp in the GameData folder to get an idea of what the tiles look like for this game.</p>
I asked the artist to cover three themes:
<ol>
<li>Outdoor—grass, trees, and paths. <br>
</li><li>Castles—walls, floor, and decorations. <br>
</li><li>Dungeon—different walls and floor. </li></ol>
<p>I asked him to create all the sections needed to make paths that connect in any direction, so there are 11 different combinations for each one. In addition, he created three doors of differing colors with both open and closed positions. The doors are themed
 to fit into the castle wall.</p>
<p>You will also see that this file includes tiles for all of the in-game objects. These are not drawn as part of the tile-based background but instead are layered over the top of the tiles depending on the location of the item in the game.</p>
<h3>Extracting Sprites and Animation from Sprite Sheets</h3>
<p>It's far more efficient to load all of the graphics in one go rather then having many different files as I did in Space Blitz. As you have already seen, the graphics for this game are all in one file. Well, actually they are in two. I asked the artist to
 put the multi-frame animations in a second file, so that we could control the layout without having to fit them around the other tiles. Take a look at animations.bmp.</p>
<p>The Sprite class currently loads its own bitmap with a file name, which is not really very efficient either; in SpaceBlitz you loaded the same bitmap multiple times each time it was used. To improve this, I added a constructor that takes an already loaded
 bitmap and just stores the reference to it. Now multiple sprites can share the same bitmap. This doesn't make sense for sprites that you want to change (like the bases in SpaceBlitz), but those are the exception to the rule.</p>
<p>So how does the sprite know which bit of the large bitmap it should draw? In the same constructor, you pass a rectangle structure that describes the top, left, height, and width of the region you wish to extract. When the sprite is drawn it uses this to
 draw only the relevant part. The function also takes the number of frames of animation within that rectangle and automatically subdivides the rectangles to extract the correct frame into the _frames collection.</p>
<b></b>
<p><b>Visual Basic</b></p>
<div class="body">
<div id="1a27d012-7879-4c10-8e9c-be9f8c392e2f" class="postBody">
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Sub</span> <span class="kwrd">New</span>(<span class="kwrd">ByVal</span> gameState <span class="kwrd">As</span> GameState, <span class="kwrd">ByVal</span> x <span class="kwrd">As</span> <span class="kwrd">Single</span>, <span class="kwrd">ByVal</span> y <span class="kwrd">As</span> <span class="kwrd">Single</span>, _<br>               <span class="kwrd">ByVal</span> bitmap <span class="kwrd">As</span> Bitmap, <span class="kwrd">ByVal</span> rectangle <span class="kwrd">As</span> Rectangle, _<br>               <span class="kwrd">ByVal</span> numberAnimationFrames <span class="kwrd">As</span> <span class="kwrd">Integer</span>)<br>    <span class="kwrd">Dim</span> i <span class="kwrd">As</span> <span class="kwrd">Integer</span> = 0<br>    <span class="kwrd">Do</span> <span class="kwrd">While</span> i &lt; numberAnimationFrames<br>        _frames.Add(bitmap)<br> <br>        <span class="rem">'Set the location and use the height and width from the 1st frame</span><br>        initialize(gameState, x, y, rectangle.Width / _<br>        numberAnimationFrames, rectangle.Height)<br> <br>        _rectangle.Add(<span class="kwrd">New</span> Rectangle(rectangle.X &#43; i * rectangle.Width / _<br>        numberAnimationFrames, rectangle.Y, rectangle.Width / _<br>        numberAnimationFrames, rectangle.Height))<br>        i &#43;= 1<br>    <span class="kwrd">Loop</span><br><span class="kwrd">End</span> <span class="kwrd">Sub</span><br><span class="kwrd">Public</span> <span class="kwrd">Overrides</span> <span class="kwrd">Sub</span> Draw(<span class="kwrd">ByVal</span> graphics <span class="kwrd">As</span> <br>Graphics)<br>    graphics.DrawImage(_frames(CurrentFrame), outputRect, _<br>    _rectangle(CurrentFrame).X, _rectangle(CurrentFrame).Y, _<br>    _rectangle(CurrentFrame).Width, _rectangle(CurrentFrame).Height, _<br>    GraphicsUnit.Pixel, _attributes)<br><span class="kwrd">End</span> <span class="kwrd">Sub</span>
</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:Consolas,"Courier New",Courier,Monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:Consolas,"Courier New",Courier,Monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style></div>
</div>
<pre>&nbsp;<code></code></pre>
<h3>Using Color Key to Make Sprites Transparent</h3>
<p>If the game objects were drawn over the top of the tiles in the same way that all of the other sprites are drawn, they would look like this:</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044549/crusader2.png"></p>
<p>In SpaceBlitz, all of the aliens were actually being drawn inside a black box (try changing the form background color and running the game). Since the game background was black, you could not see this. That was fine for SpaceBlitz but obviously isn't suitable
 for Crusader. The technique used is called Color Key and it's the same one used in movies to put actors in front of a green screen into a sci-fi setting. It's more often called
<a href="http://blogs.msdn.com/ControlPanel/Blogs/%20%0A%0Ahttp://en.wikipedia.org/wiki/Chroma_key%20">
chroma key</a>. The general idea is that you do not draw a pixel where it is a certain color. I requested the artist choose an RGB color that he was not using in the artwork and set the backgrounds to that color. He chose (75, 75, 75), which is the dark grey
 you see in the image above. When you ask GDI to draw the shape, you tell it which color to remove and all the magic is done for you giving this corrected image:</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/1044549/crusader3.png"></p>
<p>The code is just a few lines of modification to the sprite drawing routine: colorKey is Color.ToArgb(75, 75, 75).</p>
<b></b>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="rem">'Set the color key for this sprite;</span><br>_attributes= <span class="kwrd">New</span> ImageAttributes()<br>_attributes.SetColorKey(_colorKey, _colorKey)<br> ....<br>graphics.DrawImage(_frames(CurrentFrame), outputRect, _<br>_rectangle(CurrentFrame).X, _rectangle(CurrentFrame).Y, _<br>_rectangle(CurrentFrame).Width, _rectangle(CurrentFrame).Height, _<br>GraphicsUnit.Pixel, _attributes)</pre>
<h3>Data Driven Map Architecture</h3>
<p>Describing what goes where in a game like this makes much more sense to be in a data file than inside the code. This means that some aspects of the game are very easy for you to change without even recompiling.</p>
<p>There are two data files that drive most of the look and feel of the game. Things like how the doors open, how the monsters fight and what happens when you pick things up are, for this sample, hard coded in the code. But there's no reason why you couldn't
 change the data files to make them even more descriptive and then drive the game from the new files. You will be able to debate file formats and how they are laid out forever, so find something that works for your game and stick to it. To keep down the amount
 of code, the error checking is minimal. For a game that is designed to be modded by the end users, this is something that would have to be improved.
</p>
<p><b>Tilelookups.csv</b></p>
<p>This file describes all of the tiles and sprites in the game. It's a comma-delimited format that contains the following information:</p>
<ul>
<li>Name: text name of the item.<br>
</li><li>Shortcut: an abbreviated lookup. This value must be unique and for background tiles must be a single character.<br>
</li><li>Path to bitmap: the bitmap this tile comes from.<br>
</li><li>X<b>:</b> the x count into the tile sheet. 1 is the 1st column. Assumes that the tiles are all the same size.<br>
</li><li>Y: the y count into the tile sheet. 1 is the 1st row. Assumes that the tiles are all the same size.<br>
</li><li>Transparent: Y or N (not case sensitive); if Y the (75, 75, 75) will be color- keyed out.<br>
</li><li>Number of frames: how many frames of animation. The frames must be laid out from left to right with X,Y being frame 0.<br>
</li><li>Traversable: Open or Block (not case sensitive); if Block then the hero cannot pass.<br>
</li><li>Special: For doors and keys this is the color, for characters this is the default health.</li></ul>
<p>Example:</p>
<pre><code>        DoorGreenOpen,G,Door,gamedata\tiles.bmp,5,1,N,1,Open,Green</code></pre>
<p><b>Map.txt</b></p>
<p>This file describes the set of 8 x 8 areas that make up the world. There is a single blank line between each area.
</p>
<ul>
<li>line 1: name of the area (must be unique).<br>
</li><li>line 2: the area you move to when you go North or —<br>
</li><li>line 3: the area you move to when you go East or —<br>
</li><li>line 4: the area you move to when you go South or —<br>
</li><li>line 5: the area you move to when you go West or —<br>
</li><li>lines 6-13: an 8 x 8 grid made up of the shortcut characters from tilelookups.csv.<br>
</li><li>lines 13 onwards: x,y,shortcut. A list of objects and their x,y position in the area; x and y are zero based.<br>
</li><li>final blank line:</li></ul>
<p>Example:</p>
<pre><code>start<br>-<br>forest1<br>-<br>-<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;<br>&gt;.&gt;.....<br>&gt;...^...<br>&gt;....ccc<br>^.^.....<br>^^......<br>&gt;..&gt;....<br>&gt;&gt;^&gt;&gt;&gt;&gt;&gt;<br>1,1,kbr<br>1,6,pot<br>3,1,arm<br>4,1,att<br>4,6,tro<br>5,6,tro<br>6,6,tro</code></pre>
<h3>Character Development and Gameplay</h3>
<p>One thing that distinguishes RPGs from other kinds of games is that usually the story is very relevant to the plot rather than being a poor excuse for why the character is about to do something very unlikely. In addition, you usually take the character from
 a low start point to some high point in the game by changing or improving the way that character works. You have probably heard of games with levels, hit points, strength, agility, and more, though different games refer to these differently. The more advanced
 the game gets, the more of these there are to track and the more effect they have in different parts of the game.
</p>
<p>Given the limited space for these games, I chose to have a very simple but often heard story. The princess has been captured by the forces of evil (in this case a wizard since that's what the artist drew) and it is your job to rescue her. The story plays
 out in three settings: an outdoor area, a dungeon, and a castle. Each has a distinct look and type of monster to fight.
</p>
<p>The characters' attributes are:</p>
<ul>
<li>Health, which should stay above 0 and is replenished by food items. <br>
</li><li>Experience, which is earned by killing monsters and gives attack and armor bonuses at certain levels.
<br>
</li><li>Attack rating, which increases your damage and ability to hit.<br>
</li><li>Armor rating, which decreases the ability of others to hit you.<br>
</li><li>Potions, which do damage to all visible monsters.<br>
</li><li>Keys, which are the ones are you holding. </li></ul>
<p>All of these attributes and the code to manipulate them can be found in the GameState or the World classes. There is too much to list here but spend some time looking through to see how the world works. Searching for &quot;Health,&quot; for example, will show you
 all the places that the health points are increased or decreased.</p>
<h2>Extending Crusader</h2>
<ul>
<li>Since most of the game is data driven, open up the maps in Notepad and make some of your own.
<br>
</li><li>Change all of the graphics to make a space themed game. <br>
</li><li>Game too hard or too easy? Change the rules of the game in the code. Give each monster its own attack and armour rating. Let the monsters attack back with magic.
<br>
</li><li>Make the monsters move toward you. You should be able to reuse some of the hero animation code but you will need to implement some path finding algorithms to avoid obstacles.</li></ul>
<h2>Online Resources</h2>
<ul>
<li>Discuss this Starter Kit in <a href="http://channel9.msdn.com/ShowForum.aspx?ForumID=16">
Channel 9's Techoff forum</a>.<br>
</li><li><a href="http://lab.msdn.microsoft.com/ProductFeedback/">Provide feedback on this documentation.</a><br>
</li><li>Check out <a href="http://blogs.msdn.com/coding4fun/gamedevelopment/default.aspx">
Game Development on Coding4Fun</a>.<br>
<br>
</li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:413320e69e2147d9b8159e7600d8b0d9">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-Visual-Basic</comments>
      <itunes:summary>



&amp;nbsp;
Welcome to the Upgrade Your Game series of tutorials. In this article, we will develop a role-playing game Crusader!!!



The Z-man Andy Dunn
The Z Buffer

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware: 
Download: Download






&amp;nbsp; 

 


Download Video  
Visual Basic Upgrade Your Game Series 

2D Game Primer
Tiny Tennis
Space Blitz&amp;nbsp;
Crusader
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX. 
Not all games are real-time action games. Role-playing games (RPGs) are generally slower paced and involve more thinking. Usually there&#39;s no penalty if you turn your attention to something else for a few moments. Many, many, many years ago,
sometime in the 1970s, RPGs were played using text or graphics made up from text. Since we&#39;re no longer in the 1970s, we can do a little better than that using the sprites from the previous
 games. 
For the third and final game, I will be creating a tile-based role-playing game. These days, role-playing games have as good graphics and special effects as any first person shooter. But the origins of graphical role-playing games are tile-based games such
 as the early Final Fantasy and
Ultima games. Because this is a beginner series with limited code, I cannot create even games as complex as those early works; however, I can give you most of the techniques you will need to put together similar-looking
 games. After that, it&#39;s really just up to your imagination. 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these </itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-Visual-Basic</link>
      <pubDate>Thu, 09 Nov 2006 14:01:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-Visual-Basic</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1044549_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/1044549_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>9</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Crusader-Visual-Basic/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan: A Holiday Screen Saver with DirectX</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">The project is a holiday-themed screen saver called DirectXmas.</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The ZMan</div>
<div class="entry_company"><a href="http://www.indiegameguy.com/blogs/zman/default.aspx">ZMan's Diary</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">C# 2005 Express Edition</a>,
<a href="http://www.microsoft.com/downloads/details.aspx?familyid=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A&amp;displaylang=en">
October 2005 DirectX SDK</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918695/DirectXmasScreenSaver.msi">Download</a>
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<p>The Coding4Fun team asked &quot;Can we have some holiday-themed Coding4Fun articles?&quot;
</p>
<p>Of course it's important to answer questions from the readers too, so over the next few articles I will build a project that answers some questions
<b>and</b> keeps the Coding4Fun &quot;powers that be&quot; happy. Here are some of the questions I will cover:
</p>
<ol>
<li>How can I build a screen saver using Managed DirectX? </li><li>Can you explain how the MatrixStack functions work? </li><li>Can I store my graphics in a resource file? </li></ol>
<p>The project will be a holiday-themed screen saver that I imaginatively called DirectXmas (not because I want to recognize any particular holiday celebration over another, but purely because I get to use the X in DirectX twice). I will use the texturing techniques
 that I explained in the previous articles to animate a series of Christmas trees and other holiday decorations.
</p>
<p><b>Creating the Screen Saver</b> </p>
<p>As luck would have it, C# and VB.Net Express Editions both ship with a screen saver starter kit (Figure 1).
</p>
<p><img height="296" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918695/directxmas_1.gif" width="485" border="0">
</p>
<p><b>Figure 1. The Screen Saver Starter Kit project type in C#.</b> </p>
<p>Reuse is just as important in tutorials as in code, so for instructions on how to create the project in the starter kit head over to
<a href="http://msdn.microsoft.com/coding4fun/weekend/weekend1/default.aspx">Andrew Coates' weekend warriors column</a>, also on
<a href="http://msdn.microsoft.com/coding4fun/">Coding4Fun</a>. You don't need to follow the entire article (unless you want to, of course). Just go as far as creating the project and running it.
</p>
<p>The project will be using the DirectX sample framework code and code from previous articles so add references to Microsoft.DirectX, .Direct3D and .Direct3DX. Browse to the sample framework source (usually C:\Program Files\Microsoft DirectX 9.0 SDK (October
 2005)\Samples\Managed\Common) and add the files that match dx*.cs (avoid the files beginning with
<i>w</i>; they are beta files for a future DirectX SDK). Finally, add the Media folder and the three source files from the
<a href="http://msdn.microsoft.com/coding4fun/zman/zmanTextures3/default.aspx">last texturing article</a>. Solution explorer should look like Figure 2.
</p>
<p><img alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918695/directxmas_2.gif" border="0">
</p>
<p><b>Figure 2. The project start point.</b> </p>
<p>If you try to compile at this point, you will get two errors. The first one complains about unsafe code. The DirectX Framework has some unsafe code in it for performance reasons. You enable this in the project properties as shown in Figure 3.
</p>
<p><img alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918695/directxmas_3.gif" border="0">
</p>
<p><b>Figure 3. Enabling unsafe code for this project.</b> </p>
<p>The second error says that there are two entry points—which makes sense, because at the moment there are two projects merged together. Since the screen saver sample has some useful code in it, you should leave that as the main entry point and rename the
 one in Texture.cs:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">static</span> <span class="kwrd">int</span> Main() </pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>becomes</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">int</span> DirectXmas()</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Everything should now compile and run and you should still see the default screen saver from the sample.
</p>
<p><b>Making the Screen Saver use DirectX</b> </p>
<p>Take a look in the program.cs source file, specifically at the <b>Main()</b> function. Screen savers are just normal .EXEs which have been renamed to .SCR. When they are run, a command-line parameter is passed to tell them if they are supposed to run as
 normal, show the options dialog or show in the preview window. The screen saver runs when the command line is
<b>/s</b> or when there are no parameters. The code is in the <b>ShowScreenSaver()</b> function. To call the old entry point and run our DirectX code, replace the 2 lines of code in that routine with:</p>
<pre><code></code></pre>
<pre class="csharpcode">AskZman.Textures.DirectXmas();</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Run the program now and you will see the textured earth from the last tutorial. But wait, that's really not how screen savers are supposed to look. Firstly, it's in a window, and secondly, it doesn't close when you move the mouse or press a key.
</p>
<p>The sample framework makes it very easy to create a full screen application. Find the line that creates the DirectX device:</p>
<pre><code></code></pre>
<pre class="csharpcode">sampleFramework.CreateDevice( 0, <span class="kwrd">true</span>, Framework.DefaultSizeWidth, <br>      Framework.DefaultSizeHeight, sample);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>then change the &quot;true&quot; to &quot;false&quot;. The second parameter controls whether the device is created in a window. You probably notice that it's running at a low resolution, since the default height and width are 640x480. This is something that could be a setting
 in the screen saver settings screen, but for now using the current screen resolution is acceptable. Change the code to read:</p>
<pre><code></code></pre>
<pre class="csharpcode">sampleFramework.CreateDevice(0, <span class="kwrd">false</span>,<br>      System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, <br>      System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height, <br>      sample);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The program now runs full screen; however, you can only get out by pressing ESC.
</p>
<p>Open the source code for the sample screen saver ScreenSaverForm.cs to see how they check for the mouse and keyboard. The
<b>KeyDown</b> and <b>MouseDown</b> events just close the form and quit the program. The
<b>MouseMove</b> event is a little more complex. The first time it is called, the code stores the position of the mouse. On subsequent calls it checks the mouse to see if it has moved significantly from the stored point. In this case significantly means more
 than 10 pixels in any direction. I'm not 100% sure why the code is like this, but I suspect it just stops desk tremors and minor earthquakes from cancelling the screen saver (vital on the West coast of the USA).
</p>
<p>If you have looked at any of the DirectX samples in any detail, you will know that although you see a form, the code does not in fact inherit from a Windows form, so that code cannot be used unchanged. Fortunately, the sample framework provides similar functionality.
</p>
<p>If you are still looking at the <b>CreateDevice()</b> call above, then look just one line higher to where the application hooks the
<b>KeyDown</b> event.</p>
<pre><code></code></pre>
<pre class="csharpcode">sampleFramework.Window.KeyDown &#43;= <br>      <span class="kwrd">new</span> System.Windows.Forms.KeyEventHandler(sample.OnKeyEvent);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>You should add two more event handlers for the <b>MouseMove</b> and the <b>MouseDown</b> events:</p>
<pre><code></code></pre>
<pre class="csharpcode">sampleFramework.Window.MouseMove &#43;= <br>      <span class="kwrd">new</span> System.Windows.Forms.MouseEventHandler(sample.OnMouseMove);<br>sampleFramework.Window.MouseDown &#43;= <br>      <span class="kwrd">new</span> System.Windows.Forms.MouseEventHandler(sample.OnMouseDown);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The new <b>OnMouseDown()</b> function looks like this:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> OnMouseDown(<span class="kwrd">object</span> sender, System.Windows.Forms.MouseEventArgs e)<br>{<br>      GraphicsWindow window = (GraphicsWindow)sender;<br>      window.Close(); <br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>And you should replace the <b>OnKeyEvent()</b> code with the same two lines. </p>
<p>Using the screen saver sample as an example, the <b>OnMouseMove()</b> function becomes:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> isActive = <span class="kwrd">false</span>;<br><span class="kwrd">private</span> Point mouseLocation;<br><span class="kwrd">private</span> <span class="kwrd">void</span> OnMouseMove(<span class="kwrd">object</span> sender, System.Windows.Forms.MouseEventArgs e)<br>{<br>  <span class="rem">// Set IsActive and MouseLocation only the first time this event is called.</span><br>  <span class="kwrd">if</span>(!isActive)<br>  {<br>    mouseLocation = e.Location;<br>    isActive = <span class="kwrd">true</span>;<br>  }<br>  <span class="kwrd">else</span><br>  {<br>    <span class="rem">// If the mouse has moved significantly since first call, close.</span><br>    <span class="kwrd">if</span> ((Math.Abs(e.Location.X - mouseLocation.X) &gt; 10) ||<br>        (Math.Abs(e.Location.Y - mouseLocation.Y) &gt; 10))<br>    {<br>      GraphicsWindow window = (GraphicsWindow)sender;<br>      window.Close();<br>    }<br>  }<br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Running the program now gives the desired effect. </p>
<p>If you have been following along building the code from the last tutorial there is a little &quot;bug&quot; to fix from last time. The code has a hard coded path to the earth texture which won't work when the screen saver is in the system32 directory where screen
 savers live. You can use the sample framework <b>Utility.FindMediaFile()</b> function to help with locating this. If you look at the source for that function it searches a set of &quot;likely&quot; paths until it finds the named file. In texture.cs,
<b>OnResetDevice()</b> replace the code that loads the earth texture with the following:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Load the textures</span><br>sphericalTexture = TextureLoader.FromFile(e.Device, Utility.FindMediaFile(<span class="str">&quot;earth2k.jpg&quot;</span>)); <br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>To make the program work as a screen saver there are a few manual steps to follow:
</p>
<ol>
<li>Browse to the debug directory and find DirectXmas.exe and rename it to DirectXmas.scr
</li><li>Copy the file to c:\windows\system32. </li><li>Browse to the Media directory and locate the earth2k.jpg and the UI folder </li><li>Copy them to c:\windows\system32. Be sure to copy the whole UI folder and its contents
</li></ol>
<p>Now right-click on your desktop and choose Properties, then select the Screen Saver tab (Figure 4).
</p>
<p><img alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918695/directxmas_4.gif" border="0">
</p>
<p><b>Figure 4. Choosing the DirectXmas screen saver.</b> </p>
<p>Select DirectXmas and press preview to see the result of your work. There's no screen shot because the screen looks exactly like it did at the end of the last tutorial; it just works as a screen saver.
</p>
<p>The code is a long way from being finished: </p>
<ul>
<li>The &quot;Settings&quot; dialog is for the old sample; </li><li>It only runs on one of my two monitors; </li><li>and worst of all, it really didn't put me in the holiday mood yet! </li></ul>
<p>Stay tuned and if you have suggestions please let me know. </p>
<p>Homework for this time (though I've never had anyone send me an answer yet!): </p>
<ul>
<li>Remove the UI code and special rendering, like the shape selection and transparency, from the sample, because it's really no use now that the mouse and keyboard have no function other than cancelling the screen saver.
</li><li>Change the camera/view matrix code so that the screen saver shows rotation around the world—and for special credit, make the world point in the right direction!
</li></ul>
<p>The code in this article uses <a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">
C# 2005 Express Edition</a> and the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A">
October 2005 DirectX SDK</a>. </p>
<p>The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the Zman then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>. </p>
<p>Credits: </p>
<p>Thanks to </p>
<ul>
<li><a href="mailto:web@carlosag.net">Carlos Aguilar</a> for the <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">
code colorizer</a> </li><li><a href="http://www.shatters.net/~t00fri/texfoundry.php4">Fridger Schrempp</a> for the earth texture from the
<a href="http://www.celestiamotherlode.net/catalog/earth.php">Celestia MotherLode</a></li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:f6a157505d334d51acba9e7600d9c919">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX</comments>
      <itunes:summary>



&amp;nbsp;
The project is a holiday-themed screen saver called DirectXmas.



The ZMan
ZMan&#39;s Diary

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: C# 2005 Express Edition,

October 2005 DirectX SDK
Hardware: 
Download: Download








&amp;nbsp; 
The Coding4Fun team asked &amp;quot;Can we have some holiday-themed Coding4Fun articles?&amp;quot;
 
Of course it&#39;s important to answer questions from the readers too, so over the next few articles I will build a project that answers some questions
and keeps the Coding4Fun &amp;quot;powers that be&amp;quot; happy. Here are some of the questions I will cover:
 

How can I build a screen saver using Managed DirectX? Can you explain how the MatrixStack functions work? Can I store my graphics in a resource file? 
The project will be a holiday-themed screen saver that I imaginatively called DirectXmas (not because I want to recognize any particular holiday celebration over another, but purely because I get to use the X in DirectX twice). I will use the texturing techniques
 that I explained in the previous articles to animate a series of Christmas trees and other holiday decorations.
 
Creating the Screen Saver  
As luck would have it, C# and VB.Net Express Editions both ship with a screen saver starter kit (Figure 1).
 

 
Figure 1. The Screen Saver Starter Kit project type in C#.  
Reuse is just as important in tutorials as in code, so for instructions on how to create the project in the starter kit head over to
Andrew Coates&#39; weekend warriors column, also on
Coding4Fun. You don&#39;t need to follow the entire article (unless you want to, of course). Just go as far as creating the project and running it.
 
The project will be using the DirectX sample framework code and code from previous articles so add references to Microsoft.DirectX, .Direct3D and .Direct3DX. Browse to the sample framework source (usually C:\Program Files\Microsoft DirectX 9.0 SDK (October
 2005)\Samples\Managed\Common) and add the files that match dx*.cs</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX</link>
      <pubDate>Wed, 01 Nov 2006 06:48:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918695_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918695_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>3</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan: A Holiday Screen Saver with DirectX, Part 2</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">The project is a holiday-themed screen saver called DirectXmas</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The ZMan</div>
<div class="entry_company"><a href="http://www.indiegameguy.com/blogs/zman/default.aspx">ZMan's Diary</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">C# 2005 Express Edition</a>,
<a href="http://www.microsoft.com/downloads/details.aspx?familyid=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A&amp;displaylang=en">
October 2005 DirectX SDK</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/DirectXmas2-CS.msi">Download Code</a>
</li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/DirectXmas1Homework-CS.msi">Download Code</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<p><a href="http://blogs.msdn.com/coding4fun/archive/2006/11/01/918695.aspx">Last time</a> you created the basic shell of a Managed DirectX screen saver. If you worked on the &quot;homework&quot; you should have a rotating earth screen saver. If you did not do the homework,
 then shame on you. You can download the slightly modified source code from the <a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/DirectXmas1Homework-CS.msi">
DirectXmas Homework for Part 1</a> link above. </p>
<p>This week I will begin the process of adding shapes into the scene to create the holiday theme and you will learn about scene graphs and the DirectX MatrixStack.
</p>
<h4>Drawing a Tree</h4>
<p>In the <a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/912559.aspx">
texturing articles</a> I talked about how DirectX does not contain APIs for mapping textures because it is something that is better done by an artist. Well, creating models falls into the same category. If you want a great-looking Christmas tree, you find one
 on the web, you learn to create models, or you pay an artist. Since this column is about programming, however, I will make a simple tree from the basic shapes in the API. You have a sphere, box, cylinder and teapot to choose from. The cylinder allows you to
 set a radius for the top and bottom, allowing us to make cone shapes. Using a thin cylinder for the trunk and 3 cone shapes for the branches, you can make a tree shape. It will look a little like it came from a cartoon, but that's what game developers call
 &quot;Programmer Art&quot;! </p>
<p>Start by replacing the code that renders the earth with the following: </p>
<p>Class declarations: This code creates transformation matrices to place each of the four objects in the correct place in the world. Since cylinders are created with their length pointing in the wrong direction, you have to rotate them as well as translate
 them:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Mesh trunk;<br><span class="kwrd">private</span> Mesh treeBottom;<br><span class="kwrd">private</span> Mesh treeMiddle;<br><span class="kwrd">private</span> Mesh treeTop;<br><span class="kwrd">private</span> Material trunkMaterial;<br><span class="kwrd">private</span> Material treeMaterial;<br><span class="kwrd">private</span> <span class="kwrd">static</span> Matrix treeOrientation = Matrix.RotationX((<span class="kwrd">float</span>)(-Math.PI / 2.0));<br><span class="kwrd">private</span> Matrix trunkPosition = treeOrientation * Matrix.Translation(0f, -1.1f, 0f);<br><span class="kwrd">private</span> Matrix treeBottomPosition = treeOrientation * Matrix.Translation(0f, -.4f, 0f);<br><span class="kwrd">private</span> Matrix treeMiddlePosition = treeOrientation * Matrix.Translation(0f, .4f, 0f);<br><span class="kwrd">private</span> Matrix treeTopPosition = treeOrientation * Matrix.Translation(0f, 1.2f, 0f); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>OnCreateDevice: This code creates a cylinder for the trunk and three cone shapes for the tree body:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Create materials and Meshes here</span><br>trunkMaterial = <span class="kwrd">new</span> Material();<br>trunkMaterial.Ambient = Color.Brown;<br>trunkMaterial.Diffuse = trunkMaterial.Ambient;<br>treeMaterial = <span class="kwrd">new</span> Material();<br>treeMaterial.Ambient = Color.Green;<br>treeMaterial.Diffuse = treeMaterial.Ambient;<br>trunk = Mesh.Cylinder(e.Device, .2f, .2f, .4f, 32, 16);<br>treeBottom = Mesh.Cylinder(e.Device, 1.0f, .4f, 1f, 32, 16);<br>treeMiddle = Mesh.Cylinder(e.Device, .8f, .2f, 1f, 32, 16);<br>treeTop = Mesh.Cylinder(e.Device, .6f, 0f, 1f, 32, 16); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>OnDestroyDevice:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Dispose meshes here</span><br><span class="kwrd">if</span> (trunk != <span class="kwrd">null</span>) trunk.Dispose();<br><span class="kwrd">if</span> (treeBottom != <span class="kwrd">null</span>) treeBottom.Dispose();<br><span class="kwrd">if</span> (treeMiddle != <span class="kwrd">null</span>) treeMiddle.Dispose();<br><span class="kwrd">if</span> (treeTop != <span class="kwrd">null</span>) treeTop.Dispose(); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>OnFrameRender</b>: In each render pass the trunk and three tree sections are drawn with the correct material and at the correct position and orientation:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Draw the tree</span><br>device.Material = trunkMaterial;<br>device.Transform.World = trunkPosition;<br>trunk.DrawSubset(0);<br>device.Material = treeMaterial; ;<br>device.Transform.World = treeBottomPosition;<br>treeBottom.DrawSubset(0);<br>device.Transform.World = treeMiddlePosition;<br>treeMiddle.DrawSubset(0);<br>device.Transform.World = treeTopPosition;<br>treeTop.DrawSubset(0); </pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>You may well ask where I got all of the numbers for the sizes and positions. I sketched it out on a good old-fashioned piece of paper and then tweaked them once I had the tree rendering.
</p>
<p>There are a few extra lines of code to remove that had to do with the texturing, but once that is all done, the result should look something like this:
</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/directxmas2_1.gif">
</p>
<h4>Problems, Problems, Problems</h4>
<p>I'm sure many of you are thinking &quot;that doesn't look like a very scalable way of doing 3D graphics&quot; and you would be correct. I wanted to show the basics of drawing multiple objects in as simple a way as possible. You can see that for each object you have
 to set the state (materials, transformations, render states, textures, texture states, etc.) and then actually draw it. Position, scale and orientation of the objects is done by setting the world transformation before each draw call. You only have to set a
 state if it changes. For example, notice that I don't set the material for each of the tree segments because it's the same for all of them.
</p>
<p>For a world which may have hundreds or thousands of objects to worry about this is not something that is going to work. A good object-oriented architecture groups together information about each object in a single class; and obviously, when you have multiple
 objects it's smart to store them in a collection. Before I solve those problems though, let's look at one other problem with the current code.
</p>
<p>Imagine if you want to move the tree to the left. You might think that changing the position of the trunk like this would work, but it doesn't:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Matrix trunkPosition = treeOrientation * Matrix.Translation(-1f, -1.1f, 0f); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>It only moves the trunk. Although the tree looks like it is a single object it's actually 4 parts with no relationship between them. So you would have to alter the X position of each part to move the whole tree. Think about your favourite RPG game: When
 the character moves, his sword moves with him and so the tree should move when the trunk moves, as should any ornaments on the tree. The problem here is that each object is positioned absolutely. In other words, when you specify the position you are saying
 exactly where in the world it should be placed. To be able to connect objects you need to use relative positions. This means that instead of treeBottom being at position (<i>x</i>,<i>y</i>,<i>z</i>) it is at (d<i>x</i>, d<i>y</i>, d<i>z</i>) where d<i>x</i>
 is the <b>change</b> in position from the object to which it is connected—in this case, the trunk. Those of you who have done any Web or Windows Forms programming should know all about relative and absolute positioning. This is exactly the same, just with
 an extra dimension. It means that as well as state and position, it's necessary to know which object this one is relative to. If you drew the relationships out for our tree (and some ornaments) it would look something like this:
</p>
<p><img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/directxmas2_2.gif" width="485" height="359">
</p>
<p>The tree object now has a single root called trunk and everything else is described in a way that is relative to the object above it in the structure. This means that if you move or rotate the root, everything else will move and rotate with it. I'm sure
 you have seen a tree structure like this in other code and you know they are fairly easy to implement. Each node in the tree has a collection of child objects of the same type. If you have done any reading on 3D programming theory then you already know that
 this is known as a <a href="http://en.wikipedia.org/wiki/Scene_graph">scene graph</a>. The &quot;scene&quot; is obvious because it represents the objects in our scene; the &quot;graph&quot; part comes from the fact that this kind of structure is more correctly known as a
<a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">directed acyclic graph</a> . I will leave it up to
<a href="http://www.wikipedia.org/">Wikipedia</a> to tell you all about that! </p>
<h4>Solutions, Solutions, Solutions</h4>
<p>There are 3 problems to solve: </p>
<ol>
<li>Collect all of the information about an object together </li><li>Store it in a structure for easier manipulation </li><li>Change the objects so that they draw relative to their parent objects </li></ol>
<p>Add a new class to your solution called <b>GameObject</b>. (I know this isn't a game, but you can't use
<b>3dObject</b> as a class name.) Add the DirectX namespaces and <b>System.Drawing</b>. Make sure you use the same namespace as your main source code file, or include the correct
<code>using</code> statements: </p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">using</span> System;<br><span class="kwrd">using</span> System.Collections.Generic;<br><span class="kwrd">using</span> System.Text;<br><span class="kwrd">using</span> System.Drawing;<br><br><span class="kwrd">using</span> Microsoft.DirectX;<br><span class="kwrd">using</span> Microsoft.DirectX.Direct3D;<br><br><span class="kwrd">namespace</span> AskZman<br>{<br>    <span class="kwrd">public</span> <span class="kwrd">class</span> GameObject<br>    {<br>        <br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>You need to add property accessors for a mesh, a color, a position, an orientation and the children collection. This is a great opportunity to use the snippets functionality in Visual C# 2005 Express Edition. Type &quot;prop&quot; and press Tab twice. You will see
 a template for a property with a private member and a public get/set accessor. </p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/directxmas2_3.gif">
</p>
<p>Type in the type—&quot;Mesh&quot;—and press Tab. Type in the name of the private member variable—&quot;mesh&quot;—and press Tab again. Finally, type in the name of the public property—&quot;Mesh&quot;—and press Enter. Notice that Visual Studio has filled in the correct places in the
 rest of the template for you. </p>
<p>You should repeat this for the following properties: </p>
<p><b>Type</b><br>
<b>private name</b><br>
<b>public name</b> </p>
<p><code></code></p>
<pre class="csharpcode">Vector3<br>position<br>Position<br><br>Vector3<br>orientation<br>Orientation<br><br>List&lt;GameObject&gt;<br>children<br>Children<br><br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Notice that I am using the new generic collection types from .NET 2.0. Previously, this collection would have been just a
<b>List</b>, which can only store things of type <b>Object</b> and so is not strongly typed. If you've written code using
<b>List</b> you will know that your code gets filled with type conversions. With the generic collections everything is strongly typed, so the compiler and VS know exactly what is stored and will enforce it for you.
</p>
<p>Modify the private definitions to set some sensible defaults:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Vector3 position = Vector3.Empty;<br><span class="kwrd">private</span> Vector3 orientation = Vector3.Empty;<br><span class="kwrd">private</span> List&lt;GameObject&gt; children = <span class="kwrd">new</span> List&lt;GameObject&gt;(); </pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Our example only needs to expose a general color rather than the entire material, so the property can be simplified to take a color and create the material as needed:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Material material = <span class="kwrd">new</span> Material();<br><br><span class="kwrd">public</span> Color Color<br>{<br>    get { <span class="kwrd">return</span> material.Ambient; }<br>    set <br>    {<br>        material.Ambient = <span class="kwrd">value</span>;<br>        material.Diffuse = <span class="kwrd">value</span>;<br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Since, most of the time, you will set all of the properties at the same time, it makes sense to have a single constructor to do that for you:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> GameObject(Mesh Mesh, Color Color, Vector3 Position, Vector3 Orientation)<br>{<br>    <span class="kwrd">this</span>.Mesh = Mesh;<br>    <span class="kwrd">this</span>.Color = Color;<br>    <span class="kwrd">this</span>.Position = Position;<br>    <span class="kwrd">this</span>.Orientation = Orientation;<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The only additional code that is needed in this class is the code to render the
<b>GameObject</b>. Since the data structure stores all of the relationships between the objects, all it takes to draw the entire object is to call a method on the root node. The root knows that it has to draw itself and all of its children. The code for rendering
 can be copied from the <b>OnRender</b> routine; rendering the children is a <code>
foreach</code> loop and a recursive call to render each child:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Render(Device device)<br>{<br>    <span class="rem">//draw this object</span><br>    device.Material = material; ;<br>    device.Transform.World = <br>        Matrix.RotationYawPitchRoll(orientation.Z, orientation.Y, orientation.X) <br>        * Matrix.Translation(Position.X, Position.Y, Position.Z);  <br>    mesh.DrawSubset(0);<br><br>    <span class="rem">//if there are any children then draw them too</span><br>    <span class="kwrd">foreach</span> (GameObject child <span class="kwrd">in</span> Children)<br>    {<br>        child.Render(device);<br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The world transformation is created from the orientation and position members for this object. This could be optimized a little by only creating the world matrix when position or orientation is changed, but I wanted to ensure everyone understands where it
 comes from. </p>
<h4>Drawing a Tree for the Second Time</h4>
<p>So let's start again now that there is a better architecture. In the final source code I have left the original code, but commented out, so that you can see both versions side by side.
</p>
<p>Add a <code>using</code> clause for the generic collections:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">using</span> System.Collections.Generic; <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Class Declarations:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Mesh trunk;<br><span class="kwrd">private</span> Mesh treeBottom;<br><span class="kwrd">private</span> Mesh treeMiddle;<br><span class="kwrd">private</span> Mesh treeTop;<br><span class="kwrd">private</span> GameObject tree; <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>OnCreateDevice</b>: Notice that the rotation is only applied to the root node. Since all of the transformations are relative, it means that any transformation applied to a parent node applies to all of the children below it; so rotating the trunk in the
 correct direction rotates the whole tree. Also notice that the positions are now relative and therefore easier to understand:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Create materials and Meshes here</span><br>trunk = Mesh.Cylinder(e.Device, .2f, .2f, .4f, 32, 16);<br>treeBottom = Mesh.Cylinder(e.Device, 1.0f, .4f, 1f, 32, 16);<br>treeMiddle = Mesh.Cylinder(e.Device, .8f, .2f, 1f, 32, 16);<br>treeTop = Mesh.Cylinder(e.Device, .6f, 0f, 1f, 32, 16);<br><br><span class="rem">//For the screen saver we create the meshes and the scene graph at the same time</span><br><span class="rem">//this may not be the most efficient thing for your application to do</span><br>tree = <span class="kwrd">new</span> GameObject(trunk, Color.Brown, <span class="kwrd">new</span> Vector3(0f, -1.1f, 0f), <br>     <span class="kwrd">new</span> Vector3(0f, (<span class="kwrd">float</span>)(-Math.PI / 2),  0f));<br>GameObject bottom = <span class="kwrd">new</span> GameObject(treeBottom, Color.Green, <br>     <span class="kwrd">new</span> Vector3(0f, 1f, 0f), Vector3.Empty);<br>GameObject middle = <span class="kwrd">new</span> GameObject(treeMiddle, Color.Green, <br>     <span class="kwrd">new</span> Vector3(0f, 1f, 0f), Vector3.Empty);<br>GameObject top = <span class="kwrd">new</span> GameObject(treeTop, Color.Green, <br>     <span class="kwrd">new</span> Vector3(0f, 1f, 0f), Vector3.Empty);<br>tree.Children.Add(bottom);<br>bottom.Children.Add(middle);<br>middle.Children.Add(top); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>OnFrameRender:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//Draw the tree</span><br>tree.Render(device); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>But if you run that program you can see it really doesn't look much like a tree any more.
</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/directxmas2_4.gif">
</p>
<p>Although the code stores the positions and rotations as relative to each other, DirectX does not work that way. All DirectX knows about is a single world transform applied before a draw call. So the trunk is positioned and rotated correctly because it is
 at the root. But the other objects are all at absolute position (0,1,0) with no rotation instead of being relative to the trunk. The
<b>Render()</b> routine needs to be modified to remember the position of the parent so that the children can take that into account when they are drawn.
</p>
<p>Since this is such a common way of rendering a scene, DirectX provides helper routines. They are encapsulated in the
<a href="http://msdn.microsoft.com/library/?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx/c/matrixstack/matrixstack.asp">
MatrixStack</a> class. </p>
<h4>Drawing a Tree Using the MatrixStack</h4>
<p>The matrix stack class provides a way for your code to remember the correct world transformation for each node in the tree as you walk through it. As you begin to draw each object, you save the current world transformation using the
<a href="http://msdn.microsoft.com/library/?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx/c/matrixstack/m/push.asp">
Push</a> method. You then add in the transformations for this particular node and they are combined with the transformations already on the stack. You retrieve the final combined transformation by reading the
<a href="http://msdn.microsoft.com/library/?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx/c/matrixstack/p/top.asp">
Top</a> property and use this to set the world transformation. Then you can draw the node and its associated children. Remember that each child will also use the
<b>MatrixStack</b> to remember its transformation. After you have drawn the node and its children, you restore the state of the world transformation by calling
<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx/c/matrixstack/m/pop.asp">
Pop</a> and you can then return from your drawing routine. </p>
<p>Modify the <b>GameObject</b> class to have a single static <b>MatrixStack</b>:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">static</span> MatrixStack stack = <span class="kwrd">new</span> MatrixStack(); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Update the <b>Render()</b> method to push and pop and use the <b>MatrixStack</b> operations to do the transformations:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Render(Device device)<br>{<br>    <span class="rem">//draw this object</span><br>    device.Material = material; ;<br>    stack.Push();<br>    stack.TranslateLocal(position.X, position.Y, position.Z);<br>    stack.RotateYawPitchRollLocal(orientation.Z, orientation.Y, orientation.X);<br>    device.Transform.World = stack.Top;<br>    mesh.DrawSubset(0);<br><br>    <span class="rem">//if there are any children then draw them too</span><br>    <span class="kwrd">foreach</span> (GameObject child <span class="kwrd">in</span> Children)<br>    {<br>        child.Render(device);<br>    }<br><br>    <span class="rem">//Restore the transformations</span><br>    stack.Pop();<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The final rendering should look like a tree once again. You should be able to change the positions and rotations of the individual items and see that the translation affects all of the children automatically.
</p>
<p>For the final source code I have added some decorations to the tree. </p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918692/directxmas2_5.gif">
</p>
<h4>Homework</h4>
<p>You've seen the tree made out of DirectX primitives. Try to make some other holiday models by using just these primitives along with transformations, rotations and the basic scene graph you created. If I get some good ones I will actually use them in the
 next column with your name attached if you want. </p>
<p>The code in this article uses <a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">
Visual C# 2005 Express Edition</a> and the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A">
October 2005 DirectX SDK</a> </p>
<p>The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>. </p>
<p><b>Credits:</b> </p>
<p>Thanks to </p>
<ul>
<li><a href="mailto:web@carlosag.net">Carlos Aguilar</a> for the <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">
code colorizer</a></li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:140c88e6025e4fbfb2799e7600d9adf1">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-2</comments>
      <itunes:summary>



&amp;nbsp;
The project is a holiday-themed screen saver called DirectXmas



The ZMan
ZMan&#39;s Diary

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: C# 2005 Express Edition,

October 2005 DirectX SDK
Hardware: 
Download: 

Download Code
Download Code






&amp;nbsp; 
Last time you created the basic shell of a Managed DirectX screen saver. If you worked on the &amp;quot;homework&amp;quot; you should have a rotating earth screen saver. If you did not do the homework,
 then shame on you. You can download the slightly modified source code from the 
DirectXmas Homework for Part 1 link above.  
This week I will begin the process of adding shapes into the scene to create the holiday theme and you will learn about scene graphs and the DirectX MatrixStack.
 
Drawing a Tree
In the 
texturing articles I talked about how DirectX does not contain APIs for mapping textures because it is something that is better done by an artist. Well, creating models falls into the same category. If you want a great-looking Christmas tree, you find one
 on the web, you learn to create models, or you pay an artist. Since this column is about programming, however, I will make a simple tree from the basic shapes in the API. You have a sphere, box, cylinder and teapot to choose from. The cylinder allows you to
 set a radius for the top and bottom, allowing us to make cone shapes. Using a thin cylinder for the trunk and 3 cone shapes for the branches, you can make a tree shape. It will look a little like it came from a cartoon, but that&#39;s what game developers call
 &amp;quot;Programmer Art&amp;quot;!  
Start by replacing the code that renders the earth with the following:  
Class declarations: This code creates transformation matrices to place each of the four objects in the correct place in the world. Since cylinders are created with their length pointing in the wrong direction, you have to rotate them as well as translate
 them: 

private Mesh trunk;private Mesh treeBottom;private Mesh treeMidd</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-2</link>
      <pubDate>Wed, 01 Nov 2006 06:48:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-2</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918692_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918692_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>2</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-2/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan: A Holiday Screen Saver with DirectX, Part 3</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">The project is a holiday-themed screen saver called DirectXmas.</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The ZMan</div>
<div class="entry_company"><a href="http://www.indiegameguy.com/blogs/zman/default.aspx">ZMan's Diary</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">C# 2005 Express Edition</a>,
<a href="http://www.microsoft.com/downloads/details.aspx?familyid=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A&amp;displaylang=en">
October 2005 DirectX SDK</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918688/DirectXmas3_20-_20CS.msi">Download Code</a>
</li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918688/DirectXmas2Homework.msi">Download Code</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p><a href="http://blogs.msdn.com/coding4fun/archive/2006/11/01/918692.aspx">Last time</a> you used a basic scene graph data structure to draw multiple shapes to create the fir tree with the decorations. Hopefully you had some fun creating new objects out of
 the basic mesh shapes provided by DirectX. Since the final download from last time, I have added another holiday object—a snowman. The body is three spheres, the hat is two cylinders, the nose is a cone just like the tree segments and the eyes are a couple
 more small spheres. In addition, I have added a very large thin box to represent the ground and put the tree creation inside a loop. Because the drawing process is now relative, all you have to do is change the position of the tree trunk and the whole tree
 will draw at a different position. All of the code is identical in style to the tree creation from last time and is almost all inside the
<b>OnCreateDevice</b> function. I've also moved the camera slightly to give a better point of view and slowed the camera rotation. You can download the start point for this column from the link at the top of the article and compare it to where you left off
 last time. The start point looks something like this: </p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918688/directxmas3_1.gif">
</p>
<p>This week you will add some animation to the scene and tidy up the code. </p>
<h4>Flashing Lights</h4>
<p>Animation in a computer game is anything that changes in your scene with time—it's not limited to changing positions or shapes, but any change in the way something is drawn, such as color or a special effect.
</p>
<p>The first animation I am going to cover is changing the colors of the tree decorations. The way the scene is currently described, the only reference to those particular shapes is inside the tree structure. It's possible to walk into the tree structure every
 time you need to change something and search for it, but it's better to be able to go straight to the items you want to change. The first thing to do, then, is add the decorations to a list so they are easy to access. Add the following declaration to store
 them:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> List&lt;GameObject&gt; decorations=<span class="kwrd">new</span> List&lt;GameObject&gt;();<br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Then store a reference as they are added to the scene graph. Modify the contents of the loop in
<b>addOrnaments</b> to this:</p>
<pre><code></code></pre>
<pre class="csharpcode">GameObject decoration=<span class="kwrd">new</span> GameObject(bauble, Color.Red, <br>      <span class="kwrd">new</span> Vector3((<span class="kwrd">float</span>)(baseWidth* Math.Sin(angle)), (<span class="kwrd">float</span>)(baseWidth * Math.Cos(angle)), -0.55f),<br>      Vector3.Empty);<br>decorations.Add(decoration);<br>treepart.Children.Add(decoration); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The sample framework provides a function called <b>OnFrameMove</b> which is always called before any rendering happens. This is the correct place to make updates to the scene, such as animation. Animation is almost always correctly done based on the current
 game time, rather than a fixed increment each time <b>OnFrameMove</b> is called. The combination of different processor speeds and different graphics hardware will mean that you can never guarantee how often
<b>OnFrameMove</b> is called. So, while an animation may play at a perfect speed on your computer, you can be sure somewhere else there is a computer that will be faster and another that will be slower. If you base all of your animations on the current game
 time you can be sure that no matter what the frame rate, everything will move at the speed you want.
</p>
<p>For example, imagine if you want to move an object 5.0 units in the <i>x</i> direction in one second. You could add 0.1 to the
<i>x</i> value on each frame. This would move the object 6.0 per second if the frame rate is 60fps, but it would move it 12.0 in the same time if the frame rate was 120fps on a faster computer. The correct way is to use a calculation based on the current elapsed
 time of the application, such as <code>x=startPoint &#43; 5.0 * appTime</code>. Then, no matter what the frame rate,
<i>x</i> will have changed by exactly 5.0 in 1 second. </p>
<p>You can see how I already do this to change the position of the camera:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">new</span> Vector3(5f * (<span class="kwrd">float</span>)(Math.Sin(appTime/10.0)), .5f, 5f * (<span class="kwrd">float</span>)(Math.Cos(appTime/10.0))) <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><code>appTime</code> is maintained by the framework and passed in to the <b>OnFrameMove</b> function.
</p>
<p>In the case of this animation, you want to change the color of the decorations every
<i>N</i> seconds, where <i>N</i> is a value that the user should be able to select in the Options dialog. There is no Options dialog yet, so for now this will just be a variable. You should also allow the user to disable the animation so there will be a boolean
 variable for that decision. </p>
<p>Add the following declarations:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">//decoration animation control variables</span><br><span class="kwrd">private</span> <span class="kwrd">bool</span> animateDecorations = <span class="kwrd">false</span>;<br><span class="kwrd">private</span> <span class="kwrd">double</span> animateDecorationsTime = 0.2;<br><span class="kwrd">private</span> <span class="kwrd">double</span> lastAnimationTickTime = 0.0;<br><span class="kwrd">private</span> Color[] decorationColors = <span class="kwrd">new</span> Color[] {Color.Red, Color.Blue, <br>      Color.BlanchedAlmond, Color.DarkOrange, Color.HotPink}; <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The animation is very trivial. If enough time has passed since you last animated, then loop through the decorations and give each a random new color in the
<b>OnFrameMove</b> function:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">if</span> (animateDecorations)<br>{<br>    <span class="kwrd">if</span> (appTime - lastAnimationTickTime &gt;; animateDecorationsTime)<br>    {<br>        lastAnimationTickTime = appTime;<br>        Random randomColor = <span class="kwrd">new</span> Random();<br>        <span class="kwrd">foreach</span> (GameObject decoration <span class="kwrd">in</span> decorations)<br>        {<br>            decoration.Color = decorationColors[randomColor.Next(5)];<br>        }<br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>If everything is going to plan you should see the lights change when you run: </p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918688/directxmas3_2.gif">
</p>
<h4>Goodbye Frosty</h4>
<p>That title probably only makes sense to those who have lived in the USA during the holidays.
<a href="http://www.imdb.com/title/tt0064349/">Frosty the Snowman</a> is a classic US holiday cartoon during which Frosty goes out in the sun and suffers the consequences. I can't do an animation worthy of
<a href="http://www.pixar.com/">Pixar</a>, but melting the snowman in this scene is as easy as changing the coordinates of the body parts so that they slide below the &quot;ground.&quot; Leaving the hat on a pile of snow is a nice end point for the animation. The
<b>GameObjects</b> to animate are currently local variables in <b>OnCreateDevice</b>, so promote their scope to the class and leave just their instantiation in
<b>OnCreateDevice</b>:</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> GameObject lowerBodyNode;<br><span class="kwrd">private</span> GameObject upperBodyNode;<br><span class="kwrd">private</span> GameObject headNode;<br><span class="rem">//melting animation control variables</span><br><span class="kwrd">private</span> <span class="kwrd">bool</span> animateSnowman = <span class="kwrd">true</span>;<br><span class="kwrd">private</span> <span class="kwrd">double</span> animateSnowmanSpeed = 120.0f; <span class="rem">//2 minutes change to a lower number if you are not patient!</span><br><span class="rem">//replace the similar lines in OnCreateDevice with these</span><br>lowerBodyNode = <span class="kwrd">new</span> GameObject(body, Color.White, <span class="kwrd">new</span> Vector3(0f, .15f, 0f), Vector3.Empty);<br>upperBodyNode = <span class="kwrd">new</span> GameObject(body, Color.White, <span class="kwrd">new</span> Vector3(0f, .3f, 0f), Vector3.Empty);<br>headNode = <span class="kwrd">new</span> GameObject(head, Color.White, <span class="kwrd">new</span> Vector3(0f, .25f, 0f), Vector3.Empty); <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>To animate these three shapes toward the ground, you just have to decrease the
<i>y</i> component of the position over a suitable period of time in the <b>OnFrameMove</b> function.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">if</span> (animateSnowman)<br>{<br>    <span class="kwrd">if</span> (appTime &lt;; animateSnowmanSpeed)<br>    {<br>        Vector3 position = lowerBodyNode.Position;<br>        position.Y = (<span class="kwrd">float</span>)(0.15 - 0.35 * (appTime / animateSnowmanSpeed));<br>        lowerBodyNode.Position = position;<br><br>        position = upperBodyNode.Position;<br>        position.Y = (<span class="kwrd">float</span>)(0.3 - 0.2 * (appTime / animateSnowmanSpeed));<br>        upperBodyNode.Position = position;<br><br>        position = headNode.Position;<br>        position.Y = (<span class="kwrd">float</span>)(0.25 - 0.15 * (appTime / animateSnowmanSpeed));<br>        headNode.Position = position;<br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Notice that because everything is relative, you don't have to worry about animating the hat, eyes, or nose. Since they are attached to the head, they just move wherever the head moves. The snowman has to stop melting at some point, so this animation stops
 once the application time passes the melting time. Each part of the snowman has its position changed based on the current application time and a speed factor that can be changed.
</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/918688/directxmas3_3.gif">
</p>
<h4>Tidying up the screen saver</h4>
<p>So the graphics work of the screen saver is now complete. If that's all you were interested in, then I will see you next time. The small remaining part of this article is adding in the screen saver controls and removing the remnants of the RSS screen saver
 that you started with. </p>
<p>Since you don't need the RSS media, or the sample UI media, you can remove the media folder. You can also get rid of the documentation folder and the RSS folder as they are no longer needed either. Delete the ScreenSaverForm.cs and then remove the couple
 of lines that still refer to the RSS object. The easiest way is to compile and remove the lines with errors.
</p>
<p>Finally, you need to update the OptionsForm with controls that map to the variables used in the animation. Since this is not a Windows Forms column I will not walk you through this step-by-step but you can download the example code to see how it works. The
 values are saved in the config file just like the screen saver starter kit and are read back when the screen saver starts up. The final code can be downloaded from the link at the top of the article.
</p>
<p>Installing the screen saver is simpler than the first article because there is no media to worry about. Simply rename the .EXE to .SCR and copy it and the config file into the system32 directory. See the first part of this series if you need more detailed
 instructions. </p>
<p>You have now completed a Managed DirectX screen saver using the sample framework, created and used a simple scene graph and learned how to animate object in the scene. Remember that, as I explained in the first part, nobody really creates graphics using
 lots of spheres and cylinders. It's just a convenient way to introduce the scene graph and the animation effects without having to worry about complex models. Hopefully its also been fun in a &quot;Lego&quot; kind of way to think about building shapes out of other shapes.
</p>
<h4>Homework</h4>
<p>I'm sure the first thing most of you did to the code was change the tree density so there were a lot more trees in the scene and I'm sure you were shocked about how quickly the performance of the screen saver dropped. After all you probably paid several
 hundred dollars for a graphics card that could draw millions of triangles per second and yet for some reason a few hundred trees with relatively few triangles is bringing it to its knees. The solutions to these will be in some future Ask The Zman columns,
 but for now I would love to hear your ideas on why you think things are going so slowly on such powerful hardware.
</p>
<p>The code in this article uses <a href="http://msdn.microsoft.com/vstudio/express/visualCsharp/default.aspx">
C# 2005 Express Edition</a> and the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1C8DC451-2DBE-4ECC-8C57-C52EEA50C20A">
October 2005 DirectX SDK</a> </p>
<p>The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan then send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>. </p>
<p><b>Credits:</b> </p>
<p>Thanks to </p>
<ul>
<li><a href="mailto:web@carlosag.net">Carlos Aguilar</a> for the <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">
code colorizer</a></li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:f2b8fcb99b9c425e98569e7600d9ce53">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-3</comments>
      <itunes:summary>



&amp;nbsp;
The project is a holiday-themed screen saver called DirectXmas.



The ZMan
ZMan&#39;s Diary

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: C# 2005 Express Edition,

October 2005 DirectX SDK
Hardware: 
Download: 

Download Code
Download Code






Last time you used a basic scene graph data structure to draw multiple shapes to create the fir tree with the decorations. Hopefully you had some fun creating new objects out of
 the basic mesh shapes provided by DirectX. Since the final download from last time, I have added another holiday object—a snowman. The body is three spheres, the hat is two cylinders, the nose is a cone just like the tree segments and the eyes are a couple
 more small spheres. In addition, I have added a very large thin box to represent the ground and put the tree creation inside a loop. Because the drawing process is now relative, all you have to do is change the position of the tree trunk and the whole tree
 will draw at a different position. All of the code is identical in style to the tree creation from last time and is almost all inside the
OnCreateDevice function. I&#39;ve also moved the camera slightly to give a better point of view and slowed the camera rotation. You can download the start point for this column from the link at the top of the article and compare it to where you left off
 last time. The start point looks something like this:  

 
This week you will add some animation to the scene and tidy up the code.  
Flashing Lights
Animation in a computer game is anything that changes in your scene with time—it&#39;s not limited to changing positions or shapes, but any change in the way something is drawn, such as color or a special effect.
 
The first animation I am going to cover is changing the colors of the tree decorations. The way the scene is currently described, the only reference to those particular shapes is inside the tree structure. It&#39;s possible to walk into the tree structure every
 time you need t</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-3</link>
      <pubDate>Wed, 01 Nov 2006 06:47:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-3</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918688_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/918688_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-A-Holiday-Screen-Saver-with-DirectX-Part-3/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Upgrade Your Game: Space Blitz (Visual C#)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article enhances Space Blitz sample application by adding new features.</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://download.microsoft.com/download/0/7/8/078f6de6-4b20-47a3-9a94-dbf3a0131ca0/space.vsi">C# Download</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<h4>&nbsp;</h4>
<h6><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/blitz.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916430/blitz1.gif"></a></h6>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916430/blitz1.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916430/media6.jpg" border="0"></a>
<a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/blitz.wmv">
Download Video</a> </p>
<p><strong>Visual&nbsp;C# Upgrade Your Game Series</strong></p>
<ul>
<li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727608.aspx">2D Game Primer</a>
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916355.aspx">Tiny Tennis</a>&nbsp;(note:<a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">Tiny Tennis using XNA</a> available)
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916430.aspx">Space Blitz</a>&nbsp;
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/11/09/1044573.aspx">Crusader</a></li></ul>
<h4>&nbsp;</h4>
<h4>Introduction</h4>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.microsoft.com/directx/">Microsoft DirectX</a>. </p>
<p>You probably noticed that the animation in the previous game was not as smooth as you would have expected for such a simple game with so little going on. The main reason for this is because of my choice of picture boxes for the sprites. As I mentioned, this
 is not something that is recommended because there is a lot of overhead that comes with Windows controls. It really is overkill to use a Windows control just to draw a rectangle or any other graphic on the screen. However, it served its purpose for making
 a simple game with only a few lines of code. </p>
<p>For the third game you will take on another classic, a Space Invaders type game. Because this game has sprites that are very clearly not rectangles, and because there are a lot more of them to draw, this example will implement the sprites using bitmap graphics.
</p>
<p>Since most developers are not graphically inclined, this is the time that your game development team needs to grow. Most games these days use graphics that are far more complex than the original
<a href="http://www.klov.com/game_detail.php?letter=&amp;game_id=9662">Space Invaders</a> or
<a href="http://www.klov.com/game_detail.php?letter=&amp;game_id=10816">Pac-man</a> and it's just not realistic to create them yourself. You may be lucky enough to find some royalty-free artwork on the Internet, but if you intend to sell your game, be sure to check
 the specific licensing for that artwork. The safest thing to do, if you are not rich enough to hire someone to produce your art, is to make friends with someone who can.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h4>Getting Started</h4>
<h5>Building and running SpaceBlitz</h5>
<p>Once your project is loaded into the Visual C# environment, you can compile and run the program in one step.
</p>
<p>To build and run SpaceBlitz: </p>
<ul>
<li>Press F5 to build and start the game under the debugger. </li></ul>
<p>The game launches and you can control the base ship using the left and right arrows. Use the spacebar to fire.
</p>
<h4>Files</h4>
<ul>
<li><b>Alien.cs<br>
</b>Inherits from Sprite. Represents a single alien. </li><li><b>Aliens.cs</b><br>
Inherits from GameObject. Represents the group of aliens. Movement of aliens is done as a group. This file also has routines that work on the whole group such as random selection of an alien to drop a bomb.
</li><li><b>Base.cs<br>
</b>Inherits from Sprite. Represents the bases you can shelter behind. Contains routine for per pixel collision and erosion of the bases.
</li><li><b>BaseShip.cs<br>
</b>Inherits from Sprite. Represents the ship. Contains routines for movement controlled by the keyboard.
</li><li><b>Bomb.cs<br>
</b>Inherits from Sprite. Represents bombs. Contains code for collision detection.
</li><li><b>GameObject.cs<br>
</b>Abstract base class that represents an object that requires updating and drawing once per frame.
</li><li><b>GameState.cs</b><br>
Stores the current state of the game and controls all gameplay. </li><li><b>Keyboard.cs<br>
</b>Static class that stores the current up/down state of the control keys. </li><li><b>Missile.cs</b><br>
Inherits from Sprite. Represents missiles. Contains code for collision detection.
</li><li><b>PointFMath.cs<br>
</b>Helper routines for common PointF calculations not included in the PointF class.
</li><li><b>Saucer.cs</b><br>
Inherits from Sprite. Represent the bonus flying saucer. </li><li><b>SpaceBlitz.cs<br>
</b>The main display form. Other than UI initialization and keyboard events, little gameplay code is performed in here. Most code calls into GameState.
</li><li><b>Sprite.cs</b><br>
Inherits from GameObject. Handles basic 2D sprite manipulation and loading.</li></ul>
<h4>Game Development Concepts</h4>
<p>If you are new to 2D game development, check out the <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/2DPrimercs/default.aspx">
2D Game Primer (C#)</a>. </p>
<h5>Bitmap Sprites</h5>
<p>Drawing a <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.bitmap(VS.80).aspx">
bitmap</a> to the screen only requires a few lines of code. Using the code from the TinyTennis sample, you can add a new member variable to store the bitmap and a new constructor that takes the file name of the bitmap file. The
<a href="http://msdn2.microsoft.com/en-us/library/0cbhe98f(VS.80).aspx">bitmap constructor</a> takes a file name, which means it's very easy to load and store.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">protected</span> Bitmap _frame;<br><span class="kwrd">public</span> Sprite(GameState gameState, <span class="kwrd">float</span> x, <span class="kwrd">float</span> y, <span class="kwrd">string</span> filename)<br>{<br>    <span class="rem">//Load the bitmap</span><br>    _frame=<span class="kwrd">new</span> Bitmap(filename);<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Drawing the bitmap is almost as trivial. Drawing to a Windows Form is done using the GDI graphics API, which is contained in the
<a href="http://msdn2.microsoft.com/en-us/library/system.drawing.aspx">System.Drawing namespace</a>. All GDI drawing is done to a
<a href="http://msdn2.microsoft.com/en-us/library/system.drawing.graphics(VS.80).aspx">
Graphics</a> object. This means that you have to provide the graphics object to the Sprite.Draw call. Fortunately, the Paint event gets the Graphics object for the window as part of its EventArgs, so this turns out to be simple to get hold of. Drawing the bitmap
 to the graphics surface is also a single line of code using the <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.graphics.drawimage(VS.80).aspx">
DrawImage </a>method. </p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Draw(Graphics graphics)<br>{<br>    <span class="rem">//Draw the first frame at the current point</span><br>    graphics.DrawImage(_frame, Location.X, Location.Y, Size.Width, Size.Height);<br>} <br> </pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>All of the movement code comes right across from the TinyTennis sample. The aliens move based on a velocity assigned to them. The base ship moves based on a velocity set by the user pressing keys on the keyboard. Once a velocity is set, the Sprite base class
 will continue to animate as time goes by. In addition, the rectangle collision code can be used to check for collisions between missile, aliens, base ships, and saucers. Reuse is great!
</p>
<h5><b>Animating Sprites by Flipping the Image</b> </h5>
<p>Animation isn't just about moving things around the screen. Our aliens need to waggle their arms, legs, and antennae. If you look in the graphics folder, you will see that the artist provided two poses for each alien. To get the animation effect, you simply
 have to draw the images one after the other. Since this game only has two frames of animation, I have created a constructor that takes the two file names and stores them in a list of bitmaps. If you are new to .NET 2.0,
<a href="http://msdn2.microsoft.com/en-us/library/system.collections.generic.aspx">
generics</a> may be new to you so you may want to go and read an <a href="http://msdn.microsoft.com/library/en-us/dnvs05/html/csharp_generics.asp">
introductory article</a>. In the Draw call a decision has to be made which frame to draw and this is done by using the CurrentFrame member variable. CurrentFrame will be set in one of the Update() methods, usually in an inherited class, depending on how fast
 or slow the animation is to be. For this game, only the aliens need image flipping animation so the member is left at its default value of 0 for all of the other sprites.
</p>
<p>Notice that just like the movement animation, the flipping speed is tied to the game time. Almost everything that happens in the Update() methods will be tied to the time, so that, no matter which machine you run on, the timing will stay exactly the same.
</p>
<pre class="csharpcode"><span class="kwrd">protected</span> List&lt;Bitmap&gt; _frames = <span class="kwrd">new</span> List&lt;Bitmap&gt;();<br><span class="kwrd">public</span> Sprite(GameState gameState, <span class="kwrd">float</span> x, <span class="kwrd">float</span> y, <span class="kwrd">string</span> filename1, <span class="kwrd">string</span> filename2)<br><br>{<br>    <span class="rem">//Load the 2 animation frames</span><br>    _frames.Add(<span class="kwrd">new</span> Bitmap(filename1));<br>    _frames.Add(<span class="kwrd">new</span> Bitmap(filename2));<br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Draw(Graphics graphics)<br>{<br>    <span class="rem">//Draw the correct frame at the current point</span><br>    graphics.DrawImage(_frames[CurrentFrame], Location.X, Location.Y, Size.Width, Size.Height);<br>} <br> </pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h5><b>Per Pixel Collisions</b> </h5>
<p>For the bases, checking the rectangle as you did in TinyTennis will not be sufficient because the shapes need to slowly get destroyed by the base ships' bullets and the aliens' missiles. This means that the shape to collide against becomes non-rectangular
 very quickly. In this case, it's necessary to check the bitmap itself to see if the bullet has hit a non-black pixel. For a perfect collision, you need to check every pixel of the first sprite against the second sprite which, as you can imagine, gets slow
 very quickly. So, just like the bounding shape checks were an approximation to the perfect check, you can look for other ways to approximate this kind of collision. Since you know that our bullets only move in the Y direction, there is no need to check for
 anything other than the leading edge of the bullet, which cuts the pixel checks down to 6 pixels. But what if you just check the 2 leading corner pixels? You would miss any collisions that happen between them, but that's just 4 pixels and, for this game, this
 is an acceptable performance/accuracy trade off. </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> CheckPixel(PointF point)<br>{<br>    <span class="rem">//Check this pixel and one 6 to its right (the size of missiles and bombs) to see if we have hit anything</span><br>    <span class="kwrd">return</span> (isPixelOpaque((<span class="kwrd">int</span>)(point.X - Location.X), (<span class="kwrd">int</span>)(point.Y - Location.Y)) || isPixelOpaque((<span class="kwrd">int</span>)(point.X - Location.X &#43; 6), (<span class="kwrd">int</span>)(point.Y - Location.Y)));<br>}<br><span class="kwrd">private</span> <span class="kwrd">bool</span> isPixelOpaque(<span class="kwrd">int</span> x, <span class="kwrd">int</span> y)<br>{<br>    <span class="rem">//If the pixel is out of range that counts as black</span><br>    <span class="kwrd">if</span> (x &lt; 0 || x &gt; _frames[0].Width - 1 || y &lt; 0 || y &gt; _frames[0].Height - 1) <span class="kwrd">return</span> <span class="kwrd">false</span>;<br>    <span class="rem">//Otherwise check for anything that is not black</span><br>    <span class="kwrd">return</span> (_frames[0].GetPixel(x, y) != Color.FromArgb(0, 0, 0));<br>}<br>  [from Aliens.Update()]<br>sprite.CurrentFrame = (<span class="kwrd">int</span>)(((gameTime * _speed) / 50f) % 2f);<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<pre><code>.....</code></pre>
<h5>Destroying Bitmaps </h5>
<p>Now that you can collide on a per pixel basis with the bases, the sprites need to be updated so that they appear to get damaged over time. It's important to do this not just because you draw the sprites in every frame, but because a user could switch applications
 or minimize the game. When the game is restored, you need to be able to redraw the whole screen.
</p>
<p>Since each sprite stores its own copy of the bitmap, it's possible for the Base sprite to set certain pixels within itself to black so that they slowly get removed. Setting the pixels to black means that any future missile will not pass the per pixel test.
 For this game, I have chosen to draw a black circle of a random radius at the point of collision.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Erode(PointF point)<br>{<br>    <span class="rem">//Draw a black circle in the bitmap over the point of intersection</span><br>    <span class="kwrd">using</span> (Graphics graphics = Graphics.FromImage(_frames[0]))<br>    {<br>        graphics.FillEllipse(Brushes.Black, point.X - Location.X - _sizeX / 2 &#43; 3, point.Y - Location.Y - _sizeY / 2, _sizeX, _sizeY);<br>    }<br>} <br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h5><b>Gameplay</b> </h5>
<p>The gameplay here, though not as advanced as in any modern game, is still something that needs to be managed properly. The game needs to be able to detect when all of the aliens are destroyed and recreate a new wave of aliens; it needs to randomly select
 an alien to drop a missile; and it needs to randomly add the bonus flying saucer to the screen.
</p>
<p>If you are not careful with your code structure you will find that these sorts of tasks get randomly scattered around your code. For this game, I have chosen to encapsulate as much of this logic in one place: the GameState class. In the TinyTennis sample,
 this was used to store the scores, but in this game you will use it to store the scores, the level, whether you are currently dropping a missile, how many aliens are left, and several other things that pertain to the current state of the game.
</p>
<p>You will also remember that for the collisions in TinyTennis you had to pass in references to the bats to the Ball object. Obviously this isn't something that is scalable beyond a handful of objects, so for this game the GameState class stores collections
 of all of the game objects and is passed into each object during creation. This means any object has access to any other object if it needs to query it for collisions or any other reason.
</p>
<p>Take a look at the GameState object (there is too much code to post in the tutorial), and see how all the mechanics of the game play function.
</p>
<h4>Extending SpaceBlitz</h4>
<ul>
<li>Make some of the aliens detach themselves from the formation and fly down as in the arcade game
<a href="http://www.klov.com/game_detail.php?letter=&amp;game_id=7885">Galaxian</a> and others.
</li><li>Add a second base ship controlled by a second player for a cooperative experience.
</li><li>Go back to TinyTennis and change it to use bitmaps for the sprites rather than the Windows controls.
</li><li>Add a high-score table and save the high scores so that they are remembered next time you play.
</li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:a995e54b0d9a42b883de9e7600da1c8c">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Space-Blitz-Visual-C</comments>
      <itunes:summary>



&amp;nbsp;
This article enhances Space Blitz sample application by adding new features.



The Z-man Andy Dunn
The Z Buffer

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware: 
Download: 

C# Download






&amp;nbsp;



Download Video  
Visual&amp;nbsp;C# Upgrade Your Game Series 

2D Game Primer
Tiny Tennis&amp;nbsp;(note:Tiny Tennis using XNA available)
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp;
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
You probably noticed that the animation in the previous game was not as smooth as you would have expected for such a simple game with so little going on. The main reason for this is because of my choice of picture boxes for the sprites. As I mentioned, this
 is not something that is recommended because there is a lot of overhead that comes with Windows controls. It really is overkill to use a Windows control just to draw a rectangle or any other graphic on the screen. However, it served its purpose for making
 a simple game with only a few lines of code.  
For the third game you will take on another classic, a Space Invaders type game. Because this game has sprites that are very clearly not rectangles, and because there are a lot more of them to draw, this example will implement the sprites using bitmap graphics.
 
Since most developers are not graphically inclined, this is the time that your game development team needs to grow. Most games these days use graphics that are far more complex than the original
Space Invaders or
Pac-man and it&#39;s just not realistic to create them yourself. You may be lucky enough to find some royal</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Space-Blitz-Visual-C</link>
      <pubDate>Tue, 31 Oct 2006 23:23:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Space-Blitz-Visual-C</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916430_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916430_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>9</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Space-Blitz-Visual-C/RSS</wfw:commentRss>
    </item>
  <item>
      <title>2D Game Primer (Visual C#)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellpadding="1" cellspacing="0" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">This article is a part of Upgrade Your Game series of tutorials. It covers some of the fundamentals of simple math needed for the games in this series.</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Studio Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a>Not available</a> </li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>&nbsp;</p>
<h4>Introduction</h4>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.microsoft.com/directx/">Microsoft DirectX</a>. </p>
<p>When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today's top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
</p>
<p>This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h4>2D Game Development Concepts</h4>
<h5><b>The Game Loop</b></h5>
<p>Window Forms and ASP applications are often called &quot;event-driven&quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that kind of application. </p>
<p>Games, on the other hand, are generally not sitting doing nothing all the time. Even if the end user is not pressing a key or a button on the gamepad, the game must animate characters, perform AI functions, and play sounds and many other things depending
 on the game. You've probably done some of these background type tasks in Windows Forms applications using timer controls or background threads. But in general these don't scale to the computer game scenario, where there are multiple animations and multiple
 background tasks all happening at very different intervals. </p>
<p>The solution that most games use (and by &quot;most games&quot; I mean everything right up to the top-selling Xbox 360 titles) is usually called the &quot;game loop.&quot; In pseudo code it looks something like this:
</p>
<pre class="csharpcode"><span class="kwrd"></span>    While (game is running)<br>        Check for input<br>        Update all objects in the game <br>        Draw all objects in the game<br></pre>
<div class="postBody" id="da00c60d-7813-4288-b54a-0527b29a609d"><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:Consolas,"Courier New",Courier,Monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style></div>
<p>This might explain one reason why games almost always use 100% of your CPU even if they don't appear to be doing much. The faster your computer is, the faster this loop will run and the smoother the animation and the synchronization will be.
</p>
<p>There is one slight problem with running a tight loop like that, at least in Windows. If you don't allow Windows to check for and process Windows messages and events, your application will be marked as &quot;Not responding&quot; by the operating system. You might
 have seen this in your applications if you have a loop that runs for a long time. You might also have solved it by putting a call to DoEvents into the loop, which allows Windows to process the events. This can work reasonably well if you know the loop will
 end eventually, but in this case the loop is the entire game and you need a better way.
</p>
<p>The method I have chosen to use for these games is NOT the most efficient (for a full discussion on this under Managed DirectX see the
<a href="http://www.thezbuffer.com/articles/185.aspx">MDX Game Loop FAQ</a>), but it is the simplest, and none of the games covered here needs the more complex method.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> TinyTennis_Paint(<span class="kwrd">object</span> sender, PaintEventArgs e)<br>{<br>    <span class="rem">//Work out how long since we were last here</span><br>    <span class="kwrd">in</span> seconds<br>    <span class="kwrd">double</span> gameTime = _timer.ElapsedMilliseconds / 1000.0;<br>    <span class="kwrd">double</span> elapsedTime = gameTime - _lastTime;<br>    _lastTime = gameTime;<br>    _frameCounter&#43;&#43;;<br> <br>    <span class="rem">//Perform any animation</span><br><br>    <span class="rem">//Draw the game objects</span><br> <br>   <span class="rem">//Force the next Paint()</span><br>    <span class="kwrd">this</span>.Invalidate();<br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h5><b>Sprites</b></h5>
<p><a href="http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29">Sprites</a> are two-dimensional images that appear in a video game. Sometimes they are static images, but in general they are the building blocks for animation. They either move around
 the screen or change the image at regular intervals, giving a &quot;flip book&quot; kind of animation; or they do both, giving you characters like Mario and Donkey Kong that can move around the screen running and jumping.
</p>
<h5><b>Positioning a Sprite</b></h5>
<p>Just like Windows Forms controls, sprites are placed at an x,y position on the form. 0,0 is the top left and ClientSize.Width, ClientSize.Height is the bottom right. Just like Windows Forms controls, sprites have a height and width too.
</p>
<p>However, unlike Windows Forms controls, sprites are primarily designed to move and animate, often hundreds of times per second, to get the smoothest animation possible. So while a sprite can only be drawn at an integer x,y position, its ACTUAL position at
 a subsecond point in time could be 1.45, 12.67. It's important to remember this position so that the animation doesn't get choppy. A sprite position is stored using a floating-point Point structure PointF rather than the integer-based Point structure like
 Windows Forms controls. This means you can store the subpixel accuracy and then just convert to integer screen positions when you draw them.
</p>
<h5><b>Vectors</b></h5>
<p>The more game programming you do, the more you will come across the term &quot;vector.&quot; Though I've avoided the term in this series for the sake of simplicity, it's worth noting that the concepts are used when the positions of the sprites are updated for animation.
</p>
<p>Simply put, a vector is just an offset. So a vector of (4,2) means that from some start point you move 4 units in the x-axis and 2 in the y-axis.
</p>
<p>You will see positions referred to as vectors. In this case, a position of (4,2) means an offset of (4,2) from the origin.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916381/2dprimer1.png" alt="" border="0">
</p>
<p>Vectors can be added together, so (4,2) &#43; (2,4) gives you a total offset of (6,6).
</p>
<p>Vectors can have negative components, so (-2,1) means move 2 units to the left on the x-axis and 1 unit down on the y-axis.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916381/2dprimer2.png" alt="" border="0">
</p>
<p>All of these concepts are used when moving a sprite around the screen. </p>
<h5><b>Moving a Sprite</b></h5>
<p>Sprites move with a certain velocity. Velocity is different from speed because velocity also contains information about the direction. For example, you could tell me you are driving at 60 mph, and I would guess that in one hour you would be 60 miles from
 the start point. But if you were driving round in a circle, that would not be the case. If I told you my velocity was 60 mph due east, then I would know for sure where you would end up.
</p>
<p>Since your position is an x, y value you can store your velocity as another two-component vector (s, t): s is how fast you want to move on the x-axis, and t is how fast you want to move on the y-axis. If you add them together: (x,y) &#43; (s,t) = (x&#43;s, y&#43;t),
 you get the new position of the sprite. </p>
<p><b>Example: </b>Sprite is at (4,10) and has a speed of (1,0). (1,0) means the sprite will move right in the x direction only. (4,10) &#43; (1,0) = (5,10). If you repeat this addition every second, then the sprite will move 1 pixel per second across the screen.
 You can see that any direction and speed can be represented just by changing the s, t values in that vector.
</p>
<h5><b>Time-Based Animation</b></h5>
<p>Imagine a sprite that starts at x=0 and is moving to the right with a velocity of &#43;10. If you walk through the game loop above, the sprite would have &#43;10 added to its position each time the sprite was updated and would move from x=0 to x={some bigger number}
 where {some bigger number} is 10 times the number of times the loop has been run. But the question is, exactly how fast would it move? Well, it depends on how fast the loop runs, which depends on how fast your computer is running. This would mean that on your
 top-of-the-line gaming rig the sprite could cross the screen in half a second, but on your parents' four-year-old &quot;we only use it for e-mail&quot; computer it could take two seconds. Obviously this isn't something that is desirable in a computer game.
</p>
<p>To fix this you need to think about what velocity really is. What does that &#43;10 mean? Velocity is a measure of distance over a period of time, so you cannot think of the &#43;1 as just a distance; it's really &#43;1 pixel in some time that you need to define. So
 each time round the loop, you just need to know how long it's been since the last update and scale the movement by that time.
</p>
<p>A sprite that has a velocity of &#43;10 actually means you move &#43;10 pixels per second. So if it's been half a second since the last frame, multiply that by the velocity and move 5 pixels. In reality the time between frames is fractions of a second. So on your
 fast gaming rig, where the loop runs very fast, the sprite will move with subpixel accuracy for some very smooth animation. On your parents' computer, where the loop only runs 5 times per second, the sprite will move 2 pixels each frame, but after 10 seconds
 the sprite will be in exactly the same place as it is on your computer. </p>
<p>The code will look something like this (notice that for accuracy elapsedTime is a double and therefore needs to be cast down to a float to match the PointF structure):
</p>
<pre><code></code></pre>
<pre class="csharpcode">    <span class="rem">//Move the sprite based on the velocity</span><br>    Location.X &#43;= Velocity.X * (<span class="kwrd">float</span>)elapsedTime;<br>    Location.Y &#43;= Velocity.Y * (<span class="kwrd">float</span>)elapsedTime;<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The loop timings I mentioned here are very exaggerated — on most computers the loop will be running hundreds or thousands of times per second, meaning that your animations will be very smooth and accurate.
</p>
<h5><b>Sprite bounds</b></h5>
<p>There are two ways to represent the rectangle containing the sprite: </p>
<ol>
<li>X, Y, Height, Width </li><li>X, Y of top left corner and X, Y of bottom right corner </li></ol>
<p>Whilst both of these are valid, you must usually find the first one in use. It's easier to update just one corner as the sprite moves around and calculate the other corner when it's needed. For tasks like collisions- and bounds-checking you need to calculate
 the bottom-right corner, so you will see X&#43;Width and Y&#43;Height as a very commonly used formula in games.
</p>
<h5><b>Simple Collision Detection</b></h5>
<p>Collisions are a vital part of almost any game — they restrict where an object can move, whether an object has taken damage, and so forth.
</p>
<p>Simple collisions can be described in terms of the positions and size of the sprites and the regions they need to collide with. Since everything is rectangular in this case, there is no need for any more complex collisions that need to be determined at the
 pixel level. All the collisions can be checked for by looking to see if the rectangles overlap or if the coordinates are outside of a certain range. Checking for rectangle overlap is
<a href="http://www.tekpool.com/?p=23">quite simple</a>. </p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> collide()<br>{<br><span class="kwrd">return</span> ! ( sprite1.Location.X &gt; sprite2.Location.X &#43; sprite2.Size.Width<br>    || sprite1.Location.X &#43; sprite1.Size.Width  &lt; sprite2.Location.X<br>    || sprite1.Location.Y &gt; sprite2.Location.Y &#43; sprite2.Size.Height<br>    || sprite1.Location.Y &#43; sprite1.Size.Height &lt; sprite2.Location.Y);<br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>This code uses an efficient algorithm for determining if the two rectangles overlap. It checks the bounds of both rectangles to determine whether they DON'T overlap and then negates the result. For example, the first line checks whether the left-hand edge
 of sprite 1 is to the right of the right-hand edge of sprite 2. If it is, then obviously they cannot overlap. The next three lines check the other three edges.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:591d31c12b174336bb739e7600da28e6">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</comments>
      <itunes:summary>



&amp;nbsp;
This article is a part of Upgrade Your Game series of tutorials. It covers some of the fundamentals of simple math needed for the games in this series.



The Z-man Andy Dunn
The Z Buffer

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Studio Express Editions
Hardware: 
Download: 

Not available 






&amp;nbsp; 
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today&#39;s top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
 
This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual C# environment. You can learn more about these topics in the product documentation by clicking
Help on the menu bar, and then clicking Contents, Index, or 
Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
 
2D Game Development Concepts
The Game Loop
Window Forms and ASP applications are often called &amp;quot;event-driven&amp;quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that ki</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</link>
      <pubDate>Tue, 31 Oct 2006 23:04:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C</guid>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>arcade</category>
    </item>
  <item>
      <title>2D Game Primer (Visual Basic)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellpadding="1" cellspacing="0" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">This article is a part of Upgrade Your Game series of tutorials. It covers some of the fundamentals of simple math needed for the games in this series.</span><br>
</td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<div class="entry_company"><a href="http://www.thezbuffer.com/"></a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Studio Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a>Not available</a> </li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<h4>Introduction</h4>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.microsoft.com/directx/">Microsoft DirectX</a>. </p>
<p>When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today's top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
</p>
<p>This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h4>2D Game Development Concepts</h4>
<h5>The Game Loop</h5>
<p>Window Forms and ASP applications are often called &quot;event-driven&quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that kind of application. </p>
<p>Games, on the other hand, are generally not sitting doing nothing all the time. Even if the end user is not pressing a key or a button on the gamepad, the game must animate characters, perform AI functions, and play sounds and many other things depending
 on the game. You've probably done some of these background type tasks in Windows Forms applications using timer controls or background threads. But in general these don't scale to the computer game scenario, where there are multiple animations and multiple
 background tasks all happening at very different intervals. </p>
<p>The solution that most games use (and by &quot;most games&quot; I mean everything right up to the top-selling Xbox 360 titles) is usually called the &quot;game loop.&quot; In pseudo code it looks something like this:
</p>
<pre class="csharpcode">    While (game is running)<br>        Check for input<br>        Update all objects in the game <br>        Draw all objects in the game</pre>
<p>This might explain one reason why games almost always use 100% of your CPU even if they don't appear to be doing much. The faster your computer is, the faster this loop will run and the smoother the animation and the synchronization will be.
</p>
<p>There is one slight problem with running a tight loop like that, at least in Windows. If you don't allow Windows to check for and process Windows messages and events, your application will be marked as &quot;Not responding&quot; by the operating system. You might
 have seen this in your applications if you have a loop that runs for a long time. You might also have solved it by putting a call to DoEvents into the loop, which allows Windows to process the events. This can work reasonably well if you know the loop will
 end eventually, but in this case the loop is the entire game and you need a better way.
</p>
<p>The method I have chosen to use for these games is NOT the most efficient (for a full discussion on this under Managed DirectX see the
<a href="http://www.thezbuffer.com/articles/185.aspx">MDX Game Loop FAQ</a>), but it is the simplest, and none of the games covered here needs the more complex method.
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> TinyTennis_Paint(<span class="kwrd">ByVal</span> sender <span class="kwrd">As</span> <span class="kwrd">Object</span>, <span class="kwrd">ByVal</span> e <span class="kwrd">As</span> PaintEventArgs) <span class="kwrd">Handles</span> <span class="kwrd">MyBase</span>.Paint<br>    <span class="rem">'Perform any animation here</span><br> <br>    <span class="rem">'Draw the game objects here</span><br> <br>    <span class="rem">'Force the next Paint()</span><br>    <span class="kwrd">Me</span>.Invalidate()<br><span class="kwrd">End</span> <span class="kwrd">Sub</span>
</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Sprites</b></p>
<p><a href="http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29">Sprites</a> are two-dimensional images that appear in a video game. Sometimes they are static images, but in general they are the building blocks for animation. They either move around
 the screen or change the image at regular intervals, giving a &quot;flip book&quot; kind of animation; or they do both, giving you characters like Mario and Donkey Kong that can move around the screen running and jumping.
</p>
<h5>Positioning a Sprite</h5>
<p>Just like Windows Forms controls, sprites are placed at an x,y position on the form. 0,0 is the top left and ClientSize.Width, ClientSize.Height is the bottom right. Just like Windows Forms controls, sprites have a height and width too.
</p>
<p>However, unlike Windows Forms controls, sprites are primarily designed to move and animate, often hundreds of times per second, to get the smoothest animation possible. So while a sprite can only be drawn at an integer x,y position, its ACTUAL position at
 a subsecond point in time could be 1.45, 12.67. It's important to remember this position so that the animation doesn't get choppy. A sprite position is stored using a floating-point Point structure PointF rather than the integer-based Point structure like
 Windows Forms controls. This means you can store the subpixel accuracy and then just convert to integer screen positions when you draw them.
</p>
<h5><b>Vectors</b></h5>
<p>The more game programming you do, the more you will come across the term &quot;vector.&quot; Though I've avoided the term in this series for the sake of simplicity, it's worth noting that the concepts are used when the positions of the sprites are updated for animation.
</p>
<p>Simply put, a vector is just an offset. So a vector of (4,2) means that from some start point you move 4 units in the x-axis and 2 in the y-axis.
</p>
<p>You will see positions referred to as vectors. In this case, a position of (4,2) means an offset of (4,2) from the origin.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916368/2dprimer1.png" alt="" border="0">
</p>
<p>Vectors can be added together, so (4,2) &#43; (2,4) gives you a total offset of (6,6).
</p>
<p>Vectors can have negative components, so (-2,1) means move 2 units to the left on the x-axis and 1 unit down on the y-axis.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916368/2dprimer2.png" alt="" border="0">
</p>
<p>All of these concepts are used when moving a sprite around the screen. </p>
<h5><b>Moving a Sprite</b></h5>
<p>Sprites move with a certain velocity. Velocity is different from speed because velocity also contains information about the direction. For example, you could tell me you are driving at 60 mph, and I would guess that in one hour you would be 60 miles from
 the start point. But if you were driving round in a circle, that would not be the case. If I told you my velocity was 60 mph due east, then I would know for sure where you would end up.
</p>
<p>Since your position is an x, y value you can store your velocity as another two-component vector (s, t): s is how fast you want to move on the x-axis, and t is how fast you want to move on the y-axis. If you add them together: (x,y) &#43; (s,t) = (x&#43;s, y&#43;t),
 you get the new position of the sprite. </p>
<p><b>Example: </b>Sprite is at (4,10) and has a speed of (1,0). (1,0) means the sprite will move right in the x direction only. (4,10) &#43; (1,0) = (5,10). If you repeat this addition every second, then the sprite will move 1 pixel per second across the screen.
 You can see that any direction and speed can be represented just by changing the s, t values in that vector.
</p>
<h5><b>Time-Based Animation</b></h5>
<p>Imagine a sprite that starts at x=0 and is moving to the right with a velocity of &#43;10. If you walk through the game loop above, the sprite would have &#43;10 added to its position each time the sprite was updated and would move from x=0 to x={some bigger number}
 where {some bigger number} is 10 times the number of times the loop has been run. But the question is, exactly how fast would it move? Well, it depends on how fast the loop runs, which depends on how fast your computer is running. This would mean that on your
 top-of-the-line gaming rig the sprite could cross the screen in half a second, but on your parents' four-year-old &quot;we only use it for e-mail&quot; computer it could take two seconds. Obviously this isn't something that is desirable in a computer game.
</p>
<p>To fix this you need to think about what velocity really is. What does that &#43;10 mean? Velocity is a measure of distance over a period of time, so you cannot think of the &#43;1 as just a distance; it's really &#43;1 pixel in some time that you need to define. So
 each time round the loop, you just need to know how long it's been since the last update and scale the movement by that time.
</p>
<p>A sprite that has a velocity of &#43;10 actually means you move &#43;10 pixels per second. So if it's been half a second since the last frame, multiply that by the velocity and move 5 pixels. In reality the time between frames is fractions of a second. So on your
 fast gaming rig, where the loop runs very fast, the sprite will move with subpixel accuracy for some very smooth animation. On your parents' computer, where the loop only runs 5 times per second, the sprite will move 2 pixels each frame, but after 10 seconds
 the sprite will be in exactly the same place as it is on your computer. </p>
<p>The code will look something like this (notice that for accuracy elapsedTime is a double and therefore needs to be cast down to a float to match the PointF structure):
</p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="rem">'Move the sprite based on the velocity</span><br>Location.X &#43;= Velocity.X * <span class="kwrd">CSng</span>(elapsedTime)<br>Location.Y &#43;= Velocity.Y * <span class="kwrd">CSng</span>(elapsedTime)<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The loop timings I mentioned here are very exaggerated — on most computers the loop will be running hundreds or thousands of times per second, meaning that your animations will be very smooth and accurate.
</p>
<h5>Sprite bounds</h5>
<p>There are two ways to represent the rectangle containing the sprite: </p>
<ol>
<li>X, Y, Height, Width </li><li>X, Y of top left corner and X, Y of bottom right corner </li></ol>
<p>Whilst both of these are valid, you must usually find the first one in use. It's easier to update just one corner as the sprite moves around and calculate the other corner when it's needed. For tasks like collisions- and bounds-checking you need to calculate
 the bottom-right corner, so you will see X&#43;Width and Y&#43;Height as a very commonly used formula in games.
</p>
<h5>Simple Collision Detection</h5>
<p>Collisions are a vital part of almost any game — they restrict where an object can move, whether an object has taken damage, and so forth.
</p>
<p>Simple collisions can be described in terms of the positions and size of the sprites and the regions they need to collide with. Since everything is rectangular in this case, there is no need for any more complex collisions that need to be determined at the
 pixel level. All the collisions can be checked for by looking to see if the rectangles overlap or if the coordinates are outside of a certain range. Checking for rectangle overlap is
<a href="http://www.tekpool.com/?p=23">quite simple</a>. </p>
<pre><code></code></pre>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Function</span> collide() <span class="kwrd">As</span> <span class="kwrd">Boolean</span><br>    <span class="kwrd">Return</span> <span class="kwrd">Not</span> (Sprite1.Location.X &gt; Sprite2.Location.X &#43; Sprite2.Size.Width      <span class="kwrd">OrElse</span> _<br>    Sprite1.Location.X &#43; Sprite1.Size.Width  &lt; Sprite2.Location.X <span class="kwrd">OrElse</span> _<br>    Sprite1.Location.Y &gt; Sprite2.Location.Y &#43; Sprite2.Size.Height <span class="kwrd">OrElse</span> _<br>    Sprite1.Location.Y &#43; Sprite1.Size.Height &lt; Sprite2.Location.Y)<br><span class="kwrd">End</span> Function</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>This code uses an efficient algorithm for determining if the two rectangles overlap. It checks the bounds of both rectangles to determine whether they DON'T overlap and then negates the result. For example, the first line checks whether the left-hand edge
 of sprite 1 is to the right of the right-hand edge of sprite 2. If it is, then obviously they cannot overlap. The next three lines check the other three edges.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:dbe04b168e9848f49ae19e7600da2b15">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</comments>
      <itunes:summary>



&amp;nbsp;
This article is a part of Upgrade Your Game series of tutorials. It covers some of the fundamentals of simple math needed for the games in this series.




The Z-man Andy Dunn
The Z Buffer


Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Studio Express Editions
Hardware: 
Download: 

Not available 






Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
When you program games, you have to use math whether you want to or not. The simpler the game, the less math there is to learn, and 2D games use simpler math — but you cannot avoid it altogether. Today&#39;s top-selling 3D games are full of 3D vector math and
 complex simulations of physics. Fortunately, you do not need to know all of that for the simple games presented in this series.
 
This 2D primer covers some of the fundamentals of simple math needed for the games in this series.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
Help on the menu bar, and then clicking Contents, Index, or 
Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
 
2D Game Development Concepts
The Game Loop
Window Forms and ASP applications are often called &amp;quot;event-driven&amp;quot; applications — they sit doing nothing for most of the time waiting for an external stimulus, such as a button press from an end user or a Web service request from another application. This
 works really well for that kind </itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</link>
      <pubDate>Tue, 31 Oct 2006 22:58:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic</guid>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-Basic/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>arcade</category>
    </item>
  <item>
      <title>Upgrade Your Game: TinyTennis (C#)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article is a part of Upgrade Your Game series of tutorials. It walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://download.microsoft.com/download/0/7/8/078f6de6-4b20-47a3-9a94-dbf3a0131ca0/tennis.vsi">C# Download</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p><b>Demo Video</b> </p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/tennis1.gif" border="0"></a>
</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/media6.jpg" border="0"></a>
<a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv">
Download Video</a> </p>
<p><strong>Visual&nbsp;C# Upgrade Your Game Series</strong></p>
<ul>
<li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2007/02/20/1727608.aspx">2D Game Primer</a>
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916355.aspx">Tiny Tennis</a>&nbsp;(note:<a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx">Tiny Tennis using XNA</a> available)
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/916430.aspx">Space Blitz</a>&nbsp;
</li><li><a class="" href="http://blogs.msdn.com/coding4fun/archive/2006/11/09/1044573.aspx">Crusader</a></li></ul>
<h4>&nbsp;</h4>
<h4>Introduction</h4>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.microsoft.com/directx/">Microsoft DirectX</a>. </p>
<p>Let's begin by creating a really simple game like <a href="http://www.pong-story.com/">
Pong!</a>, which uses only three moving objects and a straightforward gameplay and scoring technique. Given that you probably play games thousands of times more complex than this (such as The Sims or Half Life), you may initially dismiss this exercise as a
 waste of time; however, it's a great way to learn some of the fundamental concepts of video games in just a few lines of code. If these techniques are already familiar to you, then you may be interested in the
<a href="http://www.microsoft.com/events/series/msdnvideodev.mspx">MSDN game development webcasts</a>, which cover 2D and 3D game development with Managed DirectX.
</p>
<p>This tutorial walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.
</p>
<p>You are also free to use the source code as the basis for your own projects, and to share your work with others or upload it to the Internet.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h4>Getting Started</h4>
<h4>Building and Running TinyTennis</h4>
<p>Once your project is loaded into the Visual Basic environment, you can compile and run the program in one step.
</p>
<p>To build and run TinyTennis: </p>
<ul>
<li>Press F5 to build and start the game under the debugger. </li></ul>
<p>The game launches and you can control the left bat using the Q and A keys. </p>
<h4>Files</h4>
<ul>
<li><b>Sprite.cs<br>
</b>The base class for the sprites. It contains initialization code and basic movement code.
</li><li><b>TinyTennis.cs</b><br>
The main form for the application. It initializes the sprites for the bats and ball, passes keyboard intput to the bats, and controls drawing the game to the screen.
</li><li><b>ControlSprite.cs<br>
</b>An implementation of a sprite that uses a Windows control to draw to the screen.
</li><li><b>Bat.cs<br>
</b>A ControlSprite representing the bat. Contains the keyboard movement code for human players and AI code for computer players.
</li><li><b>Ball.cs</b><br>
A ControlSprite representing the ball. Contains the code for checking for collisions with the walls and the bats and the bounces. Also plays the only sound in the game.
</li><li><b>GameState.cs<br>
</b>Stores the scores.</li></ul>
<p>&nbsp;</p>
<h4>Game Development Concepts</h4>
<p>If you are new to 2D game development, check out the <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/2DPrimervb/default.aspx">
2D Game Primer (Visual Basic)</a>. </p>
<p><b></b></p>
<p><b>Implementing Sprites</b> </p>
<p>For TinyTennis, you'll need three very simple rectangular sprites that can be moved around the screen. In order to keep things simple for the first game (and because I recognize that a lot of .NET developers come from a Windows Forms background), I have
 chosen to use PictureBox controls to represent the sprites. A picture box has all the characteristics needed for this simple game:
</p>
<ul>
<li>It's rectangular. </li><li>It can have a background color. </li><li>It can be positioned at specific positions on the screen. </li></ul>
<p>Using a picture box is not something you would do in a real computer game, but it's something that is very simple to get started with and hopefully something you already know about. In the next game, you will replace the picture box with real graphics.
</p>
<p>The base class definition is: </p>
<pre></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Sprite<br>{<br>    <span class="kwrd">public</span> PointF Velocity;<br>    <span class="kwrd">public</span> PointF Location;<br>    <span class="kwrd">public</span> SizeF Size;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The inherited class adds a member for the control. </p>
<pre></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ControlSprite : Sprite<br>{<br>    <span class="kwrd">public</span> Control Control;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The inherited class defines how to draw it. Since Windows Forms can only be positioned at integer pixel boundaries, you have to round the sprite positions.
</p>
<pre></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Draw()<br>{<br>    <span class="rem">//Move the control to the correct location </span><br>    Control.Location = <span class="kwrd">new</span> Point((<span class="kwrd">int</span>)(Location.X &#43; .5f), (<span class="kwrd">int</span>)(Location.Y &#43; .5f));<br>     <span class="rem">//and redraw it</span><br>    Control.Refresh();<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The Windows Forms controls used in this game are created in the designer by dragging picture boxes onto the form. Since the size and position are set in the code, there's no need to position or size them correctly in the designer. All you need to do is name
 them correctly. </p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/tennis2.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/tennis2_thumb.gif" border="0"></a>
</p>
<p><b>(Click image to zoom)</b> </p>
<p><b></b></p>
<p><b>Code structure</b> </p>
<p>Just because the game is simple doesn't mean that you should avoid good software engineering practices. This is especially important since you want to create a base on which to build the next two games. And, although Visual Studio Express has some refactoring
 support, it always helps to get things right from the beginning. </p>
<p>The most important class is the sprite. Sprites have a position and a velocity. Velocity is how fast the position changes in pixels per second. If velocity is 0, then the position will stay the same and you'll have a static sprite. In addition, you need
 to remember how big the sprite is so that you can work out collisions. </p>
<p>The game loop needs to call each sprite and perform two tasks: update and draw. Since you know the velocity, you can implement the movement part of the animation in the base class. Any complex or additional updates will be handled in an inherited class.
 For this game, drawing the sprite will be left to an inherited class since there is no general case.
</p>
<p>Because I'm using PictureBox controls, I've decided to create an inherited ControlSprite class that can be thrown away in the later examples. ControlSprite sets the position of the control that represents the sprite and calls the RefreshMethod to paint it
 on the screen. </p>
<p>The Bat and Ball objects inherit from ControlSprite and provide the special processing that each of those require. For example the Bat class changes its velocity based on keyboard presses and AI. The Ball class changes its velocity based on collisions with
 bats and the edges of the gameplay area. </p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/tennis3.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916355/tennis3_thumb.gif" border="0"></a>
</p>
<p><b>(Click image to zoom)</b> </p>
<h6>Implementing Time Based Animation</h6>
<p>As mentioned in <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/2DPrimervb/default.aspx">
2D Game Primer (Visual Basic)</a>, it's important to move the sprites based on time rather than a fixed distance per frame.
</p>
<p>The first thing to do is make sure you have an accurate measure of the time. The .NET Framework 2.0 added the StopWatch class, which uses the most accurate measure available on your computer.
</p>
<pre></pre>
<pre class="csharpcode"><span class="kwrd">private</span> Stopwatch _timer = <span class="kwrd">new</span> Stopwatch();<br><span class="kwrd">public</span> TinyTennis()<br>{<br>    <span class="rem">//Initialise and start the timer</span><br>    _lastTime = 0.0;<br>    _timer.Start();<br>}<br><span class="kwrd">private</span> <span class="kwrd">void</span> TinyTennis_Paint(<span class="kwrd">object</span> sender, PaintEventArgs e)<br>{<br>    <span class="rem">//Work out how long since we were last here in seconds </span><br>    <span class="kwrd">double</span> gameTime = _timer.ElapsedMilliseconds / 1000.0;<br>    <span class="kwrd">double</span> elapsedTime = gameTime - _lastTime;<br>    _lastTime = gameTime;<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Sometimes animation is based on how far into the game you are; sometimes it's based on how long it has been since the last time around the game loop. Rather than having every object calculate these two values, you do it once and pass it to the Update() function
 for each object. </p>
<p>The Update method of the Sprite objects and their inherited classes eventually gets called with these times:
</p>
<pre></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> Update(<span class="kwrd">double</span> gameTime, <span class="kwrd">double</span> elapsedTime)<br>{<br>    <span class="rem">//Move the sprite based on the velocity</span><br>    Location.X &#43;= Velocity.X * (<span class="kwrd">float</span>)elapsedTime;<br>    Location.Y &#43;= Velocity.Y * (<span class="kwrd">float</span>)elapsedTime;<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h4>Simple AI (Artificial Intelligence)</h4>
<p>The interesting thing about AI for TinyTennis is actually making the AI do things wrong. It's interesting because normally AI is about making a computer play well. For this game playing, a perfect game is trivial for the computer:
</p>
<ul>
<li>Calculate the exact position the ball will end up and move the bat there. This involves some math but is simple to do.
</li><li>Track the ball by moving the bat towards the current Y position of the ball. There is no math involved, but as long as the ball speed is not greater than the bat speed this will always work.
</li></ul>
<p>Of course this kind of opponent is no fun to play against, so the AI challenge for this game is making the computer miss the ball in a realistic, human way. I have chosen to take three approaches to this:
</p>
<ol>
<li>The computer doesn't start moving the bat until the ball is close to the computer side of the screen. How close can be varied to make the AI smarter or dumber.
</li><li>The computer doesn't track bounces — it will look which way the ball is heading and move towards it, but a last-minute bounce may throw it off.
</li><li>Just like a human, sometimes the computer will over- or underestimate how well it tracks the ball. This is implemented by adding a random offset into the movement that can, once again, be varied to change the skill level.
</li></ol>
<h4>Extending TinyTennis</h4>
<ul>
<li>Add a start-up splash screen that allows the player to choose between one and two players.
</li><li>Add an additional bat for each player by creating an extra picture box, and then creating additional Bat objects.
</li><li>Add multiple balls. The game play will need to change a little. For example, do you want to pause the game when a point is scored? Or, do you want to score the point and make a new ball appear?
</li><li>Since the sprites are just picture boxes, you can set the background image property to give the game a whole new look and feel. Remember that the collision detection is done based on the rectangular shape of the picture box; if the image does not fill the
 picture box, it might look odd when the ball bounces.</li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:4e97fbbe0aaf4a089ea69e7600da2edc">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-TinyTennis-C</comments>
      <itunes:summary>



&amp;nbsp;
This article is a part of Upgrade Your Game series of tutorials. It walks you through the game architecture components for our tribute to Pong!, which we&#39;ll call TinyTennis.



The Z-man Andy Dunn
The Z Buffer

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware: 
Download: 

C# Download






Demo Video  

 


Download Video  
Visual&amp;nbsp;C# Upgrade Your Game Series 

2D Game Primer
Tiny Tennis&amp;nbsp;(note:Tiny Tennis using XNA available)
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp;
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
Let&#39;s begin by creating a really simple game like 
Pong!, which uses only three moving objects and a straightforward gameplay and scoring technique. Given that you probably play games thousands of times more complex than this (such as The Sims or Half Life), you may initially dismiss this exercise as a
 waste of time; however, it&#39;s a great way to learn some of the fundamental concepts of video games in just a few lines of code. If these techniques are already familiar to you, then you may be interested in the
MSDN game development webcasts, which cover 2D and 3D game development with Managed DirectX.
 
This tutorial walks you through the game architecture components for our tribute to Pong!, which we&#39;ll call TinyTennis.
 
You are also free to use the source code as the basis for your own projects, and to share your work with others or upload it to the Internet.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics i</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-TinyTennis-C</link>
      <pubDate>Tue, 31 Oct 2006 22:50:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-TinyTennis-C</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916355_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916355_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>25</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-TinyTennis-C/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Upgrade Your Game: Tiny Tennis (Visual Basic)</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article is a part of Upgrade Your Game series of tutorials. It walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Basic or Visual C# Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://download.microsoft.com/download/2/d/1/2d1afc02-08ea-46d5-88e0-bbe2036b92f9/tennis.vsi">VB Download</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p><b>Demo Video</b></p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/tennis1.gif" border="0"></a>
</p>
<p><a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/media6.jpg" border="0"></a>
<a href="http://download.microsoft.com/download/3/b/a/3ba16a61-f2c1-4ab6-94b4-5a232335f95e/tinytennis.wmv">
Download Video</a></p>
<p><strong>Visual Basic Upgrade Your Game Series</strong></p>
<ul>
<li><a class="" href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1727545">2D Game Primer</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916341">Tiny Tennis</a>
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=916405">Space Blitz</a>&nbsp;
</li><li><a href="http://msdn.microsoft.com/coding4fun/gaming/arcade/article.aspx?articleid=1044549">Crusader</a></li></ul>
<p>&nbsp;</p>
<h4>Introduction</h4>
<p>Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
<a href="http://msdn.microsoft.com/directx/">Microsoft DirectX</a>. </p>
<p>Let's begin by creating a really simple game like <a href="http://www.pong-story.com/">
Pong!</a>, which uses only three moving objects and a straightforward gameplay and scoring technique. Given that you probably play games thousands of times more complex than this (such as The Sims or Half Life), you may initially dismiss this exercise as a
 waste of time; however, it's a great way to learn some of the fundamental concepts of video games in just a few lines of code. If these techniques are already familiar to you, then you may be interested in the
<a href="http://www.microsoft.com/events/series/msdnvideodev.mspx">MSDN game development webcasts</a>, which cover 2D and 3D game development with Managed DirectX.
</p>
<p>This tutorial walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.
</p>
<p>You are also free to use the source code as the basis for your own projects, and to share your work with others or upload it to the Internet.
</p>
<p><b>Note:</b> This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
<b>Help</b> on the menu bar, and then clicking <b>Contents</b>, <b>Index</b>, or <b>
Search</b>. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.
</p>
<h4>Getting Started</h4>
<h5>Building and Running TinyTennis</h5>
<p>Once your project is loaded into the Visual Basic environment, you can compile and run the program in one step.
</p>
<p>To build and run TinyTennis: </p>
<ul>
<li>Press F5 to build and start the game under the debugger. </li></ul>
<p>The game launches and you can control the left bat using the Q and A keys. </p>
<p>&nbsp;</p>
<h4>Files</h4>
<ul>
<li><b>Sprite.vb<br>
</b>The base class for the sprites. It contains initialization code and basic movement code.
</li><li><b>TinyTennis.vb</b><br>
The main form for the application. It initializes the sprites for the bats and ball, passes keyboard intput to the bats, and controls drawing the game to the screen.
</li><li><b>ControlSprite.vb<br>
</b>An implementation of a sprite that uses a Windows control to draw to the screen.
</li><li><b>Bat.vb<br>
</b>A ControlSprite representing the bat. Contains the keyboard movement code for human players and AI code for computer players.
</li><li><b>Ball.vb</b><br>
A ControlSprite representing the ball. Contains the code for checking for collisions with the walls and the bats and the bounces. Also plays the only sound in the game.
</li><li><b>GameState.vb<br>
</b>Stores the scores.</li></ul>
<p>&nbsp;</p>
<h4>Game Development Concepts</h4>
<p>If you are new to 2D game development, check out the <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/2DPrimervb/default.aspx">
2D Game Primer (Visual Basic)</a>. </p>
<p><b></b>&nbsp;</p>
<p><b>Implementing Sprites</b></p>
<p>For TinyTennis, you'll need three very simple rectangular sprites that can be moved around the screen. In order to keep things simple for the first game (and because I recognize that a lot of .NET developers come from a Windows Forms background), I have
 chosen to use PictureBox controls to represent the sprites. A picture box has all the characteristics needed for this simple game:
</p>
<ul>
<li>It's rectangular. </li><li>It can have a background color. </li><li>It can be positioned at specific positions on the screen. </li></ul>
<p>Using a picture box is not something you would do in a real computer game, but it's something that is very simple to get started with and hopefully something you already know about. In the next game, you will replace the picture box with real graphics.
</p>
<p>The base class definition is:</p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Class</span> Sprite<br>    <span class="kwrd">Public</span> Velocity <span class="kwrd">As</span> PointF<br>    <span class="kwrd">Public</span> Location <span class="kwrd">As</span> PointF<br>    <span class="kwrd">Public</span> Size <span class="kwrd">As</span> SizeF</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>&nbsp;</p>
<p>The inherited class adds a member for the control.</p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Class</span> ControlSprite : <span class="kwrd">Inherits</span> Sprite<br> <br>    <span class="kwrd">Public</span> Control <span class="kwrd">As</span> Control</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>&nbsp;</p>
<p>The inherited class defines how to draw it. Since Windows Forms can only be positioned at integer pixel boundaries, you have to round the sprite positions.</p>
<p>&nbsp;</p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Overrides</span> <span class="kwrd">Sub</span> Draw()<br>    <span class="rem">'Move the control to the correct location </span><br>    Control.Location = <span class="kwrd">New</span> Point(<span class="kwrd">CInt</span>(Location.X &#43; 0.5F), <span class="kwrd">CInt</span>(Location.Y &#43; 0.5F))<br> <br>    <span class="rem">'and redraw it</span><br>    Control.Refresh()<br><span class="kwrd">End</span> Sub</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The Windows Forms controls used in this game are created in the designer by dragging picture boxes onto the form. Since the size and position are set in the code, there's no need to position or size them correctly in the designer. All you need to do is name
 them correctly.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/tennis2.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/tennis2_thumb.gif" border="0"></a>
</p>
<p><b>(Click image to zoom)</b></p>
<p><b></b>&nbsp;</p>
<p><b>Code structure</b></p>
<p>Just because the game is simple doesn't mean that you should avoid good software engineering practices. This is especially important since you want to create a base on which to build the next two games. And, although Visual Studio Express has some refactoring
 support, it always helps to get things right from the beginning. </p>
<p>The most important class is the sprite. Sprites have a position and a velocity. Velocity is how fast the position changes in pixels per second. If velocity is 0, then the position will stay the same and you'll have a static sprite. In addition, you need
 to remember how big the sprite is so that you can work out collisions. </p>
<p>The game loop needs to call each sprite and perform two tasks: update and draw. Since you know the velocity, you can implement the movement part of the animation in the base class. Any complex or additional updates will be handled in an inherited class.
 For this game, drawing the sprite will be left to an inherited class since there is no general case.
</p>
<p>Because I'm using PictureBox controls, I've decided to create an inherited ControlSprite class that can be thrown away in the later examples. ControlSprite sets the position of the control that represents the sprite and calls the RefreshMethod to paint it
 on the screen. </p>
<p>The Bat and Ball objects inherit from ControlSprite and provide the special processing that each of those require. For example the Bat class changes its velocity based on keyboard presses and AI. The Ball class changes its velocity based on collisions with
 bats and the edges of the gameplay area. </p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/tennis3.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/916341/tennis3_thumb.gif" border="0"></a>
</p>
<p>&nbsp;</p>
<p><b>(Click image to zoom)</b> </p>
<h5>Implementing Time Based Animation</h5>
<p>As mentioned in <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/2DPrimervb/default.aspx">
2D Game Primer (Visual Basic)</a>, it's important to move the sprites based on time rather than a fixed distance per frame.
</p>
<p>The first thing to do is make sure you have an accurate measure of the time. The .NET Framework 2.0 added the StopWatch class, which uses the most accurate measure available on your computer.
</p>
<pre class="csharpcode"><span class="kwrd">Private</span> _timer <span class="kwrd">As</span> Stopwatch = <span class="kwrd">New</span> Stopwatch()<br><span class="kwrd">Public</span> <span class="kwrd">Sub</span> <span class="kwrd">New</span>()<br>    <span class="rem">'Initialise and start the timer</span><br>    _lastTime = 0.0<br>    _timer.Start()<br><span class="kwrd">End</span> <span class="kwrd">Sub</span><br> <br><span class="kwrd">Private</span> <span class="kwrd">Sub</span> TinyTennis_Paint(<span class="kwrd">ByVal</span> sender <span class="kwrd">As</span> <span class="kwrd">Object</span>, <span class="kwrd">ByVal</span> e <span class="kwrd">As</span> PaintEventArgs) <span class="kwrd">Handles</span> <span class="kwrd">MyBase</span>.Paint<br>    <span class="rem">'Work out how long since we were last here in seconds</span><br>    <span class="kwrd">Dim</span> gameTime <span class="kwrd">As</span> <span class="kwrd">Double</span> = _timer.ElapsedMilliseconds / 1000.0<br>    <span class="kwrd">Dim</span> elapsedTime <span class="kwrd">As</span> <span class="kwrd">Double</span> = gameTime - _lastTime<br>    _lastTime = gameTime<br> <span class="kwrd">End</span> <span class="kwrd">Sub</span>
</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>&nbsp;</p>
<p>Sometimes animation is based on how far into the game you are; sometimes it's based on how long it has been since the last time around the game loop. Rather than having every object calculate these two values, you do it once and pass it to the Update() function
 for each object. </p>
<p>The Update method of the Sprite objects and their inherited classes eventually gets called with these times:
</p>
<p>&nbsp;</p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Overridable</span> <span class="kwrd">Sub</span> Update(<span class="kwrd">ByVal</span> gameTime <span class="kwrd">As</span> <span class="kwrd">Double</span>, <span class="kwrd">ByVal</span> elapsedTime <span class="kwrd">As</span> <span class="kwrd">Double</span>)<br>    <span class="rem">'Move the sprite based on the velocity</span><br>    Location.X &#43;= Velocity.X * <span class="kwrd">CSng</span>(elapsedTime)<br>    Location.Y &#43;= Velocity.Y * <span class="kwrd">CSng</span>(elapsedTime)<br> <br><span class="kwrd">End</span> Sub</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>&nbsp;</p>
<h5><b>Simple AI (Artificial Intelligence)</b></h5>
<p>The interesting thing about AI for TinyTennis is actually making the AI do things wrong. It's interesting because normally AI is about making a computer play well. For this game playing, a perfect game is trivial for the computer:
</p>
<ul>
<li>Calculate the exact position the ball will end up and move the bat there. This involves some math but is simple to do.
</li><li>Track the ball by moving the bat towards the current Y position of the ball. There is no math involved, but as long as the ball speed is not greater than the bat speed this will always work.
</li></ul>
<p>Of course this kind of opponent is no fun to play against, so the AI challenge for this game is making the computer miss the ball in a realistic, human way. I have chosen to take three approaches to this:
</p>
<ol>
<li>The computer doesn't start moving the bat until the ball is close to the computer side of the screen. How close can be varied to make the AI smarter or dumber.
</li><li>The computer doesn't track bounces — it will look which way the ball is heading and move towards it, but a last-minute bounce may throw it off.
</li><li>Just like a human, sometimes the computer will over- or underestimate how well it tracks the ball. This is implemented by adding a random offset into the movement that can, once again, be varied to change the skill level.
</li></ol>
<h4>Extending TinyTennis</h4>
<ul>
<li>Add a start-up splash screen that allows the player to choose between one and two players.
</li><li>Add an additional bat for each player by creating an extra picture box, and then creating additional Bat objects.
</li><li>Add multiple balls. The game play will need to change a little. For example, do you want to pause the game when a point is scored? Or, do you want to score the point and make a new ball appear?
</li><li>Since the sprites are just picture boxes, you can set the background image property to give the game a whole new look and feel. Remember that the collision detection is done based on the rectangular shape of the picture box; if the image does not fill the
 picture box, it might look odd when the ball bounces. </li></ul>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:22574cd914ac4ce3b3389e7600da3d24">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Tiny-Tennis-Visual-Basic</comments>
      <itunes:summary>



&amp;nbsp;
This article is a part of Upgrade Your Game series of tutorials. It walks you through the game architecture components for our tribute to Pong!, which we&#39;ll call TinyTennis.



The Z-man Andy Dunn
The Z Buffer

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware: 
Download: 

VB Download






Demo Video 

 


Download Video 
Visual Basic Upgrade Your Game Series 

2D Game Primer
Tiny Tennis
Space Blitz&amp;nbsp;
Crusader
&amp;nbsp; 
Introduction
Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds
 on the last to improve your skills. The skills can be applied to more complex games including 3D games using
Microsoft DirectX.  
Let&#39;s begin by creating a really simple game like 
Pong!, which uses only three moving objects and a straightforward gameplay and scoring technique. Given that you probably play games thousands of times more complex than this (such as The Sims or Half Life), you may initially dismiss this exercise as a
 waste of time; however, it&#39;s a great way to learn some of the fundamental concepts of video games in just a few lines of code. If these techniques are already familiar to you, then you may be interested in the
MSDN game development webcasts, which cover 2D and 3D game development with Managed DirectX.
 
This tutorial walks you through the game architecture components for our tribute to Pong!, which we&#39;ll call TinyTennis.
 
You are also free to use the source code as the basis for your own projects, and to share your work with others or upload it to the Internet.
 
Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking
Help on</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Tiny-Tennis-Visual-Basic</link>
      <pubDate>Tue, 31 Oct 2006 22:46:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Tiny-Tennis-Visual-Basic</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916341_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/916341_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>8</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Upgrade-Your-Game-Tiny-Tennis-Visual-Basic/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan: Applying Textures, Part 2</title>
      <description><![CDATA[ <p>Part 2 of a three part series explaining the addition of textures to DirectX Primitive shapes.This column covers how to get a different texture on each side of the box.</p><p><span id="c4fmetadata"></span>Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to <a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a></p><p><span><span class="entry_description"><strong>Source code:</strong><br></span></span></p><ul><span id="c4fmetadata"><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/ZManTex03.msi">C# Download</a></li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/ZManTex04.msi">C# Download</a></li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/253768_TexturesPart2_VB.zip">VB Download</a></span></li></ul><p>Since Coding4Fun has only just launched, there aren't any specific questions to answer so I thought I would start with&nbsp;a question that occurs frequently on the <a href="http://msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.win32.programmer.directx.managed">Managed DirectX newsgroup</a>: </p><h5>&quot;I've created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them a) nothing happens b) the shapes go black or c) the shapes disappear. How can I add a texture to the DirectX primitive shapes?&quot;</h5><p>Last time I covered how texture coordinates are stored inside the mesh object, the relationship between the texture coordinates and the texture, and the most useful of the texture sampling states. In this column I will cover how to get a different texture on each side of the box. </p><p><strong>A New Start Point</strong> </p><p>I left you last time with an exercise to add rotation into the crate texture viewer program. Nobody sent me their homework on time so I'm not sure if it was too easy or too hard. </p><p>Download the sample code using the link at the top of this article to see my solution (see figure 1).&nbsp; You will need Beta2 of Visual C# Express and the April 2005 DirectX SDK. You can get Visual C# 2005 Express Edition Beta 2 by visiting http://msdn.microsoft.com/express. You can also use other Express Editions depending on the language of your choice, but this demonstration will utilize C#. </p><p>From the picture you can see I've added both rotation and translation. It is now possible to position the texture anywhere on the face of the box. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/figure2-1.gif" alt="" width="500" height="396"><br>Figure 1. A solution to the exercise from the last column&nbsp; </p><p>You will see that I have refactored the code to begin creating a reusable library. I would have preferred to create a new class inheriting from the DirectX mesh . However, the DirectX mesh class is sealed so this is not possible. I chose to create a static library which takes DirectX mesh objects as parameters. </p><p>Take a look at SetBoxTexture in TexturedMesh.cs and you will see some resemblance to the TextureMesh function from last time. To add in the rotation and translation I made the code a little more generic. I also parameterized the function rather than picking up the global variables. </p><p>First, I created a unit square which for the texture coordinates. Unchanged, these coordinates would cause the whole texture to cover each face. </p><p><strong>C#</strong><br><pre class="brush: csharp">Vector2[] corners = new Vector2[4] 
{
    new Vector2(0f, 0f), //bottom left
    new Vector2(1f, 0f), //top left
    new Vector2(1f, 1f), //top right
    new Vector2(0f, 1f) //bottom right
};
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">Dim corners As Vector2() = New Vector2() { _
    New Vector2(0.0!, 0.0!), 
    New Vector2(1.0!, 0.0!), 
    New Vector2(1.0!, 1.0!), 
    New Vector2(0.0!, 1.0!)}
</pre></p><p>Then I applied a transformation to each of these and stored the result into the texture coordinates of the mesh. </p><p><strong>C#</strong><br><pre class="brush: csharp">//apply the transformation to each corner and store the result back 
//into the texture coordinates
for (int j=0; j&lt;4; j&#43;&#43;)
{
  corners[j].TransformCoordinate(transform);
  verts[i &#43; j].Tu = corners[j].X;
  verts[i &#43; j].Tv = corners[j].Y;
}
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">For j As Integer = 0 To 3
    'apply the transformation to each corner and store the result back
    ' into the texture coordinates
    corners(j).TransformCoordinate(transform)
    verts(i &#43; j).Tu = corners(j).X
    verts(i &#43; j).Tv = corners(j).Y
Next
</pre></p><p>The transformation was created by concatenating together transformation matrices for each of the input parameters. </p><p><strong>C#</strong><br><pre class="brush: csharp">Matrix transform =
Matrix.Translation(offsetX, offsetY, 0f)  
  * Matrix.Translation(-0.5f, -0.5f, 0f) //Translate the center of rotation
* Matrix.RotationZ(angle)               
  * Matrix.Scaling(1 / scaleX, 1 / scaleY, 1f) 
  * Matrix.Translation(.5f, .5f, 0f); //and move back the center of rotation
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">Dim transform As Matrix = Matrix.Translation(offsetX, offsetY, 0.0F) * _
    Matrix.Translation(-0.5F, -0.5F, 0.0F) * Matrix.RotationZ(angle) * _
    Matrix.Scaling(1 / scaleX, 1 / scaleY, 1.0F) * _
    Matrix.Translation(0.5F, 0.5F, 0.0F)
</pre></p><p>I also added a TexturedMesh.Box() function which creates a mesh with texture coordinates already set to a useful default. </p><p><strong>Displaying a Different Texture on Each Side</strong> </p><p>For boxes, it often makes sense to show the same texture on each side. But does this make sense for other shapes? Most of the meshes you encounter in a video game don't really have the same concept of sides that a box does and so it's worth finding out how to draw different things on different faces. Some of you may have heard that meshes can have multiple textures applied to them so it is theoretically possible to load up 6 textures, one for each face, and blend them together in some way. This technique is more often used to apply different kinds of textures to the whole object (for example, a base texture followed by a shadow map to darken some areas). </p><p>What I am going to describe is how to wrap a single texture around the box. Remember that the box is made up of 6 square faces, each of which is made up of 2 triangles. If you take these 6 squares and lay them side by side over a single texture it is possible to deduce the correct texture coordinates for each face. </p><p>You will eventually have many textures so it's important to make them as small as possible. This means leaving as little space between the squares as possible. DirectX also prefers textures to be as square as possible so the layout in figure 2 is optimal. This bitmap is what is normally called a texture map. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/figure2-2.gif" alt=""><br>Firgure 2. A texture map template for a box </p><p>The larger typeface signifies which of the box faces applies to which part of the texture map. The smaller typeface is to give you an idea of the orientation of the texture and indicates which face touches that edge. The highlighted face is the example I will use to generate texture coordinates. </p><p>I have added a new overload to SetBoxTexture(). This one takes the mesh and a parameter called technique. Right now there is just one technique called Divide which means that the texture will be divided evenly between the 6 faces. Most of the function is similar to the other overloads. This version hard codes the texture coordinates for each face. There really is no easy mathematical way to do this. Remember texture coordinates go from 0.0 to 1.0 so the face texture coordinates had to be 0, 1/3, 2/3, 1.0 in the x direction and 0, 0.5, 1.0 in the y direction. I guessed which face was which and rendered the box. Once I saw where I was wrong I simply switched the indexes of the vertices around until the faces were in the correct place and had the correct orientation. This process took about 15 minutes to complete. Last time I mentioned how texture mapping was hard to do by hand. Imagine doing this for a more complex shape. </p><p>To set up the texture coordinates I simply assign the correct values to each vertex. There is a block of code similar to this for each face of the box. You should be able to match the vertex indices to those in figure 2 and confirm that the texture coordinates are correct. </p><p><strong>C#</strong><br><pre class="brush: csharp">//Front
verts[20].Tu = 1f / 3f; verts[20].Tv = 1f;
verts[21].Tu = 1f / 3f; verts[21].Tv = 0.5f;
verts[22].Tu = 2f / 3f; verts[22].Tv = 0.5f;
verts[23].Tu = 2f / 3f; verts[23].Tv = 1f;
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">'Front
verts(21).Tu = 1.0F / 3.0F
verts(21).Tv = 0.5F
verts(22).Tu = 2.0F / 3.0F
verts(22).Tv = 0.5F
verts(23).Tu = 2.0F / 3.0F
verts(23).Tv = 1.0F
verts(20).Tu = 1.0F / 3.0F
verts(20).Tv = 1.0F
</pre></p><p>To complete the render (see figure 3) a new mesh is created and its texture coordinates are set using the new function. </p><p><strong>C#</strong><br><pre class="brush: csharp">MyBox = TexturedMesh.Box(e.Device, 2.0f, 2.0f, 2.0f);
TexturedMesh.SetBoxTexture(MyBox, TextureTechnique.Divide);
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">MyBox = TheZBuffer.DirectX.Direct3D.TexturedMesh.Box(e.Device, 2.0F, 2.0F, 2.0F)
TheZBuffer.DirectX.Direct3D.TexturedMesh.SetBoxTexture(MyBox, _
    TheZBuffer.DirectX.Direct3D.TextureTechnique.Divide)
</pre></p><p>There are a couple of extra lines of code to load the template.bmp texture and ensure it is set before the mesh is rendered. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/figure2-3.gif" alt="" width="500" height="396"><br>Figure 3 - Textured box showing the texture template </p><p>To make use of the template provided, load it up into your favorite image editor and replace the labels with graphics of your choice. Like most developers, I am not a great graphic artist so I chose to make a dice as an example since it only involves drawing circles. The final solution can be found by downloading the zmanTex04.msi file using the link at the top of this article. In the media folder you will find dice.bmp. If you load that texture instead of template.bmp you should see something like figure 4.&nbsp; </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912553/figure2-4.gif" alt="" width="500" height="396"><br>Figure 4. Final render of the dice </p><p><strong>Exercise for the Reader<br></strong>You have seen what the texture map template for the box looks like. What do you think a texture map for a cylinder or a sphere would look like? </p><p><em><strong>Future texturing questions coming soon:</strong><br>How can &nbsp;I texture the cylinder, sphere, torus, and teapot?</em> </p><p>Credits:<br>Thanks to <br>Chris Zastrow (<a href="mailto:czastrow@newlogicmedia.com">czastrow@newlogicmedia.com</a>) for the crate textures found at <a href="http://www.planetquake.com/subverse/">http://www.planetquake.com/subverse/</a><br>Carlos Aguilar (<a href="mailto:web@carlosag.net">web@carlosag.net</a>) for the code colorizer found at <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">http://www.carlosag.net/Tools/CodeColorizer/Default.aspx</a>&nbsp;&nbsp;&nbsp;</p><p>Copyright © 2005 TheZBuffer.com</p> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:0147d6b459d747439d399e7600dae070">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-2</comments>
      <itunes:summary> Part 2 of a three part series explaining the addition of textures to DirectX Primitive shapes.This column covers how to get a different texture on each side of the box. Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to zman@thezbuffer.com Source code: C# DownloadC# DownloadVB DownloadSince Coding4Fun has only just launched, there aren&#39;t any specific questions to answer so I thought I would start with&amp;nbsp;a question that occurs frequently on the Managed DirectX newsgroup:  &amp;quot;I&#39;ve created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them a) nothing happens b) the shapes go black or c) the shapes disappear. How can I add a texture to the DirectX primitive shapes?&amp;quot;Last time I covered how texture coordinates are stored inside the mesh object, the relationship between the texture coordinates and the texture, and the most useful of the texture sampling states. In this column I will cover how to get a different texture on each side of the box.  A New Start Point  I left you last time with an exercise to add rotation into the crate texture viewer program. Nobody sent me their homework on time so I&#39;m not sure if it was too easy or too hard.  Download the sample code using the link at the top of this article to see my solution (see figure 1).&amp;nbsp; You will need Beta2 of Visual C# Express and the April 2005 DirectX SDK. You can get Visual C# 2005 Express Edition Beta 2 by visiting http://msdn.microsoft.com/express. You can also use other Express Editions depending on the language of your choice, but this demonstration will utilize C#.  From the picture you can see I&#39;ve added both rotation and translation. It is now possible to position the texture anywhere on the face of the box.  Figure 1. A solution to the exercise from the las</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-2</link>
      <pubDate>Tue, 31 Oct 2006 14:50:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-2</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912553_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912553_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>4</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-2/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan:Applying Textures, Part 1</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">Part 1 of a three part series explaining the addition of textures to DirectX Primitive shapes.This column covers how texture coordinates are stored inside the mesh object, the relationship between the texture coordinates
 and the texture, and the most useful of the texture sampling states.</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">The Z-man Andy Dunn</div>
<div class="entry_company"><a href="http://www.thezbuffer.com/">The Z Buffer</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Intermediate</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Studio Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=89812117-2b35-44b9-80bd-4b1e09909b60">C# Download</a>
</li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/253763_TexturesPart1_VB.zip">VB Download</a></li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to
<a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a> </p>
<p>Since Coding4Fun has only just launched, there aren't any specific questions to answer so I thought I would start with&nbsp;a question that occurs frequently on the
<a href="http://msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.win32.programmer.directx.managed">
Managed DirectX newsgroup</a>: </p>
<h5>&quot;I've created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them a) nothing happens b) the shapes go black or c) the shapes disappear. How can I add
 a texture to the DirectX primitive shapes?&quot;</h5>
<p>This is often a stumbling block for beginners in managed DirectX. The texture tutorial (<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9_m/directx/direct3d/tutorials/tutorial5.asp">tutorial 5</a>)&nbsp;in the SDK creates a cylinder
 mesh in code rather than using Mesh.Cylinder and there are not many examples of how to add texture to an existing mesh, especially in managed code.
</p>
<p>The first thing to point out is that, for the most part, manually adding textures is a futile thing to do. In the today's games there are very few boxes, cylinders, tori or teapots. All of the objects that are used in modern games are created by artists
 in modeling programs like Maya. Designers also create the textures and texture the models. By the time the programmer gets the artwork they have both a shape and a texture. As you will also see in future columns, the more complex the shape becomes the less
 likely you can add a texture programmatically. Of course, there is an exception to this rule: you can add programmatic textures, for example representing wood and marble with mathematical equations, but this requires you to dip into the world of pixel shaders.
</p>
<p>However, it IS a worthwhile exercise to learn about the innards of the Mesh object, how textures connect to objects, and which settings you can apply to textures to to change the way they look.
</p>
<p>To start, download textures0.zip using the link at the top of this article. You will need Beta2 of Visual C# Express and the April 2005 DirectX SDK. You can get Visual C# 2005 Express Edition Beta 2 by visiting http://msdn.microsoft.com/express. You can
 also use other Express Editions depending on the language of your choice, but our demonstration will utilize C#.
</p>
<p><img height="396" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/image001.gif" width="500"><br>
Figure 1. Rendering of a simple box in Managed DirectX </p>
<p><b>How Did You Create This Project? </b><b><br>
</b>This project began life as the EmptyProject from the Managed DirectX sample browser. I removed the effects framework code and some of the extraneous UI elements. Then I added Mesh and Material creation in OnCreateDevice() and disposal in OnDestroyDevice(),
 and light creation in OnResetDevice(). There's also a slight change to the camera eye point in OnCreateDevice() to give it a slightly more interesting point of view. In OnFrameMove(), &nbsp;I set the view and projection matrices from the camera class in the framework
 which allows you to use the right mouse button for moving the camera. Finally, I turned on the lights - including some ambient lighting -&nbsp;and&nbsp;draw the box in the correct place with the correct material in the OnFrameRender() function.&nbsp;
</p>
<p><b>What's Inside a Mesh?<br>
</b>Put a break point on the Mesh.Box() call and run your code. Press F10 to execute that line of code and take a look at the MyBox variable using the watch window (Figure 2).
</p>
<p><img height="341" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/image002.gif" width="500"><br>
Figure 2. The watch window of a Mesh.Box() object </p>
<p>Interesting things to remember: </p>
<ul>
<li>
<p><i>12 faces</i>: In 3-D graphics programming, everything is made up of triangles. Each face of the box takes 2 triangles, there are 6 sides to the box, so there are 12 faces needed to draw the box.</p>
</li><li>
<p><i>24 vertices</i>: Because each face needs to have its own normals,&nbsp;each&nbsp;of the 6 faces of the box has to have its own set of 4 vertices,&nbsp;totaling 24.</p>
</li><li>
<p><i>The VertexFormat is PositionNormal</i>: Each vertex stores just the x,y,z position in space and the normal for that vertex.</p>
</li><li>
<p><i>VertexBuffer</i>: The actual vertices are stored here. However, this buffer cannot be opened and browsed because the values are actually stored in an unmanaged part of DirectX.
</p>
</li></ul>
<p>Hit F10 one more time and look in the output or immediate window for the debug output. The DumpMesh function converts the unmanaged vertex buffer to a managed array and then writes the coordinates out to debug. You should see something like this:
</p>
<p>Vertices<br>
Vert 0: -1, -1, -1<br>
Vert 1: -1, -1, 1<br>
Vert 2: -1, 1, 1<br>
...<br>
Vert 23: 1, -1, -1 </p>
<p>If you were to sketch those coordinates out, you would find that each set of 4 describes one of the faces of the box.
</p>
<p><b>How Does a Mesh Know What Texture to Draw Where?<br>
</b>Imagine that Figure 3 shows one of the faces of the cube and the crate texture I want to place on it. Besides the obvious &quot;fill the whole face with the texture,&quot; there are many ways that the texture can be placed, for example the texture can be:
</p>
<ul>
<li>Rotated by 10 degrees </li><li>Scaled by 1/4 so that there are 16 copies of the texture tiled on each face </li><li>Roated and scales in any combination with different angles and scales </li></ul>
<p>Each vertex on each triangle has to be mapped to a particular pixel on the texture so the DirectX knows what color to draw. In Figure 3, I have chosen to map the vertices of the box face in such a way that it picks up a rotated area in the top left of the
 texture. The resultant face when rendered would look something like the final picture:
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/image003.gif"><br>
Figure 3. Mapping vertices to a texture </p>
<p>Textures are mapped through the use of texture coordinates, which are also known as u,v coordinates. Each vertex in the triangle has a u,v coordinate which corresponds to a point on the texture. As you can see from Figure 3,&nbsp;texture coordinates&nbsp;floating
 point values that always range from 0.0 to 1.0. In this example the u,v coordinates for the top left vertex of the face are probably (0.0, 0.9) and the lower right vertex is (0.4, 0.7).
</p>
<p><b>Adding Texture Coordinates to the Box<br>
</b>You will remember that the VertexFormat of the box was PostitionNormal. There are no texture coordinates in there. Before I can add them, &nbsp;I need to modify the Mesh so there is space for the u,v coordinates. This is done through the use of the Mesh.Clone
 function. </p>
<p>Add declarations for the TexturedBox and the Texture: </p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="kwrd">private</span> Mesh TexturedBox;  <br><span class="kwrd">private</span> Texture texture = <span class="kwrd">null</span>;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> TexturedBox <span class="kwrd">As</span> Mesh<br><span class="kwrd">Private</span> texture <span class="kwrd">As</span> Direct3D.Texture = Nothing</pre>
<p>Create a function called TextureBox(). This function takes the untextured mesh and adds the texture, so add a call to that after the DumpInfo() call:
</p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode">MyBox = Mesh.Box(e.Device, 2.0f, 2.0f, 2.0f);<br>DumpInfo(MyBox);<br>TexturedBox = TextureBox(MyBox);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">MyBox = Mesh.Box(e.Device, 2.0F, 2.0F, 2.0F)<br>DumpInfo(MyBox)<br>TexturedBox = TextureBox(MyBox)</pre>
<p>Make sure to tidy it up in OnDestroyDevice(): </p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode">TexturedBox.Dispose();</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">TexturedBox.Dispose()</pre>
<p>Add code to render it after MyBox.DrawSubset() in OnFrameRender(). I will draw this cube off to the right of the first one so that you can compare them:
</p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode">MyBox.DrawSubset(0);<br>device.Transform.World = Matrix.Translation(1.2f, 0f, 0f);<br>TexturedBox.DrawSubset(0);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">MyBox.DrawSubset(0)<br>device.Transform.World = Matrix.Translation(-1.2F, 0.0F, 0.0F)<br>TexturedBox.DrawSubset(0)</pre>
<p>Finally, add the TextureBox function somewhere in the textures class: </p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="kwrd">private</span> Mesh TextureBox(Mesh box)<br>{<br>    <span class="rem">//First make sure this is a box</span><br>    <span class="rem">//There's no quick test, so we will count the vertices and faces</span><br>    Debug.Assert(box.NumberVertices == 24 &amp;&amp; box.NumberFaces == 12, <br>        <span class="str">&quot;TextureBox called with a mesh which is not box like&quot;</span>);<br>    <span class="rem">//Take a copy of the Mesh, adding space for texture coordinates</span><br>    Mesh TexturedBox = box.Clone(box.Options.Value,<br>        VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0 |<br>        VertexFormats.Texture1, box.Device);<br>    <span class="kwrd">return</span> TexturedBox;<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Function</span> TextureBox(<span class="kwrd">ByVal</span> box <span class="kwrd">As</span> Mesh) <span class="kwrd">As</span> Mesh<br>    <span class="rem">'First make sure this is a box</span><br>    <span class="rem">'There's no quick test, so we will count the vertices and faces</span><br>    Debug.Assert(box.NumberVertices = 24 <span class="kwrd">AndAlso</span> box.NumberFaces = 12, _<br>        <span class="str">&quot;TextureBox called with a mesh which is not box like&quot;</span>)<br><br>    <span class="rem">'Take a copy of the Mesh, adding space for texture coordinates</span><br>    <span class="kwrd">Dim</span> TexturedBox <span class="kwrd">As</span> Mesh = box.Clone(box.Options.Value, _<br>        VertexFormats.Position <span class="kwrd">Or</span> VertexFormats.Normal <span class="kwrd">Or</span> _<br>        VertexFormats.Texture0 <span class="kwrd">Or</span> VertexFormats.Texture1, _<br>        box.Device)<br><br>    <span class="kwrd">Return</span> SetTextureCoordinates(TexturedBox)<br><span class="kwrd">End</span> Function</pre>
<p>After some sanity checking of the input mesh,&nbsp;this function clones the mesh that is passed in but tells DirectX to change the vertex format from PositionNormal to PositionNormalTextured. Notice the logical ORing together of the flags that make up the various
 possible parts of a vertex. See&nbsp;<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx.direct3d/e/vertexformats/vertexformats.asp?frame=true">MSDN VertexFormats</a>&nbsp;and
<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9_m/directx/ref/ns/microsoft.directx.direct3d/c/customvertex/customvertex.asp?frame=true">
MSDN CustomVertex</a> for the full lists. </p>
<p>If you run the program now you will see 2 identical cubes (Figure 4). I have added space for the texture coordinates but I haven't set them to reasonable values or&nbsp;loaded a texture.
</p>
<p><img height="396" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/image004.gif" width="500"><br>
Figure 4. Identical cubes without textures </p>
<p>Load the texture in OnResetDevice(): </p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="rem">//Load the texture</span><br>texture = TextureLoader.FromFile(e.Device, <br>    System.Windows.Forms.Application.StartupPath &#43; <br>    <span class="str">@&quot;\..\..\media\woodcrate.bmp&quot;</span>);<br></pre>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="rem">'Load the texture</span><br>texture = TextureLoader.FromFile(e.Device, _<br>    System.Windows.Forms.Application.StartupPath _<br>    &amp; <span class="str">&quot;\..\..\media\woodcrate.bmp&quot;</span>)</pre>
<p>Tidy up in OnLostDevice(): </p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="kwrd">if</span> (texture !=<span class="kwrd">null</span>) texture.Dispose();</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">If</span> (<span class="kwrd">Me</span>.texture IsNot <span class="kwrd">Nothing</span>) <span class="kwrd">Then</span><br>    <span class="kwrd">Me</span>.texture.Dispose()<br><span class="kwrd">End</span> If</pre>
<p>Change the rendering code to set the correct texture for each box. Notice how I use null in the SetTexture() call to say &quot;do not use a texture&quot; for the first box. Try commenting out that line later to see the effect:
</p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="rem">//Render our scene</span><br>device.SetTexture(0, <span class="kwrd">null</span>);<br>device.Transform.World = Matrix.Translation(-1.2f, 0f, 0f);<br>MyBox.DrawSubset(0);<br>device.SetTexture(0, texture);<br>device.Transform.World = Matrix.Translation(1.2f, 0f, 0f);<br>TexturedBox.DrawSubset(0);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">With</span> device<br>    .SetTexture(0, <span class="kwrd">Nothing</span>)<br>    .Transform.World = Matrix.Translation(-1.2F, 0.0F, 0.0F)<br>    MyBox.DrawSubset(0)<br>    .SetTexture(0, texture)<br>    .Transform.World = Matrix.Translation(1.2F, 0.0F, 0.0F)<br>    TexturedBox.DrawSubset(0)<br> <span class="kwrd">End</span> With</pre>
<p>Finally, add the updated TextureBox function and its helper SetTextureCoordinates. This function locks the vertex buffer so that it can safely make changes and then adds identical texture coordinates to each of the 6 box faces. The texture coordinates I
 have chosen are the simple &quot;cover the whole face&quot; ones, which are (0,0) (1,0) (1,1) and (0,1) representing the 4 corners of the texture. Notice that the u,v coordinates are properties called tu and tv in DirectX:
</p>
<p><b>Visual C#</b> </p>
<pre class="csharpcode"><span class="kwrd">private</span> Mesh TextureBox(Mesh box)<br>{<br>    <span class="rem">//First make sure this is a box</span><br>    <span class="rem">//There's no quick test, so we will count the vertices and faces</span><br>    Debug.Assert(box.NumberVertices == 24 &amp;&amp; box.NumberFaces == 12, <br>        <span class="str">&quot;TextureBox called with a mesh which is not box like&quot;</span>);<br>    <span class="rem">//Take a copy of the Mesh, adding space for texture coordinates</span><br>    Mesh TexturedBox = box.Clone(box.Options.Value,<br>        VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0 |<br>        VertexFormats.Texture1,box.Device);<br>    <span class="kwrd">return</span> SetTextureCoordinates(TexturedBox);<br>}<br><br><span class="kwrd">private</span> Mesh SetTextureCoordinates(Mesh TexturedBox)<br>{<br>    <span class="rem">//The following code makes the assumption that the vertices of the box are</span><br>    <span class="rem">// generated the same way as they are in the April 2005 SDK</span><br>    <span class="kwrd">using</span> (VertexBuffer vb = TexturedBox.VertexBuffer)<br>    {<br>        CustomVertex.PositionNormalTextured[] verts = <br>            (CustomVertex.PositionNormalTextured[])vb.Lock(0,<br>             <span class="kwrd">typeof</span>(CustomVertex.PositionNormalTextured), LockFlags.None, <br>            TexturedBox.NumberVertices);<br>        <span class="kwrd">try</span><br>        {<br>            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; verts.Length; i &#43;= 4)<br>            {<br>               verts[i &#43; 0].Tu = 0.0f;<br>               verts[i &#43; 0].Tv = 0.0f;<br>               verts[i &#43; 1].Tu = 1.0f;<br>               verts[i &#43; 1].Tv = 0.0f;<br>               verts[i &#43; 2].Tu = 1.0f;<br>               verts[i &#43; 2].Tv = 1.0f;<br>               verts[i &#43; 3].Tu = 0.0f;<br>               verts[i &#43; 3].Tv = 1.0f;<br>            }<br>        }<br>        <span class="kwrd">finally</span><br>        {<br>            vb.Unlock();<br>        }<br>    }<br>    <span class="kwrd">return</span> TexturedBox;<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Function</span> TextureBox(<span class="kwrd">ByVal</span> box <span class="kwrd">As</span> Mesh) <span class="kwrd">As</span> Mesh<br>    <span class="rem">'First make sure this is a box</span><br>    <span class="rem">'There's no quick test, so we will count the vertices and faces</span><br>    Debug.Assert(box.NumberVertices = 24 <span class="kwrd">AndAlso</span> box.NumberFaces = 12, _<br>        <span class="str">&quot;TextureBox called with a mesh which is not box like&quot;</span>)<br><br>    <span class="rem">'Take a copy of the Mesh, adding space for texture coordinates</span><br>    <span class="kwrd">Dim</span> TexturedBox <span class="kwrd">As</span> Mesh = box.Clone(box.Options.Value, _<br>        VertexFormats.Position <span class="kwrd">Or</span> VertexFormats.Normal <span class="kwrd">Or</span> _<br>        VertexFormats.Texture0 <span class="kwrd">Or</span> VertexFormats.Texture1, _<br>        box.Device)<br><br>    <span class="kwrd">Return</span> SetTextureCoordinates(TexturedBox)<br><span class="kwrd">End</span> <span class="kwrd">Function</span><br><br><span class="kwrd">Private</span> <span class="kwrd">Function</span> SetTextureCoordinates(<span class="kwrd">ByVal</span> TexturedBox <span class="kwrd">As</span> Mesh) <span class="kwrd">As</span> Mesh<br>    <span class="rem">'The following code makes the assumption that the vertices of the box</span><br>    <span class="rem">' are generated the same way as they are in the April 2005 SDK</span><br>    Using vb <span class="kwrd">As</span> VertexBuffer = TexturedBox.VertexBuffer<br>        <span class="kwrd">Dim</span> verts <span class="kwrd">As</span> CustomVertex.PositionNormalTextured() = _<br>            <span class="kwrd">DirectCast</span>(vb.Lock(0, <span class="kwrd">GetType</span>(CustomVertex.PositionNormalTextured), _<br>            LockFlags.None, TexturedBox.NumberVertices), _<br>            CustomVertex.PositionNormalTextured())<br><br>        <span class="kwrd">Try</span><br>            <span class="kwrd">Dim</span> i <span class="kwrd">As</span> <span class="kwrd">Integer</span> = 0<br>            <span class="kwrd">Do</span> <span class="kwrd">While</span> (i &lt; verts.Length)<br>                verts(i).Tu = 0.0!<br>                verts(i).Tv = 0.0!<br>                verts((i &#43; 1)).Tu = <span class="kwrd">Me</span>.NumXTiles<br>                verts((i &#43; 1)).Tv = 0.0!<br>                verts((i &#43; 2)).Tu = <span class="kwrd">Me</span>.NumXTiles<br>                verts((i &#43; 2)).Tv = <span class="kwrd">Me</span>.NumYTiles<br>                verts((i &#43; 3)).Tu = 0.0!<br>                verts((i &#43; 3)).Tv = <span class="kwrd">Me</span>.NumYTiles<br>                i = (i &#43; 4)<br>            <span class="kwrd">Loop</span><br>        <span class="kwrd">Finally</span><br>            vb.Unlock()<br>        <span class="kwrd">End</span> <span class="kwrd">Try</span><br>    <span class="kwrd">End</span> Using<br>    <span class="kwrd">Return</span> TexturedBox<br><span class="kwrd">End</span> Function</pre>
<p>Now if you run the code you will see a crate, not a box (Figure 5). </p>
<p><img height="396" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912559/image005.gif" width="500"><br>
Figure 5. Identical cubes, one with a crate texture applied. </p>
<p>The final version of the code is included in textures1.zip in the download above. The final version has&nbsp;some enhancements. I've added a couple of slider controls that vary the 1.0f in the texture coordinates. As you slide them you will see the textures tile.
 This is the default behavior for DirectX when texture coordinates are &gt;1.0; its called wrapping. However, you can change that behavior by changing the sampler states before you render the mesh. I've added a radio button to switch between wrapping and clamping.
 Clamping means use the texture as far as you can but after that just repeat the last row of pixels. As you can see, it causes some strange effects.
</p>
<p><b>Exercise for the Reader<br>
</b>Modify the solution to add a rotation factor into the texture coordinates. </p>
<p><i><b>Future texturing questions coming soon:</b><br>
How can I put different textures on each side?<br>
How can&nbsp;I texture the cylinder, sphere, torus, and teapot?</i> </p>
<p>Credits:<br>
Thanks to <br>
Chris Zastrow (<a href="mailto:czastrow@newlogicmedia.com">czastrow@newlogicmedia.com</a>) for the crate textures found at
<a href="http://www.planetquake.com/subverse/">http://www.planetquake.com/subverse/</a><br>
Carlos Aguilar (<a href="mailto:web@carlosag.net">web@carlosag.net</a>) for the code colorizer found at
<a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">http://www.carlosag.net/Tools/CodeColorizer/Default.aspx</a>&nbsp;&nbsp;</p>
<p>Copyright © 2005 TheZBuffer.com</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:7a731b66ec81471f83c69e7600dad9e2">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZManApplying-Textures-Part-1</comments>
      <itunes:summary>



&amp;nbsp;
Part 1 of a three part series explaining the addition of textures to DirectX Primitive shapes.This column covers how texture coordinates are stored inside the mesh object, the relationship between the texture coordinates
 and the texture, and the most useful of the texture sampling states.



The Z-man Andy Dunn
The Z Buffer

Difficulty: Intermediate
Time Required: 
1-3 hours
Cost: Free
Software: Visual Studio Express Editions
Hardware: 
Download: 

C# Download
VB Download






Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to
zman@thezbuffer.com  
Since Coding4Fun has only just launched, there aren&#39;t any specific questions to answer so I thought I would start with&amp;nbsp;a question that occurs frequently on the

Managed DirectX newsgroup:  
&amp;quot;I&#39;ve created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them a) nothing happens b) the shapes go black or c) the shapes disappear. How can I add
 a texture to the DirectX primitive shapes?&amp;quot;
This is often a stumbling block for beginners in managed DirectX. The texture tutorial (tutorial 5)&amp;nbsp;in the SDK creates a cylinder
 mesh in code rather than using Mesh.Cylinder and there are not many examples of how to add texture to an existing mesh, especially in managed code.
 
The first thing to point out is that, for the most part, manually adding textures is a futile thing to do. In the today&#39;s games there are very few boxes, cylinders, tori or teapots. All of the objects that are used in modern games are created by artists
 in modeling programs like Maya. Designers also create the textures and texture the models. By the time the programmer gets the artwork they have both a shape and a texture. As you will also see in future columns, the more complex the shape becomes the l</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZManApplying-Textures-Part-1</link>
      <pubDate>Tue, 31 Oct 2006 14:50:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZManApplying-Textures-Part-1</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912559_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912559_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>6</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZManApplying-Textures-Part-1/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Ask the ZMan: Applying Textures, Part 3</title>
      <description><![CDATA[ <p><span id="c4fmetadata"><span class="entry_description">Part 3 of a three part series explaining the addition of textures to DirectX Primitive shapes.</span></span></p><p><span id="c4fmetadata"><span class="entry_description">&nbsp;</span></span>Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to <a href="mailto:zman@thezbuffer.com">zman@thezbuffer.com</a>. </p><p>Since Coding4Fun has only just launched, there aren't any specific questions to answer so I thought I would start with a question that occurs frequently on the <a href="http://msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.win32.programmer.directx.managed">Managed DirectX newsgroup</a>: </p><ul><span id="c4fmetadata"><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/Textures5.msi">C# Download</a></li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/Textures6.msi">C# Download</a></li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/253773_TexturesPart3_VB.zip">VB Download</a></span></li></ul><p>&quot;I've created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them, <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-13.gif?v=c9' alt='Angel' /> nothing happens (b) the shapes go black or (c) the shapes disappear. How can I add a texture to the DirectX primitive shapes?&quot; </p><h4>Homework</h4><p><a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/912553.aspx">Last time</a> I covered how to manually assign points on a texture map to a box. If you spent any time thinking about the homework you will have realised that as the meshes get more complex, the texture map that goes with them and the set of texture coordinates gets too complex to do by hand very quickly. I left you with the following question: </p><p><em>You have seen what the texture map template for the box looks like. What do you think a texture map for a cylinder or a sphere would look like?</em></p><p>Download textures5.msi using the link at the top of this article. This solution allows you to display any of the <code>Mesh.{shape}</code> primitives and to render them in wireframe so that you can see the underlying mesh. Imagine unfolding those shapes until all the triangles lie flat. Figure 1 shows the cylinder and a texture map that would work for this mesh. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/zmantextures3-1a.gif" border="0" alt=""></p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/zmantextures3-1b.gif" border="0" alt=""></p><p><strong>Figure 1. The wireframe cylinder and one possible texture map that could be associated with it</strong></p><p>Not only do you have to work out a suitable texture map, you have to work out all of the corresponding texture coordinates. The cylinder isn't too bad—the sides are represented by the rectangle in Figure 1 and the texture coordinates would be evenly distributed across it. The top and bottom are represented by the two circles and those coordinates can be calculated with some simple sine and cosine formula. You would still have to work out which vertex was which in the mesh structure, e.g., is vertex[49] one of the sides or the top? </p><p>Hopefully, you now agree with my assertion from the <a href="http://msdn.microsoft.com/coding4fun/gamedevelopment/zmanTextures/default.aspx">first article in the series</a> that texturing is best left to the artists in most cases. At the very least you should not do it manually for anything other than the simplest meshes. There are, however, some automated ways of assigning textures. </p><h4>Automatic Texture mapping</h4><p>Imagine a globe of the earth. Now take an imaginary pocket knife and cut a line straight down the International Date line and peel the skin off the globe. What you have is a texture that represents the surface of the earth. The first problem is that it's not flat. Imagine that the skin is made of rubber so you can stretch it until it's flat. You have to do most of the stretching at the north and south poles to make it as wide as the equator but when you are done you will have a flat texture that looks something like Figure 2. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/zmantextures3-2.gif" border="0" alt=""></p><p><strong>Figure 2. An example texture map for the earth.</strong> </p><p>The problem to solve is how to map this texture back onto the sphere. It's obviously possible, since it came from there in the first place. The solution is called <em>spherical texture mapping</em>. </p><p>Take a look at Figure 3 (click it for a large version). The red vector is what I will call the vertex ray. It represents a point on the surface of the sphere that needs texture coordinates and is a vector starting at the center of the object and passing through the point of interest. The point can be described by a longitude (the light blue curve) and latitude (the light green curve). The longitude and latitude equations are based on the angles between the vertex ray and the north vector and the equator vector, respectively (the 2 black vectors). After these are calculated they are scaled in the range 0.0 to 1.0 to give the corresponding point on the texture map. </p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/ZManTextures3-3large.gif"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/ZManTextures3-3.gif" border="0" alt="Click here for larger image"></a></p><p><strong>Figure 3. The mapping between longitude and latitude and the uv texture space</strong></p><p>The longitude and latitude functions are described in <a href="http://www.cs.unc.edu/~rademach/">Paul Rademacher's</a><a href="http://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html#texturemap"> Ray Tracing article</a> and the code looks like the following: </p><p><strong>C#</strong><br><pre class="brush: csharp">//Ref:http://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html and
//Glassner, A. (ed) An Introduction to Ray Tracing. Academic Press New York, N.Y. 1989. 
phi = Math.Acos((double)Vector3.Dot(north, vertexRay));
verts[i].Tv = (float)(phi / Math.PI);
if (phi == 0.0) //if north and vertex ray are coincident then we can pick an 
                //arbitrary u since its the entire top/bottom line of the texture
{
    u = 0.5f;
}
else
{
    //Clamp the acos() param to 1.0/-1.0 
    //(rounding errors are sometimes taking it slightly over).
    u = (float)(Math.Acos(Math.Max(Math.Min((double)Vector3.Dot(equator, vertexRay)
        / Math.Sin(phi), 1.0), -1.0)) / (2.0 * Math.PI));
    if (Vector3.Dot(northEquatorCross, vertexRay) &lt; 0.0)
    {
        verts[i].Tu = u;
    }
    else
    {
        verts[i].Tu = 1 - u;
    }
}
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">'Ref:http://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html and
'Glassner, A. (ed) An Introduction to Ray Tracing. Academic Press New York, N.Y. 1989. 
phi = Math.Acos(CType(Vector3.Dot(north, vertexRay), Double))
verts(i).Tv = CType((phi / Math.PI), single)
If phi = 0.0 Then
    u = 0.5f
Else 
    'Clamp the acos() param to 1.0/-1.0 
    '(rounding errors are sometimes taking it slightly over).
    u = (single)(Math.Acos(Math.Max(Math.Min((Double)Vector3.Dot(equator, vertexRay)
        / Math.Sin(phi), 1.0), -1.0)) / (2.0 * Math.PI))
    If Vector3.Dot(northEquatorCross,vertexRay) &lt; 0.0 Then
        verts(i).Tu = u
    Else 
        verts(i).Tu = 1 - u
    End If
End If
</pre></p><p><strong></strong></p><p><strong></strong>Though this looks complex, it can be simplified in this case because the north vector is (0, 1, 0) and the equator vector is (1, 0, 0). Since (a, b, c) dot (d, e, f) is ad&#43;be&#43;cf, most of the dot products can be simplified to one component of the vertex, and the cross product is a constant (0, 0, 1). The final code is therefore: </p><p><strong>C#</strong><br><pre class="brush: csharp">//Since we know we are using normalised axes we can simplify this somewhat!
//Note these simplifcations only apply if the basis vectors are the unit axis
//north=(0,0,1)=zaxis, equator=(0,1,0)=yaxis and north x equator=(1,0,0)=xaxis
//since (0,0,1)dot(x,y,z)==z and (0,1,0)dot(x,y,z)==y

//if north and vertex ray are coincident then we can pick an arbitray u, since
//it's the entire top/bottom line of the texture
phi = Math.Acos((double)vertexRay.Z);
verts[i].Tv = (float )(phi / Math.PI);

if (vertexRay.Z ==  1.0f || vertexRay.Z  == -1 .0f)
{
    verts[i].Tu = 0.5f;
}
else
{
    u = ( float)(Math.Acos(Math.Max(Math.Min(( double)vertexRay.Y / 
    Math.Sin(phi),  1.0 ), -1. 0)) / (2 .0 * Math.PI)) ;
    //Since the cross product is just giving us (1,0,0) i.e. the xaxis 
    //and the dot product was giving us a &#43;ve or -ve angle, we can just
    //compare the x value with 0
    verts[i].Tu = (vertexRay.X &gt; 0f) ? u :  1 - u;
}
</pre><br><br><strong>Visual Basic</strong><br><pre class="brush: vb">'Since we know we are using normalised axis we can simplify this somewhat!
'Note these simplifcations only apply if the basis vectors are the unit axis
'north=(0,0,1)=zaxis, equator=(0,1,0)=yaxis and north x equator=(1,0,0)=xaxis
'since (0,0,1)dot(x,y,z)==z and (0,1,0)dot(x,y,z)==y

'if north and vertex ray are coincident then we can pick an arbitray u since 
'its the entire top/bottom line of the texture
phi = Math.Acos(CDbl(vertexRay.Z))
verts(i).Tv = CSng(phi / Math.PI)
If vertexRay.Z = 1.0F OrElse vertexRay.Z = -1.0F Then
    verts(i).Tu = 0.5F
Else
    u = CSng((Math.Acos(Math.Max(Math.Min(CDbl(vertexRay.Y) / _
        Math.Sin(phi), 1), -1)) / (2 * Math.PI)))
    'Since the cross product is just giving us (1,0,0) i.e. the xaxis and the dot product
    ' was giving us a &#43;ve or -ve angle, we can just compare the x value with 0
    verts(i).Tu = IIf((vertexRay.X &gt; 0.0F), u, 1 - u)
End If
</pre></p><p>Download textures6.msi using the link at the top of this article for the complete application. </p><p>For an interesting aside into debugging this algorithm and why the Min and Max functions are necessary, see my <a href="http://www.indiegameguy.com/blogs/zman/archive/2005/08/17/53.aspx">blog entry</a> on the subject. </p><p>So that has put the imaginary globe back together, as you can see from Figure 4, but how can the same theory be applied to arbitrary meshes? </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/zmantextures3-4.gif" border="0" alt=""></p><p><strong>Figure 4. The texture mapped sphere</strong> </p><p>It turns out that the spherical texture mapping can be applied to any shape. Once the center is found, a ray can be projected through each vertex, just as was done with the sphere, and the texture map sampled in the same way. (There are lots of ways of visualizing what is happening here. If my explanation doesn't do it for you, then try reading some of the references below, as everyone's mind works differently.) </p><p>I like to imagine a surrounding sphere around the mesh. When the ray is projected from the center through the mesh vertex, it can be extended out to touch the surrounding sphere giving you the texture coordinates for that point. </p><p>The sample code allows you to switch between all of the DirectX primitives and see how a spherical mesh is applied to each of them. In addition, I have added the ability to show the vertex rays and the surrounding texture mapped sphere to help get your head around how it all works. </p><p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/912562/zmantextures3-5.gif" border="0" alt=""></p><p><strong>Figure 5. A texture mapped cylinder using spherical mapping</strong> </p><p>Homework for this time: Explain the odd texturing you see in the middle of the Pacific Ocean. It's easiest to see on the sphere and cylinder. I will revisit this and fix it in a future article when I cover mesh structures. </p><p>This concludes the series on texture mapping, until I get some other questions on the subject. </p><p><strong>Credits:</strong> </p><p>Thanks to </p><ul><li><a href="mailto:web@carlosag.net">Carlos Aguilar</a> for the <a href="http://www.carlosag.net/Tools/CodeColorizer/Default.aspx">code colorizer</a> </li><li><a href="http://www.cs.unc.edu/~rademach/">Paul Rademacher</a> for his <a href="http://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html#texturemap">Ray Tracing article</a> with the Spherical texture mapping formula </li><li><a href="http://www.mvps.org/directx/">Robert Dunlop</a> for his <a href="http://www.mvps.org/directx/articles/spheremap.htm">spherical texture mapping article</a> </li><li>Peter Donnelly for an <a href="http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnardir3d/html/msdn_wrapfun.asp">old article about Texture Wrapping</a> </li><li><a href="http://www.shatters.net/~t00fri/texfoundry.php4">Fridger Schrempp</a> for the earth texture from the <a href="http://www.celestiamotherlode.net/catalog/earth.php">Celestia MotherLode</a></li></ul><p>Copyright © 2005 TheZBuffer.com</p><p><em>(Editor's note: These examples, like the two previous articles in the series, were built using the August 2005 DirectX 9.0 SDK update.)</em></p> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Dunn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:652b9b1e0b12485ca51c9e7600dad3ca">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-3</comments>
      <itunes:summary> Part 3 of a three part series explaining the addition of textures to DirectX Primitive shapes. &amp;nbsp;Welcome to Ask The ZMan, a new column on the Coding4Fun game portal. The ZMan is here to solve your Managed DirectX programming problems. If you have a question for the ZMan send it to zman@thezbuffer.com.  Since Coding4Fun has only just launched, there aren&#39;t any specific questions to answer so I thought I would start with a question that occurs frequently on the Managed DirectX newsgroup:  C# DownloadC# DownloadVB Download&amp;quot;I&#39;ve created my first Managed DirectX project and can successfully draw shapes created using the Mesh.{shape} primitives. However, when I try to apply a texture to them,  nothing happens (b) the shapes go black or (c) the shapes disappear. How can I add a texture to the DirectX primitive shapes?&amp;quot;  HomeworkLast time I covered how to manually assign points on a texture map to a box. If you spent any time thinking about the homework you will have realised that as the meshes get more complex, the texture map that goes with them and the set of texture coordinates gets too complex to do by hand very quickly. I left you with the following question:  You have seen what the texture map template for the box looks like. What do you think a texture map for a cylinder or a sphere would look like? Download textures5.msi using the link at the top of this article. This solution allows you to display any of the Mesh.{shape} primitives and to render them in wireframe so that you can see the underlying mesh. Imagine unfolding those shapes until all the triangles lie flat. Figure 1 shows the cylinder and a texture map that would work for this mesh.    Figure 1. The wireframe cylinder and one possible texture map that could be associated with it Not only do you have to work out a suitable texture map, you have to work out all of the corresponding texture coordinates. The cylinder isn&#39;t too bad—the sides are represented by the rectangle in Figure 1 and the </itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-3</link>
      <pubDate>Tue, 31 Oct 2006 14:50:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-3</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912562_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/912562_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Dunn</dc:creator>
      <itunes:author>Andy Dunn</itunes:author>
      <slash:comments>5</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Ask-the-ZMan-Applying-Textures-Part-3/RSS</wfw:commentRss>
    </item>    
</channel>
</rss>