<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sgt. Conker &#187; XNA</title>
	<atom:link href="http://www.sgtconker.com/category/xna/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Thu, 09 Sep 2010 19:48:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Article: XNA Farseer Platform Physics Tutorial</title>
		<link>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 19:48:45 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Physics]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Farseer]]></category>
		<category><![CDATA[Platformer]]></category>
		<category><![CDATA[Roy Triesscheijn]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1756</guid>
		<description><![CDATA[by Roy Triesscheijn
Today I’m going to introduce you to a neat 2D physics engine for XNA called Farseer. With the help of this 2D physics engine we are going to create a small platform ‘game’ while introducing the important concepts of Farseer like bodies, geometry, joints and springs.
By the end of the tutorial, you'll be [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <span><a href="http://www.roy-t.nl">Roy Triesscheijn</a></span></h4>
<p>Today I’m going to introduce you to a neat 2D physics engine for XNA called Farseer. With the help of this 2D physics engine we are going to create a small platform ‘game’ while introducing the important concepts of Farseer like bodies, geometry, joints and springs.</p>
<p>By the end of the tutorial, you'll be able to build something like:</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/iC_Y9Tq5JeU?fs=1&amp;hl=en_US" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/iC_Y9Tq5JeU?fs=1&amp;hl=en_US" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><span id="more-1756"></span></p>
<h2>Set-up<img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/SolutionExplorer.PNG" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/see-saw.png" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/boxboy.jpg" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/BoxAndGround.png" alt="" /></h2>
<p>Before we can get started please download the latest stable release at <a href="http://farseerphysics.codeplex.com/">http://farseerphysics.codeplex.com</a> (at the time of writing that was 2.1.3) and extract the solution somewhere. Now also download the “Added motor to RevoluteJoint and FixedRevoluteJoint” patch at <a href="http://farseerphysics.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=70619">http://farseerphysics.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=70619</a>. You will find two files in the archive (RevoluteJoint.cs and FixedRevoluteJoint.cs) extract these and copy these over the files in “Farseer Physics 2.1.3 XNA\Dynamics\Joints”.</p>
<h2>Creating a project</h2>
<p>Now let’s fire up Visual Studio and create a new XNA 3.1 Windows Game project, call it anything you like. I’ve called it “FarseerPlatformer”. Now add the Farseer project to our solution: right click the our solution in the solution explorer and select “Add existing project”, then browse to where you’ve extracted Farseer and select the FarseerPhysicsXNA.csproj.</p>
<p style="text-align: center;"><img class="aligncenter" title="Solution Explorer" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/SolutionExplorer.PNG" alt="" width="261" height="326" /></p>
<p>Now add a reference to the FarseerPhysicsXNA project in your own project by right clicking the References folder in the solution explorer and choosing “Add reference”. Then select FarseerPhysicsXNA from the tab “Projects” and press ok.</p>
<p>If your solution explorer now looks like the picture on the left we’re ready to try and compile. Hit F6 on your keyboard. There should be no errors.</p>
<h2>My  first physics</h2>
<p>The physics simulator class is the heart of the Farseer physics engine and will control all our physics objects. Let’s create one!</p>
<p>Open Game1.cs and add the following using statements at the top of the file.</p>
<pre class="brush: csharp;">
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Factories;
using FarseerGames.FarseerPhysics.Collisions;
</pre>
<p>Now let’s create a PhysicsSimulator called physics. Add this definition at the top of the class.</p>
<pre class="brush: csharp;">
PhysicsSimulator physics;
</pre>
<p>And instantiate it by adding the following line to the end of the constructor.</p>
<pre class="brush: csharp;">
physics = new PhysicsSimulator(Vector2.UnitY * 500);
</pre>
<p>This will create a new physics simulator with a predefined gravity of (0, 500) which means that there is a constant force of strength 500 pushing everything down. 500 here is just an arbitrary number, play around with this value as much as possible to tweak the feel of your games.</p>
<p>All we need todo to make the physics simulator work is making it update every frame by adding the following line at the end of the Update method.</p>
<pre class="brush: csharp;">
physics.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
</pre>
<p>So that’s it. We’re done! But well, you can’t actually see anything yet. Let’s make a very simple class called PhysicsObject. I will not put down the entire class right here, see the source code for that. However there is one method that deserves special attention:</p>
<pre class="brush: csharp;">
protected virtual void SetupPhysics(PhysicsSimulator physics,
            Vector2 position, float width, float height, float mass)
        {
            body = BodyFactory.Instance.CreateRectangleBody(physics,
                                                width, height, mass);
            body.Position = position;

            geom = GeomFactory.Instance.CreateRectangleGeom(physics,
                                                body, width, height);
            geom.FrictionCoefficient = 0.5f;
        }
</pre>
<p>In this method we create the ‘physical representation’ for our new object.  For this we need two fields: body of type Body and geom of type Geom. Body represents a handle which we can push and pull and apply all sorts of forces to. Geom (short for geometry) handles the actual collisions and friction. Both objects fire numerous events which you can handle, the most useful one is geom’s OnCollision event that we will use in the final chapter.</p>
<p>Instantiating them is very easy. Just use the apropiate factory class to get a new instances, make sure to always choose the overload that also asks for a PhysicsSimulator object so that your object is automatically registered in the simulation. Also note that the PhysicsSimulator uses the center of an object as its position, while the SpriteBatch uses the top left corner normally, take this into account when drawing by setting the origin to the center of the texture when using the SpriteBatch.<br />
Add a texture to your content project and quickly instantiate a new PhysicsObject like this:</p>
<pre class="brush: csharp;">
squareTex = Content.Load&lt;Texture2D&gt;(&quot;square&quot;);
box = new PhysicsObject(physics, new Vector2(100, 0), 64, 64, 10, squareTex);
</pre>
<p>Then add the following lines to the draw method in Game1.</p>
<pre class="brush: csharp;">
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate,
                                              SaveStateMode.SaveState);
box.Draw(spriteBatch);
spriteBatch.End();
</pre>
<p>If you run the simulation now you should see a falling square. Nifty isn’t it?</p>
<h2>Laying grounds</h2>
<p>Now we need to make some ground that will stop our square from falling down at terminal velocity. To do this we’re going to make a static body. This means that the body is unaffected by all forces but still is in our simulation, handy for making immovable objects like ground and walls. To do this neatly we will make a new class that inherits from the PhysicsObject class. Call this class StaticPhysicsObject.<br />
Because of inheritance all we have to write in this new clas is this:</p>
<pre class="brush: csharp;">
    public class StaticPhysicsObject : PhysicsObject
    {
        public StaticPhysicsObject(PhysicsSimulator physics, Vector2 position, float width, float height, Texture2D texture)
            : base(physics, position, width, height, 1, texture)
        {
            body.IsStatic = true;
        }
    }
</pre>
<p>Note how we always pass a mass of 1, mass isn’t important for a static object.</p>
<p>Create a new field StaticPhysicsObject ground in Game1 and instantiate it in LoadContent like this:</p>
<pre class="brush: csharp;">
ground = new StaticPhysicsObject(physics, new Vector2(GraphicsDevice.Viewport.Width / 2, 500), GraphicsDevice.Viewport.Width, 64, squareTex);
</pre>
<p>Don’t forget to draw it in the Draw method.</p>
<p>You should now see a square falling down  and stopping when it hits our new ground.</p>
<p><img class="alignnone" title="Box and Ground" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/BoxAndGround.png" alt="" width="100%" /></p>
<h2>Joints</h2>
<p>Let’s make the simulation a bit more interesting by creating a see-saw. Quickly add two more PhysicsObjects, instantiate them like this:</p>
<pre class="brush: csharp;">
            seeSawBottom = new PhysicsObject(physics, new Vector2(175, 300), 50, 50, 1000, squareTex);
            seeSawTop = new PhysicsObject(physics, new Vector2(175, 200), 300, 30, 25, squareTex);
</pre>
<p>And write some draw code. Now let’s fire up the simulation again. You will now see our original block smash hard into our see-saw, rolling out of screen while the see-saw almost falls apart.</p>
<p>This looks awesome, however we would like the see-saw to behave as one object, so let’s introduce a joint. A joint is a way of fixing two bodies or a body and the background together (like an axel that connects a wheel to a car). There are multiple types of joints. For an explantion of the different types of joints see this page: <a href="http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068491">http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068491</a></p>
<p>We are going to create a revolute joint, that fixes two bodies together but still alows them to rotate independently, very handy for a see-saw or a wheel. To demonstate this we will create a new class called CompositePhysicsObject as below:</p>
<pre class="brush: csharp;">
public class CompositePhysicsObject
    {
        public CompositePhysicsObject(PhysicsSimulator physics, PhysicsObject poA, PhysicsObject poB, Vector2 relativeJointPosition)
        {
            this.poA = poA;
            this.poB = poB;

            joint = JointFactory.Instance.CreateRevoluteJoint(physics, poA.body, poB.body, poA.Position + relativeJointPosition);
            poA.geom.IgnoreCollisionWith(poB.geom);
            poB.geom.IgnoreCollisionWith(poA.geom);
        }

        public virtual void Draw(SpriteBatch spriteBatch)
        {
            poA.Draw(spriteBatch);
            poB.Draw(spriteBatch);
        }

        protected RevoluteJoint joint;
        protected PhysicsObject poA;
        protected PhysicsObject poB;
    }
</pre>
<p>Just as with the bodies and geoms we create a joint with a factory. Creating a revolute joint is very easy, the second body is attached to the first body at the absolute (world) position. To make it easier to create a composite physics object we are using a relative position (or offset) from the first body. Note that you will have to make sure yourself that the bodies overlap, the second body will not be moved by creating a joint. (Note: bodies don’t have to overlap to be fixed together by joints, but this will look pretty funny).</p>
<p>We also need to make sure that the geometries of both physics objects do not register colliding with each other; else we would get some very buggy results.</p>
<p>Let’s go back to the Game1 class, add a field called seeSaw of type CompositePhysicsObject and change the load content method to look like this:</p>
<pre class="brush: csharp;">
protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            squareTex = Content.Load&lt;Texture2D&gt;(&quot;square&quot;);
            box = new PhysicsObject(physics, new Vector2(100, 0), 64, 64, 10, squareTex);
            seeSawBottom = new PhysicsObject(physics, new Vector2(175, 300), 50, 50, 1000, squareTex);
            seeSawTop = new PhysicsObject(physics, new Vector2(175, 285), 300, 30, 25, squareTex);
            seeSaw = new CompositePhysicsObject(physics, seeSawTop, seeSawBottom, new Vector2(0, 15));
            ground = new StaticPhysicsObject(physics, new Vector2(GraphicsDevice.Viewport.Width / 2, 500), GraphicsDevice.Viewport.Width, 64, squareTex);
        }
</pre>
<p>Also update the drawing method:</p>
<pre class="brush: csharp;">
protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            box.Draw(spriteBatch);
            seeSaw.Draw(spriteBatch);
            ground.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }
</pre>
<p>Run, you will now have a box dropping on a fully functional see-saw.</p>
<h2>Springs</h2>
<p>You know what would be even cooler? If our see-saw would have a spring that would make our see-saw come back up again after our falling box hits it. With Farseer you can make numerous types of springs, for a full overview see the Springs section in the manual here: <a href="http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068498">http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068498</a></p>
<p>To improve our see-saw we are going to use an AngleSpring. This type of spring tries to keep two objects (or one object and the background) at a specified angle by applying a specified amount of torque (or less).</p>
<p>Let’s create a new class that inherits from our CompositePhysicsObject class. I couldn’t think of a decent name for it, so I just called it SpringPhysicsObject. This new class will compose two physics objects together (just as before) but will now also add an angle spring to try and keep two objects at a specified angle. (If you want to force two objects to always stay at a specified angle of each other you should use an angle joint, and if you want one object to always stay at a specified angle, use a fixed angle joint).</p>
<pre class="brush: csharp;">
public class SpringPhysicsObject : CompositePhysicsObject
    {
        public SpringPhysicsObject(PhysicsSimulator physics, PhysicsObject poA, PhysicsObject poB, Vector2 relativeJointPosition, float springForce, float springDampening)
            : base(physics, poA, poB, relativeJointPosition)
        {
            angleSpring = SpringFactory.Instance.CreateAngleSpring(physics, poA.body, poB.body, springForce, springDampening);
            angleSpring.MaxTorque = springForce;
        }

        protected AngleSpring angleSpring;
    }
</pre>
<p>As you can see we again don’t need to write a lot of code since inheriting from CompositePhysicsObject will already join our two bodies together. All we need to do is to create a new angle spring, as always via a factory. I think spring force and spring dampening speak for themselves. MaxTorque is the maximum amount of torque that will be applied to stay at the given angle. Note that you usually need very high values for spring force to make this work properly (just as in real life).<br />
Now that we have this new SpringPhysicsObject, replace our CompositePhysicsObject and instantiate it like this in the LoadContent method.</p>
<pre class="brush: csharp;">
seeSaw2 = new SpringPhysicsObject(physics, seeSawTop, seeSawBottom, new Vector2(0, 15), 10000000, 10000);
</pre>
<p>Also update the draw method.<br />
Now run the simulation and see how our see-saw behaves now!</p>
<p><img class="alignnone" title="See Saw" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/see-saw.png" alt="" width="100%" /></p>
<h2>Force</h2>
<p>Now what if we want to control the falling box? Maybe make it move a little, have it jump up and down, etc.<br />
To do this we need to apply force to our object. To demonstrate this we’re going to make a new class called Character that inherits from PhysicsObject.</p>
<pre class="brush: csharp;">
public class Character : PhysicsObject
    {
        public Character(PhysicsSimulator physics, Vector2 position, float width, float height, float mass, Texture2D texture)
            : base(physics, position, width, height, mass, texture)
        {
        }

        public virtual void Update(GameTime gameTime)
        {
            HandleInput(gameTime);
        }

        protected virtual void HandleInput(GameTime gameTime)
        {
            keyState = Keyboard.GetState();

            //Apply force in the arrow key direction
            Vector2 force = Vector2.Zero;
            if (keyState.IsKeyDown(Keys.Left))
            {
                force.X -= forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Right))
            {
                force.X += forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Up))
            {
                force.Y -= forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Down))
            {
                force.Y += forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            body.ApplyForce(ref force);

            oldState = keyState;
        }

        public float forcePower;
        protected KeyboardState keyState;
        protected KeyboardState oldState;

    }
</pre>
<p>As you can see force is easily applied just by constructing a force vector and calling body.ApplyForce(). We pass the vector by reference so that the garbage collector doesn’t have to jump in and act too often (since Vector2 is a value type, its normally copied each time it’s passed to a different method, don’t worry too much about that right now).<br />
You can apply impulse in the same way. (Impulse is direct, useful for jumping and explosions, while force is steadily added, more useful to make a jetpack work for example).<br />
Let’s play: in Game1 replace our box of type PhysicsObject with a box of type Character. Set box.forcePower to 1000000.  Also add box.Update(gameTime); to the Update method in Game1 and make sure the box is being drawn.<br />
If you did everything correct you should now be able to control the falling box with the arrows on your keyboard.</p>
<h2>A game character</h2>
<p>Now we’ve got all of the basics covered it’s time to talk about creating a more realistic game character. Without physics you would move an object by changing its position when a key is pressed. Jumping would be done by creating two ‘fake forces’ that sent the object up and down. When using a physics engine you shouldn’t just move your character, this will make it very hard for Farseer to handle collisions because for Farseer it looks like the character just teleported a tiny amount (there are no forces, impulses or torque present). For a realistic character we need to apply forces to a body, however this causes a problem: how much force do we apply? Do we keep applying forces (e.g. the character keeps accelerating)? This sounds very unrealistic, as a normal person quickly accelerates in just a few steps and then stays at his running speed. We could do with impulses, that instantly generate movement, however stopping the character is going to be even more problematic then. And if we encounter a slope or if the friction is not set to 0 the character will slow down until the user releases and presses the move key again.<br />
Suffice it to say that I’ve been trying all sorts of stuff for two days to get a character moving the way I want it (instant start and stop, controllable air movements, steady running speed, also characters normally don’t fall over).<br />
Luckily I came across Bryan Dismas’ blog who wrote an article on this <a href="http://amazingretardo.simiansoftwerks.com/2010/02/17/platformer-character-control-farseer-physics-engine/">http://amazingretardo.simiansoftwerks.com/2010/02/17/platformer-character-control-farseer-physics-engine/</a>. He adopted this idea from Robert Dodd (<a href="http://boxycraft.wordpress.com">http://boxycraft.wordpress.com</a>) and I’m going to change it even further.</p>
<p><img src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/boxboy.jpg" alt="Boxboy" /><br />
<em>Image by Robert Dodd</em></p>
<p>The idea is to create a character from two parts: the upper body is just a simple rectangle. The lower body is a circle/wheel that we rotate so that we can move around and climb slopes without problems. We’re going to create a slightly simpler version of this.</p>
<ul>
<li>Upper body: a rectangle body always kept up-right using a fixed angle joint.</li>
<li>Lower body: a circle connected to the upper body using a revolute joint.</li>
</ul>
<p>With the current version of Farseer this is enough to have a nice character jumping around. So let’s write some code.<br />
Create a class called CompositeCharacter which inherits from Character.<br />
The class is fairly long because I also had to add a bit of state management to make walking, jumping and moving in-air work. However for this tutorial the most important is the overloaded method SetupPhysics that is listed here below.</p>
<pre class="brush: csharp;">
protected override void SetupPhysics(PhysicsSimulator physics, Vector2 position, float width, float height, float mass)
        {
            //Create a body that is almost the size of the entire object
            //but with the bottom part cut off.
            float upperBodyHeight = height - (width / 2);
            body = BodyFactory.Instance.CreateRectangleBody(physics, width, upperBodyHeight, mass / 2);
            //also shift it up a tiny bit to keep the new object's center correct
            body.Position = position - Vector2.UnitY * (width / 4);
            centerOffset = position.Y - body.Position.Y; //remember the offset from the center for drawing

            //Now let's make sure our upperbody is always facing up.
            fixedAngleJoint = JointFactory.Instance.CreateFixedAngleJoint(physics, body);

            //Create a wheel as wide as the whole object
            wheelBody = BodyFactory.Instance.CreateCircleBody(physics, width / 2, mass / 2);
            //And position its center at the bottom of the upper body
            wheelBody.Position = body.Position + Vector2.UnitY * (upperBodyHeight / 2);

            //These two bodies together are width wide and height high <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
            //So let's connect them together.
            motor = JointFactory.Instance.CreateRevoluteJoint(physics, body, wheelBody, wheelBody.Position);
            motor.Motor_Enabled = true;
            motor.Motor_MaxTorque = 1000f; //set this higher for some more juice
            motor.Motor_Speed = 0;

            //Create geomitries.
            wheelGeom = GeomFactory.Instance.CreateCircleGeom(physics, wheelBody, width / 2, 16);
            geom = GeomFactory.Instance.CreateRectangleGeom(physics, body, width, upperBodyHeight);

            wheelGeom.IgnoreCollisionWith(geom);
            geom.IgnoreCollisionWith(wheelGeom);

            //Set the friction of the wheelGeom to float.MaxValue for fast stopping/starting
            //or set it higher to make the character slip.
            wheelGeom.FrictionCoefficient = float.MaxValue;
        }
