Home Game Development Windows Phone 7 XNA Cookbook

Windows Phone 7 XNA Cookbook

By Zheng Yang
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Jump into Windows Phone Developer Tools and XNA Game Studio 4.0
About this book
Developing games for Windows Phone 7, a new mobile platform, is your big chance to impact the world of mobile games. The XNA 4.0 for Windows Phone 7 integrates a lot of capabilities from software and hardware for you to create incredible games. The next generation of mobile games will be built by you. Windows Phone 7 XNA Cookbook is the best choice for you to make a game on Windows Phone 7. The book helps you to master the indispensable techniques to create your games using XNA 4.0. From the basics such as animating a 2D sprite and interacting with the customized graphical user interface to the more challenging such as 3D graphic rendering and collision detection. This comprehensive cookbook covers all the essential areas of XNA game development for Windows Phone 7, such as approaches to control the sensors, gestures and typical kinds of cameras. We also have recipes for sprite animation, texture rendering, and graphical user interface development that will give you a powerful tool to work with 2D effects. After this we move onto the more juicy stuff with recipes covering 3D graphic rendering and collision detection, and major ways to improve your loading efficiency. You will also work with Xbox live so you can take your game global. Finally, no mobile game development book would be complete without a look at performance optimization to make your games run faster. Windows Phone 7 XNA Cookbook will equip you with the firepower to rock the game world.
Publication date:
February 2012
Publisher
Packt
Pages
450
ISBN
9781849691208

 

Chapter 1. Jump into Windows Phone Developer Tools and XNA Game Studio 4.0

In this chapter, we will cover:

  • Installing Windows Phone Developer Tools

  • Creating your first Windows Phone XNA application

  • Deploying your game on an emulator or device

  • Getting familiar with orientation

  • Using DrawableComponent and GameServices

Introduction

Windows Phone 7 is a new platform from Microsoft. It succeeds the Windows Mobile and combines the UI features of Microsoft Zune. Windows Phone is a consumer-oriented platform while Windows Mobile is more about business. On Windows Phone 7, or the latest release of Mango, you have more flexibility to develop with the hardware using the user design tool Microsoft Expression Blend and Design. Besides the approach to develop regular applications, Windows Phone also provides the capability to make amazing mobile games around Xbox Live based on XNA Game Studio 4.0. Unlike the previous version, XNA 4.0 is included in a tool collection called Windows Phone Developer Tools utilized for producing Windows Phone games. With the tools and Visual Studio 2010, it will be easy to have and employ the Windows Phone application to the device. As a bonus, if you were a marketing-oriented developer, the App Hub would be an attractive place for promoting your applications and making income. In this chapter, you will discover the most useful and common features of XNA 4.0 for Windows Phone. Even if you are relatively new to Windows Phone 7 and XNA 4.0, this chapter should get you up and running. Can't wait to begin Windows Phone 7? Let's begin.

 

Introduction


Windows Phone 7 is a new platform from Microsoft. It succeeds the Windows Mobile and combines the UI features of Microsoft Zune. Windows Phone is a consumer-oriented platform while Windows Mobile is more about business. On Windows Phone 7, or the latest release of Mango, you have more flexibility to develop with the hardware using the user design tool Microsoft Expression Blend and Design. Besides the approach to develop regular applications, Windows Phone also provides the capability to make amazing mobile games around Xbox Live based on XNA Game Studio 4.0. Unlike the previous version, XNA 4.0 is included in a tool collection called Windows Phone Developer Tools utilized for producing Windows Phone games. With the tools and Visual Studio 2010, it will be easy to have and employ the Windows Phone application to the device. As a bonus, if you were a marketing-oriented developer, the App Hub would be an attractive place for promoting your applications and making income. In this chapter, you will discover the most useful and common features of XNA 4.0 for Windows Phone. Even if you are relatively new to Windows Phone 7 and XNA 4.0, this chapter should get you up and running. Can't wait to begin Windows Phone 7? Let's begin.

 

Installing Windows Phone Developer Tools


Microsoft XNA Game Studio 4.0 is included as part of the Windows Phone Development Tools. It is a set of software tools that can be used by developers to create games for Windows Phone 7, Xbox LIVE Indie Games, and Windows. The entire tool package contains:

  • Visual Studio 2010 Express for Windows Phone

  • Windows Phone Emulator Resources

  • Silverlight 4 Tools For Visual Studio

  • XNA Game Studio 4.0

  • Microsoft Expression Blend for Windows Phone

Installing the toolset is the first step of your Windows Phone XNA game programming journey. In this recipe, you will learn how to set up the handy programming environment.

How to do it...

The following steps show you how to install the Windows Phone Developer Tools.

