Home Game Development Building your First Mobile Game using XNA 4.0

Building your First Mobile Game using XNA 4.0

By Brecht Kets , Thomas Goussaert
books-svg-icon Book
eBook $25.99 $17.99
Print $43.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 $25.99 $17.99
Print $43.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
About this book
With the dawn of the Windows Phone 7 platform, Microsoft has offered us an easy way to create 3D mobile games. In this book, we will build a 3D game for Windows Phone 7 together, taking full advantage of the graphics and touch capabilities, along with the sensors of the platform."Building your First Mobile Game using XNA 4.0" is the book for starting game development on the Windows Phone 7 platform. This book will go over the technical aspects of building games along with designing your own framework. Finally we'll build an actual game together from the ground up! This book will set future mobile game developers in the right direction.The XNA framework empowers us to build 2D and 3D games for PC, Xbox 360 and Windows Phone 7. We will use those capabilities to create stunning 3D games for the Windows Phone 7 platform. We will start by covering the basics like drawing graphics, followed by building a custom framework and end with building a game together!In this book, we will cover drawing 2D and 3D graphics, both static and animations. We will also cover the various ways of handling user input and help set the mood of our game playing both 2D and 3D sound, and accessing the user's media library. The only thing left before building a game is covering several techniques created for making our life easier while building the game, whilst building a framework to do just that. Finally, we'll build a 3D game together that will run on the Windows Phone 7 platform."Building your First Mobile Game using XNA 4.0" is the book you need to get started with mobile game development for Windows Phone 7. Its hands on approach will set you on your way in no time. Let's build some games!
Publication date:
January 2013
Publisher
Packt
Pages
158
ISBN
9781849687744

 

Chapter 1. Getting Started

Welcome to the world of Windows Phone development. By reading this book you've made the first step necessary to write games for Windows Phone. Let's get started!

In this chapter we will cover:

  • The basics of developing games for the Windows Phone platform

  • Getting up and running with Windows Phone SDK

  • Deploying our first app to the emulator and to a Windows Phone device

  • The structure of the XNA Game class

 

Developing for Windows Phone


Let us start by talking about the Windows Phone platform itself. All Windows Phone devices have minimum sets of hardware they have to comply with. This includes three buttons: start, search, and back, a resolution of 480x800, a touch screen, an accelerometer, and more. The list of specifications can be found at http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff637514(v=vs.92).aspx.

With the launch of Windows Phone 7 back in 2010, Microsoft offered two possible ways to develop applications for Windows Phone. The applications we write must be developed using either Silverlight or XNA Game Studio 4.0. Both Silverlight and XNA are powered by the .NET framework. This means we can develop apps for Windows Phone using managed programming languages such as C# (version 3). This book will only cover XNA development, as this framework is very suitable for developing games. We won't be discussing Silverlight.

But first, what is XNA? XNA is a managed framework which runs on top of the .NET framework. It enables us to build games for Windows, Xbox 360, and Windows Phone, with limited adaptations to the source code when switching to another platform. Because it runs on top of the .NET framework, you can use VB.NET or C# as programming languages. In this book, we will use C# and won't cover VB.NET.

What makes XNA interesting in terms of game development is that it takes care of the boring stuff (initializing and maintaining the graphics device and setting up your render loop for instance) for us; this enables us to skip the boiler plate code and focus on the interesting part, being our game.

XNA Game Studio 4.0—the development environment for XNA—is part of the Windows Phone SDK. This toolset is an extension for Visual Studio 2010, and is available for free. Using XNA Game Studio 4.0, you can develop XNA games for Windows Phone (amongst others), and deploy to an emulator or an actual Windows Phone device. However, when you want to deploy to an actual device, the device has to be registered. To register your Windows Phone, you need a valid Dev Center Developer account, which costs $99 annually—unless you are a student. Students can get a free (limited) developer account through www.dreamspark.com. A valid Dev Center Developer account will enable you to create games for and deploy them to Windows Phone. This does not include deploying to Xbox 360.

Installing the Windows Phone SDK

Let us start by installing all the software we need. XNA Game Studio 4.0 (our development environment) is part of the Windows Phone SDK. You can download the latest version from https://dev.windowsphone.com/en-us/downloadsdk. At the time of writing, the most recent version is 'Windows Phone SDK 7.1'. The setup will install the following applications:

  • Microsoft Visual Studio 2010 Express for Windows Phone

  • Windows Phone Emulator

  • Windows Phone SDK Assemblies

  • Windows Phone SDK Extensions for XNA Game Studio 4.0

  • Microsoft Expression Blend SDK for Windows Phone

  • Silverlight 4 SDK and DRT

  • WCF Data Services Client for Windows Phone

  • Microsoft Advertising SDK for Windows Phone