</pre>
<p>Quite a lot is happening here, but nothing should be really new. We first create a body that is going to be the upper part of our character, we then shift its position a bit and calculate its shift from the center. (This is handy for if we want to draw our final character). A simple fixed angle joint keeps our upper body at all times.</p>
<p>We then create the lower body (wheelBody) which is sized like a wheel just as wide as our upper body. Its center is positioned at the bottom of the upper body (see the picture above again).</p>
<p>The lower body is fixed to the upper body with a revolute joint, and because we downloaded the ‘motor’ patch we can force the lower body to rotate while it stays attached to the upper body. If you think about we’ve  just created a Segway actually.<br />
Geometries are created as usual and the upper and lower bodies are told not to collide with each other.</p>
<p>Finally we set the friction of the lower body to the highest possible value. This way the movement of our character will be very responsive. You can lower the amount of friction for a different feel (be sure to play around a bit, 0.5f gives quite a funny feel).</p>
<p>Congratulations, you’re now familiar with the basics of the Farseer physics engine. Be sure to fire up the simulation and play around a bit. Maybe try to make a more complicated level with the objects you now have.</p>
<h2>Afterthoughts</h2>
<p>You now have a bit of a grasp on the techniques that the Farseer physics engine offers you. This engine could easily be extended to make even more fun physics objects, like moving platforms. However because this is a tutorial, some things in the code have been neglected, so if you would like to extend the tutorial code, please first make sure that you make some kind of base object, of which CompositePhysicsObject and PhysicsObject extend. Then make some sort of drawing manager, this will make your life a lot easier!<br />
This tutorial has shown you a few useful tricks like Polymorphism (a Character is still a PhysicsObject) which saves writing a lot of duplicate code. Make sure that you use these techniques to the max they will make your life a lot easier!<br />
I hope you’ve enjoyed this tutorial, for more of my tutorials see <a href="http://www.roy-t.nl">www.roy-t.nl</a>.</p>
<p><strong>Download sample source</strong>: <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/FarseerPlatformer.zip">FarseerPlatformer.zip</a> (under the <a href="http://www.microsoft.com/opensource/licenses.mspx#Ms-PL">MS-PL License</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article: Rolling World Tutorial</title>
		<link>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 21:01:46 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Christian Schlager]]></category>
		<category><![CDATA[Content Creation]]></category>
		<category><![CDATA[Rolling World]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1745</guid>
		<description><![CDATA[by Christian Schlager



When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Christian Schlager</h4>
<div align="center">
<img width="60%" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/gfx/aerial_perspective_in_game.jpg">
</div>
<p>When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the next pages will be the starting point of a great 3D indie game by  one of you <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>We will make a prototype that features the kind of rolling world effect  that you can see in games such as Animal Crossing or DeathSpank. We will  also create the textures and 3D models that go along with the rolling  effect and recreate the combination of 2D art with a 3D world you can  see in the game DeathSpank.<br />
<span id="more-1745"></span></p>
<h4>Difficulty</h4>
<p>This tutorial is intended for Beginner/Intermediate developers.<br />
If you played around with XNA and /or worked on 2D games before this tutorial should be no problem for you.</p>
<h4>Content</h4>
<p>The first section of this tutorial covers the creation of the assets for our game.<br />
We will draw textures for the world, for the trees and a very simple one for the hero.<br />
We will also create a simple DirectX effect file which we will use to render the models we create in SoftImage Mod Tool.<br />
Once we have all the assets we will set up our game project in Visual  Studio, load and render game objects and then move the hero of our game  around.<br />
In the last section we will add the rolling world effect. We will  develop a concept of the effect with sketches and pseudo-code and then  implement the effect.<br />
Finally, there is some bonus content you might try once you are done with the tutorial.<br />
This tutorials comes with pre-made assets in case you are only  interested in the programming side of the tutorial. You can also skip  the foreplay completely and jump to the rolling world effect part using  the project in the folder WorldGame.<br />
You can also explore for yourself with the complete rolling world game in the folder RollingWorldGame.</p>
<h4>Software</h4>
<dl>
<dt>Visual C# 2008 Express</dt>
<dd>The Visual Studio 2008 Express is a free set of tools for developing applications for Windows.<br />
<a href="http://www.microsoft.com/express/Downloads/#2008-Visual-CS" target="new">Download Visual C\# 2008 Express</a> </dd>
<dt>XNA Game Studio 3.1</dt>
<dd>This software package contains the XNA framework which includes an  extensive set of class libraries specific to game development. Once you  installed the Game Studio you can use it in Visual Studio:<br />
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=80782277-d584-42d2-8024-893fcd9d3e82" target="new">Microsoft XNA Game Studio 3.1</a> </dd>
<dt>Paint.NET</dt>
<dd>Paint.NET is free image and photo editing software for Windows. We will use it to create textures for our game:<br />
<a href="http://www.getpaint.net/download.html" target="new">Download Paint.NET</a> </dd>
<dt>SoftImage Mod Tool</dt>
<dd>We will be using Autodesk SoftImage Mod Tool to create the 3D  models. The version we will use is for non-commercial use only which is  fine for this tutorial:<br />
<a href="http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&amp;id=13571320" target="new">Download Autodesk Softimage Mod Tool</a></dd>
</dl>
<h4>Feedback</h4>
<p>My name is Christian Schlager and I wrote this tutorial. If you like it,  have constructive feedback or found a mistake in the tutorial please  leave a comment here, or on my page: <a href="http://googoobachoo.blogspot.com/2010/08/rolling-world-tutorial.html" target="new">http://googoobachoo.blogspot.com</a></p>
<h2>Downloads</h2>
<p>This tutorial is accompanied by the following downloads:</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/WorldGame.zip">WorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/RollingWorldGame.zip">RollingWorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/Assets.zip">Assets.zip</a></p>
<h4>Next Page: Creating the assets</h4>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Article: I Can Has Platformer? (Part 5)</title>
		<link>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-5/</link>
		<comments>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-5/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 19:33:56 +0000</pubDate>
		<dc:creator>ElementCy</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Article]]></category>
		<category><![CDATA[ICanHasPlatformer]]></category>
		<category><![CDATA[Platformer]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1697</guid>
		<description><![CDATA[by Casey Young
Welcome back to the fifth part of my series on how to create a simple platformer game.  In this article, we give our hero something to collect.

Please refer to my fourth article to grab the final project before continuing this part, you will need that code to edit along with to make [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.ubergamermonkey.com/">Casey Young</a></h4>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP5_FinalImage.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP5_FinalImage-300x175.png" alt="I Can Has Platformer Part 5 Final Image" title="I Can Has Platformer Part 5 Final Image" width="300" height="175" class="alignright size-medium wp-image-1353" /></a>Welcome back to the fifth part of my series on how to create a simple platformer game.  In this article, we give our hero something to collect.<br />
<span id="more-1697"></span></p>
<p>Please refer to my <a href="http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-4/">fourth article</a> to grab the final project before continuing this part, you will need that code to edit along with to make things work. =D</p>
<p>From the last part, we had our hero meet his nemisis, MuffinMan.  Our hero is a little bored with him, and wants something else to do.  Let's have our hero collect things throughout the level shall we?</p>
<div style="background-color:#000">
<a href="http://www.sgtconker.com/wp-content/uploads/2010/09/scribbles.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/scribbles.png" alt="I Can Has Platformer Part 5, scribbles" title="I Can Has Platformer Part 5, scribbles" width="128" height="32" class="aligncenter size-medium wp-image-1353" /></a></div>
<p>Save this file under Content/Sprites, in a new directory called Collectables.  The sprite sheet should be transparent with the sprites in white. I made a black background so you could see them on the page.</p>
<p>Now with the new sprite sheet saved and loaded into our project, let's start creating the Collectable class.  The Collectable class will be very similar to the Enemy class.  Start off by creating a new class file named Collectable, and have it inherit our AnimatedSprite class.  Let's start off with the public properties and private fields of the file.  Notice that everything should be very similar to our Player and Enemy class, except for one thing, colorOffset.  This field will give our collectables a different color when we draw them, so we don't have to add more sprite sheets for each color.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ScribblePlatformer
{
    class Collectable : AnimatedSprite
    {
        private string currentAnim = &quot;Idle&quot;;
        private Rectangle localBounds;
        bool isAlive;
        Level level;
        Vector2 position;
        private Color colorOffset;

        /// &lt;summary&gt;
        /// Is the collectable alive, or has been collected?
        /// &lt;/summary&gt;
        public bool IsAlive
        {
            get { return isAlive; }
        }

        /// &lt;summary&gt;
        /// What level are we on, used for collision and interaction
        /// with the level's entities.
        /// &lt;/summary&gt;
        public Level Level
        {
            get { return level; }
        }

        /// &lt;summary&gt;
        /// What position the collectable is in the world
        /// &lt;/summary&gt;
        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        /// &lt;summary&gt;
        /// Gets a rectangle which bounds this collectable in world space.
        /// &lt;/summary&gt;
        public Rectangle BoundingRectangle
        {
            get
            {
                int left = (int)Math.Round(Position.X - Origin.X) + localBounds.X;
                int top = (int)Math.Round(Position.Y - Origin.Y) + localBounds.Y;

                return new Rectangle(left, top, localBounds.Width, localBounds.Height);
            }
        }
</pre>
<p>When we want to create a new Collectable, we want to tell our system what type of collectable it is.  This is exactly what the Enemy class did, but this time we are going to use it.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Constructs a new Collectable.
        /// &lt;/summary&gt;
        public Collectable(Level _level, Vector2 _position, string _collectable)
            : base(32, 32, 4)
        {
            level = _level;
            position = _position;
            isAlive = true;

            LoadContent(_collectable);
        }
[/chsharp]

Notice something different?  What is this base() call?  If you recall, our AnimatedSprite class was hard coded for sprite sheets with frames of 96x96 and 4 frames per row.  We want this to be more dynamic per entity we add to the game.  We are going to pause on the Collectable class here and modify the AnimatedSprite class, and add the base() to the Player and Enemy class's constructors.  First up, let's open up the AnimatedSprite class and add 3 new parameters for the constructor.

[csharp]
		public AnimatedSprite(int _frameWidth, int _frameHeight, int _framesPerRow)
		{
			FrameWidth = _frameWidth;
			FrameHeight = _frameHeight;
			framesPerRow = _framesPerRow;
			SpriteTextures = new List&lt;Texture2D&gt;();
			SpriteAnimations = new Dictionary&lt;string, Animation&gt;();
		}
</pre>
<p>This allows us to change the frame width/height and frames per row for each different instance of the AnimatedSprite class.  Now let's add the base() call to Player and Enemy like so:</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
		/// Constructors a new player.
		/// &lt;/summary&gt;
		public Player(Level _level, Vector2 _position) : base(96, 96, 4)
		{
			level = _level;

			LoadContent();

			Reset(_position);
		}

        /// &lt;summary&gt;
        /// Constructs a new Enemy.
        /// &lt;/summary&gt;
        public Enemy(Level _level, Vector2 _position, string _enemy)
            : base(96, 96, 4)
        {
            level = _level;
            position = _position;
            isAlive = true;
            isCompletelyDead = false;

            LoadContent(_enemy);
        }
</pre>
<p>Alright, now let's get back to the Collectable class.  We need to load the content, and since we are wanting to use the colorOffset to change the colors of the collectables, we will have 2 different values for the collectable type in our level.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Loads the player sprite sheet.
        /// &lt;/summary&gt;
        public void LoadContent(string _collectable)
        {
            string sheetString = string.Empty;
            switch (_collectable)
            {
                case &quot;s&quot;:
                    sheetString = &quot;Sprites/Collectables/scribbles&quot;;
                    colorOffset = Color.Black;
                    break;
                case &quot;S&quot;:
                    sheetString = &quot;Sprites/Collectables/scribbles&quot;;
                    colorOffset = Color.Gold;
                    break;
                default:
                    sheetString = &quot;Sprites/Collectables/scribbles&quot;;
                    colorOffset = Color.White;
                    break;
            }
            // Load animated textures.
            Texture2D tex = Level.Content.Load&lt;Texture2D&gt;(sheetString);
            if(!SpriteTextures.Contains(tex))
                SpriteTextures.Add(tex);

            Animation anim = new Animation();
            anim.LoadAnimation(&quot;Idle&quot;, 0, new List&lt;int&gt;
			{
				0,
				1,
                2,
                3
			}, 16, true);
            SpriteAnimations.Add(&quot;Idle&quot;, anim);

            // Calculate bounds within texture size.
            // subtract 4 from height to remove a 2px buffer
            // around the collectable.
            int width = FrameWidth;
            int left = (FrameWidth - width) / 2;
            int height = FrameHeight - 4;
            int top = FrameHeight - height;
            localBounds = new Rectangle(left, top, width, height);

            SpriteAnimations[currentAnim].ResetPlay();
        }
</pre>
<p>For a collectable, we don't have a death animation, just the single Idle animation.  We do want to know when the collectable was collected, so we can do things later on, like add to a score, play a sound, etc.  This is where the OnKilled function comes into play.  Right now, we just want to say it is not alive anymore.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when the player has collected us.
        /// &lt;/summary&gt;
        public void OnKilled()
        {
            isAlive = false;
        }
</pre>
<p>The last two things left for our Collectable class is to animate it and telling it to draw.  The Update function is very bare, it only tells the the animation to update.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Animate the collectable
        /// &lt;/summary&gt;
        public void Update(GameTime _gameTime)
        {
            SpriteAnimations[currentAnim].Update(_gameTime);
        }
</pre>
<p>The Draw function is very similar to the previous class's Draw function.  We want to draw our collectable with the correct frame of animation and with the correct color tint.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Draws the animated enemy.
        /// &lt;/summary&gt;
        public void Draw(GameTime _gameTime, SpriteBatch _spriteBatch)
        {
            Rectangle source = GetFrameRectangle(SpriteAnimations[currentAnim].FrameToDraw);

            // Draw the enemy.
            _spriteBatch.Draw(SpriteTextures[0], position, source, colorOffset, 0.0f, Origin, 1.0f, SpriteEffects.None, 0.0f);
        }
[csharp]

And that is the Collectable class.  Very similar to our Enemy class, except for the collectables don't move, and we added a tint to the collectable when drawn.  There is just a few things left to do.  We need to tell the Level to load up a collectable, and implement the collision detections.  Let's load up the Level1.txt file and make some spawn points for some collectables.  We are going to use the letter 's' for a black scribble, and 'S' for a golden one.

[text]
.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,.,.,e,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,r,b,g,o,y,.,.,.,.,.,.
.,b,.,e,.,.,s,.,.,.,.,.,.,.,.,S,.,.,.,.
.,r,y,o,G,B,R,.,.,.,.,.,.,.,.,s,.,.,.,.
.,.,.,.,.,.,.,.,.,.,S,.,.,.,.,s,.,.,.,.
.,.,.,.,.,.,.,.,.,O,Y,R,.,.,.,s,.,.,.,.
.,.,.,.,.,s,.,.,.,.,.,.,.,.,.,s,.,.,.,.
.,.,.,.,R,B,G,.,.,.,g,.,.,.,B,G,O,.,.,.
.,+,.,.,.,.,.,.,.,.,b,.,.,.,.,.,.,.,e,.
r,r,b,b,g,g,o,o,y,y,r,b,g,o,y,r,b,g,o,y
[/text]

If we try to run this right now, our Level will complain that it doesn't know what to do with the value of 's' or 'S'.  Let's load up the Level class and make it aware of the new collectables.  First off, let's add two lists of collectables one for active, and another for removing from active.

[csharp]
        private List&lt;Collectable&gt; collectables = new List&lt;Collectable&gt;();
        private List&lt;Collectable&gt; collectedCollectables = new List&lt;Collectable&gt;();
</pre>
<p>In the LoadTile function, we need to add a case for 's' and 'S', and have it load up a collectable.  So add this case to the switch.</p>
<pre class="brush: csharp;">
	// Collectables spawns
	case 's':
		return LoadCollectableTile(_x, _y, &quot;s&quot;);
	case 'S':
		return LoadCollectableTile(_x, _y, &quot;S&quot;);
</pre>
<p>Now with that added, we need to implement this new function.  It creates a collectable, adds it to the collectables list, and creates a blank tile on the map.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Instantiates an collectable and puts it in the level.
        /// &lt;/summary&gt;
        private Tile LoadCollectableTile(int _x, int _y, string _collectable)
        {
            Vector2 position = new Vector2((_x * 64) + 48, (_y * 64) + 20);
            collectables.Add(new Collectable(this, position, _collectable));

            return new Tile(String.Empty, 0, TileCollision.Passable);
        }
</pre>
<p>In the Update function, we want to update the collectables.  The updated Update function should look something like this:</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
		/// Updates all objects in the world, performs collision between them,
		/// and handles the time limit with scoring.
		/// &lt;/summary&gt;
		public void Update(GameTime _gameTime)
		{
            Player.Update(_gameTime);

            if (Player.IsCompletelyDead)
                Player.Reset(start);

            UpdateEnemies(_gameTime);

		    UpdateCollectables(_gameTime);
		}
</pre>
<p>The new Update function has a new call in it we need to implement.  Inside this new function, we are going to tell each collectable to update, and check if he has been collected by our hero.  If there are any collectables that have been collected, we want to remove them from the main update list.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Animates each enemy and allow them to kill the player.
        /// &lt;/summary&gt;
        private void UpdateCollectables(GameTime _gameTime)
        {
            foreach (Collectable collectable in collectables)
            {
                collectable.Update(_gameTime);

                if (player.IsAlive &amp;&amp; collectable.IsAlive)
                {
                    // Touching an enemy instantly kills the player
                    if (collectable.BoundingRectangle.Intersects(Player.BoundingRectangle))
                    {
                        OnCollectableCollected(collectable);
                    }
                }
            }

            if (collectedCollectables.Count &gt; 0)
            {
                foreach (Collectable collectable in collectedCollectables)
                {
                    collectables.Remove(collectable);
                }
                collectedCollectables.Clear();
            }
        }
</pre>
<p>We are almost done here, we now need to implent the new function that we are calling in UpdateCollectables, OnCollectableCollected.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when an collectable is collected.
        /// &lt;/summary&gt;
        private void OnCollectableCollected(Collectable _collectable)
        {
            _collectable.OnKilled();
            collectedCollectables.Add(_collectable);
        }
</pre>
<p>The last thing to do is tell our active collectables to draw themselves.  To do this, we need to modify the Draw function and call Draw for each collectable in the list.</p>
<pre class="brush: csharp;">
		public void Draw(GameTime _gameTime, SpriteBatch _spriteBatch)
		{
			DrawTiles(_spriteBatch);
            player.Draw(_gameTime, _spriteBatch);

		    foreach (Collectable collectable in collectables)
		        collectable.Draw(_gameTime, _spriteBatch);

            foreach (Enemy enemy in enemies)
                enemy.Draw(_gameTime, _spriteBatch);
		}
</pre>
<p>That should do it.  Our hero now has some Scribbles to collect!  Build the project and run it.</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP5_FinalImage.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP5_FinalImage-300x175.png" alt="I Can Has Platformer Part 5 Final Image" title="I Can Has Platformer Part 5 Final Image" width="300" height="175" class="aligncenter size-medium wp-image-1353" /></a></p>
<p>In the next article, we are going to add some UI features, like a HUD for scores and lives.  To get a hold of the project as it should be by the end of this part, <a href='http://www.sgtconker.com/wp-content/uploads/2010/09/ScribblePlatformer_Part5.zip'>click here</a>.</p>
<p>Stay tuned for the 6th part of the "I Can Has Platformer" series...</p>
<p><a href="http://www.sgtconker.com/2010/01/article-i-can-has-platformer-part-1/">Part 1</a></p>
<p><a href="http://www.sgtconker.com/2010/02/article-i-can-has-platformer-part-2/">Part 2</a></p>
<p><a href="http://www.sgtconker.com/2010/03/article-i-can-has-platformer-part-3/">Part 3</a></p>
<p><a href="http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-4/">Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-5/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Article: I Can Has Platformer? (Part 4)</title>
		<link>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-4/</link>
		<comments>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-4/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 16:46:06 +0000</pubDate>
		<dc:creator>ElementCy</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[ICanHasPlatformer]]></category>
		<category><![CDATA[Platformer]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1685</guid>
		<description><![CDATA[by Casey Young
Welcome back to the fourth part of my series on how to create a simple platformer game.  In this article, we give our hero a purpose to live.

Please refer to my third article to grab the final project before continuing this part, you will need that code to edit along with to [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.ubergamermonkey.com/">Casey Young</a></h4>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP4_FinalImage.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP4_FinalImage-300x175.png" alt="I Can Has Platformer Part 4 Final Image" title="I Can Has Platformer Part 4 Final Image" width="300" height="175" class="alignright size-medium wp-image-1353" /></a>Welcome back to the fourth part of my series on how to create a simple platformer game.  In this article, we give our hero a purpose to live.<br />
<span id="more-1685"></span></p>
<p>Please refer to my <a href="http://www.sgtconker.com/2010/03/article-i-can-has-platformer-part-3/">third article</a> to grab the final project before continuing this part, you will need that code to edit along with to make things work. =D</p>
<p>From the last part, we gave our hero some motivation and made him animated.  He is all hyped up and ready to go, but nothing to do.  In this part we are going to give our hero some obsticles, and add some baddies for him to fend off!  First things first, grab this sprite sheet of our hero's ruffian friend, The MuffinMan!</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/muffinman.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/muffinman.png" alt="I Can Has Platformer Part 4, MuffinMan" title="I Can Has Platformer Part 4, MuffinMan" width="384" height="192" class="aligncenter size-medium wp-image-1353" /></a></p>
<p>Save this file under Content/Sprites, in a new directory called Enemies.  While we are grabbing the new assets, grab a new sprite sheet of our hero, and override the previous one under Content/Sprites/Player.</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/player.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/player.png" alt="I Can Has Platformer Part 4, Player" title="I Can Has Platformer Part 4, Player" width="384" height="384" class="aligncenter size-medium wp-image-1353" /></a></p>
<p>Now with the two sprite sheets saved and loaded into our project, let's start creating the Enemy class.  Our enemy class will be very similar to the player class, but not as complex.  Start off by creating a new class file named Enemy, and have it inherit our AnimatedSprite class.  Let's start off with the public properties and private fields of the file.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ScribblePlatformer
{
    class Enemy : AnimatedSprite
    {
        private SpriteEffects flip = SpriteEffects.None;
        private string currentAnim = &quot;Walk&quot;;
        private const float MoveSpeed = 128.0f;
        private Rectangle localBounds;
        bool isAlive;
        bool isCompletelyDead;
        Level level;
        Vector2 position;
        Vector2 velocity;

        /// &lt;summary&gt;
        /// Is the enemy alive, or dead?
        /// &lt;/summary&gt;
        public bool IsAlive
        {
            get { return isAlive; }
        }

        /// &lt;summary&gt;
        /// Is enemy completely dead, if so, flag for removal from level
        /// &lt;/summary&gt;
        public bool IsCompletelyDead
        {
            get { return isCompletelyDead; }
        }

        /// &lt;summary&gt;
        /// What level are we on, used for collision and interaction
        /// with the level's entities.
        /// &lt;/summary&gt;
        public Level Level
        {
            get { return level; }
        }

        /// &lt;summary&gt;
        /// What position the enemy is in the world
        /// &lt;/summary&gt;
        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        /// &lt;summary&gt;
        /// The enemy's movement velocity
        /// &lt;/summary&gt;
        public Vector2 Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }

        /// &lt;summary&gt;
        /// Gets a rectangle which bounds this enemy in world space.
        /// &lt;/summary&gt;
        public Rectangle BoundingRectangle
        {
            get
            {
                int left = (int)Math.Round(Position.X - Origin.X) + localBounds.X;
                int top = (int)Math.Round(Position.Y - Origin.Y) + localBounds.Y;

                return new Rectangle(left, top, localBounds.Width, localBounds.Height);
            }
        }
</pre>
<p>When we want to create a new Enemy, we want to tell our system what type of enemy it is.  This article doesn't use this feature, yet, but I am implementing it now so you can add new enemies with just a simple modifications.</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
        /// Constructs a new Enemy.
        /// &lt;/summary&gt;
        public Enemy(Level _level, Vector2 _position, string _enemy)
        {
            level = _level;
            position = _position;
            isAlive = true;
            isCompletelyDead = false;

            LoadContent(_enemy);
        }
</pre>
<p>In our LoadContent function for our Enemy class, this is where it can load a different sprite sheet for a different enemy, right now we just have MuffinMan, so it is the default sprite sheet to load.  We are also giving our MuffinMan 2 sets of animations, Walk and Dead.  Walk is the default because he likes to pace back and forth.  When our hero kills the MuffinMan, he will run through a death animation.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Loads the player sprite sheet.
        /// &lt;/summary&gt;
        public void LoadContent(string _enemy)
        {
            string enemyString = string.Empty;
            switch (_enemy)
            {
                case &quot;e&quot;:
                    enemyString = &quot;Sprites/Enemies/muffinman&quot;;
                    break;
                default:
                    enemyString = &quot;Sprites/Enemies/muffinman&quot;;
                    break;
            }
            // Load animated textures.
            Texture2D tex = Level.Content.Load&lt;Texture2D&gt;(enemyString);
            if(!SpriteTextures.Contains(tex))
                SpriteTextures.Add(tex);

            Animation anim = new Animation();
            anim.LoadAnimation(&quot;Walk&quot;, 0, new List&lt;int&gt;
			{
				0,
				1
			}, 4, true);
            SpriteAnimations.Add(&quot;Walk&quot;, anim);

            anim = new Animation();
            anim.LoadAnimation(&quot;Dead&quot;, 0, new List&lt;int&gt;
			{
				2,
				3,
                4,
                5
			}, 36, false);
            anim.AnimationCallBack(DeadAnimEnd);
            SpriteAnimations.Add(&quot;Dead&quot;, anim);

            // Calculate bounds within texture size.
            // subtract 10 from width and height to remove a 5px buffer
            // around the enemy.
            int width = FrameWidth - 10;
            int left = (FrameWidth - width) / 2;
            int height = FrameHeight - 10;
            int top = FrameHeight - height;
            localBounds = new Rectangle(left, top, width, height);

            SpriteAnimations[currentAnim].ResetPlay();
        }
</pre>
<p>Notice that the Dead animation sequence has a callback function tied to it.  This is when we know the death animation is done, and tell the level to remove the enemy from itself.  So let's implement that function, which just sets a flag saying the enemy is completely killed off.  Also, let's creat a function for our level to call telling the enemy that he just got squished.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when the player has squished us.
        /// &lt;/summary&gt;
        public void OnKilled()
        {
            isAlive = false;
            SpriteAnimations[currentAnim].Stop();
            currentAnim = &quot;Dead&quot;;
            SpriteAnimations[currentAnim].ResetPlay();
        }

        /// &lt;summary&gt;
        /// Called when Dead animation is done, letting the level know to remove.
        /// &lt;/summary&gt;
        public void DeadAnimEnd()
        {
            isCompletelyDead = true;
        }
</pre>
<p>The last two things left for our Enemy class is the simple ai and telling it to draw.  Our enemy, the MuffinMan just likes to walk back and forth, and dosn't like to fall off ledges.  So in our update function, let's have him move back and forth, and keep him on ledges.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Paces back and forth along a platform.
        /// &lt;/summary&gt;
        public void Update(GameTime _gameTime)
        {
            SpriteAnimations[currentAnim].Update(_gameTime);
            if (isAlive)
            {
                float elapsed = (float) _gameTime.ElapsedGameTime.TotalSeconds;

                // Calculate tile position based on the side we are walking towards.
                int direction = 1;
                if (Velocity.X &lt; 0)
                    direction = -1;
                float posX = Position.X + localBounds.Width/2*direction;
                int tileX = (int) Math.Floor(posX/Tile.Width) - direction;
                int tileY = (int) Math.Floor(Position.Y/Tile.Height);

                // If we are about to run into a wall or off a cliff, reverse direction.
                if (Level.GetCollision(tileX + direction, tileY - 1) == TileCollision.Impassable ||
                    Level.GetCollision(tileX + direction, tileY + 1) == TileCollision.Passable ||
                    Level.GetCollision(tileX + direction, tileY) == TileCollision.Impassable)
                {
                    direction *= -1;
                }

                // Move in the current direction.
                velocity = new Vector2(direction*MoveSpeed*elapsed, 0.0f);
                position = position + velocity;
            }
        }
</pre>
<p>The Draw function is very similar to our Player's Draw function.  We want to draw our enemy with the correct frame of animation and flip him if he is moving the opposite direction.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Draws the animated enemy.
        /// &lt;/summary&gt;
        public void Draw(GameTime _gameTime, SpriteBatch _spriteBatch)
        {
            Rectangle source = GetFrameRectangle(SpriteAnimations[currentAnim].FrameToDraw);

            // Flip the sprite to face the way it is moving.
            if (Velocity.X &gt; 0)
                flip = SpriteEffects.FlipHorizontally;
            else if (Velocity.X &lt; 0)
                flip = SpriteEffects.None;

            // Draw the enemy.
            _spriteBatch.Draw(SpriteTextures[0], position, source, Color.White, 0.0f, Origin, 1.0f, flip, 0.0f);
        }
[csharp]

And that is our Enemy class.  Pretty short and easy, no?  Now let's edit our Player class, and get him ready for his battles with the MuffinMan.  We want to implement a new property to tell the level that he is completely dead and have him respawn.

[csharp]
        /// &lt;summary&gt;
        /// Is player completely dead?
        /// &lt;/summary&gt;
        public bool IsCompletelyDead
        {
            get { return isCompletelyDead; }
        }
        bool isCompletelyDead;
</pre>
<p>In the Player Class's LoadContent, we want to load up a new animation sequence, his death sequence called Dead.  We don't want it to loop, just like the Enemy's animation, and have it call a function when done.  Add the new animation sequence after the Jump sequence.</p>
<pre class="brush: csharp;">
            anim = new Animation();
            anim.LoadAnimation(&quot;Dead&quot;, 0, new List&lt;int&gt;
			{
				13,
				14,
				15
			}, 6, false);
            anim.AnimationCallBack(DeadAnimEnd);
            SpriteAnimations.Add(&quot;Dead&quot;, anim);
</pre>
<p>The Player Class's Reset function needs to reset our new property we added, so set it back to false.  Our Reset should look like the following:</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
		/// Resets the player to life.
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;_position&quot;&gt;The position to come to life at.&lt;/param&gt;
		public void Reset(Vector2 _position)
		{
			Position = _position;
			Velocity = Vector2.Zero;
			isAlive = true;
		    isCompletelyDead = false;
			SpriteAnimations[currentAnim].Stop();
			currentAnim = &quot;Idle&quot;;
			SpriteAnimations[currentAnim].ResetPlay();
		}
</pre>
<p>We need to make sure to only handle input when our hero is alive, so we need to modify the Update function to only call the GetInput function when the hero is alive.  The updated Update function should look similar to this:</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
		/// Handles input, performs physics, and animates the player sprite.
		/// &lt;/summary&gt;
		public void Update(GameTime _gameTime)
		{
            if (isAlive)
            {
                GetInput();
            }
		    ApplyPhysics(_gameTime);

			SpriteAnimations[currentAnim].Update(_gameTime);

			// Clear input.
			movement = 0.0f;
			isJumping = false;
		}
</pre>
<p>Now to handle our hero's death, we need to implement the Dead animation's callback and also create a function to get called if our hero runs into the MuffinMan.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when the player has been killed.
        /// &lt;/summary&gt;
        public void OnKilled()
        {
            isAlive = false;
            SpriteAnimations[currentAnim].Stop();
            currentAnim = &quot;Dead&quot;;
            SpriteAnimations[currentAnim].ResetPlay();

        }

        /// &lt;summary&gt;
        /// Called when the player has been killed.
        /// &lt;/summary&gt;
        public void DeadAnimEnd()
        {
            isCompletelyDead = true;
        }
</pre>
<p>That should be all for the player.  There is just a few things left to do.  We need to tell the Level to load up an enemy, and implement the collision detections.  Let's load up the Level1.txt file and make some spawn points for the MuffinMan.  We are going to use the letter 'e' for the MuffinMan.</p>
<pre class="brush: plain;">
.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,.,.,e,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,r,b,g,o,y,.,.,.,.,.,.
.,b,.,e,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.
.,r,y,o,G,B,R,.,.,.,.,.,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,O,Y,R,.,.,.,.,.,.,.,.
.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.
.,.,.,.,R,B,G,.,.,.,g,.,.,.,B,G,O,.,.,.
.,+,.,.,.,.,.,.,.,.,b,.,.,.,.,.,.,.,e,.
r,r,b,b,g,g,o,o,y,y,r,b,g,o,y,r,b,g,o,y
</pre>
<p>If we try to run this right now, our Level will complain that it doesn't know what to do with the value of 'e'.  Let's load up the Level class and make it aware of our new friend here.  First off, let's add two lists of enemies one for active, and another for removing from active.</p>
<pre class="brush: csharp;">
        private List&lt;Enemy&gt; enemies = new List&lt;Enemy&gt;();
        private List&lt;Enemy&gt; deadEnemies = new List&lt;Enemy&gt;();
</pre>
<p>In the LoadTile function, we need to add a case for 'e', and have it load up an Enemy.  So add this case to the switch.</p>
<pre class="brush: csharp;">
	// enemies spawns
	case 'e':
		return LoadEnemyTile(_x, _y, &quot;e&quot;);
</pre>
<p>Now with that added, we need to implement this new function.  It creates an enemy, adds it to the enemy list, and creates a blank tile on the map.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Instantiates an enemy and puts him in the level.
        /// &lt;/summary&gt;
        private Tile LoadEnemyTile(int _x, int _y, string _enemy)
        {
            Vector2 position = new Vector2((_x * 64) + 48, (_y * 64) + 20);
            enemies.Add(new Enemy(this, position, _enemy));

            return new Tile(String.Empty, 0, TileCollision.Passable);
        }
</pre>
<p>In the Update function, we want to check if we need to respawn our hero, and also we need to update our Enemies.  The updated Update function should look something like this:</p>
<pre class="brush: csharp;">
		/// &lt;summary&gt;
		/// Updates all objects in the world, performs collision between them,
		/// and handles the time limit with scoring.
		/// &lt;/summary&gt;
		public void Update(GameTime _gameTime)
		{
            Player.Update(_gameTime);

            if (Player.IsCompletelyDead)
                Player.Reset(start);

            UpdateEnemies(_gameTime);
		}
</pre>
<p>The new Update function has a new call in it we need to implement.  Inside this new function, we are going to tell each enemy to update, and check if he has been squished by our hero, or has achieved victory in killing our hero.  If there are any enemies that have finished thier death animation, we want to remove them from the main update list.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Animates each enemy and allow them to kill the player.
        /// &lt;/summary&gt;
        private void UpdateEnemies(GameTime _gameTime)
        {
            foreach (Enemy enemy in enemies)
            {
                enemy.Update(_gameTime);

                if (player.IsAlive &amp;&amp; enemy.IsAlive)
                {

                    // Touching an enemy instantly kills the player
                    if (enemy.BoundingRectangle.Intersects(Player.BoundingRectangle))
                    {
                        if (enemy.BoundingRectangle.Y &gt; Player.BoundingRectangle.Y)
                        {
                            OnEnemyKilled(enemy);
                        }
                        else
                        {
                            OnPlayerKilled();
                        }
                    }
                }
                else
                {
                    if(enemy.IsCompletelyDead)
                        deadEnemies.Add(enemy);
                }
            }

            if (deadEnemies.Count &gt; 0)
            {
                foreach (Enemy deadEnemy in deadEnemies)
                {
                    enemies.Remove(deadEnemy);
                }
                deadEnemies.Clear();
            }
        }
</pre>
<p>We are almost done here, we now need to implent the new functions that we are calling in UpdateEnemies, namely OnEnemyKilled and OnPlayerKilled.</p>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when the player is killed.
        /// &lt;/summary&gt;
        private void OnPlayerKilled()
        {
            Player.OnKilled();
        }

        /// &lt;summary&gt;
        /// Called when an enemy is killed.
        /// &lt;/summary&gt;
        private void OnEnemyKilled(Enemy _enemy)
        {
            _enemy.OnKilled();
        }
</pre>
<p>The last thing to do is tell our active enemies to draw themselves.  To do this, we need to modify the Draw function and call Draw for each enemy in the list.</p>
<pre class="brush: csharp;">
		public void Draw(GameTime _gameTime, SpriteBatch _spriteBatch)
		{
			DrawTiles(_spriteBatch);
            player.Draw(_gameTime, _spriteBatch);

            foreach (Enemy enemy in enemies)
                enemy.Draw(_gameTime, _spriteBatch);
		}
</pre>
<p>That should do it.  Our hero now has some Muffin butt to kick!  Build the project and run it.  Our hero should now be able to jump on top of the MuffinMan to squish him, or die running into him.</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP4_FinalImage.png"><img src="http://www.sgtconker.com/wp-content/uploads/2010/09/ICHP4_FinalImage-300x175.png" alt="I Can Has Platformer Part 4 Final Image" title="I Can Has Platformer Part 4 Final Image" width="300" height="175" class="aligncenter size-medium wp-image-1353" /></a></p>
<p>In the next article, we are going to add some collectibles that our hero will try to collect.  To get a hold of the project as it should be by the end of this part, <a href='http://www.sgtconker.com/wp-content/uploads/2010/09/ScribblePlatformer_Part4.zip'>click here</a>.</p>
<p>Stay tuned for the 5th part of the "I Can Has Platformer" series...</p>
<p><a href="http://www.sgtconker.com/2010/01/article-i-can-has-platformer-part-1/">Part 1</a></p>
<p><a href="http://www.sgtconker.com/2010/02/article-i-can-has-platformer-part-2/">Part 2</a></p>
<p><a href="http://www.sgtconker.com/2010/03/article-i-can-has-platformer-part-3/">Part 3</a></p>
<p><a href="http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-5/">Part 5</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-i-can-has-platformer-part-4/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Article: Simple 3D Camera in XNA</title>
		<link>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/</link>
		<comments>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 09:30:13 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1674</guid>
		<description><![CDATA[by Pete Street
How do I make a 3D camera?
This is the most common question I hear from people starting out with 3D game development.
There are many different types of possible cameras and various ways to achieve each of them.  The amount of unique camera samples available online, while some are more complicated than others, [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Pete Street</h4>
<p><strong>How do I make a 3D camera?</strong></p>
<p>This is the most common question I hear from people starting out with 3D game development.<br />
There are many different types of possible cameras and various ways to achieve each of them.  The amount of unique camera samples available online, while some are more complicated than others, can be daunting to those just beginning with 3D games.</p>
<p>Additionally, it’s frustrating and nearly impossible to combine two different samples without doing some serious hacking.<br />
My goal for this tutorial is to remove that frustration from 3D-beginners by providing a back-to-basics approach to three of the most common types of cameras used in games:</p>
<ul>
<li>a free camera</li>
<li>a chase camera</li>
<li>a orbit camera</li>
</ul>
<p><span id="more-1674"></span></p>
<p>The free camera will be able to yaw, pitch, and roll, and move in any direction.</p>
<p>The chase camera follows an object at a specified distance while also allowing for limited rolling and panning.</p>
<p>Finally, the orbit camera follows an object, can rotate any amount around it, and allows for limited rolling.</p>
<p>All three of these cameras are independent of one another and no other code relies on them.  This way, it’s easy to add your own cameras later or modify one of mine without worrying about it changing something else.<br />
The focus for this tutorial will be on simplicity and getting your camera running with as little code as possible.<br />
Interspersed with the code examples, I’ll do my best to thoroughly explain what is going on – however, feel free to skip right to the example at any time.<br />
If you already have a decent understanding of cameras or need help on something specific, the code is structured such that, once the controls are altered to fit your needs, you should be able to plug it right into your existing game.</p>
<p>This tutorial assumes a basic understanding of C#, XNA, vector math, and world matrices.  Nothing taught here is very complicated or math-heavy, but having an idea of how these work ahead of time will help.</p>
<p><strong>On to the Game!</strong></p>
<p>We’ll begin by starting a new XNA game project in Visual C#.  I’ve named my project “SimpleCamerasTutorial,” but you may name yours whatever you wish.<br />
Once your project is created, add the two .fbx models that I’ve included, “ConeModel” and “CubeModel,” to the Content folder.</p>
<p>These models are for demonstration purposes only, as you’ll probably want to use much better-looking art assets in your actual game.</p>
<p>Now that we have everything in the project up and running, it’s time to begin coding.</p>
<p><strong>The Basic Camera</strong></p>
<p>The first thing to do is to add a Camera class.  Right-click on your project and click Add ? Class, and name it “Camera.cs.”  Then add the following Using statements to the top of the class:</p>
<pre class="brush: csharp;">
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
</pre>
<p>Now we’ll begin to add the class-level variables to Camera.cs.  Type in the following fields:</p>
<pre class="brush: csharp;">
private Vector3 position;
private Vector3 target;
public Matrix viewMatrix, projectionMatrix;
</pre>
<p>These are the four variables that are absolutely necessary to a 3D camera.  Position is the 3D coordinate of the camera, and target is the 3D coordinate of where the camera is looking at.</p>
<p>The viewMatrix is the “eye” in 3D space, and it takes in the position, target, and an Up vector to determine the camera’s position, where it’s looking, and which way is up.</p>
<p>The up vector will become important once we implement roll in the camera.</p>
<p>Finally, the projectionMatrix determines the camera’s properties like field-of-view, aspect ratio, and what distance in front of the camera to draw.</p>
<p>In essence, the projection matrix takes the 3D data from the view matrix and transforms (or projects) it onto the 2D screen.<br />
The View Matrix will need to be updated any time we change either the position, target, or up vector, but the Projection Matrix only needs to be defined once.</p>
<p>Next, add the constructor to Camera.cs:</p>
<pre class="brush: csharp;">
public Camera()
{
    ResetCamera();
}
</pre>
<p>We’ll use the ResetCamera() method to define the initial values for the camera.  Here’s ResetCamera():</p>
<pre class="brush: csharp;">
public void ResetCamera()
{
    position = new Vector3(0, 0, 50);
    target = new Vector3();

    viewMatrix = Matrix.Identity;
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 16 / 9, .5f, 500f);
}
</pre>
<p>As you can see, the default values are set for the position, target, view matrix, and projection matrix.<br />
We’ve set the position to 50 units in front of the origin, initialized the view matrix to a standard identity matrix, and set the projection matrix to standard values.<br />
The first parameter in the projection matrix is field-of-view, which is usually at 45 degrees.  Second is the aspect ratio, set to the 16:9 standard.<br />
The last two values in the projection matrix are the near plane and far plane, which are distances in front of the camera.<br />
The camera will only draw something if it is within these two boundaries.  The target vector isn’t initialized to any values yet, because it will always depend on what type of camera you are using.</p>
<p>Next we’ll add an Update () method which will be called every frame and a private method called UpdateViewMatrix() to re-calculate the view matrix, which will be called from Update():</p>
<pre class="brush: csharp;">
public void Update()
{
    UpdateViewMatrix();
}
private void UpdateViewMatrix()
{
    viewMatrix = Matrix.CreateLookAt(position, target, Vector3.Up);
}
</pre>
<p>UpdateViewMatrix() calculates a view matrix at the camera’s position, looking at the target, and with the standard up vector Vector3.Up using the Matrix.CreateLookAt() function.<br />
At the moment, the camera doesn’t move and its target and up vectors are fixed.  We’re starting out with the most basic form of a view matrix to make sure that it draws properly.<br />
Later, this this code will be used as a base to add functionality for all of our cameras.</p>
<p><strong>The Basic Game</strong></p>
<p>That’s all we need for a basic, stationary camera.  Now let’s move over to the Game1.cs class to make a sample to use the camera.  Add the following variables to the top of Game1.cs:</p>
<pre class="brush: csharp;">
Camera camera = new Camera();

Matrix cubeWorld;
Matrix coneWorld;

Model cubeModel;
Model coneModel;
</pre>
<p>In Initialize(), set both of the world matrices to their identities:</p>
<pre class="brush: csharp;">
protected override void Initialize()
{
    cubeWorld = Matrix.Identity;
    coneWorld = Matrix.Identity;

    base.Initialize();
}
</pre>
<p>Then in the LoadContent() method, load both of the models:</p>
<pre class="brush: csharp;">
protected override void LoadContent()
{
    cubeModel = Content.Load&lt;Model&gt;(&quot;CubeModel&quot;);
    coneModel = Content.Load&lt;Model&gt;(&quot;ConeModel&quot;);
}
</pre>
<p>In the Update() method, we’ll be updating the camera, and thus the camera’s view matrix:</p>
<pre class="brush: csharp;">
protected override void Update(GameTime gameTime)
{
    camera.Update();
}
</pre>
<p>Finally, let’s draw both of the models using a private method named DrawModel(), and call that method in Draw():</p>
<pre class="brush: csharp;">
protected override void Draw(GameTime gameTime)
{
    //Draws both models
    DrawModel(cubeModel, cubeWorld);
    DrawModel(coneModel, coneWorld);
}

private void DrawModel(Model model, Matrix worldMatrix)
{
    Matrix[] modelTransforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(modelTransforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = modelTransforms[mesh.ParentBone.Index] * worldMatrix;
            effect.View = camera.viewMatrix;
            effect.Projection = camera.projectionMatrix;
        }
        mesh.Draw();
    }
}
</pre>
<p>The DrawModel() method takes in a model and its world matrix.  If the model has multiple bones or many complex parts, this method then breaks them down to modelMeshes in order to be drawn with an effect.  BasicEffect draws the scene here, but if you have a custom effect then feel free to use that instead.  We have enabled the default lighting inside BasicEffect so there is shading on the model and not just an ambient light.  The effect takes the world matrix of the model, and then the camera’s view and projection matrices.  At this point, both the cone and the cube model should be set up and displayed correctly using the view and projection matrices from the camera.  Press ‘F5’ to ensure that everything is working properly – you should see the front face of the cube with a cone sticking out of the top.</p>
<p>If everything looks correct, we can move on and make the cube a little more interesting with movement and rotation.</p>
<p><strong>Finishing the Game Sample</strong></p>
<p>We’ll now finish off the game sample to go along with the Camera class by adding rotation and movement to the cube.  The cone will remain at the origin and serve as a point of reference, so we won’t need any fancy environments in order to know if the cube is moving.  We already have the cube’s world matrix set up, and all we have to do is change it in Update().</p>
<p>Type the following code in the Update() method of Game1.cs:</p>
<pre class="brush: csharp;">
protected override void Update(GameTime gameTime)
{
	KeyboardState keyBoardState = Keyboard.GetState();

	//Rotate Cube along its Up Vector
	if (keyBoardState.IsKeyDown(Keys.X))
	{
		cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, .02f) * cubeWorld;
	}
	if (keyBoardState.IsKeyDown(Keys.Z))
	{
		cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, -.02f) * cubeWorld;
	}

	//Move Cube Forward, Back, Left, and Right
	if (keyBoardState.IsKeyDown(Keys.Up))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Forward);
	}
	if (keyBoardState.IsKeyDown(Keys.Down))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Backward);
	}
	if (keyBoardState.IsKeyDown(Keys.Left))
	{
		cubeWorld *= Matrix.CreateTranslation(-cubeWorld.Right);
	}
	if (keyBoardState.IsKeyDown(Keys.Right))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Right);
	}
}
</pre>
<p>First, we use the ‘Z’ and ‘X’ keys to call Matrix.CreateFromAxisAngle().  This function rotates the cube along the standard up vector by .02 radians every frame.  Then we move the cube using the arrow keys.  Matrix.CreateTranslation() translates a world matrix by a vector.  Instead of using standard vectors like Vector3.Forward, the vectors are taken directly from the cube’s world matrix.  This way if we rotated the cube, all of its vectors rotated with it, and the cube moves whatever direction it’s facing rather than straight forward, back, left, and right.  Press ‘F5’ again, and you should be able to rotate the cube and move it around.</p>
<p><strong>The Free Camera</strong></p>
<p>Now that we’ve finished with the basic game sample, we can work on the camera’s code, beginning with a 6-degrees-of-freedom camera.  In Camera.cs, add the following variables and initialize them in ResetCamera():</p>
<pre class="brush: csharp;">
private float yaw, pitch, roll;
private float speed;
private Matrix cameraRotation;

public void ResetCamera()
{
    yaw = 0.0f;
    pitch = 0.0f;
    roll = 0.0f;

    speed = .3f;

	cameraRotation = Matrix.Identity;
}
</pre>
<p>cameraRotation is the matrix we’ll be using to rotate the camera.  Yaw, pitch, and roll are angles that will be passed in to cameraRotation, and speed is how fast the camera will move.  Next, add a private method named HandleInput(), and call it in the Update() method:</p>
<pre class="brush: csharp;">
public void Update()
{
    HandleInput();
	UpdateViewMatrix();
}

private void HandleInput()
{
	KeyboardState keyboardState = Keyboard.GetState();

	if (keyboardState.IsKeyDown(Keys.J))
	{
		yaw += .02f;
	}
	if (keyboardState.IsKeyDown(Keys.L))
	{
		yaw += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.I))
	{
		pitch += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.K))
	{
		pitch += .02f;
	}
	if (keyboardState.IsKeyDown(Keys.U))
	{
		roll += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.O))
	{
		roll += .02f;
	}

	if (keyboardState.IsKeyDown(Keys.W))
	{
		MoveCamera(cameraRotation.Forward);
	}
	if (keyboardState.IsKeyDown(Keys.S))
	{
		MoveCamera(-cameraRotation.Forward);
	}
	if (keyboardState.IsKeyDown(Keys.A))
	{
		MoveCamera(-cameraRotation.Right);
	}
	if (keyboardState.IsKeyDown(Keys.D))
	{
		MoveCamera(cameraRotation.Right);
	}
	if (keyboardState.IsKeyDown(Keys.E))
	{
		MoveCamera(cameraRotation.Up);
	}
	if (keyboardState.IsKeyDown(Keys.Q))
	{
		MoveCamera(-cameraRotation.Up);
	}
}
</pre>
<p>Finally, we put in another private method called MoveCamera():</p>
<pre class="brush: csharp;">
private void MoveCamera(Vector3 addedVector)
{
	position += speed * addedVector;
}
</pre>
<p>HandleInput() will take care of both the camera’s rotation and movement based on manual keyboard input (remember, this is just a sample, so you’re free to change the controls to whatever you like).  Currently, the camera’s yaw is controlled by ‘J’ and ‘L,’ pitch is controlled by ‘I’ and ‘K,’ and roll is<br />
controlled by ‘U’ and ‘O.’  Similarly, the camera’s movement is mapped to ‘E’ and ‘Q’ moving up and down, ‘W’ and ‘S’ moving forward and back, and ‘D’ and ‘A’ moving left and right.</p>
<p>The MoveCamera() method alters the camera’s position in any direction at the camera’s speed.  We use vectors from the rotation matrix instead of standard vectors like Vector3.Forward so if the camera is rotated at all, it will move in the direction that it’s facing.  If you run the project right now, you should be able to move the camera around using the WASD + EQ keys, but you won’t be able to rotate the camera and it will always look at the same point.  This is because cameraRotation isn’t affected by the yaw, pitch, and roll angles yet.  To fix that, add the following code to the UpdateViewMatrix() method before you calculate the view matrix:</p>
<pre class="brush: csharp;">
cameraRotation.Forward.Normalize();
cameraRotation.Up.Normalize();
cameraRotation.Right.Normalize();

cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Right, pitch);
cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Up, yaw);
cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