Visual Studio 2010 is a required tool for XNA game development. If you do not have it:

  1. 1. You can download it from http://www.microsoft.com/express/downloads/.

  2. 2. Choose Visual Studio 2010 Express for Windows Phone, and the main page for downloading the tool will show up. Then follow the on-screen guidance to finish the downloading and installing process.

  3. 3. Once web installation begins, your computer must connect to the Internet to completely download the installer.

The following are the steps for installing XNA Game Studio 4.0 with Windows Phone Developer Tools:

  1. 1. Navigate to http://create.msdn.com/en-us/resources/downloads to download XNA Game Studio 4.0.

  2. 2. Click on the link to download XNA Game Studio 4.0 you will see a new download page.

  3. 3. Follow the on-screen guidance to finish the downloading and installing process.

Now, all the preliminary work of XNA game development is done.

 

Creating your first Windows Phone XNA application


After installing the Visual Studio 2010 and Windows Phone Developer Tools, I am sure you cannot wait to begin your first Windows Phone XNA application. In this section, you will start the charming journey, learn about the basic and important code of XNA, and how this code works. It is easy to get started.

How to do it...

  1. 1. Once the XNA Game Studio 4.0 is successfully installed, click the top-left menu item File | New | Project. The XNA and Windows Phone Game Project Template will show up in the New Project window, as shown in the following screenshot:

  2. 2. In the New Project pop-up window, select Visual C# from the left-hand side pane, and then choose the Window Phone Game project template.

  3. 3. Next, give a Name, Location, and Solution name to the project. Solution name will be the same as your project name by default.

  4. 4. Finally, click OK to let Visual Studio 2010 automatically create the Windows Phone Game project for you.

  5. 5. The generated Windows Phone Game project WindowPhoneGame1 automatically has the main game functionalities; the other generated associate project WindowsPhoneGame1Content is responsible for the game content:

How it works...

The basic methods in Game1 class residing in Game1.cs of your first Windows Phone Game project WindowsPhoneGame1 are very useful. They are clear and easy to understand according to the method name and comments. This template is your first gift, and you will find new ways here to speed up your development. The complete game skeleton presents several significant methods:

  • Game1() constructor method: The constructor, called before the Initialize method, is a typical one found in any class and, therefore, has the same meaning used to set default values to required elements. For example, instantiating the graphics device manager, define the game frame rate, and so on.

  • Initialize() method: Sets default and preliminary values to your game, queries and initializes user-based information, such as starting positions and frame updating rate.

  • LoadContent() method: Loading all game content may include images, sprite sheet, sounds, models, and so on. In XNA game development, all artwork loading should be done in the LoadContent() method before the Update() and Draw() methods.

  • UnloadContent() method: Unloads all game content and content managers, a controller of all contents with loading and unloading when the objects used in your game need specific disposing or unloading.

  • Update() method: This method is very important when your game is running. It performs ongoing game logic such as calculating current positions, physics, collisions, and states; collecting the input information from various input devices; updating animations. Note that at this stage you only decide upon the current frame to display. Drawing is not performed because all drawing should be done by the Draw() method. It updates the camera, refers to the update animation note, plays audios, and so on. The Update() method updates the game logic, which will make your game more fun depending on the interaction with the game data, such as player life, experience value, and score.

  • Draw() method: As the method name implies, in this method your work is to render all the graphics, including 2D and 3D views, onto the screen to make the game data visible, so that players can experience the real game world.

For the recipes in the following chapters, we will be revising this code many times from different perspectives. When you build the project and run it, you will see an emulator window with a solid blue background by default. Your first XNA Windows Phone Game is done, although it is just a blank screen as shown in the following screenshot. Isn't it easy?

 

Deploying your game on an emulator or device


In the previous recipe, you completed your first XNA Windows Phone Game. In this recipe, you will learn more details on how you can deploy your Windows Phone application on the emulator or device.

Getting ready

When you build the Windows Phone 7 project, in the Output window, you will see the building messages similar to the following screenshot:

Here, you may be curious about Xap packaging. A .xap is a simple file similar to a .zip file, renamed to .xap. It contains the app and all relevant dependencies. There are a number of possible .xml files that could be included inside .xap, such as required security access level.

For better understanding, you could change the extension from .xap to .zip and use WinZip to extract the .zip file. Several necessary information will be presented such as the content directory with .xnbl binary files, dependency files with .dll extension, configuration xml files, an xml file named AppManifest, and so on. The xaml file is very important for Windows Phone 7 applications. This file provides the emulator or device with the application start-up information, the entry point, and the dependency.

How to do it...

After project building, the next step is to deploy your Windows Phone 7 XNA application to the device or emulator. The direct method is by using Visual Studio Deploy Options, as shown in the following screenshot:

In the drop-down list, you could choose Windows Phone 7 Emulator or Windows Phone 7 Device. If you are a member of App Hub, which is free for students and is charged at $99 for regular users, you can successfully deploy to the real device or the emulator. Otherwise, you can choose the emulator as the test platform.

If using an emulator, Visual Studio 2010 will boot the emulator first, and then initialize (this may take a long time if the user's PC does not have hardware virtualization enabled.) The next step is to copy the .xap file to the emulator and execute it.

If using the device for the first time, the preparation work is a little complex (I promise this is only once), as follows:

  1. 1. The first step is to check if the Zune software is installed on your computer. (If the Zune software has not been installed, you can download it from http://www.zune.net/en-US/products/software/download/default.htm).

    Besides this, you need to make sure that your phone has loaded the proper device drivers. At this point, you are now ready to start publishing your custom app to the phone.

  2. 2. Next, you will need to click Start | All Programs | Windows Phone Developer Tools | Windows Phone Developer Registration. You will see a screen as shown in the following screenshot. You can use the Windows Live ID that you linked to. You can also unregister the device.

    • Wow! All the preparation work is over now. It is now time for the final step, that is deploy. Open Visual Studio 2010 and choose Windows Phone 7 Device in the drop-down list.

    Note

    If you deploy the application to your phone device and not the emulator, the phone must be turned on and unlocked (displaying the start/home tiles screen). To debug on the phone you just need to hit Run (F5).

  3. 3. Run the application.

  4. 4. When you have done this, on your Windows Phone, you will need to slide over to the Application list page with a right direction button at the top-right, and search for the application you named before. Touch it and run the application.

 

Getting familiar with orientation


The orientation for Windows Phone 7 stands for different directions, landscape or portrait. By default, XNA programs for Windows Phone 7 run in landscape mode. This recipe discusses how to transcend those defaults and explores other issues involving screen size and events.

Getting ready

The following two screenshots demonstrate the different modes of Windows Phone 7. The image on the left indicates the landscape mode with a resolution of 800 * 480 and the screenshot to the right shows the portrait mode with a resolution of 480 * 800. By default, XNA for Windows Phone is set up for a landscape orientation. If you prefer designing your game for a portrait display, it's easy to do.

How to do it...

Now, let's create a new Windows Phone Project named WindowsPhoneOrientation. Find the class Game1 in Game1.cs. You can also rename the filename and class name to any other name you like:

  1. 1. Add the following line in the class field:

    Texture2D arrows;
    
  2. 2. Next, find the Game1() constructor and insert the following lines:

    graphics.SupportedOrientations =
    DisplayOrientation.Portrait |
    DisplayOrientation.LandscapeLeft|
    DisplayOrientation.LandscapeRight;
    // Switch to full screen mode
    graphics.IsFullScreen = true;
    

    Note

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  3. 3. Load the following content in the LoadContent() method:

    // Load the arrow content.
    arrows = Content.Load<Texture2D>("Windows Phone Arrow");
    
  4. 4. In the next step, add the following lines to the Update() method:

    graphics.SupportedOrientations = DisplayOrientation.Portrait | DisplayOrientation.LandscapeLeft| DisplayOrientation.LandscapeRight;
    
  5. 5. Find the Draw() method and insert the following code:

    spriteBatch.Begin();
    // Draw the directions texture centered on the screen
    Vector2 position = new Vector2(
    GraphicsDevice.Viewport.Width / 2 - arrows.Width / 2,
    GraphicsDevice.Viewport.Height / 2 - arrows.Height / 2);
    spriteBatch.Draw(arrows, position, Color.White);
    spriteBatch.End();
    
  6. 6. All done! Build the project and run it in the emulator. Change the orientation by clicking on the change buttons located at the top-right of the emulator. If the application runs well, you will see three different presentations, as shown in the following screenshots:

How it works...

In step 1, Texture2D represents the images, SpriteFont represents text, showing the different directions.

In step 2, in class constructor, set the SupportedOrientations attribute of GraphicsDeviceManager (here is graphics) to DisplayOrientation options: Portrait, LandscapeLeft, and LandscapeRight enables the Windows Phone to adjust the resolution according to the different orientations.

In step 4, you may be curious about the code. Why do we have to set SupportedOrientation in a similar way as we have in step 2? The reason is that the responsibility of the Update() method is to update the game status, game logic, input, and so on. Here, for Windows Phone Orientation, the Update() method needs to listen to the changes in the device orientation. The method should react to any change between Landscape or Portrait mode. Once the orientation meets the settings of the DisplayOrientation, the GraphicsDeviceManager(graphics) will apply the change to the default device. Again, when the Update() method completes its work in every cycle, by default, the XNA will call the Draw() method to render the new face of the game.

In step 5, the snippet provides a way for placing the image or texture in the middle of the screen. Half of the viewport just makes the top-left of the image locate at the center of the screen. We need the center of the image to replace the image top-left point, therefore, we should subtract half of the width and length of the image. Then the SpriteBatch.Draw() method renders the image on the Windows Phone screen. Notice that all the position manipulations and sprite drawing methods must be placed between the SpriteBatch.Begin() and SpriteBatch.End() methods.

 

Using DrawableComponent and GameServices


In XNA game programming, a lot of built-in or customized objects exist in the game data container. When the quantity increases and it becomes onerous for you to manage, you will need a service to make your XNA programming life easier; this recipe will give you the necessary guidance.

Getting ready

In an XNA application, some parts or objects of your game need to be separately updated or drawn, such as radar, player, or monster. Within your XNA game, you need to create separate defined classes for the substances, then build an instance of one of them, initialize it, update it, and finally, render it to the screen within the Draw() method reserved for game loop calling. Hence, you need to define these kind of classes, which have their own Initialize(), Load/UnloadContent(), Update(), and Draw() methods, so that you can easily call them in the XNA game loop.

Again, it is better to inherit these classes from GameComponent, which promises your classes are added to the Component List, Game.Component a global objects manager in XNA application. It simplifies the management of the game shared objects to the delight of the XNA programmer

Furthermore, if you are sure your separated class has the rendering ability, DrawableGameComponent could be the best choice for you because the overridden Draw() method will be called automatically from DrawableGameComponent.

How to do it...

  1. 1. As an example, define a Radar class inherited from DrawableGameComponent:

    public class Radar : DrawableGameComponent
    {
    . . .
    Rectangle destRec;
    Rectangle playerPositionRec;
    Vector2 playerVector;
    List<Vector2> enemiesPosition;
    Texture2D texture;
    SpriteBatch spriteBatch;
    Texture2D texPlayerPosition;
    public Radar(Texture2D texture, Rectangle rectangle,
    SpriteBatch spriteBatch, Game game) : base(game)
    {
    // Initialize the radar member variables
    . . .
    }
    protected override void Draw(GameTime gameTime)
    {
    spriteBatch.Draw(texture, destRec, Color.White);
    spriteBatch.Draw(texPlayerPosition, playerVector,
    Color.Red);
    foreach (Vector2 vec in this.enemiesPosition)
    {
    spriteBatch.Draw(texPlayerPosition, vec,
    Color.Yellow);
    }
    base.Draw(gameTime);
    }
    protected override void Initialize()
    {
    // Initialize the device
    . . .
    base.Initialize();
    }
    protected override void LoadContent()
    {
    // Load radar and player texture content
    . . .
    base.LoadContent();
    }
    protected override void UnloadContent()
    {
    base.UnloadContent();
    }
    public override void Update(GameTime gameTime)
    {
    // Update the player position
    . . .
    base.Update(gameTime);
    }
    }
    
  2. 2. Now, that you have defined your GameComponent, the next step is to insert the Component to the GameComponent list of the Game class. Once added, the overridden method will be called automatically:

    public Game1()
    {
    . . .
    Components.Add(new Radar(this));
    }
    
  3. 3. Another way is to initiate the instance first and then pass it to the Add() method. The second approach provides the door. Sometimes, you might need to update some public variables of the component. For the Radar class, you can update the player's position:

    Radar radar;
    public Game1()
    {
    . . .
    Components.Add(radar);
    }
    
  4. 4. The Draw() method in the Game class is a very simple ascribe to the GameComponent list. The Draw() method of DrawableComponent belongs to the GameComponent list and will be called automatically. The code snippet is similar to the following code:

    protected override void Draw(GameTime gameTime)
    {
    GraphicsDevice.Clear(Color.CornflowerBlue);
    base.Draw(gameTime);
    }
    

How it works...

In step 1, the code presents a brief code snippet of the Radar class inherited from DrawableGameComponet. So far, your focus is on how to override the Initialize(), Update(), LoadContent(), UnloadContent(), and Draw() methods.

About the Author
  • Zheng Yang

    Zheng Yang is a hands-on technical leader with 5 years combined professional experience providing core development engineering for consumer-facing applications of global Microsoft and as an independent game developer. He is a dynamic, results-oriented developer with a proven history of providing innovative solutions to complex technical problems. When he was a student, he got the recognition from Microsoft Research Asia and Microsoft Imagine Cup Team. Zheng Yang has advanced technical knowledge of key development technologies including C#, the .NET framework, C++, Visual Studio, DirectX and SQL Server. Solid expertise across the full life cycles of both software development and game production.

    Browse publications by this author
Windows Phone 7 XNA Cookbook
Unlock this book and the full library FREE for 7 days
Start now