All posts in XNA

At the end of Part 2 of this series, we had our character running in place. image_thumb5

This was done through the Update method of the XNA Game class processing when the frame should change, and then the Draw method called the appropriate SpriteBatch.Draw method to draw the current frame. Here is the source code that we’ll start with and build upon in this post.

http://www.billreiss.com/wp-content/uploads/2012/04/MyFirstGame_part2_completed.zip

This is a fairly short one, we just need to build upon some of the topics so far to build a platform for our player to run on, and then we’ll be done with Step 1 (“Draw Stuff”) of building an XNA game.

Here is the platform image:

Platform

Click on the image and then select to save it to your computer. Call it platform.png.

Now just like with the player image from Part 1, add an existing item to the content project. This time we’ll use platform.png. Now we want to do exactly the same thing we did before, adding a field to store the texture, and a couple of others to store the animation state:

Texture2D platform;
float platformOffset = 0;
float platformScrollSpeed = 200;

And in LoadContent we’ll load it:

platform = Content.Load<Texture2D>("platform");

And then in the Draw method we’ll draw a row of these under the player:

for (float f = -platformOffset; f < 800; f += platform.Width)
{
    spriteBatch.Draw(platform, new Vector2(f, 300 + runFrameHeight),
        Color.White);
}

Notice that you can use the same texture multiple times when drawing. This is starting to look better:

image

Now to give an illusion of motion we can scroll the platform by changing the platformOffset in the Update method based on the speed and the elapsed time:

platformOffset += platformScrollSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (platformOffset > platform.Width) platformOffset -= platform.Width;

Every time we scroll more than the width of a block, we’ll subtract the width of the block from the offset so that the number doesn’t keep getting bigger, but since we shift by exactly the width of one block the motion looks smooth and continuous.

Run it again. You should now see the running man and the scrolling platform. Not bad for less than 40 lines of code.

Here is the source code for the project at this point:

http://www.billreiss.com/wp-content/uploads/2012/04/MyFirstGame_part3_completed.zip

In the next post we’ll start Step 2 and look at how to handle input in XNA.

In the last post we created a new XNA game solution for Windows Phone, added an image to draw to the content project, loaded it, and drew it to the screen. We also explored how to remove the taskbar and taking advantage of hardware scaling for performance. At the end of Part 1 we were somewhere around here:

image

Here is the source code for the starting point for this post:

http://www.billreiss.com/wp-content/uploads/2012/04/MyFirstGame_part1_completed.zip

Now let’s take it a step further and only draw a part of the image so that we only see one frame at a time.

This image that we’re drawing (called a texture in XNA) is known as a sprite sheet and it’s copied from the Platformer sample that ships with XNA. A sprite sheet is an image that contains multiple frames of motion for a sprite or sprites.

When using the graphics processor (GPU) to draw like XNA does, it’s more efficient to use a single texture and draw only what you need from it instead of loading a texture for each frame and swapping them. It’s even more efficient to pack all of your textures into a single texture and with each draw call draw only what you need. This is because there is significant overhead in telling the graphics processor to use a different texture.

The sprite sheet that we’re using is the texture used when the character is running. There is one part of the texture for each frame in the running animation and by drawing these in sequence we can get the illusion that the character is running.

TIP: If creating your own character, you can draw over an existing sprite sheet, it’s easy to find these on the internet. By drawing over an existing one it’s easier to draw the character in the correct positions. Instead of figuring out what positions you need to give the illusion of running you can just focus on the artwork.

To draw only a single frame, let’s add fields to store the current frame and the frame height and width:

int playerCurrentFrame = 0;
int runFrameWidth = 0;
int runFrameHeight = 0;

In the LoadContent method we’ll take the loaded player texture and calculate the frame width and height from it:

player = Content.Load<Texture2D>("run");
runFrameWidth = player.Width / 10;
runFrameHeight = player.Height;

Then in the Draw method, we’ll change the Draw call as follows:

spriteBatch.Draw(player, new Vector2(80, 300),
    new Rectangle(playerCurrentFrame * runFrameWidth, 0,
    runFrameWidth, runFrameHeight), Color.White);

This is a different overload of the Draw method, there are a lot of them. Take some time to look at all of the different SpriteBatch Draw calls since the right overload can save you a lot of effort.