Note that all these applications will enable you to build applications for Windows Phone 7.0 and Windows Phone 7.5. The tools we will use are the Windows Phone Emulator and XNA Game Studio 4.0.

When you already have a version of Visual Studio 2010 installed (Professional for instance), the add-ins for this version will be installed automatically. Make sure you have all service packs installed for that installation version.

After installing the SDK, make sure you install the latest update. This can be downloaded from the same location as the SDK. At the time of writing, the latest update is 'Windows Phone SDK 7.1.1 Update'.

Registering your Windows Phone

To be able to deploy games to our Windows Phone, we need to register the device. There are three prerequisites:

  • Obtain a Microsoft account if you don't have one. This can be done through www.live.com.

  • Create a valid Dev Center Developer account (if you don't have one). This can be done through https://dev.windowsphone.com/en-us/join. An Dev Center Developer account costs $99 annually, and it will enable you to deploy games to Windows Phone.

  • If you are a student, you can register for free using a valid DreamSpark account. Go to www.dreamspark.com to register. Your university/school representative can help you out here.

  • Install Zune from www.zune.net.

Once the above is taken care of, we can start registering our Windows Phone. Start by making sure that the date and time are correct and connect your phone to your PC using the USB cable. Zune will start automatically. If it does not start, we need to start it ourselves. If everything went okay, the phone will appear in the 'Device' tab of the Zune software. On the first run, this might take a few minutes, while Windows installs the drivers for the phone.

Next we can open the Windows Phone Developer registration tool we can find by clicking Start | All Programs | Windows Phone SDK 7.1. Once the application has started, you should see the following window:

Once the status says Phone ready, register using your Microsoft account.

 

Getting started with your first application


Let us start by creating our first—empty—application, and deploying it to the emulator or an actual Windows Phone device.

After installing everything, go ahead and open up Microsoft Visual Studio 2010 Express for Windows Phone or your Visual Studio 2010 if you have another version installed.

  1. Go to File | New | Project. The New Project window will pop up as shown in the following screenshot:

  2. Among the installed templates (on the left-hand side of the New Project window) we can find XNA Game Studio 4.0. Click it and select Windows Phone Game (4.0) in the middle of the screen.

  3. At the bottom of the window, we can give our game a proper name and choose a file location for our game. Click on the OK button.

  4. Next we get asked which platform of Windows Phone we want to develop for, that is 7.0 or 7.1. Go ahead and choose Windows Phone OS 7.1 as illustrated in the following screenshot and click on OK.

Note

With Windows Phone OS 7.0, Microsoft means the Windows Phone 7 Mango devices. Windows Phone OS 7.1 means the Windows Phone 7.5 Tango devices.

Now XNA Game Studio created a new project that contains a class called Game1. This is our main game class. Don't worry about the code yet, we will go over this in the next chapters. The important part is that everything is set up for us to begin.

Take a look at the toolbars at the top. There you can find a drop-down menu where we can select what device we want to deploy to.

We can choose between a Windows Phone device, an emulator with 512 MB RAM, and an emulator with 256 MB RAM. The latter aims at the low end devices. Choose Windows Phone Emulator – 512 MB. If you want to deploy to an actual device, choose Windows Phone Device; make sure it is connected to your PC and that the Zune Software is running. The device also needs to be unlocked. During development, it can be wise to make sure the device doesn't lock automatically. This can be done via Settings | Lock + Wallpaper | Screen time out after.

When you press F5, our game will be compiled and then deployed. After everything is loaded correctly, two different screens pop up. With the Additional Tools window, we can simulate the accelerometer, GPS data, and take screenshots. On the phone emulator, we can see an empty, cornflower blue screen.

This might not seem like a lot, but our entire render loop has been made, and we are ready to start loading content and displaying models. Let's get going!

 

The Game class


Let's go over the Game class that XNA Game Studio created for us. This class inherits from Microsoft.Xna.Framework.Game. This is our main game class. This class has some fields and methods that have been created for us.

Fields

Our game class has two fields, a GraphicsDeviceManager field and a SpriteBatch field. The GraphicsDeviceManager class will handle the configuration and management of our graphics card, so we don't have to. The SpriteBatch class we can use to draw 2D graphics.

Constructor

The constructor is called once at the start of the game. It creates a new GraphicsDeviceManager instance and sets the root directory for our content manager. This property will determine where the content is loaded from when calling Content.Load<>(""). We will use the content manager later on to load content. The constructor also sets the default framerate, being 30 frames per second for Windows Phone.

public MainGame()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
    // Frame rate is 30 fps by default for Windows Phone.
    TargetElapsedTime = TimeSpan.FromTicks(333333);
}