yaw = 0.0f;
pitch = 0.0f;
roll = 0.0f;

target = position + cameraRotation.Forward;

viewMatrix = Matrix.CreateLookAt(position, target, cameraRotation.Up);
</pre>
<p>I make it a habit to normalize all the camera vectors that I’ll be using, and it’s really just a safeguard in case I accidentally edited it elsewhere.  The first three lines of code normalize three of cameraRotation’s vectors, as those are the vectors that the camera will rotate around.  The next three lines multiply cameraRotation by the Matrix.CreateFromAxisAngle() function, which rotates the matrix around any vector by a certain angle.  We rotate the matrix around its own vectors so that it works properly no matter how it’s rotated already.  After the matrix is rotated, the yaw, pitch, and roll values are set back to zero.  Finally, the target is changed to accommodate the rotation matrix.  It is set at the camera’s position, and then cameraRotation’s forward vector is added to it.  This ensures that the camera is always looking in the direction of the forward vector, no matter how it’s rotated.  Finally, we calculate the view matrix.  The only change we made in this line is the last parameter – now the up vector is based on how the camera is rotated and not off the standard Vector3.Up.  The view matrix needs an up vector to fully orient itself in 3D space, otherwise, the camera would have no way of knowing whether or not it’s upside-down.</p>
<p>Once this code is added, press ‘F5’ to run the program.  Hooray!  You should now have a free camera capable of moving in any direction, rotating in any direction, and independent of the cube!</p>
<p><strong>Expanding the Camera’s Horizons</strong></p>
<p>Now that we have a working free camera and the base of the Camera class, let’s make the class expandable so we can easily add new cameras in the future.  Later, it will be simple to add the chase and orbit cameras, and any other cameras that you might come up with.  To have multiple cameras within the same class, we’ll need an enum to keep track of which mode the camera is currently in.  Add this code to the top of the Camera class:</p>
<pre class="brush: csharp;">
public enum CameraMode
{
	free = 0,
	chase = 1,
	orbit = 2
}
public CameraMode currentCameraMode = CameraMode.free;
</pre>
<p>The currentCameraMode will keep track of which camera mode is active.  Right now, we only have the code for a free camera, so that is what we’ll set it to.</p>
<p>We also need to change the camera movement code in the HandleInput() method to make sure that it’s only run if the free camera is the current camera mode.  The reason for this is the chase and orbit cameras’ positions don’t have their own movement code, and instead use the movement of an outside object.  In HandleInput(), simply check if the free camera is currently active around the camera’s movement code:</p>
<pre class="brush: csharp;">
private void HandleInput()
{
	//Camera’s Rotation code

	if (currentCameraMode == CameraMode.free)
	{
		//Camera’s Movement code.
	}
}
</pre>
<p>Then in UpdateViewMatrix(), place the code you just added for the free camera inside this switch block, keeping the view matrix calculation outside of it:</p>
<pre class="brush: csharp;">
switch (currentCameraMode)
{
	case CameraMode.free:

		//Free-camera code goes here.

		break;

	case CameraMode.chase:

		break;

	case CameraMode.orbit:

		break;
}