Run the app again. Now you should only see one frame.

image

Now if we want to animate the character, we can do this with the Update method.

playerCurrentFrame++;
playerCurrentFrame = playerCurrentFrame % 10;

Since there are 10 frames in this animation, the frame count is incremented every time the Update method is called, and when it gets to 10 it starts over. Run the app again.

Looks like he’s running a little fast, so let’s slow him down a bit. Instead of updating the current frame every time Update is called, it’s do it based on a time value. Add the following fields to the Game class:

double playerAnimationDelay = .05;
double currentPlayerAnimationDelay = 0;

And in the Update method, the code changes as follows:

currentPlayerAnimationDelay += gameTime.ElapsedGameTime.TotalSeconds;
while (currentPlayerAnimationDelay > playerAnimationDelay)
{
    playerCurrentFrame++;
    playerCurrentFrame = playerCurrentFrame % 10;
    currentPlayerAnimationDelay -= playerAnimationDelay;
}

Now by changing the playerAnimationDelay value you can control exactly how fast your character animates. He’s also facing the wrong way for our needs, so change the spriteBatch Draw call as follows:

spriteBatch.Draw(player, new Vector2(80, 300),
    new Rectangle(playerCurrentFrame * runFrameWidth, 0,
    runFrameWidth, runFrameHeight),
    Color.White, 0, Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0);

Cool now he should be facing the right way and running at a slower speed.

image

http://www.billreiss.com/wp-content/uploads/2012/04/MyFirstGame_part2_completed.zip

In the next post we’ll look at giving our character something to run on.

To get started developing games for Windows Phone you need to have the Windows Phone 7.1 SDK installed. You can get it here. Once you’ve installed this you’ll also want the 7.1.1 update, which you can get here. The update requires the 7.1 SDK to be installed first.

If you’re installing on Windows 8, check out my post about installing the Windows Phone development environment on Windows 8.

In this post we’ll start creating a new XNA game, and begin with the most visible step, and the one people thing of first when they think of game development. We’ll draw something to the screen.

Step 1: Draw Stuff

Let’s start by creating a new XNA game project. Run Visual Studio 2010 with Windows Phone SDK 7.1.1 installed. Select File -> New -> Project and select XNA Game Studio 4.0 and choose Windows Phone Game. We’ll call our game MyFirstGame.

image

Choose to target Windows Phone 7.1, there’s no real reason to target 7.0 anymore.

image

With 7.1 there are many new capabilities with the most important for games being fast app switching, or the ability to resume your game via the back button without reloading everything.

This creates two projects, one for your XNA game and one for your game’s content. Content projects contain any assets for your game, including images, sound effects, 3D meshes, shaders, and level data. Assets that are added to the content project are compiled to a proprietary XNB format that XNA understands so that XNA doesn’t need to know how to deal with the various asset types when the game is running, the heavy lifting is done at compile time.

image

The solution that is generated is a fully functioning game. It doesn’t do a whole lot yet, but helps you to know where your code needs to be added. Run the game in the emulator and you will see the “blue screen of life”, by default you get a Cornflower Blue background and not much else, but at least the back button works.

Run the game and show what it looks like so far.

image

Now one thing you may notice is that the game doesn’t fill the entire screen. It’s kind of hard to see in the emulator, but by default the system tray is displayed, and your game is scaled (letterboxed and preserving aspect ratio) in the remaining space.

To remove the system tray, in the game project, go to Game1.cs. and add the following to the Game1 constructor:

graphics.IsFullScreen = true;

Run the app again and you should see that it fills the entire area.

image

Now it’s time to draw something.

Save this image to your computer. You can do this by clicking on it and then right clicking and save the image. Call it run.png.

Run

In the content project, select Add Existing Item and go to the Assets folder and pick run.png from wherever you saved it to.

Add a field to the Game1 class:

Texture2D player;

and in the LoadContent method after the TODO comment add the following:

player = Content.Load<Texture2D>("run");

The text “run” is the asset name of the content we want to load. By default this is the filename without the extension, but you can change this in the properties pane for the content item.

In the Draw method, add the following to draw the texture:

spriteBatch.Begin();
spriteBatch.Draw(player, new Vector2(80, 300), Color.White);
spriteBatch.End();