Initialize

We can use the Initialize method to initialize all non-graphics related content and query for services. By default, the Initialize method of the base class gets called. This makes sure all components are initialized as well. Make sure you create your objects before calling Initialize on the base class.

protected override void Initialize()
{
    // TODO: Add your initialization logic here
            
    base.Initialize();
}

LoadContent

We can use the LoadContent method to load our content. This will also be called once per game. In this method, we can use the content manager to load a variety of content—textures, models, and sounds for instance. By default, the spriteBatch field gets instantiated.

protected override void LoadContent()
{
    // Create a new SpriteBatch
    spriteBatch = new SpriteBatch(GraphicsDevice);
}

UnloadContent

We can use the UnloadContent method to unload any content. As most of the content we will use, uses the content pipeline, we won't have much use for this method. The UnloadContent method gets called once per game.

protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

Update

The Update method will run multiple times, and to be more specific, it will do its best to run 30 times per second (depending on the TargetElapsedTime property). In this method we will perform all calculations we need, such as collision detection, updating positions, playing sound, and gathering input. The method has one argument, an object of type GameTime. This object contains the total amount of time since the game started, as well as the time passed since the last update was called. We will use this object to make sure our game logic is frame rate independent. This means our object will move at the same speed, regardless the current frame rate—for example, if the Update method fails to be executed 30 times per second, we want our hero to move just as fast as if it were executing 30 times per second.

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==ButtonState.Pressed)
        this.Exit();
    // TODO: Add your update logic here
    base.Update(gameTime);
}

Also note that in the Update method, we exit the game when the back button is pressed on the gamepad with index one. The interesting thing here is that the back button of the phone registers as the back button of the gamepad.

Draw

As the name suggests, we will use the Draw method to render our objects to the screen. By default, XNA will try to call this method 30 times per second on Windows Phone. Depending on how much you are drawing, this could be less. The method also has a GameTime object as argument, which provides a snapshot of the timing values. The first thing that happens in the method is that the graphics device gets cleared. Each time Draw is called, we render to a render target. A render target can be seen as a 2D image, or a whiteboard. Each time we want to draw a new frame, we need to clear the render target, or wipe the board. The Clear method takes a color as argument, by default cornflower blue. This means our background will be cornflower blue. After clearing our render target, we can draw all our graphics and call Draw on our base class. The default render target is the screen, but we don't have to worry about that just now.

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

    // TODO: Add your drawing code here

    base.Draw(gameTime);
}
 

Summary


In this chapter, we've discussed the basics of Windows Phone game development and the XNA framework. We got started and installed all the tools we need to develop games on Windows Phone, registered our device so we could deploy to it and we created our first—be it limited—game!

Let's jump to the next chapter where we will learn how to draw sprites and display sprite animations on screen.

About the Authors
  • Brecht Kets

    Brecht Kets is a Senior Lecturer at Howest University in Belgium, where he teaches game development in one of the leading international game development study programs, Digital Arts and Entertainment (www.digitalartsandentertainment.com). He's been actively involved in game development for several years, and has been writing about XNA since the launch in December 2006. He hosts the website www.3dgameprogramming.net and has received the Microsoft Most Valuable Professional award in the category DirectX/XNA five times in a row for his contributions in the community. Brecht has also co-authored the video series XNA 3D Game Development By Example, Packt Publishing.

    Browse publications by this author
  • Thomas Goussaert

    Thomas Goussaert graduated in Digital Arts And Entertainment (DAE), from Howest University. With a wide range of skills acquired by his studies, he explored the world of programming and game development. Thomas is always curious and eager to learn new things; always feeding his passion for programming. Now he's a lecturer at Howest University, where he teaches game development in one of the leading international game development study programs, Digital Arts and Entertainment (www.digitalartsandentertainment.com). It's nice to have a passion for programming, but it's even better to share it with the world! Thomas has also co-authored the video series XNA 3D Game Development By Example, Packt Publishing

    Browse publications by this author
Building your First Mobile Game using XNA 4.0
Unlock this book and the full library FREE for 7 days
Start now