viewMatrix = Matrix.CreateLookAt(position, target, cameraRotation.Up);
</pre>
<p>The goal is to keep all of the code simple, concise, and reusable, and as such the view matrix calculation should never change.  Only the parameters it takes in should change.</p>
<p><strong>The Chase Camera</strong></p>
<p>Now it’s time to add the chase camera’s code.  Add the following variables to the top of the Camera class and initialize them in the ResetCamera() method:</p>
<pre class="brush: csharp;">
private Vector3 desiredPosition;
private Vector3 desiredTarget;
private Vector3 offsetDistance;

public void ResetCamera()
{
	desiredPosition = position;
	desiredTarget = target;

	offsetDistance = new Vector3(0, 0, 50);
}
</pre>
<p>The desired position and target will be used in conjunction with the actual position and target so we can get smooth transitions.  A value that’s “desired” is what the actual values will constantly move to, but they don’t necessarily need to be equal to the desired value.  The offset distance is how far displaced the camera is from the target.  For both the chase and orbit cameras, the target won’t be defined by a vector in the rotation matrix, but rather by an outside object’s position – in this case, the target will be defined by the position of the cube.  We’re going to add a matrix parameter to the Camera’s Update() method, and pass that matrix into the UpdateViewMatrix() method.  In the game, we’ll pass the cube’s world matrix into camera.Update() in order to set that matrix as the one to chase.  First change the Camera’s Update() and UpdateViewMatrix() methods like so:</p>
<pre class="brush: csharp;">
public void Update(Matrix chasedObjectsWorld)
{
	UpdateViewMatrix(chasedObjectsWorld);
}

private void UpdateViewMatrix(Matrix chasedObjectsWorld)
{
}
</pre>
<p>Then in Game1.cs, change camera.Update() to camera.Update(cubeWorld).  Now we have a target to chase that isn’t dependent upon the camera’s code.  Finally, for the actual chase camera’s code, add the following to the chase camera section of the switch block inside UpdateViewMatrix():</p>
<pre class="brush: csharp;">
case CameraMode.chase:

	cameraRotation.Forward.Normalize();
	chasedObjectsWorld.Right.Normalize();
	chasedObjectsWorld.Up.Normalize();

	cameraRotation = Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

	desiredTarget = chasedObjectsWorld.Translation;
	target = desiredTarget;
	target.X += yaw;
	target.Y += pitch;

	desiredPosition = Vector3.Transform(offsetDistance, chasedObjectsWorld);
	position = Vector3.SmoothStep(position, desiredPosition, .15f);

	yaw = MathHelper.SmoothStep(yaw, 0f, .1f);
	pitch = MathHelper.SmoothStep(pitch, 0f, .1f);
	roll = MathHelper.SmoothStep(roll, 0f, .2f);

	break;
</pre>
<p>In this chase camera, I’ve allowed for a limited amount of yaw, pitch, and roll.  This is to ensure that the camera always follows the target, but it will still have some degree of freedom on where to look.  The first thing we do is normalize the rotation matrix’s forward vector because we’ll be using that vector to roll around.  Notice that we don’t alter the rotation matrix with yaw and pitch like we did in the free camera.  That’s because this camera’s yaw and pitch will depend on the target (not the rotation matrix), and that’s where desiredTarget comes in.  Each frame, desiredTarget will be set to the position of whatever object we’re chasing (in this case the cube).  We then set the actual target equal to the desiredTarget, and we can change the target’s X and Y coordinates at will.  The yaw and pitch angles work well for this, as we can alter the target’s X to look a little left and right, and alter the target’s Y to look a little up and down.</p>
<p>Next we set the camera’s desiredPosition.  The desired position could simply be set by adding the offset distance to the target, but what if the object we’re chasing rotates?  Since we always want the camera positioned behind the object, desiredPosition needs to be transformed by the chased object’s world matrix.</p>
<p>Finally, we need to smooth the camera’s movement and transition the target vector back to the desired target.  This is done with the SmoothStep() functions, which take in the current value, a desired value, and the factor that the current value is changed by.  Using these methods, the position smoothly moves to desiredPosition, and the angles on which the camera rolls and pans on are constantly being moved back to zero.</p>
<p>At the top of Camera.cs, change currentCameraMode = CameraMode.free to currentCameraMode = CameraMode.chase.  Now that the camera is in chase mode, you can run the project to ensure the chase camera works properly.  You should be able to move and rotate the cube, and the camera should follow it smoothly.  You can also pan the camera up, down, left, and right using the IJKL keys.  In HandleInput(), you may want to increase the yaw and pitch values in order to make the camera panning more prominent, but you should be able to see the effect either way.</p>
<p>One fluke that you may notice after playing around with the chase camera is when you pan left or right and rotate the cube at the same time.  You’ll see that the cube seems to be moving back and forth across your screen.  The reason this happens has to do with how we define the target.  Right now only the target’s X and Y coordinates are being edited, so it behaves much like a flat plane.  When the camera rotates to the side of that flat plane, all of the points will appear to be in the center of the screen.  As the camera rotates around it, the points in the plane will look like they’re inverted.  Depending on the game, this may be a rather serious problem.  Fortunately, it comes with a very simple solution, which is to multiply certain vectors in the chased object’s world matrix by the rotation angles so the target rotates with the cube.  In UpdateViewMatrix(), replace these two lines:</p>
<pre class="brush: csharp;">
target.X += yaw;
target.Y += pitch;
</pre>
<p>…with these lines:</p>
<pre class="brush: csharp;">
target += chasedObjectsWorld.Right * yaw;
target += chasedObjectsWorld.Up * pitch;
</pre>
<p>Run the project again.  You should be able to pan to the side and rotate the cube at the same time, and the target will rotate along with it.</p>
<p><strong>The Orbit Camera</strong></p>
<p>It’s now time to put the orbit camera in place.  This will be especially easy to do since we already have all the necessary base code.  We don’t need any more variables, but change the currentCameraMode at the top of the class to CameraMode.orbit.  In UpdateViewMatrix(), inside the orbit section of the switch block, add the following code:</p>
<pre class="brush: csharp;">
case CameraMode.orbit:

cameraRotation.Forward.Normalize();

cameraRotation = Matrix.CreateRotationX(pitch) * Matrix.CreateRotationY(yaw) * Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

desiredPosition = Vector3.Transform(offsetDistance, cameraRotation);
desiredPosition += chasedObjectsWorld.Translation;
position = desiredPosition;

target = chasedObjectsWorld.Translation;

roll = MathHelper.SmoothStep(roll, 0f, .2f);