When drawing using SpriteBatch, you need to make sure that for every Begin of the SpriteBatch that you have a corresponding End. You should also limit the number of Begin and End calls that you do, but you can do as many Draw calls as you want between a single Begin and End. It’s not a big deal to have a few Begins and Ends but don’t have one per draw call, since most of the overhead when drawing is in the End call because this is where the graphics are actually rendered.

Run the game. It should look like this:

image

One thing you’ll notice is that the texture is being drawn sideways.

By default XNA apps are in landscape mode on the phone. You can change this by adding the following to the Game constructor:

graphics.PreferredBackBufferWidth = 480;
graphics.PreferredBackBufferHeight = 800;

 

By specifying a height that is larger than the width, XNA automatically determines that it should be in portrait mode.

image

There’s another neat trick when it comes to the back buffer width and height and XNA on the phone. The phone resolution of 800×480 is almost 400,000 pixels. Drawing this many pixels can potentially impact the performance of your game, especially if drawing a lot of big textures. You can automatically scale the game using hardware scaling by specifying smaller values for the preferred width and height. By specifying values of half the native size you end up drawing one quarter of the pixels that you do in full resolution. Of course, all of your textures will be scaled up too, so you’re sacrificing level of detail for performance, but if you need it, it’s good to have it available. Change the constructor code as follows:

graphics.PreferredBackBufferWidth = 240;
graphics.PreferredBackBufferHeight = 400;

 

Run the app and it should look like this:

image

Everything is now double size. Now that we’ve had fun with orientation and scaling, let’s remove the code to set the width and height and go back to displaying it in landscape mode. We can also rotate the emulator so that it’s displaying in landscape mode on the screen.

image

Here is the source code for everything up to this point: http://www.billreiss.com/wp-content/uploads/2012/04/MyFirstGame_part1_completed.zip

In the next post we’ll look at drawing a single frame of this image and how to draw different frames over a period of time.

I recently revamped my Intro to XNA presentation so that I could present something fresh at the Orlando Code Camp. I have this problem where I don’t like to take the easy path and keep presenting the same thing.

When I’ve presented about game development recently I’ve had the impression that most of the attendees thought it was cool but it was something that they couldn’t actually do.

Because of this, I decided to try to make it more approachable and break down game development into its core parts and if you take them one at a time it’s not that scary.

So these are the steps I broke it down to:

  • Draw stuff
  • Handle and act on input
  • Play sounds
  • Monetize
  • Stick with it!

You can find my presentation slides and demos here: http://www.billreiss.com/wp-content/uploads/2012/04/XnaWp7GameDev.zip

I’ve decided to turn this presentation into a series of blog posts, so stay tuned and I hope you enjoy the posts as much as I enjoyed putting it together. When we get to the end it will look something like this:

image

I’ve done a bunch of sessions over the years on beginning XNA game development but for the Orlando Code Camp I did a major revamp of the presentation and created a new set of demos which build upon each other to make a great start to a game, at least as much as can be covered in an hour.

I have packaged up the powerpoint presentation, very detailed demo script, and source code and made it available here:

http://www.billreiss.com/wp-content/uploads/2012/04/XnaWp7GameDev.zip

The topics include drawing 2D sprites, frame based animation, handling input, playing sounds, and using the Microsoft ad control.

Feel free to reuse all or part of the presentation and demos, my only request is that if you re-present or publish anything that you provide proper attribution and a link to http://www.billreiss.com

I’ve been running the Windows 8 Consumer Preview on my personal laptop as my primary (and only) OS since it was released at the end of February, and for the most part it’s been a good experience. There hasn’t been much that I miss since almost everything works. The one major exception to this was that the Windows Phone emulator wouldn’t run. You could still compile your apps and deploy to a device, but not having the emulator was a major limitation, especially since I will presenting at the Orlando Code Camp this weekend and one session is on Windows Phone so last night I broke down and set up a dual boot of Windows 7. It figures that they day after I did this that Microsoft would release support for the Windows Phone emulator in Windows 8 Consumer Preview.

This support comes in the form of the official release of the Windows Phone SDK 7.1.1, an update to the 7.1 SDK which allows you to develop and test apps for 256MB “Tango” Windows Phones.