break;
</pre>
<p>We start out by normalizing the rotation matrix’s forward vector, and then cameraRotation is calculated.  The camera rolls using the same code that we’ve done in the past, rotating the matrix over its forward vector.  What has changed is how the matrix takes in the yaw and pitch angles.  Instead of yawing and pitching over cameraRotation’s vectors, we yaw and pitch over the world axes.  By rotating over world axes instead of local axes, the orbiting effect is achieved.  Next we transform the camera’s position by the offset distance and rotation matrix, much like what happened in the chase camera.  At this point, the camera will orbit around the origin, but it won’t follow the cube if it moves.  This is why the cube’s position is added to desiredPosition, so it will follow the cube and orbit around it no matter where it is.  Since the target will always stay at the center of the cube, it is set to the cube’s position.  Finally, the roll is smoothly brought back to zero.</p>
<p>Unlimited roll is not allowed in this sample for two reasons:  1) it’s disorienting and doesn’t look good, and 2) it can cause some stability issues.  Because of floating-point precision, more roll than what we have right now will cause the camera to lose control and the game will become unplayable.  However, as long as the amount of roll is contained, the camera is perfectly stable.</p>
<p>That’s all you need for the orbit camera!  Run the game now and you should be able to move the cube and rotate around it.  Something you may notice about the orbit camera’s code is that this line:</p>
<pre class="brush: csharp;">
position = desiredPosition;
</pre>
<p>…seems redundant.  The reason I don’t simply transform the position is because you may want to add a SmoothStep() function to it like I did in the chase camera.  I opted to leave it out of this sample, but you’re free to add it to your own code.</p>
<p><strong>Touching Up</strong></p>
<p>Congratulations!  You made it through all the basic camera examples with (hopefully) little heartache.  All there is left is to add a simple method to allow for easy switching between cameras.  Add a public method named SwitchCameraMode() to Camera.cs:</p>
<pre class="brush: csharp;">
public void SwitchCameraMode()
{
	ResetCamera();

	currentCameraMode++;

	if ((int)currentCameraMode &gt; 2)
	{
		currentCameraMode = 0;
	}
}
</pre>
<p>It’s a pretty simple method that loops through the camera modes.  First, all of the camera’s default values are reset, then it cycles through the entire camera modes list.  If you happen to add more camera modes in the future, just change the ‘2’ in this line:</p>
<pre class="brush: csharp;">
if ((int)currentCameraMode &gt; 2)
</pre>
<p>…to the highest number in the enum at the top of the class.  This method will be called in the game class, so head over to Game1.cs and type this line in the top of the class:</p>
<pre class="brush: csharp;">
KeyboardState previousKeyBoardState = Keyboard.GetState();
</pre>
<p>Now simply add the following code to Update():</p>
<pre class="brush: csharp;">
protected override void Update(GameTime gameTime)
{
	if (keyBoardState.IsKeyDown(Keys.Space) &amp;&amp; previousKeyBoardState.IsKeyUp(Keys.Space))
	{
		camera.SwitchCameraMode();
	}

	//This line should be at the bottom of Update()
	//after all of the input code.
	previousKeyBoardState = keyBoardState;

}
</pre>
<p>That’s it!  You now have a simple, working sample with three distinct camera modes which you can change on-the-fly.</p>
<p><strong>The Next Step</strong></p>
<p>This tutorial contains simple examples of what you can do with 3D cameras.  Everything is reliable and designed to be easy to use, but it’s also somewhat primitive.  Using these examples as a launch pad, you can improve the cameras by adding more sophisticated functions to them.  For instance, most chase camera samples (including the one in XNA’s education catalog) use a physics-based spring system for smoothly updating the position.  We faked a spring by using the SmoothStep() functions, but if you need something more advanced, you might consider making one yourself.</p>
<p>You may also want to make different types of cameras.  These three examples are among the most common in games and can be adapted to fill many needs, but if your needs aren’t met, then you have the base code to easily make a different camera.</p>
<p>If you want to save fiddling with your camera for later and want to get started with the game right now, this sample is easy to integrate with your game.  All you have to do is add the camera class to your own game project, and initiate and update the camera in the game as I’ve shown above.  Right out of the box, you’ll have three different cameras to use for developing your game.</p>
<p><strong>Closing Words</strong></p>
<p>Throughout this tutorial, I’ve made an effort to keep everything simple and to explain all of the code in detail.  Again, my goal is to give people starting out with 3D an easy-to-understand introduction into 3D cameras.  This will hopefully curb some of the frustration that comes out of learning something new, and will allow you to focus on the rest of your game more quickly and easily.  Thanks for reading, and keep making games that are absolutely fine!</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/SimpleCamerasTutorial.zip">Download Sample Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7, XNA and XAP Size</title>
		<link>http://www.sgtconker.com/2010/09/wp7-xna-and-xap-size/</link>
		<comments>http://www.sgtconker.com/2010/09/wp7-xna-and-xap-size/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 20:54:04 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[Audio]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Bob Taco Ind]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[size]]></category>
		<category><![CDATA[XAP]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1672</guid>
		<description><![CDATA[Yeah, whenever Michael B. McLaughlin says "quick post", you need to watch out.... In his latest quick post, Michael talks about the size of various content that gets packed into an XAP file, and gives some suggestion on how to shrink the size of your XAP file. The whole post is here, for your reading [...]]]></description>
			<content:encoded><![CDATA[<p>Yeah, whenever Michael B. McLaughlin says "quick post", you need to watch out.... In his latest <a href="http://geekswithblogs.net/mikebmcl/archive/2010/09/02/wp7-xna-and-xap-size.aspx">quick post</a>, Michael talks about the size of various content that gets packed into an XAP file, and gives some suggestion on how to shrink the size of your XAP file. The whole post is <a href="http://geekswithblogs.net/mikebmcl/archive/2010/09/02/wp7-xna-and-xap-size.aspx">here</a>, for your reading pleasure.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/wp7-xna-and-xap-size/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Article: WCF on the Windows Phone 7–The How to Guide</title>
		<link>http://www.sgtconker.com/2010/09/article-wcf-on-the-windows-phone-7%e2%80%93the-how-to-guide/</link>
		<comments>http://www.sgtconker.com/2010/09/article-wcf-on-the-windows-phone-7%e2%80%93the-how-to-guide/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 20:31:09 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Article]]></category>
		<category><![CDATA[How To Guide]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Simon Jackson]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1665</guid>
		<description><![CDATA[by Simon Jackson
Well at the behest of Michael B McLaughlin (@MikeBMCL on Twitter), here's a run down of what you need to know to get WCF working on the Windows Phone 7, both for Silverlight and XNA.  This is just going to be a brief overview and the full detail will be included in the [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Simon Jackson</h4>
<p>Well at the behest of <a href="http://geekswithblogs.net/mikebmcl/Default.aspx" target="_blank">Michael B McLaughlin</a> (<a href="http://twitter.com/mikebmcl" target="_blank">@MikeBMCL</a> on Twitter), here's a run down of what you need to know to get WCF working on the Windows Phone 7, both for Silverlight and XNA.  This is just going to be a brief overview and the full detail will be included in the LeaderBoard sample for Silverlight and XNA coming soon.</p>
<p>Many thanks to <a href="http://twitter.com/mikebmcl" target="_blank">@MikeBMCL</a> pointing me to this <a href="http://geekswithblogs.net/Mathoms/archive/2010/06/17/using-web-services-from-an-xna-4.0-wp7-game.aspx" target="_blank">post by Michael Cummings</a> who details one approach to getting WCF working for XNA.  It does work, but it’s a long way round.  It did however point me in the right direction to solve the problem and now I’ve got WCF working the way I Like it.  As in Working.</p>
<h1><span id="more-1665"></span></h1>
<p>P.S. little or no sample code for now, this is a rush job after all!,  if you have questions please either comment or drop me a line and I'll  be happy to help.</p>
<p>P.P.S Sample code can be found on <a href="http://startrooper2dxna.codeplex.com/releases/view/51124" target="_blank">Codeplex here</a>,  I started to feel bad about not giving a sample so I knocked a rough  one up here.  It’s pointing to the test Dark Omen Games Leaderboard on  XNA-UK, so it should work fine (unless you are behind a proxy &gt;:) ).   When it’s working you should get output in the debug window stating  “Invalid Auth Credentials” back from the service.  that’s all (well I  did day it was rough).</p>
<h1>WCF - What you need to know</h1>
<p>First off in case you were not aware, WCF on the Windows Phone device is Asynchronous only, meaning you fire off a request and need to capture the response (usually by capturing the Completed event from the service) when it eventually gets back, for more detail check the <a href="http://msdn.microsoft.com/en-us/magazine/cc163537.aspx" target="_blank">MSDN article</a> here.  This is opposed to the traditional synchronous operations normally used (or not normally who knows), where the same channel you request the data it is received back through.</p>
<p>Now I'm not going to go in to the ins and out of how to write a WCF service and write WCF methods, <a href="http://blogs.msdn.com/b/rjacobs/" target="_blank">Rob Jacobs</a> does a far better job than I so ask him.</p>
<h1>WCF - The options</h1>
<p>So here's a breakdown of what you need to know and do:</p>
<p><strong><em>WCF service in a single Silverlight project</em></strong></p>
<p>This works straight out of the box, just add a service reference to your WCF service in the project, add in your asynch calls and delegate events and you are cooking.</p>
<p><strong><em> WCF service in a single XNA project</em></strong></p>
<p>The only way to do this is using <a href="http://geekswithblogs.net/Mathoms/archive/2010/06/17/using-web-services-from-an-xna-4.0-wp7-game.aspx" target="_blank">Mike Cummings method</a>.  Personally I’d use the last option below for XNA, but that’s just me. If it has to be one project then Mikes post is the way to go.</p>
<p><strong><em> A WCF Service Silverlight Library and a Silverlight project (in the Sample)</em></strong></p>
<p>A little more tricky here and you would think it would work straight out of the Box, but it doesn’t.  but fear not, getting it working is as easy as copying one file.  Because that’s all it involves.</p>
<p>Simply Add a Silverlight Library project to your Silverlight Phone project as normal.  Do your normal steps of adding your service reference and Asych calls plus delegates.  Build the project (which will show as successful <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  , misleading there).  Reference your library from your main project and call plus handle the return events in the way you wish (could use delegates or just expose the return values with a little handling).  now if you run the project now it will happily launch and then crash silently, your app none the wiser and no data will be returned.  If you look in the Debug view you should see some exceptions logged against “System.ServiceModel.dll”.</p>
<p>The crash is caused by WCF not knowing what the hell you are talking about because the “ServiceReferences.ClientConfig” is missing.  Except it’s not missing it’s there in my Silverlight Library.  (Thanks to Mike Cummings for that tip).  Fixing this is easy because it’s the MAIN project that is complaining about the config file being missing and not the library (this could be another bug but we can work around it for now), so the easy fix for now is this:</p>
<ul>
<li>Copy the “ServiceReferences.ClientConfig” file from your library project in to your main project.</li>
</ul>
<ul>
<li> The other thing you have to do is a little magic, change/set the build type of the config file to “Content” in the main project and set the “Copy to output folder” option to “Copy if newer” (these are in the properties for the file in VS)</li>
</ul>
<p>Fire it up and everything will work fine now.!!</p>
<p><strong>Remember though, if you regenerate your service or change it’s endpoint top copy this file over again or it won’t change.</strong></p>
<p><strong><em>A WCF Service Silverlight Library and an XNA project (In the Sample)</em></strong></p>
<p>Now this I feel is the better way to add Service references and WCF to your XNA project, main reason is because I can use the same WCF Silverlight library in both my projects so I only have to write the service code once (when you have decided how to handle the returning data).</p>
<p>This is now VERY easy with one exception.  Like above, you need to set/change the properties for the service configuration file, but this time you have to do it in the library itself (don’t worry this will still work for Silverlight projects that use the same library) and that’s it, you don’t even need to copy the configuration file over, it is all contained in the library.</p>
<p>How easy is that.  Well it would have been easier to know that weeks ago when I was banging my head against a paper mashie wall (because brinks are to hard) trying to get this working the first 17 times.</p>
<h1>WCF natively in XNA</h1>
<p>As for just using WCF natively in XNA or an XNA library, forget it.  At least for the BETA, it does not work.  Adding WCF services tries to create synchronous services (which is a No No) and causes all sorts of referencing errors.  Even with the tricks above, XNA cannot do it alone, it needs the support of Silverlight to either host or generate the service code.</p>
<p>Even when you force it to create Asynchronous proxy code, it still does it wrong.</p>
<p>Maybe this will change going forward (if it’s a bug) or they will remove service references all together (still a possibility) if WCF isn’t going to be natively supported in XNA.  Time will tell.</p>
<h1>Conclusion</h1>
<p>Right, now that I've distracted myself for long enough to write this post, I'm back to finishing up the leaderboard sample (thankfully back to being both XNA and Silverlight again now, thanks again Mike)</p>
<p>Somewhere in all this I need to finish my Launch title (if it ever gets finished at this rate), I must really stop looking into more shiny stuff, I am a real Magpie after all.</p>
<p>And just for that SPAM! - <a href="http://www.youtube.com/watch?v=g8huXkSaL7o">http://www.youtube.com/watch?v=g8huXkSaL7o</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-wcf-on-the-windows-phone-7%e2%80%93the-how-to-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article: Scripting on the Xbox 360, Windows Phone, and Beyond!</title>
		<link>http://www.sgtconker.com/2010/09/article-scripting-on-the-xbox-360-windows-phone-and-beyond/</link>
		<comments>http://www.sgtconker.com/2010/09/article-scripting-on-the-xbox-360-windows-phone-and-beyond/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 20:08:38 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Beyond!]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[UberGeekGames]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[Xbox 360]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1657</guid>
		<description><![CDATA[by UberGeekGames

Scripting. It’s a recurring theme on the XNA forums: “Can I use Lua?” “Can I script on the Xbox 360?” “Scripting FTW! No, scripting FTL!”. Do a quick search for “scripting” on the XNA forums and you’ll find many threads with the preceding themes. There’s a lot of information about scripting, and it usually [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.ubergeekgames.com/">UberGeekGames</a></h4>
<p style="text-align: center;"><img class="aligncenter" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/scripting.jpg" alt="Scripting" width="614" height="346" /></p>
<p>Scripting. It’s a recurring theme on the XNA forums: “Can I use Lua?” “Can I script on the Xbox 360?” “Scripting FTW! No, scripting FTL!”. Do a quick search for “scripting” on the XNA forums and you’ll find many threads with the preceding themes. There’s a lot of information about scripting, and it usually ends with “no, you can’t do scripting on the Xbox, and it’s probably not a good idea anyway”.<br />
In this tutorial, I’m going to show you what scripting is, a very useful type of scripting that I’ve been using more and more, and how you can make your own scripting system and use it effectively.<br />
<span id="more-1657"></span></p>
<h1>What is Scripting?</h1>
<p>First, let’s back up a little and define what scripting really is. New programmers sometimes have very misinformed ideas as to what scripting is, thinking it’s a magic way of being able to do lots of cool things without having to learn programming. <strong>Scripting is not a replacement for being able to write C#</strong>. In fact, you’ll need a pretty good grasp of lists, inheritance, interfaces, value types and string parsing in order to make your own scripting system and make it useful. That’s because your scripting language is only as powerful as you make it.</p>
<p>Once your scripting system is finished, it’s entirely possible for artists and other non-programmers to use it, depending on how you make it. With good documentation, simple commands, and dedication on the part of the script-writer, it’s entirely possible for non-programmers to make useful scripts for your game. This was my main goal when I created my scripting system – I needed non-programmers to be able to make changes to the script, without needing the entire solution and having to recompile the source code each time they made a change.</p>
<p>That leads us to the next big plus of scripting: you can make changes to the game without needing its source code, and without needing to recompile the project each time you change it. Depending on the size of your project, it can also make tweaking things much, much faster if it takes several minutes to rebuild.</p>
<p>Scripting does have it’s drawbacks. One, it’s more complicated to maintain since you need to add another layer of abstraction between your game and the scripting language. Two, this is likely to make it less efficient than straight C# code, especially in very high-frequency areas. However, I’ve been using scripting in BulletAsylum and it runs at 60FPS on the Xbox while using my scripting system to handle the spawn waves, so the performance hit shouldn’t deter you that much. <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
So, now that we have a firm grasp of the pros and cons of scripting, let’s make our own scripting system!</p>
<h1>The Game</h1>
<p>Load up the <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/XboxScriptingSampleGame.ZIP">sample program</a> and run it. It’s a bare bones, no frills twin stick shooter. It randomly spawns powerups and enemies, which if it were a real game, wouldn’t make for very interesting gameplay. Our scripting system will allow the designer to craft each level for the game, and determine when and where powerups and enemies appear.<br />
First off, we need to determine exactly what we need to expose in the script. For our game, we’ll be controlling the enemy spawn system. For larger games you will probably need more for things like powerups, NPCs, particles, and anything else you can think of.</p>
<p>A sample script will look like this:</p>
<pre class="brush: plain;">
wave 1:
spawn enemy ( 100, 200, White )
spawn enemy( 100, 400, Red )
End wave
Wave 2:
Loop(10)
{
        Spawn enemy(random(0, 50), random(50, 650), Blue)
}
Loop(20)
{
        Spawn enemy(random(1000, 1100), random(50,650), Red)
}
End wave
</pre>
<p>Keep in mind that this is just an example; in a real game you would probably need many more parameters and commands.</p>
<h1>Creating the Scripting Engine</h1>
<p><P><br />
At its core, the scripting system is just taking the raw text file, figuring out what command is on each line, and adding them to a list of command objects that will be executed later. Those commands will have names like Wave and SpawnEnemy, and have parameters such as position and velocity. We can even add modifiers like Random so we can add some pseudorandomness to the game, or Loop which will execute the same statement more than once.
</p>
<p>Let’s begin.<br />
Let’s define what the commands are first:</p>
<pre class="brush: plain;">
//interface that all commands use
interface IScriptCommand
{
    void Do(Wave wave);
}

//spawns a new enemy
struct ScriptCommand_SpawnEnemy : IScriptCommand
{
    //holds the position, velocity, and color
    private Vector2 pos, vel;
    private Color color;
    public ScriptCommand_SpawnEnemy(Vector2 position, Vector2 velocity, Color color)
    {
        this.pos = position;
        this.vel = velocity;
        this.color = color;
    }
    public new void Do(Wave wave)
    {
        //tells the Wave to spawn this enemy.
        wave.SpawnEnemy(pos, vel, color);
    }
}
</pre>
<p>Each script command is a struct that implements the IScriptCommand interface. They do little more than take the command’s parameters in their constructors, and executre the command in the Do method.<br />
You’ve probably noticed that we’re missing the Wave class. This is the class that holds each Wave. A Wave consists of a list of IScriptCommands, and the methods which the commands can call when they are executed (the SpawnEnemy class in the case of ScriptCommand_SpawnEnemy):</p>
<pre class="brush: plain;">
class Wave
{
    //list of commands in this wave
    List&lt;IScriptCommand&gt; commands = new List&lt;IScriptCommand&gt;();

    //adds a new command to the list
    public void AddCommand(IScriptCommand command)
    {
        commands.Add(command);
    }

    //hold on to a reference of the game so that we can interact with it's elements
    GameManager gameManager;

    //index of current command we're at
    int currentCommandIndex = 0;
    public void Reset()
    {
        currentCommandIndex = 0;
    }

    //executes the next command. Not literally, mind you. That would be... messy.
    public bool Run(GameManager theGameManager)
    {
        this.gameManager = theGameManager;

        //next command
        currentCommandIndex++;

        //if we're at the end of the line exit
        if (currentCommandIndex &gt; commands.Count - 1)
            return true;
        else
        {
            //otherwise run this command
            commands[currentCommandIndex].Do(this);
            return false;
        }
    }

    //spawns an enemy. all commands access the Wave class, so it acts as
    //an intermediary to the rest of the game. This is useful if you add things
    //like spawn timer modifiers.
    public void SpawnEnemy(Vector2 pos, Vector2 vel, Color color)
    {
        gameManager.enemyManager.Spawn(pos, vel, color);
    }
}
</pre>
<p>Most notable here is the reference to the Game Manager class. This is needed for most commands, as they usually interact with objects in the Game Manager (the EnemyManager in this case). So why not directly pass a reference of Game Manager to the script commands? Well, there’s no reason you couldn’t, but I chose to because A) it made more sense to me to add an abstraction layer so I’d never have to worry about some command doing something with the GameManager that I had forgotten about, and B) it keeps every part of the game that the script commands interact with in one place.</p>
<p>Lastly, we have the real meat of the program: the Script Manager. I’m not going to paste all of the code here because it’s 267 lines. <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I’ll briefly go over the important parts here. I highly encourage you to go through <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/XboxScriptingSampleGame_Finished.ZIP">the second (finished) project</a> in the download and look through its code.</p>
<pre class="brush: plain;">
//parses a command. This is the real meat of the script parsing engine.
private void ParseCommand(Wave wave, string line, string[] lines, int currentLine, out int linesToSkip)
{
    //make sure we're in lowercase
    line = line.ToLower();
    linesToSkip = 0;

    //this is where you would place your commands and parse them.
    if (line.Contains(&quot;spawnenemy&quot;))
    {
</pre>
<p>This is the most important function in the entire class. After the script is loaded from your hard drive (either from a physical location such as C:\Projects\script.txt or the game’s content folder), this method actually converts the script into commands that the game understands. In this example, let’s go over the spawnenemy command, as it’s a great template to start from and make your own commands.</p>
<pre class="brush: plain;">
//get the contents of the command
string parms = GetContents(&quot;(&quot;, &quot;)&quot;, line);
parms = ParseMath(parms);
string[] parmz = parms.Split(',');
</pre>
<p>This semi-cryptic bit of code uses some helper function to convert the command’s parameters into actual variables. Take the following example command:<br />
spawnEnemy (100, 200, White)<br />
parms would now contain “100, 200, white”. ParseMath() does nothing to it since there aren’t any special variables in it. After it’s split into a string array by its commas, parmz will now contain<br />
“100”<br />
“200”<br />
“white”</p>
<p>These can be quite easily parsed into actual integer values and a Color variable:</p>
<pre class="brush: plain;">
//xy coords are the first two
int x = Int32.Parse(parmz[0]);
int y = Int32.Parse(parmz[1]);
//color is the third
string colorStr = parmz[2];

//trim any useless whitespace
colorStr = colorStr.TrimStart(' ');

//sadly there's no easy way to get a color from text, so we'll parse it manually.
Color color = Color.White;
if (colorStr == &quot;red&quot;)
    color = Color.Red;
else if (colorStr == &quot;blue&quot;)
    color = Color.Blue;
else if (colorStr == &quot;cornflowerblue&quot;)
    color = Color.CornflowerBlue;
</pre>
<p>And we can now take those values and use them to create a ScriptCommand_SpawnEntity:</p>
<pre class="brush: plain;">
//add the command to the length
wave.AddCommand(new ScriptCommand_SpawnEnemy(new Vector2(x,y), vel, color));
</pre>
<p>Repeating the above for each type of command that you have in your scripting language, you’ll end up with a dictionary of Waves which each contain a list of commands to be executed. In this case, they’re commands for spawning enemies! Let’s update the code in GameManager so that we can see it in action:</p>
<pre class="brush: plain;">
//----------------------
//| Level spawn stuff! |
//----------------------
int Level = 1;
int TimeSinceSpawn = 0;

//update our spawning system
void UpdateSpawns()
{
    if (System.Environment.TickCount &gt;= TimeSinceSpawn + 1000)
    {
        TimeSinceSpawn = System.Environment.TickCount;

        //run the current wave
        bool finished = scriptManager.waveDict[Level].Run(this);

        //if the wave finished go to the next one
        if (finished)
        {
            //reset it for later use
            scriptManager.waveDict[Level].Reset();
            Level++;
            if (!scriptManager.waveDict.ContainsKey(Level))
            {
                Level = 1;
            }
        }
    }
}
</pre>
<h1>The End</h1>
<p>
Run the program and check out it’s output! (Note that you’ll have to use the second solution in the download, since some code was omitted from the script manager for brevity)
</p>
<p><img src="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/scripting.jpg" alt="Scripting" width="691" height="389" /></p>
<p>Okay, so it’s a bunch of blocks moving around. What makes this special? You created those blocks from a scripting language! Go ahead, open the script and change the positions, or the number of loops, or even the color, and see how it updates in game without ever touching a line of C# code.<br />
Now that you have the base system in place, it will be easy to expand this and add more commands for things like spawning powerups, triggering cinematics, or anything else your game can do that you want to expose in the scripting language! The sky is the limit.<br />
And best of all, this code will run on the Xbox 360 and WP7 (with some changes and upgrades to the latter to account for XNA 4.0, of course) because it doesn’t rely on reflection, interop, or any other such tomfoolery that scripting systems traditionally use.</p>
<p>Download code:<br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/XboxScriptingSampleGame.ZIP">XboxScriptingSampleGame.ZIP</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/scripting/XboxScriptingSampleGame_Finished.ZIP">XboxScriptingSampleGame_Finished.ZIP</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-scripting-on-the-xbox-360-windows-phone-and-beyond/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>XPF: A Layout Framework for XNA</title>
		<link>http://www.sgtconker.com/2010/08/xpf-a-layout-framework-for-xna/</link>
		<comments>http://www.sgtconker.com/2010/08/xpf-a-layout-framework-for-xna/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 14:29:40 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[XNA 4.0]]></category>
		<category><![CDATA[XPF]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2010/08/xpf-a-layout-framework-for-xna/</guid>
		<description><![CDATA[Right after Mr. Styrchak shared his work on a Sinner clone now comes the word that the brave people at Red Badger just released a first build of BronzeglowXPF – I even named it XPF at first, too  
]]></description>
			<content:encoded><![CDATA[<p>Right after <a href="http://badcorporatelogo.spaces.live.com/">Mr. Styrchak</a> <a title="An Optimizing MSIL Rewriter (First Working Prototype)" href="http://badcorporatelogo.spaces.live.com/blog/cns!43EB71B104A2D711!505.entry">shared his work</a> on a <a title="Sinner &amp; Inquisitor: The Gathering" href="http://bxnaa.spaces.live.com/blog/cns!85007EAD17D3E592!387.entry">Sinner clone</a> now comes the word that the brave people at <a href="http://red-badger.com/">Red Badger</a> just <a href="http://red-badger.com/Blog/post/Introducing-XPF-e28093-A-Layout-Framework-for-XNA.aspx">released a first build of <strike>Bronzeglow</strike>XPF</a> – I even <a title="Björn&#39;s XNA Adventures: XPF (Working Title)" href="http://bxnaa.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&amp;_c=BlogPart&amp;partqs=cat%3DXPF%2520%2528Working%2520Title%2529">named it XPF at first</a>, too <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/08/xpf-a-layout-framework-for-xna/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article: Programming your first XNA 4.0 game for PC, Xbox 360 &amp; Windows Phone 7: Pong</title>
		<link>http://www.sgtconker.com/2010/08/programming-your-first-xna-4-game-pong/</link>
		<comments>http://www.sgtconker.com/2010/08/programming-your-first-xna-4-game-pong/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 19:58:10 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Mister Helmut]]></category>
		<category><![CDATA[Pong]]></category>
		<category><![CDATA[Thomas Altenburger]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1626</guid>
		<description><![CDATA[by Thomas "Mister Helmut" Altenburger

I’d like to introduce the XNA framework to you with this very simple   and straightforward tutorial. We will see what XNA is and how its basic features works to continue with the programming of your first game, a simple Pong clone for Windows. At last, we’ll try to convert [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Thomas "Mister Helmut" Altenburger</h4>
<p style="text-align: center;"><img class="aligncenter" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/emulator.png" alt="Programming your first XNA 4.0 game" /></p>
<p style="text-align: justify;">I’d like to introduce the XNA framework to you with this very simple   and straightforward tutorial. We will see what XNA is and how its basic features works to continue with the programming of your first game, a simple <a hreflang="en" href="http://en.wikipedia.org/wiki/Pong">Pong</a> clone for Windows. At last, we’ll try to convert it to the Xbox 360 and  Windows Phone 7. This tutorial assumes that the readers have a basic C#/.Net  understanding. I hope that it will help you to understand the  basics of  the framework and that it will motivate you to go further in. The article should be suitable to complete beginners in game  programming.</p>
<p style="text-align: justify;"><strong>About this tutorial:</strong> I wrote this tutorial back in the days of XNA 2.0 beta and used it as an introductory course I taught to master degree students. Since then, it evolved to support XNA 4.0 beta with added Window Phone 7 development.</p>
<p style="text-align: justify;">English not being my native language, please forgive and/or report   any English oddities.</p>
<p style="text-align: justify;"><em>This tutorial targets XNA 4.0 beta. It will be   updated when the final version will be released. It uses some new   features of XNA 4.0 so it will not run out-of-the-box on previous XNA   version (mainly due to the usage of <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.bounds%28XNAGameStudio.40%29.aspx">Viewport.Bounds</a> and changed <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw</a> arguments order).</em></p>
<p><span id="more-1626"></span></p>
<p style="text-align: justify;"><strong> </strong><strong>Required assets:</strong> <a hreflang="en" href="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/PongCloneContent.zip">download  link</a>.</p>
<h1 style="text-align: justify;">The XNA framework</h1>
<p style="text-align: justify;">XNA is a free development framework by Microsoft, enabling  cross-platform game development thanks to simple and comprehensive  programming tools. The supported platforms are Windows PC’s, the Xbox  360, Zune media players and Windows Phone 7. The framework integrates  itself into Visual Studio 2010 (as of XNA 4.0), including the free  Express edition, and features the following components:</p>
<ul style="text-align: justify;">
<li>A powerful .NET API to handle graphics, sounds, videos, inputs,  networking and storage;</li>
<li>An audio development tool, XACT, to build complex cross-platform  sound banks;</li>
<li>A debugger capable of remote debugging Xbox 360 and Zune games;</li>
<li>A Windows Phone 7 emulator so that you don’t need to own such a  device to debug WP7 games.</li>
</ul>
<p style="text-align: justify;">XNA has been designed for hobbyist and independent developers and  builds upon a strong community. If you have any problems during your XNA  journey, don’t hesitate to ask for help at the official XNA community, <a hreflang="en" href="http://creators.xna.com/">the creators club</a>. If  correctly and gently exposed, your problem will most likely be resolved  with the help of XNA experts or the XNA team itself.</p>
<p style="text-align: justify;">Last but not least, the creators club allows you to release and sell  your creations on the Xbox 360 or Windows Phone 7 marketplaces.</p>
<h1 style="text-align: justify;">First steps to the XNA framework</h1>
<p style="text-align: justify;">In order to begin with the framework, let’s review the requirements before setting up our environment. You’ll need a computer with the following  specifications (see XNA 4 specs):</p>
<ul style="text-align: justify;">
<li>Windows Vista or Seven (or their “server” equivalent);</li>
<li>A <a hreflang="en" href="http://www.microsoft.com/windows/directx/">DirectX  9.1c</a> capable graphic card (or better) with up to date drivers and  DirectX runtime; A DirectX 10 capable graphic card if you’d like to  debug Windows Phone 7 XNA projects;</li>
<li><a hreflang="en" href="http://creators.xna.com/en-US/downloads">Windows Phone 7 Development Tools</a> (which includes XNA 4.0 and an Express edition of Visual Studio 2010).</li>
</ul>
<p style="text-align: justify;">If you’re a student, you may be able to get a copy of Windows  Vista/Seven and/or a professional release of Visual Studio through the  MSDN AA of your school (if it has subscribed to it). So go ask the IT  manager of your school for further detail. If you’re school don’t have  access to the MSDN AA, you can still pretend to student advantages  thanks to the <a hreflang="en" href="https://www.dreamspark.com/">Microsoft’s  Dreamspark program</a> (sign up and follow the instructions).</p>
<p style="text-align: justify;">If you’re not a student or simply don’t want to bother with a  professional edition of Visual Studio, the Express edition (included in the WP7 dev tools) is fairly  enough for XNA purpose. Another version wouldn’t bring you more features  unless you have other programming need than XNA.</p>
<p style="text-align: justify;">When you’re fully equipped and may now install the WP7 dev tools. You’re now ready to go.</p>
<p style="text-align: justify;"><strong>Note about XNA 4.0 beta:</strong> commercial copies of Visual Studio aren't supported by XNA 4.0 beta.</p>
<h1 style="text-align: justify;">Creating your first project</h1>
<p style="text-align: justify;">Start up Visual Studio and create a new project by clicking the  “File/New Project…” menu. Here you’ll have a list of the available  project templates. Give the name and directory you want to your project  and under the Visual C# item, pick “Windows Game (4.0)”.</p>
<p style="text-align: justify;">The project you’ve just created is now composed of the following  elements:</p>
<p><img class="aligncenter size-full wp-image-9" title="solution" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/solution.png" alt="" width="302" height="262" /></p>
<ul>
<li style="text-align: justify;">The “Properties” directory, holding application manifest  (not-so-important stuff for our needs);</li>
<li style="text-align: justify;">The “References” meta-directory, listing all the .Net assemblies  your project needs;</li>
<li style="text-align: justify;">The “Content References”, listing the linked Content Pipeline (we’ll  see what it is soon);</li>
<li style="text-align: justify;">The “App.config” file, holding basic .Net setup, no need to edit it  (for a XNA game);</li>
<li style="text-align: justify;">The “Game.ico” file, is the icon of the executable file of your  game;</li>
<li style="text-align: justify;">The “Game1.cs” file, is the main source code file of a XNA project  (I’ll detail this later);</li>
<li style="text-align: justify;">The “GameThumbnail.png” file, is the icon of your game that will be  displayed on the Xbox 360 and Windows Phone 7 marketplaces;</li>
<li style="text-align: justify;">The “Program.cs” file, is the entry point of your program  (initializing your Game1 class).</li>
</ul>
<p style="text-align: justify;">Alongside your project, you’ll find another project having the same  name with a “Content” suffix. This represents the Content Pipeline of  your project, a very important XNA component.</p>
<h2 style="text-align: justify;">The Content Pipeline</h2>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/bb203887%28v=XNAGameStudio.40%29.aspx">Content Pipeline</a> has an almost explicit name. Its  purpose is to manage your game assets (graphics, sounds, 3D models…)  from the importation up to the execution with barely any hassle. Its  main features are:</p>
<ul style="text-align: justify;">
<li>Importing the most common asset file formats and transparently load  them into comprehensible C# objects;</li>
<li>Ease of use (one line asset loading);</li>
<li>Automatically links dependent assets (3D models, textures,  shaders…);</li>
<li>Ensures that your assets are cross-platform, loaded and displayed  the same way;</li>
<li>Offers on-the-fly assets compression/decompression;</li>
<li>Bake up your assets and bundle it with you game.</li>
</ul>
<p style="text-align: justify;">The use of the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/bb203887%28v=XNAGameStudio.40%29.aspx">Content Pipeline</a> is mandatory for non-Windows  deployment. You can still load your assets the “hard way” from files on  PC if you’d like to.</p>
<p style="text-align: justify;">You can create as many Content projects as you want but it is more  convenient to stick with one per game project. Remember the “Content  References” in your game project? This is where you link your project to  your Content project. By default, your project is linked to the already  created Content project (you can check this by unfolding the “Content  References”).</p>
<p style="text-align: justify;">Now for the supported file formats, here’s the list:</p>
<ul style="text-align: justify;">
<li><strong>2D graphics</strong>: .bmp, .png, .jpg;</li>
<li><strong>3D models</strong>: .x, .fbx;</li>
<li><strong>Shaders</strong>: .fx;</li>
<li><strong>Audio</strong>: .mp3, .wav, .wma;</li>
<li><strong>Video</strong>: .wmv;</li>
<li><strong>Font</strong>: TrueType;</li>
<li>Any XML, text or binary files.</li>
</ul>
<p style="text-align: justify;">You may find many other format importers on the web or code one  yourself if you need to (<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/bb447754.aspx">http://msdn.microsoft.com/en-us/library/bb447754.aspx</a>).</p>
<h3 style="text-align: justify;">Adding assets to your project</h3>
<p style="text-align: justify;">To add assets to your project, right click on your Content project,  and “Add/Add an existing item” and pick your assets. You can also  organize your assets into folders or add assets just by drag’n’droping  files to your Content project.</p>
<h3 style="text-align: justify;">The Game class</h3>
<p style="text-align: justify;">Now open up the Game1.cs file. You should notice that the Game1 class  is inherited from a class named <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a>. The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> class is provided by XNA and manages the game  loop (more generally the game workflow). It is composed of the following  methods:</p>
<ul style="text-align: justify;">
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.initialize%28v=XNAGameStudio.40%29.aspx">Initialize</a>: called after the construction of the  class, it ensures that all the class fields are constructed and ready to  be initialized. The purpose of this method is (as you may have guessed)  to initialize class members (in the same way of the Winforms’  Initialize method);</li>
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent%28v=XNAGameStudio.40%29.aspx">LoadContent</a>: called after Initialize, this method is  meant to be used to load your game assets;</li>
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.unloadcontent%28v=XNAGameStudio.40%29.aspx">UnloadContent</a>: called during the disposal of  the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> class and ensure that your game assets are  disposed correctly when you exit it (it doesn’t mean that you don’t have  to take care of your memory allocation);</li>
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a>: called every time before the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method and should be used to update your game  engine. This will be the place of collision handling, inputs handling,  game world updating etc. Its <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gametime%28v=XNAGameStudio.40%29.aspx">GameTime</a> argument propose services to know the amount  of time elapsed since the last Update call. This is very useful to  synchronize your game engine;</li>
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a>: called in an infinite loop, it is meant to draw  your game. Even if it is possible, for the sake of clean code, you  should avoid writing any logic update here.</li>
</ul>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> and <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> methods represent the Game Loop and are called  in an infinite loop so that your game is constantly refreshed and  running. XNA default settings set the loop frequency to 60 loops per  second, meaning that your game should run at 60 frames per second (as  long as your <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a>/<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> don’t take too much time). You can adjust the  settings to void this limit so that your game runs as fast as your <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a>/<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> allow it to, but we’re not going to cover this  in this tutorial.</p>
<p style="text-align: justify;">The following figure depicts the general workflow of a game:</p>
<p style="text-align: justify;"><img class="aligncenter size-full wp-image-10" title="workflow" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/workflow.png" alt="" width="507" height="208" />You’re free to not use the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> class but it provides useful services behind the  Game Loop and if you’re coding yourself such a class, you’ll most  likely end up with a pretty similar one. So why bothering re-writing the  wheel? Plus the fact the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> class ensures the workflow of your game.</p>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class comes with two fields initialized:</p>
<ul style="text-align: justify;">
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphicsdevicemanager%28v=XNAGameStudio.40%29.aspx">GraphicsDeviceManager</a> graphics: manages what is  called the “graphical context”. More accurately, it allows you to setup  the graphics card states (i.e. screen resolution, vertical  synchronization, anti-aliasing, etc.) and to get information about the  hardware capabilities;</li>
<li><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch%28v=XNAGameStudio.40%29.aspx">SpriteBatch</a> spriteBatch: provides services for 2D  drawings. This will be the most important object covered by this  tutorial.</li>
</ul>
<h3 style="text-align: justify;">Initializing and drawing 2D graphics</h3>
<p style="text-align: justify;">We will now take a look at how one can import 2D graphics and display  it. You will need some game assets in order to continue. I’ve prepared a  bundle with everything you need to follow this tutorial: <a hreflang="en" href="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/PongCloneContent.zip">grab it there</a>.</p>
<p style="text-align: justify;">Now take a look at the file named texture1.bmp. It is a simple image  with 2D graphics. Notice that there are many single graphic entities  inside the picture. An individual graphical entity is called a sprite  and if an image contains many sprites, we’re in front of a sprite sheet.</p>
<p style="text-align: justify;">Other terms do exist to describe sprites and sprite sheets. Like  tiles and tile sets. If you have already toyed with some “RPG maker”,  you should be familiar with their meanings. Like a sprite sheet, a tile  set is an image containing several tiles, a tile being an independent  rectangle of your image. To the difference with sprites, tiles inside a  tile set are usually the same size, forming a regular grid. You may have  noticed that tiles can be disposed side by side to form complex  graphics, like a puzzle, using several times the same tile. This  technique is commonly used in 2D games (RPG, side-scroller…) and was  historically used because of the lack of memory of the 8/16bit systems.</p>
<p style="text-align: justify;">Let’s import the texture: right click on your Content project, create  a new folder named “Textures”, and add the existing texture1.bmp to  this folder. It should now appear in your project. Right click on the  texture1.bmp item and select “properties”, this will obviously show the  asset properties. You’ll see a bunch of stuff, the one that is important  for now is the “Asset Name” which should be set to “texture1”. This is  the internal name of your asset, not its filename. XNA set a default  name corresponding to the filename without its file extension, but you  can freely change it. Keep in mind it has nothing to do with the  filename.</p>
<p style="text-align: justify;">Now, inside your <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class, as a class member, add a new member to  host our texture. To this purpose, the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d%28v=XNAGameStudio.40%29.aspx">Texture2D</a> is intended manage your 2D texture (as you  could have found out by yourself).</p>
<pre class="brush: csharp;">
Texture2D myTexture;
</pre>
<p style="text-align: justify;">We now need to code the actual loading of the asset, so go inside the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent%28v=XNAGameStudio.40%29.aspx">LoadContent</a> method and add the following line of code:</p>
<pre class="brush: csharp;">
myTexture = Content.Load&lt;Texture2D&gt;(@&quot;Textures/texture1&quot;);
</pre>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.content.contentmanager%28v=XNAGameStudio.40%29.aspx">Content</a> object is a default <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> class member representing your Content project.  Everything linked to your Content project should be accessed through the  Content member. Its Load function is generic and will allow you to  easily load any supported type of asset by specifying the wanted type to  the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/bb197848%28v=XNAGameStudio.40%29.aspx">Load&lt;Type&gt;</a> template. To load an asset, just  specify the desired type and the asset name (not its file name). If you  try to load an unsupported type for the given asset, you’ll encounter an  exception at runtime. The “@” before the asset name is a C# operator  specifying that the special characters of the following string don’t  need to be escaped. It is way more convenient to use it when dealing  with asset locations since it will avoid you from doubling all the  dashes (making your code more readable). Notice that you access assets  as if they were files in the hierarchy of your Content project, but with  assets names as their filename (this may be a bit puzzling at first  glance).</p>
<p style="text-align: justify;">Take a look at the content of the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method:</p>
<pre class="brush: csharp;">
protected override void Draw(GameTime gameTime)
{
      GraphicsDevice.Clear(Color.CornflowerBlue);
      // TODO: Add your drawing code here
      base.Draw(gameTime);
}
</pre>
<p style="text-align: justify;">The first line cleans the entire buffer so that the whole screen is  reset to a blue color (the infamous <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.color.cornflowerblue%28v=XNAGameStudio.40%29.aspx">CornflowerBlue</a>). The last line calls the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game</a> base <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method and should always be the last instruction  of your <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method. I will not cover this feature as we will  not use inheritance and game components.</p>
<h3 style="text-align: justify;">The SpriteBatch.Draw(…) method</h3>
<p style="text-align: justify;">To draw 2D graphics, the only thing you will need is the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw(…)</a> method. But beforehand, take a  look at how the screen is addressed by XNA:</p>
<p style="text-align: center;"><img class="aligncenter" title="axes.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/axes.png" alt="axes.png" /></p>
<p style="text-align: justify;">As you can see, the screen origin is in the upper left corner and  goes positively to the opposite screen corner. This is a bit strange if  you’re used to <a hreflang="en" href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system">the Cartesian system</a>. The unit is the pixel, meaning  that (with default XNA screen resolution of 800x480) the X axis goes up  to 800 and the Y one to 480. Textures are addressed the same way.</p>
<p style="text-align: justify;">Here’s one the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw(…)</a> overload header:</p>
<p><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw</a>( <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d%28v=XNAGameStudio.40%29.aspx">Texture2D</a>, <span style="color: #339966;">// the texture to use for drawing</span><br />
<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a>, <span style="color: #339966;">// the rectangle where you want to draw on  the screen (in screen coordinate) </span><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a>,<span style="color: #339966;"> // the part of the texture you want to  draw (in texture coordinate)</span><br />
<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.color%28v=XNAGameStudio.40%29.aspx">Color</a>); <span style="color: #339966;">// the color hue of the drawing, Color.White  will give a default hue</span></p>
<p style="text-align: justify;">Now, considering our texture1, here’s an example call and the  expected result:</p>
<pre class="brush: csharp;">
spriteBatch.Begin();
spriteBatch.Draw(
      myTexture,
      new Rectangle(10, 20, 50, 100),
      new Rectangle(0, 0, 50, 100),
      Color.White);
spriteBatch.End();
</pre>
<p style="text-align: justify;">The main difficulty in understanding 2D drawing is to understand the difference between source and destination rectangles. Have a look at the following illustration.</p>
<p style="text-align: center;"><img class="aligncenter" title="sprite.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/sprite.png" alt="sprite.png" /></p>
<p style="text-align: justify;">On the left, we have the texture containing the objects we’d like to  draw, but we only want to draw a portion of that texture. The source  rectangle defines this portion and must use the texture coordinates.  Then, you define where on the screen you want that portion to be drawn  by defining the destination rectangle (in screen coordinates). Note that  the destination rectangle doesn’t have to be as wide/high as the source  rectangle. Different sizes will result in stretched drawing.</p>
<h3 style="text-align: justify;">SpriteBatch.Begin(…) / End()</h3>
<p style="text-align: justify;">You may notice that the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw</a> call is surrounded by two other  methods, namely <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.begin%28v=XNAGameStudio.40%29.aspx">Begin</a> and <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.end%28v=XNAGameStudio.40%29.aspx">End</a>. <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.begin%28v=XNAGameStudio.40%29.aspx">Begin</a> could mean “ok mister GPU, here’s what you’re  going to draw and how you’re going to draw it”. It tells the GPU to draw  what’s coming and the properties to apply, like the usage of <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.blendstate.alphablend%28v=XNAGameStudio.40%29.aspx">AlphaBlend</a>, the order in which the sprites are going  to be drawn etc.</p>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.end%28v=XNAGameStudio.40%29.aspx">End</a> method tells to the GPU that the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> calls are complete and that he can now draw  everything with the properties it have been configured.</p>
<p style="text-align: justify;">You have to know that the CPU will tell the GPU what to draw only  when you call the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.end%28v=XNAGameStudio.40%29.aspx">End</a> method. The result of this method is the transfer  of the drawing primitives to the GPU and transferring data between the  CPU and the GPU is very expensive. So try to put as many Draw calls as  possible between the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.begin%28v=XNAGameStudio.40%29.aspx">Begin</a> and <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.end%28v=XNAGameStudio.40%29.aspx">End</a> statements, this will greatly improve your game  performance by reducing transfers to the GPU. Using several <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.begin%28v=XNAGameStudio.40%29.aspx">Begin</a>/<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.end%28v=XNAGameStudio.40%29.aspx">End</a> is mainly intended to use different drawing  parameters or to ensure that some elements are drawn before/after other  elements.</p>
<h1>Coding a Pong clone in 5 minutes</h1>
<p style="text-align: justify;">You should now master the basics of XNA. Despite the title of this  section, we’re not going to write a Pong clone in 5 minutes, but if you  were confident in XNA, you should be able to do it.</p>
<h2>Defining the basics</h2>
<p style="text-align: justify;">Ok, what do we need to make a Pong game?</p>
<ul style="text-align: justify;">
<li>Two playable bars (2 x <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a>);</li>
<li>A ball (1 x Circle);</li>
<li>A tennis field;</li>
<li>A score display;</li>
<li>Motivated supporters.</li>
</ul>
<p style="text-align: justify;">Inside the assets package you should have already downloaded (if not  so, <a hreflang="en" href="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/PongCloneContent.zip">grab it here</a>), you should find the following files:</p>
<ul style="text-align: justify;">
<li><strong>Objects.png</strong>: an image file containing the graphics  for the two bars and the ball;</li>
<li><strong>Grass.png</strong>: an image file, a grass texture;</li>
<li><strong>Bounce.wav</strong>: a sound file for ball bounces;</li>
<li><strong>Supporters.wav</strong>: a sound file for goals.</li>
</ul>
<p style="text-align: justify;">Add all of them to your Content project.</p>
<p style="text-align: justify;">Let’s now define all those entities in our project, as <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class members.</p>
<pre class="brush: csharp;">
// our pong entities
Rectangle blueBar;
Rectangle redBar;
Rectangle ball; // since there’s no &quot;circle&quot; class in XNA, we’ll simulate it with a bounding rectangle box

// our pong clone textures
Texture2D grass;
Texture2D spriteSheet;

// our sound effects
SoundEffect ballBounce;
SoundEffect playerScored;
</pre>
<p style="text-align: justify;">We now need to initialize our three Rectangle structures and we’ll do it  in the (suspense…) <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.initialize%28v=XNAGameStudio.40%29.aspx">Initilize</a> method:</p>
<pre class="brush: csharp;">
protected override void Initialize()
{
      // initializing our entities
      blueBar = new Rectangle(
            32, // x coordinate of the upper left corner of our rectangle
            GraphicsDevice.Viewport.Bounds.Height / 2 - 64, // y coordinate of the upper left corner
            32, // its width
            128); // and its height
      redBar = new Rectangle(
            GraphicsDevice.Viewport.Bounds.Width - 64, // x coordinate of the upper left corner of our rectangle
            GraphicsDevice.Viewport.Bounds.Height / 2 - 64, // y coordinate of the upper left corner
            32, // its width
            128); // and its height
      ball = new Rectangle(
            GraphicsDevice.Viewport.Bounds.Width / 2 - 16, // x coordinate of the upper left corner of our rectangle
            GraphicsDevice.Viewport.Bounds.Height / 2 - 16, // y coordinate of the upper left corner
            32, // its width
            32); // and its height

      base.Initialize();
}
</pre>
<p style="text-align: justify;"><strong>Explanation:</strong></p>
<p style="text-align: justify;">We want our bars to be 32x128 pixels and be placed left and right to  the screen and perfectly centered. Defining a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> consist of four parameter: the x coordinate  of the upper left corner (in screen coordinate), the y coordinate of  the upper left corner, the width of the rectangle (32) and its height  (128).</p>
<p style="text-align: justify;">Noticed this kind of math?</p>
<pre class="brush: csharp;">
GraphicsDevice.Viewport.Bounds.Height / 2 - 64
</pre>
<p style="text-align: justify;">This is how we vertically center our bars. <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.bounds%28XNAGameStudio.40%29.aspx">GraphicsDevice.Viewport.Bounds</a> is a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> provided by XNA that will always represent  the actual bounds of the screen. If the resolution of your game is  800x480, the bounds will be <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle(0, 0, 800, 480)</a>. So if we want to center  something, we just have to consider the half of the screen, minus the  half of the rectangle we’d like to be centered (or else only its upper  left corner will be centered).</p>
<p style="text-align: justify;">If you understood all this, you shouldn’t have difficulties  understanding our ball definition. We’d like our ball to have a 32  pixels diameter so we bound it with a 32x32 <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> (since no circle class exists in XNA, up to  you write one). Yes, using a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> to simulate a circle isn't very accurate, but as long as our game is simple enough, we just don't care about it (the purpose of this tutorial isn't to be super accurate).</p>
<p style="text-align: justify;">Let’s now load the assets we’ve defined earlier, so go to the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent%28v=XNAGameStudio.40%29.aspx">LoadContent</a> method. The following code should be  straightforward if you read the introduction of this article:</p>
<pre class="brush: csharp;">
protected override void LoadContent()
{
      // Create a new SpriteBatch, which can be used to draw textures.
      spriteBatch = new SpriteBatch(GraphicsDevice);

      // load our textures from the Content Pipeline
      grass = Content.Load&lt;Texture2D&gt;(@&quot;Textures/Grass&quot;);
      spriteSheet = Content.Load&lt;Texture2D&gt;(@&quot;Textures/Objects&quot;);

      // load our sound effects from the Content Pipeline
      ballBounce = Content.Load&lt;SoundEffect&gt;(@&quot;Sounds/Bounce&quot;);
      playerScored = Content.Load&lt;SoundEffect&gt;(@&quot;Sounds/Supporters&quot;);
}
</pre>
<h2 style="text-align: justify;">Drawing the scene</h2>
<p style="text-align: justify;">At last, we will draw the entire scene but beforehand, I’ll introduce  to you a simple problem.</p>
<p style="text-align: justify;"><a hreflang="en" href="http://en.wikipedia.org/wiki/Painter%27s_algorithm">The painter’s problem</a>: even if you never heard about  it, you should be familiar to it. When a painter would like to drawn a  landscape on the background and a house in front of it, it has to first  complete the background and then paint the house over it. If he did the  house first, he would encounter problems detailing the background at the  house’s edges. Graphics API works pretty much the same way but are more  restrictive: everything that is drawn will recover what’s already drawn  if it overlaps. So you have to draw graphics according to their distance  from the camera.</p>
<p style="text-align: justify;">Currently, what I said is not completely true since there’s some  hardware magic called the Z-buffer which sorts everything out even if  you draw everything in a random order. But the Z-buffer has been  designed for 3D purposes and when dealing with 2D graphics, we’re no  more working with Z coordinate so we have to sort this ourselves.</p>
<p style="text-align: justify;">XNA offers mechanisms to sort 2D graphics via the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritesortmode%28v=XNAGameStudio.40%29.aspx">SpriteSortMode</a> argument of the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw%28v=XNAGameStudio.40%29.aspx">SpriteBatch.Draw</a> method but it is cleaner to draw  things in the right order and to tell XNA to draw directly (<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritesortmode%28v=XNAGameStudio.40%29.aspx">SpriteSortMode.Immediate</a>) because: 1) your code will  be much more readable 2) it will be faster at execution.</p>
<p style="text-align: justify;">Let’s draw our background first:</p>
<pre class="brush: csharp;">
protected override void Draw(GameTime gameTime)
{
      GraphicsDevice.Clear(Color.CornflowerBlue); // clear all the screen with a blue color

      // draw the grass background
      spriteBatch.Begin();
      spriteBatch.Draw(
            grass, // use the grass texture
            GraphicsDevice.Viewport.Bounds, // stretch the texture to the whole screen
            // GraphicsDevice.Viewport.Bounds is Rectangle corresponding to the actual viewport (meaning the entire screen no matter the resolution), only available as of XNA 4.0
            Color.White);
      spriteBatch.End();
</pre>
<p style="text-align: justify;">What’s new here? We’re using the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.bounds%28XNAGameStudio.40%29.aspx">Viewport.Bounds</a> as our destination <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a>, why? Do you remember that this Rectangle  always represent the whole screen resolution? We’re just telling the  Draw method to stretch the entire grass texture to the entire screen.  And we’re done with our background. At this state, if you try to run the  game (by pressing F5 to debug it), it should display our nice grass  tennis field.</p>
<p>game (by pressing F5 to debug it), it should display our nice grass  tennis field.</p>
<p style="text-align: center;"><img class="aligncenter" title="grass.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/grass.png" alt="grass.png" /></p>
<p style="text-align: justify;">What comes after the background? The bars and the ball should be on  the same plane. We can draw all of them at the same time since there’s  no risk that they overlap but, wait… all the assets of those entities  are in the same single texture. Once again, do you remember the usage of  “source rectangle”? (Check the introduction if the answer is no).  Before drawing our elements we need to define a source rectangle for  each of them to access individual portion of the texture. Look at what’s  inside the texture and how it is placed:</p>
<p style="text-align: center;"><img class="aligncenter" title="spritesheet.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/spritesheet.png" alt="spritesheet.png" /></p>
<p style="text-align: justify;">The following three source rectangles should be easy to understand  (define them as <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class members):</p>
<pre class="brush: csharp;">
// source rectangles of our graphics
Rectangle blueSrcRect = new Rectangle( // blue bar src rectangle
      0, // upper left corner x-coordinate of the blue bar inside the spriteSheet
      0, // upper left corner y-coordinate
      32, // width
      128); // height
Rectangle redSrcRect = new Rectangle( // red bar src rectangle
      32, // upper left corner x-coordinate of the red bar inside the spriteSheet
      0,
      32,
      128);
Rectangle ballSrcRect = new Rectangle( // ball src rectangle
      64, // upper left corner x-coordinate of the ball inside the spriteSheet
      0,
      32,
      32);
</pre>
<p style="text-align: justify;">We now have everything up to draw the remaining elements. Here’s what  comes after our backgrounds drawing:</p>
<pre class="brush: csharp;">
// draw the entities (bars and ball)
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); // setup alpha blend to support transparency
// draw the red bar
spriteBatch.Draw(
      spriteSheet, // use the sprites texture
      redBar, // the rectangle where to draw the bar on the screen
      redSrcRect, // the source rectangle of the bar inside the sprite sheet
      Color.White);
// draw the blue bar
spriteBatch.Draw(
      spriteSheet,
      blueBar,
      blueSrcRect,
      Color.White);
// draw the ball
spriteBatch.Draw(
      spriteSheet,
      ball,
      ballSrcRect,
      Color.White);
spriteBatch.End();
</pre>
<p style="text-align: justify;">Press F5, and see that our game almost look like it is finished.  There’s still all the gameplay to implement but our graphics are setup  and we’re now free to toy with the gameplay.</p>
<p style="text-align: center;"><img class="aligncenter" title="nogameplay.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/nogameplay.png" alt="nogameplay.png" /></p>
<h2 style="text-align: justify;">Coding the gameplay</h2>
<h3 style="text-align: justify;">Handling the inputs</h3>
<p style="text-align: justify;">Now that we’re done with the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method, we’ll take a look at the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method, so go at the corresponding line of  code, we’re going to examine its default content:</p>
<pre class="brush: csharp;">
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) // if the Back gamepad button is pressed
      this.Exit(); // exit our game
</pre>
<p style="text-align: justify;">The <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepad%28v=XNAGameStudio.40%29.aspx">GamePad</a> class allows getting the current state of an  Xbox 360 gamepad, being plugged to a PC or to your 360. Its <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepad.getstate%28v=XNAGameStudio.40%29.aspx">GetState(PlayerIndex)</a> method returns the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate%28v=XNAGameStudio.40%29.aspx">GamePadState</a> of the player corresponding to the given  <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.playerindex%28v=XNAGameStudio.40%29.aspx">PlayerIndex</a>.</p>
<p style="text-align: justify;">A <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate%28v=XNAGameStudio.40%29.aspx">GamePadState</a> object has a Buttons member, listing  every up-down buttons and their state (A, B, Y, X, RB, LB, Back, Start,  and Buttons on Sticks). If you want to know if a button is pressed, just  compare a button to a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.buttonstate%28v=XNAGameStudio.40%29.aspx">ButtonState</a>. Buttons of the directional pad works the  same way and their states are stored in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate.dpad%28v=XNAGameStudio.40%29.aspx">DPad</a> member of a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate%28v=XNAGameStudio.40%29.aspx">GamePadState</a>. The other inputs of a gamepad are  different, they’re continuous (Sticks’ X &amp; Y axes and Triggers) so  you can’t compare them to a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.buttonstate%28v=XNAGameStudio.40%29.aspx">ButtonState</a> since they are floating point values.  When in default position, those controls have 0.0f value. Triggers go up  to 1.0f when fully pressed and the axes range from -1.0f up to 1.0f  depending the direction of the axes. (X = 1.0f and Y = -1.0f would mean  that the stick is in the lower right corner).</p>
<p style="text-align: justify;">Getting the keyboard state works pretty much the same way. Let’s add a  keyboard control to the default code:</p>
<pre class="brush: csharp;">
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || // if the Back gamepad button is pressed
      Keyboard.GetState().IsKeyDown(Keys.Escape)) // or if the Escape key is down
      this.Exit(); // exit our game
</pre>
<p style="text-align: justify;"><a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keyboard.getstate%28v=XNAGameStudio.40%29.aspx">Keyboard.GetState()</a> should be simple to understand  now. But what is this <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keyboardstate.iskeydown%28v=XNAGameStudio.40%29.aspx">IsKeyDown</a> method? Unlike a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate%28v=XNAGameStudio.40%29.aspx">GamePadState</a>, <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keyboardstate%28v=XNAGameStudio.40%29.aspx">KeyboardState</a> don’t hold directly fields with keys’  states, you have to ask for a state with the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keyboardstate.iskeydown%28v=XNAGameStudio.40%29.aspx">IsKeyDown</a> / <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keyboardstate.iskeyup%28v=XNAGameStudio.40%29.aspx">IsKeyUp</a> methods. Actually, <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate%28v=XNAGameStudio.40%29.aspx">GamePadState</a> has a similar mechanism and propose the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate.isbuttondown%28v=XNAGameStudio.40%29.aspx">IsButtonDown</a> / <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.gamepadstate.isbuttonup%28v=XNAGameStudio.40%29.aspx">IsButtonUp</a> methods.</p>
<h3>Moving the bars</h3>
<p style="text-align: justify;">Our bars are represented by the redBar and blueBar rectangles, so if  we want them to move, when need to modify their Y position (in a Pong  game, bars only move along the Y axis). We will use the keyboard as our  main input method, up to you to andle two different gamepads (this will be covered later).</p>
<pre class="brush: csharp;">
// handling keyboard inputs
if (Keyboard.GetState().IsKeyDown(Keys.E)) // E key down ?
      blueBar.Y -= 10; // move the blue bar up
else if (Keyboard.GetState().IsKeyDown(Keys.D)) // D key down ?
      blueBar.Y += 10; // move the blue bar down
if (Keyboard.GetState().IsKeyDown(Keys.Up)) // Up key down ?
      redBar.Y -= 10; // move the red bar up
else if (Keyboard.GetState().IsKeyDown(Keys.Down)) // Down key down ?
      redBar.Y += 10; // move the red bar down
</pre>
<p style="text-align: justify;">Quite simply isn’t it? If you launch the game and try to move the bars  (with the E/D and Up/Down keys) you’ll notice that the bar can go behind  the screen. We don’t want that behavior since they should stop at  screen borders.</p>
<pre class="brush: csharp;">
// limit the bars movement to the screen bounds
if (redBar.Y &lt; 0) // upper bound
      redBar.Y = 0; // limit
if (blueBar.Y &lt; 0)
      blueBar.Y = 0;
if (redBar.Y + redBar.Height &gt; GraphicsDevice.Viewport.Bounds.Height)
      redBar.Y = GraphicsDevice.Viewport.Bounds.Height - redBar.Height;
if (blueBar.Y + blueBar.Height &gt; GraphicsDevice.Viewport.Bounds.Height)
      blueBar.Y = GraphicsDevice.Viewport.Bounds.Height - blueBar.Height;
</pre>
<p style="text-align: justify;">Now the bars don’t move outside the screen. The only trick resides in  the handling of the lower bound: don’t forget to consider the bar  height (the Y coordinates being the one of the upper left corner).</p>
<h3>Ball’s motion</h3>
<p style="text-align: justify;">In order to make the ball moving, we need something to represent its  velocity. Using a 2D vector seems to be the way to go. Fortunately, XNA  already have everything at your disposal. Here we define a 2D vector (<a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2%28v=XNAGameStudio.40%29.aspx">Vector2</a>) for our ball velocity (as a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class member):</p>
<pre class="brush: csharp;">
// ball speed
Vector2 ballVelocity = Vector2.Zero;
</pre>
<p style="text-align: justify;">And back in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method, we can now make our ball move by  adding its velocity to its current position:</p>
<pre class="brush: csharp;">
// move the ball
ball.X += (int)ballVelocity.X;
ball.Y += (int)ballVelocity.Y;
</pre>
<p style="text-align: justify;">But, our ball isn’t really moving yet. Notice that we initialized the  velocity to zero speed. We need to set a positive speed somewhere so the  gameplay can begin. We will do this by adding a separate method we can  re-use to re-initialize the ball every time we need it (when players  score):</p>
<pre class="brush: csharp;">
private void InitBall()
{
      int speed = 5; // default velocity
      Random rand = new Random();

      // randomize the ball orientation
      switch (rand.Next(4))
      {
            case 0: ballVelocity.X = speed; ballVelocity.Y = speed; break;
            case 1: ballVelocity.X = -speed; ballVelocity.Y = speed; break;
            case 2: ballVelocity.X = speed; ballVelocity.Y = -speed; break;
            case 3: ballVelocity.X = -speed; ballVelocity.Y = -speed; break;
      }

      // initialize the ball to the center of the screen
      ball.X = GraphicsDevice.Viewport.Bounds.Width / 2 - ball.Width / 2;
      ball.Y = GraphicsDevice.Viewport.Bounds.Height / 2 - ball.Height / 2;
}
</pre>
<p style="text-align: justify;">We have a default velocity defined and a random number generator to  add some unpredictability to the ball direction. In a switch statement,  we make the ball go randomly in one of the four diagonal. Then, we set  the ball’s position to the center of the screen, and the gameplay shall  begin.</p>
<p style="text-align: justify;">We can now call our newly created method to initialize the game. Back  in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method:</p>
<pre class="brush: csharp;">
// handling ball initialization
if (Keyboard.GetState().IsKeyDown(Keys.Space))
      InitBall();
</pre>
<p style="text-align: justify;">This code means that every time we press the space bar, the ball is  reset. Meaning that even during the gameplay, one can re-init the ball.  That’s not a correct behavior but we don’t care since we’re aiming a  playable game, not a polished one <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . Keep in mind that this is for  educational purpose.</p>
<h3>Worlds collide</h3>
<p style="text-align: justify;">If you tried to run the project, you’ll see that the ball is not  bouncing on screen bounds. In the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method, we add the required code:</p>
<pre class="brush: csharp;">
// collision handling
if (ball.Y &lt; 0 || // if the ball reach the upper bound of the screen
      ball.Y + ball.Height &gt; GraphicsDevice.Viewport.Bounds.Height) // or the lower one
{
      ballVelocity.Y = -ballVelocity.Y; // make if bounce by inverting the Y velocity
}
</pre>
<p style="text-align: justify;">This is similar to the way we managed the bars’ movement, with the  particularity that instead of blocking the movement, we invert the Y  velocity so the ball bounce.</p>
<p style="text-align: justify;">We also need to manage the collision with the bars. It is a little  bit different, since we’re going to check for Rectangle to <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> collisions. To this purpose, XNA is making  our life a lot easier since the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> class has a very useful method to test if  two <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle%28v=XNAGameStudio.40%29.aspx">Rectangle</a> are colliding:</p>
<pre class="brush: csharp;">
if (ball.Intersects(redBar) || // if the ball collide with blue bar
      ball.Intersects(blueBar)) // or the red one
{
      ballVelocity.X = -ballVelocity.X; // make if bounce by inverting the X velocity
}
</pre>
<p style="text-align: justify;">Very simple: we just check if the ball (which is a Rectangle) is  colliding with either one of the bars, and invert the X velocity to make  it bounce.</p>
<p style="text-align: justify;">Here we are! We have a fully playable gameplay. The game only need  some polish and it is almost ready for huge commercial success (if we  were in the 70’s by the way…).</p>
<h3>Scoring</h3>
<p style="text-align: justify;">To add some competition, we will handle a simple score counter and  display. We’ll use two more <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> class members to manage the scores:</p>
<pre class="brush: csharp;">
// scores
int blueScore = 0;
int redScore = 0;
</pre>
<p style="text-align: justify;">We need to detect if the ball goes behind a bar in order to increment  the corresponding score. We’ll do it in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method:</p>
<pre class="brush: csharp;">
// score handling
if (ball.X &lt; 0) // red scores
{
      redScore++;
      InitBall(); // re-init the ball
}
else if (ball.X + ball.Width &gt; GraphicsDevice.Viewport.Bounds.Width) // blue scores
{
      blueScore++;
      InitBall(); // re-init the ball
}
</pre>
<p style="text-align: justify;">Same math as before to check screen bounds. When the ball goes behind  the left or right bound, a player just scored and we re-initialize the  ball.</p>
<p style="text-align: justify;">Displaying the score involves to draw some text. Drawing text with  graphics API is a bit problematic, text fonts are not ready-to-be-drawn  graphics and their structure is not suitable with how graphics cards  operate. Prior to use a font, it has to be processed or converted to a  suitable asset. Some tools allow you to do so by generating a sprite  sheet containing one sprite per character in the font. I let you imagine  how boring it is to write a helper class able to seamlessly use this  sprite sheet. Graphics API like SDL or OpenGL don’t do this  out-of-the-box but some useful libraries exist.</p>
<p style="text-align: justify;">XNA has the feature to handle fonts easily. Let’s have a look at it.  We need to add a special type of asset to our Content project: right on  the Content project, add a new file, select the Sprite Font item and  name it “ScoreFont.spritefont”. An XML file should be showing up after  you added it. This file will hold the properties of the font we want to  use: the font name, its size, its type (bold, italic…) and other  not-so-important stuff. We want the score to be displayed with big  readable font, so change the size to 18 and the type to “Bold” (case  sensitive!):</p>
<pre class="brush: xml;">
&lt;Size&gt;18&lt;/Size&gt;
...
&lt;Style&gt;Bold&lt;/Style&gt;
</pre>
<p style="text-align: justify;">Like any asset, we have to define the corresponding variable and to load  it. As a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> member:</p>
<pre class="brush: csharp;">
SpriteFont font;
</pre>
<p style="text-align: justify;">And then in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent%28v=XNAGameStudio.40%29.aspx">LoadContent</a> method:</p>
<pre class="brush: csharp;">
// load our score font
font = Content.Load&lt;SpriteFont&gt;(@&quot;ScoreFont&quot;);
</pre>
<p style="text-align: justify;">All we have to do now is to draw the text, the same way if it was 2D  graphics with the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch%28v=XNAGameStudio.40%29.aspx">SpriteBatch</a> (in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw%28v=XNAGameStudio.40%29.aspx">Draw</a> method, after the grass drawing so it isn’t  underneath):</p>
<pre class="brush: csharp;">
// draw the score
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
spriteBatch.DrawString( // draw our score string
      font, // our score font
      blueScore.ToString() + &quot; - &quot; + redScore.ToString(), // building the string
      new Vector2( // text position
      GraphicsDevice.Viewport.Bounds.Width / 2 - 25, // half the screen and a little to the left
      10.0f),
      Color.Yellow); // yellow text
spriteBatch.End();
</pre>
<p style="text-align: justify;">Note that drawing text needs a dedicated method, <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.drawstring%28v=XNAGameStudio.40%29.aspx">DrawString</a>. It takes as argument the font, the string  to display, a 2D vector for the screen coordinate where we want the  text to be displayed (remind that it consider the upper left corner of  the text box), and finally, the color of the text.</p>
<h3>Sound blasting</h3>
<p style="text-align: justify;">Last but not least, the sound. We already have our two <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.soundeffect%28v=XNAGameStudio.40%29.aspxhttp:/msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.soundeffect%28v=XNAGameStudio.40%29.aspx">SoundEffect</a> ready (ballBounce &amp; playerScored).  Since XNA 3.0, playing a sound is simple as pie: <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.soundeffect.play%28v=XNAGameStudio.40%29.aspx">SoundEffect.Play()</a>. All we have to do, is to call the  play method when the ball bounce and when a player scores. Here’s the  code update:</p>
<pre class="brush: csharp;">
// collision handling
if (ball.Y &lt; 0 || // if the ball reach the upper bound of the screen
      ball.Y + ball.Height &gt; GraphicsDevice.Viewport.Bounds.Height) // or the lower one
{
      ballVelocity.Y = -ballVelocity.Y; // make if bounce by inverting the Y velocity
      ballBounce.Play(); // bounce sound
}

if (ball.Intersects(redBar) || // if the ball collide with blue bar
      ball.Intersects(blueBar)) // or the red one
{
      ballVelocity.X = -ballVelocity.X; // make if bounce by inverting the X velocity
      ballBounce.Play(); // bounce sound
}

// score handling
if (ball.X &lt; 0) // red scores
{
      redScore++;
      playerScored.Play(); // hurray !
      InitBall(); // re-init the ball
}
else if (ball.X + ball.Width &gt; GraphicsDevice.Viewport.Bounds.Width) // blue scores
{
      blueScore++;
      playerScored.Play(); // hurray !
      InitBall(); // re-init the ball
}
</pre>
<h2>Intermediary conclusion</h2>
<p style="text-align: center;"><img class="aligncenter" title="full.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/full.png" alt="full.png" /></p>
<p style="text-align: justify;">Our Windows game is now complete! At least what I wanted to expose.  Our prototype is far from being perfect, but one of the goals of this  article is to give you opportunity to express yourself in the polishing  of the game. You may copy/pasted everything but now, it’s up to you to  enhance it. Here’s a list of thing you may consider doing:</p>
<ul>
<li style="text-align: justify;">Enhance collision handling: our model is very rough and far from a  true physical model, plus the fact that the bar-to-ball collision is  poorly managed (if the ball collide with another border than the front  one, you can expect strange behaviors);</li>
<li style="text-align: justify;">Enhance the beginning of the game: in a classic Pong, the ball  should go randomly in any direction while our game only throw the ball  with 45° angles (more randomness is needed!); when a player score, the  ball should be thrown at the him next (and not randomly);</li>
<li>Add a menu;</li>
<li>Handle the end of the game: our prototype doesn’t stop the score;</li>
<li style="text-align: justify;">Add an artificial intelligence: pretty easy, just apply a movement  to the enemy’s bar if the ball is up or down the middle of the bar;</li>
<li>…</li>
</ul>
<h2>Porting our Pong clone to the Xbox 360 and testing it</h2>
<p style="text-align: justify;">To run a game on the Xbox 360, we need to setup a new project, a 360  one. When it comes to port an existing project, XNA allow you to copy  your current project and to create a port with one click. Right click on  your Windows project, and select “Create a Copy of Project for Xbox  360”. Tadam, you’ve successfully ported your game. Note that this “copy”  isn’t really a copy: all the source files are the one from the original  project, they’re just shared between all the ports. This means that if  you modify the Windows project, the changes will be applied to the Xbox  360 version as well. You’ll see that you know have two Game1.cs files  (one in the Windows project, and one in the 360 one) but actually,  there’s only one file, shared. The fact that it appears in all the  projects is a little bit misleading.</p>
<h3>Running the game on your 360</h3>
<p style="text-align: justify;"><em>Please note that the XNA 4.0 beta doesn’t allow deploying games on an Xbox 360 yet. The following process is valid as of  XNA 3.1 and should remain the same with the final XNA 4.0 version. I’ll  update the article once it is released. <strong>Meanwhile, it is advised to skip this part</strong> since if you create an Xbox 360 project inside XNA 4.0 beta, it will prevent you from debugging any other project since you can't set a target device for the Xbox 360 port.<br />
</em></p>
<p style="text-align: justify;">Prior to be able to run code on your Xbox 360, you need your Xbox to  be on the same LAN as your computer (I suppose you know how to setup a  network) and a Creators Club license. This license is mandatory to  publish games on the Xbox and Windows Phone marketplaces and to debug  code on the gaming console. This is because Microsoft host and promote  your games on the marketplaces and it is a good way to regulate the  community by letting in only serious people (plus the fact that  Microsoft want to stay in control of what’s being executed on the 360,  for obvious security reasons). The license has a yearly cost of $99 and  can be acquired from the Xbox Live marketplace or from xbox.com.</p>
<p style="text-align: justify;">There’s a possibility to get a free trial license enabling you to  debug code on your console, but not to sell games (as well as not having  access to premium content and forums on the creators club). You may  find a trial license via a MSDN AA account, if you’re a student/teacher  and if your school has subscribed to the program. If you don’t know if  your school can get you a MSDN AA account, go ask the person in charge  of your school’s computers. Another way to a trial license is to (still)  be student and subscribe to the <a href="https://www.dreamspark.com/default.aspx">Microsoft’s Dreamspark program</a>.</p>
<p style="text-align: justify;">Once you have successfully registered your license, you can start  downloading the XNA launcher to your 360. You’ll find it on the games  marketplace along with the Indie Games. It should be named “XNA Game  Studio Connect”. This program will only run if you’re connected to the  Xbox Live and if the connected GamerTag has a valid creators club  license. Run it and go back to Visual Studio.</p>
<p style="text-align: justify;">You now have to link your PC to your Xbox 360. This is to ensure that  only trusted computer can deploy trusted code to a trusted console. In  Visual Studio, click on the “Add a New Device”.</p>
<p style="text-align: center;"><img class="aligncenter" title="add_device.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/add_device.png" alt="add_device.png" /></p>
<p style="text-align: justify;">Choose to add an Xbox 360 console. Visual Studio should now ask you  to enter a keycode, this code should be displayed on your 360 if you’ve  successfully started the XNA launcher. Enter the code and validate. If  everything went ok, you’re now ready to go and you won’t need to do this  step anymore. If not, check out your network setup.</p>
<p style="text-align: justify;">When you’re ready, select the Xbox 360 as the target of your  application.</p>
<p style="text-align: center;"><img class="aligncenter" title="change_target.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/change_target.png" alt="change_target.png" /></p>
<p style="text-align: justify;">Before launching our Pong game we need to adjust the screen resolution to fit the native Xbox 360 resolution of 1280x720. To do so, we will add a conditional pre-processing code so that the screen resolution code is only considered when the project is compiled to target the Xbox 360 (in the Game1 constructor):</p>
<pre class="brush: csharp;">
#ifdef XBOX360
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
graphics.ApplyChanges();
#endif
</pre>
<p style="text-align: justify;">And run the Xbox 360 project. You now have your game running on your  TV! You can also debug the game like if it was running on the computer  by putting some break points etc. Remote debugging works pretty darn  well.</p>
<p style="text-align: justify;">We now have a problem: we didn’t handle the gamepad so the game isn’t  playable. The only thing you can do, is to press the “back” button to  exit the game. The update is simple to achieve:</p>
<pre class="brush: csharp;">
// handling keyboard and gamepad inputs
if (Keyboard.GetState().IsKeyDown(Keys.E) // E key down ?
      || GamePad.GetState(PlayerIndex.One).DPad.Up == ButtonState.Pressed)
      blueBar.Y -= 10; // move the blue bar up
else if (Keyboard.GetState().IsKeyDown(Keys.D) // D key down ?
      || GamePad.GetState(PlayerIndex.One).DPad.Down == ButtonState.Pressed)
      blueBar.Y += 10; // move the blue bar down
if (Keyboard.GetState().IsKeyDown(Keys.Up) // Up key down ?
      || GamePad.GetState(PlayerIndex.Two).DPad.Up == ButtonState.Pressed)
      redBar.Y -= 10; // move the red bar up
else if (Keyboard.GetState().IsKeyDown(Keys.Down) // Down key down ?
      || GamePad.GetState(PlayerIndex.Two).DPad.Down == ButtonState.Pressed)
      redBar.Y += 10; // move the red bar down
</pre>
<pre class="brush: csharp;">
// handling ball initialization
if (Keyboard.GetState().IsKeyDown(Keys.Space)
      || GamePad.GetState(PlayerIndex.One).Buttons.Start == ButtonState.Pressed)
      InitBall();
</pre>
<p>Here it is, we can now play with two gamepad and our Xbox 360 port is  complete!</p>
<h2 style="text-align: justify;">Serious business: porting our game to Windows Phone 7</h2>
<p style="text-align: justify;">As we did for the Xbox 360 port, create copy for Windows Phone of  your project. If you try to run the game in the emulator, you’ll most  likely end up with a cornflower blue screen. This means our game has  incompatible graphics properties. To fix this, we need to switch to  Windows Phone 7 specific parameters, namely a screen resolution of 800x480, a refresh rate of 30 frames per second, forcing the landscape mode (playing our Pong in lortrait wouldn't be natural for a Pong game) and updating the referenced assemblies. But we don’t want to  apply these changes to our other ports. Fortunately, there’s a way to  write code that we only be considered by a specific port thanks to  preprocessor statements (like we did for the Xbox 360 port). The changes will be applied in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game%28v=XNAGameStudio.40%29.aspx">Game1</a> constructor:</p>
<pre class="brush: csharp;">
public Game1()
{
      graphics = new GraphicsDeviceManager(this);
      Content.RootDirectory = &quot;Content&quot;;

#if XBOX360
      graphics.PreferredBackBufferWidth = 1280;
      graphics.PreferredBackBufferHeight = 720;
#endif

#if WINDOWS_PHONE
      // Frame rate is 30 fps by default for Windows Phone.
      TargetElapsedTime = TimeSpan.FromTicks(333333);

      // Pre-autoscale settings.
      graphics.PreferredBackBufferWidth = 800;
      graphics.PreferredBackBufferHeight = 480;
      graphics.IsFullScreen = true; // so the battery meter and other stuff are not displayed
      graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft; // forcing our game to support only one landscape mode so the screen doesn't rotate if the two players are shaking the device
#endif

      graphics.ApplyChanges();
}
</pre>
<p style="text-align: justify;">Note that we also set the game to run in full screen mode. On Windows  Phone 7, it means that the battery status will not show up over the  game. If it wasn’t in full screen, the battery status would hide our  score display.</p>
<p style="text-align: justify;">We also need to update the references. Unfold the references of the Windows Phone 7 project and delete all references with a warning icon (Avatar, Net, Storage, Video, XACT) and add a new reference to the project: Microsoft.Xna.Framework.Input.Touch. Last thing to do, adding a conditional statement to include this new reference only to our WP7 port (after the other using statements):</p>
<pre class="brush: csharp;">
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif
</pre>
<p style="text-align: justify;">Try to run the game and look at our super pong.</p>
<p style="text-align: center;"><img class="aligncenter" title="emulator.png, Jun 2010" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/images/emulator.png" alt="change_target.png" /></p>
<p style="text-align: justify;">You may notice that the inputs don’t work. Some Windows Phone 7  devices come with a physical keyboard, but since some are not, XNA  designer choose to not support keyboards as an input method so that  games are experienced the same way on all Windows Phone 7 devices. The  only method we have at our disposal if the multi-touch screen.</p>
<p style="text-align: justify;">First, we need to design some sort of interaction scheme: to move the  blue bar, we’ll consider the upper left and lower left corners of the  screen as our up and down buttons; the opposite corners will be used to  move the red bar; to initialize the game, we’ll consider a tap on the  middle of the screen. The following code comes right after the inputs  handling in the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.update%28v=XNAGameStudio.40%29.aspx">Update</a> method:</p>
<pre class="brush: csharp;">
#if WINDOWS_PHONE
// for each detected touch
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation touchLocation in touchCollection)
{
      // upper left corner touche detection
      if (touchLocation.Position.X &lt; 50
            &amp;&amp; touchLocation.Position.Y &lt; 50)
            blueBar.Y -= 10; // move the blue bar up
      // lower left corner
      else if (touchLocation.Position.X &lt; 750
            &amp;&amp; touchLocation.Position.Y &gt; 50)
            blueBar.Y += 10; // move the blue bar down

      // upper right corner touche detection
      if (touchLocation.Position.X &gt; 430
            &amp;&amp; touchLocation.Position.Y &lt; 50)
            redBar.Y -= 10; // move the red bar up
      // lower right corner
      else if (touchLocation.Position.X &gt; 750
            &amp;&amp; touchLocation.Position.Y &gt; 430)
            redBar.Y += 10; // move the red bar down

      // ball touch
      if (touchLocation.Position.X &lt; 420
            &amp;&amp; touchLocation.Position.X &gt; 380
            &amp;&amp; touchLocation.Position.Y &lt; 260
            &amp;&amp; touchLocation.Position.Y &gt; 220)
      InitBall();
}
#endif
</pre>
<p style="text-align: justify;">This is a quite rough technique. If you’d like to better use the  touch screen, try to use the <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.touch.touchlocation.trygetpreviouslocation%28v=XNAGameStudio.40%29.aspx">TryGetPreviousPosition</a> method of a <a hreflang="en" href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.touch.touchlocation%28v=XNAGameStudio.40%29.aspx">TouchLocation</a> to follow a finger along the left or  right corner of the screen and make the bar follow the gesture.</p>
<p style="text-align: justify;">By the way, our Pong clone is now fully playable on Windows Phone 7!  And that’s it.</p>
<h1>Conclusion</h1>
<p style="text-align: justify;">Your Pong clone is now (almost) finished and working on three  different platforms. There are still many aspects to fine tune, but this  up to you now. You should have the background to do basic 2D games.</p>
<p style="text-align: justify;">Hopefully, you noticed that I’m referring to the MSDN online  documentation as much as possible. This was a secret message telling you  that reading the documentation can save you much time and avoid you  some useless search on the internet. If you still have problems, search  on the creators club forum, or expose your problem on the forum.</p>
<p style="text-align: justify;">I hope that you enjoyed following this tutorial and don’t hesitate to  give me some feedback about it.</p>
<p><strong>Download sample code:</strong> <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/Altenburger/PongCode.zip">PongCode.zip</a> (public domain)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/08/programming-your-first-xna-4-game-pong/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