So here are the steps I followed to get the environment up and running.

1. Install Windows 8 Consumer Preview (duh) – Can’t really go much further without this, you can download it now. In order to run the emulator and have it perform well, you’ll want to either install it as your primary OS or dual boot from a VHD. You don’t want to run in Virtual PC or something similar because the emulator takes advantage of hardware acceleration.

Note that if you install it as your primary OS you’re better off installing it clean instead of upgrading since there was an issue with registering to develop Windows 8 Metro Style apps after upgrading from Windows 7, not sure if this is still an issue, if you know this is fixed please mention in the comments and I’ll update this post.

Update: Reordered steps 2 through 4, and made 3 and 4 optional. Ginny Caughey pointed out that Windows Phone SDK 7.1 will install Visual Studio 2010 Express and related updates if Visual Studio is not installed.

2. Install the Games for Windows Marketplace Client. If you don’t do this, XNA Game Studio (which is included in the Windows Phone SDK) will not install properly.

3. Install Visual Studio 2010 (optional, the Windows Phone SDK will install Express if Visual Studio 2010 not installed).

4. Install Visual Studio 2010 Service Pack 1 (only required if you do step 3).

5. Install the Windows Phone SDK 7.1. Yes, that’s right, you need to install 7.1 first, the Windows Phone 7.1.1 SDK requires it.

6. Install the latest Async CTP for Windows Phone (optional) This will make it easier to create cross platform Win8 Metro/Windows Phone libraries (where the code can be shared). Thanks to Jay Kimble for this tip!

7. Install the Windows Phone SDK 7.1.1 Update.

8. Profit! You should now be ready to go. The 7.1.1 SDK also includes an updated Microsoft Advertising control which is supposed to fix some issues.

9. While you’re at it, install Visual Studio 11 Beta. You can’t develop Windows Phone apps with it yet, but it’s a great time to get started writing Windows 8 Metro Style apps. Visual Studio 2010 and Visual Studio 11 Beta will happily coexist.

Just when Microsoft was getting to the point where it looked like XNA was going to be the unifying game development technology across platforms the BUILD conference came along and they dropped the bombshell that XNA wasn’t an option for creating games to sell in the new Windows 8 Store. This seemed crazy at the time, and I still think it is since Microsoft is losing out on all of the games developed for Xbox Live Indie Games and Windows Phone over the last few years. These would give an instant boost to the fledgling store and I’m sure that many of the developers that created these games would do what it takes to move them over.

There are no indications that XNA will have any new releases, and some key team members have moved on, with the latest being Shawn Hargreaves who is now on the Windows Phone team working on undisclosed projects.

Michael Klucher, a key XNA team member who was involved in the original port of XNA to Zune among many other things moved on about a year ago.

GDC is around the corner, and I would expect to hear a lot more about Microsoft’s game development strategy going forward but I’d be very surprised to hear much about XNA.

It seems that Microsoft is unwilling to take some short term gains instead focusing on where they want the technology to go moving forward. Here is a quote from Shawn Hargreaves which I think sums it up nicely:

If you want to make games for Windows 8 Metro, XNA is not an option. Take your pick out of C++/D3D, C++/XAML, C#/XAML, Javascript/HTML5, or one of the third party C#/D3D wrappers.
If you want to make games for Windows Phone or XBLIG, XNA remains your best option, just like it always has been.
If you want to make games for Windows Classic (XP, Vista, Win7, Win8 desktop mode), you can use whatever programming technologies you like, including XNA, just like always.
Hopefully that ends your confusion?

One question mark is still Windows Phone 8, although XNA games will run on Windows Phone 8, there are also indications that Microsoft will be adding C++ to the options for developing games for Windows Phone 8.

So what will I be doing? I have an open source .NET 2D game framework called Frolic that I’ve been working on which abstracts out the rendering technologies to make it easier to adapt to these changing times and to avoid a lot of the lock in to a particular technology. It currently can use either Silverlight or XNA for its rendering and I have a prototype working on WinRT. I’ll also be looking at how I can use some of the concepts I developed in Frolic in C++ for Metro Style apps. Finally, I’ll be listening closely to what comes out of GDC and the Mobile World Congress related to Microsoft game development strategies.