Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
XNA 4.0 Game Development by Example: Beginner's Guide
XNA 4.0 Game Development by Example: Beginner's Guide

XNA 4.0 Game Development by Example: Beginner's Guide: The best way to start creating your own games is simply to dive in and give it a go with this Beginner’s Guide to XNA. Full of examples, tips, and tricks for a solid grounding.

eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

XNA 4.0 Game Development by Example: Beginner's Guide

Chapter 1. Introducing XNA Game Studio

With the release of Windows 95, Microsoft also introduced the DirectX Application Programming Interface (API), which allowed Windows-based applications to integrate closely, in a standard way, with the graphics hardware available on the system. Prior to DirectX, most PC game development targeted MS-DOS, as Windows-based graphics were too slow for most gaming needs.

Although faster, working with the DirectX API could be challenging. The DirectX Software Development Kit (SDK) is targeted at C++, with no official support for other languages. The developer is also faced with large volumes of background work to get a DirectX project to the point where he can display images on the screen before ever considering the logic of the game itself.

In 2002, Microsoft released Managed DirectX as an interface to the API from its new .NET development environment. The .NET Framework consists of a set of code libraries to perform common programming tasks, and the Common Language Runtime (CLR) which allows code written in the various .NET languages (including Visual Basic .NET and C#) to be compiled into common runtime code. In order to support devices such as Windows Mobile phones, a subset of the .NET Framework was released, called the .NET Compact Framework. The .NET CF, as it is often abbreviated, removed non-essential components of the full Framework in the interest of saving storage space on handheld devices.

While Managed DirectX 2.0 was still in the beta phase, the project was cancelled, and Microsoft XNA was introduced in its place. XNA consists of the XNA Framework, a set of code libraries to perform common graphics, sound, and other game related tasks, and XNA Game Studio, an extension of the Visual Studio C# interface that includes a number of project templates to make use of the XNA Framework.

The XNA project templates include an integrated game loop, easy to use (and fast) methods to display graphics, full support for 3D models, and simple access to multiple types of input devices.

In addition to Windows games, XNA allows deployment to both the Xbox 360, the Zune handheld media player (with XNA 3.1) and Windows Phone 7 Series phones (with XNA 4.0). For the first time, a game console manufacturer has released a supported method for individual game developers to create (and sell!) content for their game console. Microsoft has even established the Xbox Indie Games system on Xbox Live to allow you to sell your creations to the world.

Tip

What does XNA stand for, anyway?

According to the developers, XNA is an acronym for "XNA's Not Acronymed".

In this introductory chapter you will:

  • Look at an overview of the games presented in this book

  • Download and install XNA Game Studio

  • Create a new Windows Game project

  • Modify the default Windows Game template to build your first XNA game

Overview of the games


Many beginning developers make the mistake of attempting to tackle far too large a project early on. Modern blockbuster video games are the result of the efforts of hundreds of programmers, designers, graphic artists, sound effects technicians, producers, directors, actors, and many other vocations, often working for years to create the game.

That does not mean that the efforts of a solo developer or small team need to be dull, boring, and unplayable. This book is designed to help you develop a solid understanding of 2D game development with XNA Game Studio. By the time you have completed the projects in this book, you will have the knowledge necessary to create games that you can complete without an army of fellow game developers at your back.

In this chapter, you will build your first XNA mini game, chasing squares around the screen with your mouse cursor. In subsequent chapters the following four more detailed games are presented:

Flood Control : An explosion in one of the research laboratories has cracked the pressure dome protecting your underwater habitat. Work quickly to construct a series of pipes to pump water out of the habitat before it floods. Flood Control is a board-based puzzle game with simple game mechanics and slowly increasing difficulty.

Asteroid Belt Assault : After being separated from your attack fleet in Hyper Space, you find yourself lost in an asteroid field without communications or navigation systems. Work your way through the chaos of the asteroid belt while combating alien pilots intent upon your destruction. A vertically scrolling space shooter, Asteroid Belt Assault introduces scrolling backgrounds, along with player and computer controlled characters.

Robot Rampage : In the secret depths of a government defence facility, a rogue computer has taken control of robotic factories across the world, constructing an army of mechanical soldiers. Your mission—infiltrate these factories and shut down their network links to break the computer's control. A multi-axis shooter utilizing both of the analog control sticks on the Xbox 360 gamepad controller, Robot Rampage generates and manages dozens of on-screen sprites and introduces world map construction.

Gemstone Hunter : Explore the Australian wilderness, abandoned mines and ancient caves in a search for fabulous treasures. In Gemstone Hunter you will construct a classic platform-style game, including a Windows Forms-based level editor and a multi-map "world" to challenge the player.

The games are each presented over two chapters. In the first chapter, the basics are implemented to the point where the game is playable. In the second chapter, features and polish are added to the game.

Each game introduces new concepts and expands on topics covered in the previous games. At the end of each game chapter, you will find a list of exercises challenging you to use your newly gained knowledge to enhance previous games in the book.

We will focus on Windows as our platform for the games presented in this book. That said, the code presented in this book requires very little in the way of changes for other XNA platforms, generally only requiring implementation of platform-specific controls (gamepads, touch screen, and so on) and consideration of the differences in display sizes and orientation on non-Windows devices.

System requirements


In order to develop games using XNA Game Studio, you will need a computer capable of running both Visual C# 2010 Express and the XNA Framework extensions. The general requirements are:

Component

Minimum requirement

Notes

Operating System

Windows Vista SP2

or

Windows 7 (All editions except Starter)

As of XNA 4.0, Windows XP is no longer officially supported.

Graphics card

Shader Model 1.1 support

DirectX 9.0 support

Microsoft recommends Shader Model 2.0 support as it is required for many of the XNA Starter Kits and code samples. The projects in this book similarly require Shader Model 2.0 support.

Optional requirements

Windows Phone

DirectX 10 or later, Compatible Video Card

Development tools include a Windows Phone emulator to test applications without deployment to a physical device.

Zune platform

Zune Software 3.0 or higher, Visual C# 2008, XNA Game Studio 3.1

Only required if you plan to deploy games to a Zune handheld device. Zune development is supported under XNA 3.1.

Xbox Live

Xbox Live Silver membership, XNA Creator's Club Premium membership

Xbox Live Silver is free. The XNA Creator's Club Premium membership costs $49 for 4 months or $99 for 1 year.

Tip

HiDef vs. Reach

As of version 4.0, XNA now supports two different rendering profiles. The HiDef profile is available on the Xbox 360 and Windows PCs with DirectX 10 or better video cards, and uses Shader Model 3.0. The Reach profile is available on all XNA platforms, and uses Shader Model 2.0. If you have a DirectX 9 video card, or wish to distribute your games to computers with DirectX 9 support, you will need to right-click on your project in Solution Explorer and select Properties. On the XNA Game Studio tab, select the Reach profile.

Installing XNA Game Studio


To get started developing games in XNA, you will need to download and install the software. You will need both Visual C# and XNA Game Studio. With the release of XNA 4.0, the install packages have been consolidated, and both required components are included in the Windows Phone Developer Tools package.

Time for action – installing XNA Game Studio


  1. Visit http://www.microsoft.com/express/Phone/ and download the Windows Phone Developer Tools package. Run the setup wizard and allow the installation package to complete.

  2. Open Visual Studio Express. Click on the Help menu and select Register Product. Click on the Register Now link to go to the Visual Studio Express registration page. After you have completed the registration process, return to Visual Studio Express and enter the registration number into the registration dialog box.

  3. Close Visual Studio Express.

  4. Download the Font Pack from http://go.microsoft.com/fwlink/?LinkId=104778.

  5. Extract the ZIP file contents to a temporary folder (leave this folder open).

  6. From the Start Menu, select Control Panel. Under Classic View, choose Fonts.

  7. Drag the fonts from the temporary folder to the Fonts folder.

  8. Close both Explorer windows.

  9. Launch Visual Studio Express, and the Integrated Development Environment (IDE) will be displayed as seen in the following screenshot:

Tip

Other versions of Visual Studio and XNA

Different versions of Visual Studio and XNA can be installed on the same PC without interfering with each other. If you wish to target the Zune platform, you will need to install Visual C# 2008 Express and XNA 3.1. Additionally, Visual Studio Express and Visual Studio Professional can coexist on the same PC, and XNA will integrate with both of them if it is installed after Visual Studio.

What just happened?

You have now successfully installed the Windows Phone Developers Tools, including XNA Game Studio 4.0 and the Redistributable Font Pack provided by Microsoft for XNA developers.

Tip

The redistributable fonts package

To use its integrated text drawing methods, XNA games need to convert normal Windows fonts into an internal format called a SpriteFont. These SpriteFonts get distributed with your game, which means you will not be able to use most of the fonts on your computer due to licensing restrictions. For this reason, Microsoft has provided a selection of fonts that XNA developers can freely distribute without purchasing an individual license to do so.

Building your first game


XNA attempts to simplify many of the basic elements of game development by handling things like the game update loop and simplifying the display of graphical objects. To illustrate just how much of the background work is integrated into the XNA project templates, let's jump in straight away and create your first game within a few minutes of finishing the installation.

In SquareChase, we will generate randomly positioned squares of different colors while the user attempts to catch them with their mouse pointer before they disappear. While building the project, we will discuss each of the major code sections pre-defined by the XNA templates.

Time for action – creating a new Windows game project


  1. In the Visual C# window, open the File menu and select New Project...

  2. Under Project Type, make sure XNA Game Studio 4.0 is selected.

  3. Under Templates, select Windows Game (4.0).

  4. Name the project SquareChase (This will automatically update the Solution Name).

  5. Click on OK:

What just happened?

Each of the XNA project templates is a series of files and settings that get copied to your new project folder. Included in this set of files is the Game1.cs file, which is the heart of your XNA game.

Tip

Backup your projects

When you create your project, the Location field specifies where it will be saved. By default, Visual Studio creates a folder in your user documents area called Visual Studio 2010 to store both programs and configuration information. Under this folder is a Projects folder that contains subfolders for each new project you create. Make backups of your projects on a regular basis. You do not want to lose your hard work to a disk failure!

Anatomy of an XNA game

The most basic XNA game will have all of its code contained in the file called Game1.cs. This file is generated when you create a new project, and contains override declarations for the methods used to manage your game. In addition to the Game1 class' declarations area, there are five primary methods you will customize for any XNA project.

The declarations area

Right below the class declaration for Game1 is the class level declarations area. By default, this area contains two variables:

GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

The graphics object provides access to, not surprisingly, the system's video card. It can be used to alter the video mode, the size of the current viewport (the area that all drawing work will be clipped to if specified), and retrieve information about Shader Models the video card supports.

XNA provides the SpriteBatch class to allow you to (very quickly) draw 2D images (called "sprites") to the screen.

The declarations area is the spot for any variables that need to be maintained outside of any of the individual methods listed below. In practice, any data you need to keep track of throughout your game will be referenced, in some way, in your declarations section.

Time for action – adding variables to the class declaration area


  1. Right below the SpriteBatch spriteBatch; line, add the following:

    Random rand = new Random();
    Texture2D squareTexture;
    Rectangle currentSquare;
    int playerScore = 0;
    float timeRemaining = 0.0f;
    const float TimePerSquare = 0.75f;
    Color[] colors = new Color[3] { Color.Red, Color.Green, Color.Blue };

What just happened?

These are all the variables you will need for the SquareChase mini game. Here is a quick breakdown:

rand : This instance of the Random class is used to generate random numbers via the Next() method. You will use this to generate random coordinates for the squares that will be drawn to the screen.

squareTexture : The Texture2D class holds a two dimensional image. We will define a small texture in memory to use when drawing the square.

currentSquare : The XNA Framework defines a structure called Rectangle that can be used to represent an area of the display by storing the x and y position of the upper left corner along with a width and height. SquareChase will generate random squares and store the location in this variable.

playerScore : Players will score one point each time they successfully "catch" a square by clicking on it with their mouse. Their score accumulates in this integer variable.

timeRemaining: When a new square is generated, this float will be set to a value representing how many seconds it will remain active. When the counter reaches zero, the square will be removed and a new square generated.

TimePerSquare : This constant is used to set the length of time that a square will be displayed before it "runs away" from the player.

colors: This array of Color objects will be used when a square is drawn to cycle through the three colors in the array. The Color structure identifies a color by four components: Red, Green, Blue, and Alpha. Each of these components can be specified as a byte from 0 to 255 representing the intensity of that component in the color. The Alpha component determines the transparency of the color, with a value of 0 indicating that the color is fully transparent and 255 indicating a fully opaque color. Alternatively, each component of a color can be specified as a float between 0.0f (fully transparent) and 1.0f (fully opaque).

The Game1 class constructor

The XNA templates define an instance of the Microsoft.Xna.Framework.Game class with the default name "Game1" as the primary component of your new game. Slightly more goes on behind the scenes, as we will see when we add an XNA game to a Windows Form in Chapter 8, but for now, we can consider the Game1 constructor as the first thing that happens when our XNA game is executed. The class constructor is identified as public Game1(), and by default, it contains only two lines:

graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";

For most of the games in this book, we will not need to make extensive modifications to the Game1 constructor, as its only job is to establish a link to the GraphicsDeviceManager object and set the default directory for the Content object which is used to load images, sound, and other game content.

The Initialize() method

After the constructor has finished and your XNA game begins to run, the Initialize() method is called. This method only runs once, and the default code created with a new project template simply calls the base version of the method. The Initialize() method is the ideal place to set up things like the screen resolution, toggle full screen mode, and enable the mouse in a Windows project. Other game objects that do not rely on external content such as graphics and sound resources can also be initialized here.

Time for action – customizing the Initialize() method


  1. Make the mouse pointer visible by adding the following before the call to base.Initialize():

    this.IsMouseVisible = true;

What just happened?

By default, the mouse is not visible inside the XNA game window. Setting the IsMouseVisible property of the running instance of the Game1 class enables the mouse cursor in Windows.

Tip

Input types on other platforms

The Xbox, Zune, and Windows Phone do not support a mouse, so what happens when the code to enable the mouse runs on these platforms? Nothing! It just gets ignored. It is also safe to ask other platforms about their non-existent keyboards and check the state of a gamepad on a Windows PC without one attached.

The LoadContent() method

Part of the responsibility of the base Initialize() method is to call LoadContent() when the normal initialization has completed. The method is used to read in any graphical and audio resources your game will need. The default LoadContent() method is also where the spriteBatch object gets initialized. You will use the spriteBatch instance to draw objects to the screen during execution of the Draw() method.

Time for action – creating the squareTexture


  1. Open Microsoft Paint or your favourite image editor and create a new 16 by 16 pixel image and fill it with white.

  2. Save the image as SQUARE.BMP in a temporary location.

  3. Back in Visual C# Express, right-click on SquareChaseContent (Content) in Solution Explorer (you may need to scroll down to see it) and select Add | Existing Item. Browse to the image you created and click on Ok.

  4. Add the following code to the LoadContent() method after the spriteBatch initialization:

    squareTexture = Content.Load<Texture2D>(@"SQUARE");

What just happened?

To load content, it must first exist. In steps 1 and 2, you created a bitmap image for the square texture. In step 3, you added the bitmap image as a piece of content to your project.

Tip

Powers of two

Very old graphics cards required that all texture images be sized to "powers of two" (2, 4, 8, 16, 32, 64, 128, 256, etc). This limitation is largely non-existent with modern video hardware, especially for 2D graphics. In fact, the sample code in the XNA Platform Starter Kit uses textures that do not conform to the "powers of two" limitation. In our case, the size of the image we created previously is not critical, as we will be scaling the output when we draw squares to the screen.

Finally, in step 4 you used the Content instance of the ContentManager class to load the image from the disk and into the memory when your game runs. The Content object is established automatically by XNA for you when you create a new project. When we add content items, such as images and sound effects to our game project, the XNA Content Pipeline converts our content files into an intermediate format that we can read via the Content object. These XNB files get deployed alongside the executable for our game to provide their content data at runtime.

The Update() method

Once LoadContent() has finished doing its job, an XNA game enters an endless loop in which it attempts to call the Update() method 60 times per second. This default update rate can be changed by setting the TargetElapsedTime property of the Game1 object, but for our purposes, the default time step will be fine. If your Update() logic starts to take too long to run, your game will begin skipping calls to the Draw() method in favour of multiple calls to Update() in an attempt to catch up with the current game time.

All of your game logic gets built into the Update() method. It is here that you check for player input, move sprites, spawn enemies, track scores, and everything else except draw to the display. Update() receives a single parameter called gameTime, which can be used to determine how much time has elapsed since the previous call to Update() or to determine if your game is skipping Draw() calls by checking its IsRunningSlowly property.

The default Update() method contains code to exit the game if the player presses the "Back" button on the first gamepad controller.

Tip

Exiting a game under Windows

The default Update() code provides anyone with a gamepad a way to end the game, but what if you do not have a gamepad? Press Alt + F4 on the keyboard or click on the standard Windows close button to exit your game when running in Windows.

Time for action – coding Update() for SquareChase


  1. Add the following to Update() right before the call to base.Update(gameTime);

    if (timeRemaining == 0.0f)
    {
        currentSquare = new Rectangle(
            rand.Next(0, this.Window.ClientBounds.Width - 25),
            rand.Next(0, this.Window.ClientBounds.Height - 25),
            25, 25);
        timeRemaining = TimePerSquare;
    }
    
    MouseState mouse = Mouse.GetState();
    
    if ((mouse.LeftButton == ButtonState.Pressed) &&
      (currentSquare.Contains(mouse.X, mouse.Y)))
    {
        playerScore++;
        timeRemaining = 0.0f;
    }
    timeRemaining = MathHelper.Max(0, timeRemaining - 
        (float)gameTime.ElapsedGameTime.TotalSeconds);
    
    this.Window.Title = "Score : " + playerScore.ToString();
    
    

What just happened?

The first thing the Update() routine does is check to see if the current square has expired by checking to see if timeRemaining has been reduced to zero. If it has, a new square is generated using the Next() method of the rand object. In this form, Next() takes two parameters: an (inclusive) minimum value and a (non-inclusive) maximum value. In this case, the minimum is set to 0, while the maximum is set to the size of the this.Window.ClientBounds property minus 25 pixels. This ensures that the square will always be fully within the game window.

Next, the current position and button state of the mouse is captured into the "mouse" variable via Mouse.GetState(). Both the Keyboard and the GamePad classes also use a GetState() method that captures all of the data about that input device when the method is executed.

If the mouse reports that the left button is pressed, the code checks with the currentSquare object by calling its Contains() method to determine if the mouse's coordinates fall within its area. If they do, then the player has "caught" the square and scores a point. The timeRemaining counter is set to 0, indicating that the next time Update() is called it should create a new square.

After dealing with the user input, the MathHelper.Max() method is used to decrease timeRemaining by an amount equal to the elapsed game time since the last call to Update(). Max() is used to ensure that the value does not go below zero.

Finally, the game window title bar is updated to display the player's score.

Tip

MathHelper

The Microsoft.Xna.Framework namespace provides a class called MathHelper that contains lots of goodies to make your life easier when dealing with numeric data, including converting degrees to and from radians, clamping values between a certain range, and generating smooth arcs between a starting and ending value.

The Draw() method

The final method in the default Game1.cs file is responsible, not surprisingly, for drawing the current game state to the display. Draw() is normally called once after each call to Update() unless something is happening to slow down the execution of your game. In that case, Draw() calls may be skipped in order to call Update() more frequently. There will always be at least one call to Update() between calls to Draw(), however, as sequential Draw() calls would provide no benefit—nothing in the game state will have changed.

The default Draw() method simply clears the display window in the Cornflower Blue color.

Time for action – draw SquareChase!


  1. Alter the GraphicsDevice.Clear(Color.CornflowerBlue); call and replace Color.CornflowerBlue with Color.Gray to make the game a bit easier on the eyes.

  2. Add the following code after the call to clear the display:

    spriteBatch.Begin();
    spriteBatch.Draw(
        squareTexture,
        currentSquare,
        colors[playerScore % 3]);
    spriteBatch.End();

What just happened?

Any time you use a SpriteBatch object to draw to the display, you need to wrap the calls inside a Begin() and End() pair . Any number of calls to spriteBatch.Draw() can be included in a single batch and it is common practice to simply start a Begin() at the top of your Draw() code, use it for all of your drawing, and then End() it right before the Draw() method exits. While not benefiting our SquareChase game, batching sprite drawing calls greatly speeds up the process of drawing a large number of images by submitting them to the rendering system all at once instead of processing each image individually.

The SpriteBatch.Draw() method is used to draw a Texture2D object to the screen. There are a number of different options for how to specify what will be drawn. In this case, the simplest call requires a Texture2D object (squareTexture), a destination Rectangle (currentSquare), and a tint color to apply to the sprite. The expression playerScore % 3 takes the player's score, divides it by 3, and returns the remainder. The result will always be 0, 1, or 2. This fits perfectly as an index to the elements in the colors array, allowing us to easily change the color of the square each time the player catches one.

Finally, the spriteBatch.End() tells XNA that we have finished queuing up sprites to draw and it should actually push them all out to the graphics card.

Time for action – play SquareChase!


  1. Run your game by clicking on Start Debugging from the Debug menu or hit F5 on the keyboard.

  2. Play an exciting game of SquareChase by holding down the mouse button and trying to catch the squares with your mouse cursor:

What just happened?

You just finished your first XNA game, that's what!

Granted it is not exactly the next blockbuster, but at only 33 lines of code, it implements a simple game mechanic, user input, score tracking and display, and clock-based timing. Not bad for a few minutes work.

Have a go hero

As simple as it is, here are a couple of enhancements you could make to SquareChase:

  • Vary the size of the square, making it smaller every few times the player catches one, until you reach a size of 10 pixels.

  • Start off with a higher setting for TimePerSquare and decrease it a little each time the player catches a square. (Hint: You'll need to remove the const declaration in front of TimePerSquare if you wish to change it at runtime).

Summary


You now have a development environment set up for working on your XNA game projects, including Visual Studio Express and XNA Game Studio 4.0.

We also saw how the XNA game loop initializes and executes, and constructs an elementary game by expanding on the default methods provided by the Windows Game template.

It is time to dive head first into game creation with XNA. In the next chapter, we will begin building the puzzle game Flood Control in which the player is challenged to pump water out of their flooding underwater research station before the entire place really is underwater!

Left arrow icon Right arrow icon

Key benefits

  • Dive headfirst into game creation with XNA
  • Four different styles of games comprising a puzzler, a space shooter, a multi-axis shoot 'em up, and a jump-and-run platformer
  • Games that gradually increase in complexity to cover a wide variety of game development techniques
  • Focuses entirely on developing games with the free version of XNA
  • Packed with many suggestions for expanding your finished game that will make you think critically, technically, and creatively
  • Fresh writing filled with many fun examples that introduce you to game programming concepts and implementation with XNA 4.0
  • A practical beginner's guide with a fast-paced but friendly and engaging approach towards game development

Description

XNA Game Studio enables hobbyists and independent game developers to easily create video games. It gives you the power to bring your creations to life on Windows, the Xbox 360, the Zune, and the Windows Phone platforms. But before you give life to your creativity with XNA, you need to gain a solid understanding of some game development concepts.This book covers both the concepts and the implementations necessary to get you started on bringing your own creations to life with XNA. It details the creation of four games, all in different styles, from start to finish using the Microsoft XNA Framework, including a puzzler, space shooter, multi-axis shoot-'em-up, and a jump-and-run platform game. Each game introduces new concepts and techniques to build a solid foundation for your own ideas and creativity. Beginning with the basics of drawing images to the screen, the book then incrementally introduces sprite animation, particles, sound effects, tile-based maps, and path finding. It then explores combining XNA with Windows Forms to build an interactive map editor, and builds a platform-style game using the editor-generated maps. Finally, the book covers the considerations necessary for deploying your games to the Xbox 360 platform.By the end of the book, you will have a solid foundation of game development concepts and techniques as well as working sample games to extend and innovate upon. You will have the knowledge necessary to create games that you can complete without an army of fellow game developers at your back.

Who is this book for?

If you are an aspiring game developer who wants to take a shot at creating games for the Microsoft Windows platform with the XNA Framework, then this book is for you. Using this book, you can get started with creating games without any game development experience. A basic knowledge of C# would be helpful to kick-start your game development, but it's not essential.

What you will learn

  • Install the Microsoft XNA Framework and its required tools
  • Build XNA Game projects and associated XNA Content projects
  • Create a puzzle-style game exploring the concepts of game states, recursion, and 2D animation
  • Add sound effects to your game with a "fire-and-forget" sound effects manager
  • Create a particle system to generate random explosions
  • Implement sound effects, collisions, and particle-based explosions by building a space shooter inside a chaotic asteroid field.
  • Implement the A path-finding algorithm to allow enemies to track down the player
  • Generate tile-based maps and path-finding enemy tanks amidst a storm of bullets in a multi-axis shooter
  • Combine XNA and Windows Forms to create a map editor for a multi-layered tile map engine
  • Run, jump, and squash enemies in a side-scrolling platform using the maps from your editor
  • Modify your creations for the Xbox 360 platform and deploy your games to the console
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 24, 2010
Length: 428 pages
Edition : 1st
Language : English
ISBN-13 : 9781849690669
Vendor :
Microsoft
Concepts :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Sep 24, 2010
Length: 428 pages
Edition : 1st
Language : English
ISBN-13 : 9781849690669
Vendor :
Microsoft
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 121.97
XNA 4.0 Game Development by Example: Beginner's Guide
€37.99
Microsoft XNA 4.0 Game Development Cookbook
€41.99
XNA 4 3D Game Development by Example: Beginner's Guide
€41.99
Total 121.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Introducing XNA Game Studio Chevron down icon Chevron up icon
Flood Control – Underwater Puzzling Chevron down icon Chevron up icon
Flood Control – Smoothing Out the Rough Edges Chevron down icon Chevron up icon
Asteroid Belt Assault – Lost in Space Chevron down icon Chevron up icon
Asteroid Belt Assault – Lost in Space
Creating the project
Time for action – creating the Asteroid Belt Assault project
Another definition for "sprite"
Time for action – declarations for the Sprite class
Time for action – Sprite constructor
Time for action – basic Sprite properties
Time for action – animation and drawing properties
Time for action – supporting collision detection
Time for action – adding animation frames
Time for action – updating the Sprite
Time for action – drawing the Sprite
A sprite-based star field
Time for action – creating the StarField class
Time for action – updating and drawing the StarField
Time for action – viewing the StarField in action
Animated sprites – asteroids
Time for action – building the AsteroidManager class
Time for action – positioning the asteroids
Time for action – checking the asteroid's position
Time for action – updating and drawing asteroids
Time for action – bouncing asteroids – part 1
Time for action – bouncing asteroids – part 2
Player and enemy shots
Time for action – adding the ShotManager class
Time for action – firing shots
Time for action – updating and drawing shots
Adding the player
Time for action – creating the PlayerManager class
Time for action – handling user input
Time for action – updating and drawing the player's ship
Enemy ships
Time for action – creating the Enemy class
Time for action – waypoint management
Time for action – enemy update and draw
Time for action – creating the EnemyManager class
Time for action – setting up the EnemyManager class
Time for action – spawning enemies
Time for action – updating and drawing the EnemyManager
Summary
Asteroid Belt Assault – Special Effects Chevron down icon Chevron up icon
Robot Rampage – Multi-Axis Mayhem Chevron down icon Chevron up icon
Robot Rampage – Lots and Lots of Bullets Chevron down icon Chevron up icon
Gemstone Hunter – Put on Your Platform Shoes Chevron down icon Chevron up icon
Gemstone Hunter – Standing on Your Own Two Pixels Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(20 Ratings)
5 star 60%
4 star 25%
3 star 5%
2 star 5%
1 star 5%
Filter icon Filter
Top Reviews

Filter reviews by




Roderick C. Dixon Jan 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great tool for learning XNA. Highly recommend it
Amazon Verified review Amazon
Mark Jan 21, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As president of the Rockford .NET User Group I get asked to review books, not all of which I actually get around to review for one reason or another. Usually the book is not engaging me and I don't wind up getting deep enough into the book to write a decent review.This book, however is different. It has fully engaged me and I am thoroughly enjoying it. After working through 8 of the 9 chapters I feel I can offer a solid review.Overall the code has been excellent with only a couple minor typos that I've noted and the games have worked as they are supposed to. I'm learning a lot about XNA and vector math. (I've even written my first game!) I love the way the author explains the mathematics of what the code is doing - instead of just saying "this is what the code does", the author takes the time to explain (sometimes with illustrations) exactly how the code does what it does and why it works the way it does.I really like the way the author introduces a topic, then dives into the code, then follows the code with a "What Just Happened?" section that explains what the code just entered is supposed to do. The explanations are clear and easy to understand, but not "dumbed down."This book is proving itself very valuable in my development efforts.Thank you for a great book!
Amazon Verified review Amazon
Pule Nong Jun 27, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought an ebook version of this book from the publisher's site. This is a practical hands on approach type of book, just at the end of the first chapter I had already built a game called SquareChase.I am not proficient in C# but I was able to follow along very well. The code is easy to read, understand and follow.You do not need to know C# to read this textbook.The book comprises of 4 games that you build as you go along and all these games are interesting. I have already mentioned SquareChase, the other 3 games are flood control, asteroid belt assault and robot rampage. These games are all engaging and fun to play too.This is a great book. I learned a lot from it despite the fact that I am not familiar with the C# programming language. Although I must mention that I have some programming experience working with PHP. I give this book a 100% rating - 5/5.
Amazon Verified review Amazon
Lance W. Larsen Dec 16, 2010
Full star icon Full star icon Full star icon Full star icon Full star icon 5
[…]Firstly, I'm the president of the Madison .NET User Group […] so I get lots of books to review - I generally don't end up doing so - as I get a chapter or two into them - then start skipping around and don't feel that I've read it thoroughly enough to give it a bad, let alone a good review.So when I DO give something a good review -- it really deserves it.And "XNA 4.0 Game Development by Example: Beginner's Guide" by Kurt Jaegers deserves a GREAT review. I'm not done with it yet, but I'm thoroughly engaged by their writing style - I love the way they they dive head first into code, and then follow it up with a "What Just Happened?" section that does a great job explaining in very simple (but not dumbed down) terms. Go here -- […] -- and look at the "Sample Chapter".On top of their writing style, the content is awesome - totally filling in a lot of the blanks and inspiring me to write new code ( which I'll be using for Windows Phone 7 XNA development ) - so look out for better games and (...wait for it... #shock# %gasp%) potential revenue from games that I publish because this book accelerated my learning new XNA techniques.So, in closing - GREAT book - very WELL written - ENGAGING content - HIGHLY encourage those even at all interested in writing Games to grab this book! And if you enjoy it half as much as I am, you will certainly keep this one close at hand while you're writing XNA code.Check out Kurt Jaegers' site - […]-- nice code here as well...!
Amazon Verified review Amazon
Melibojangles May 27, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you have been teaching yourself C#/XNA and are familiar with the concepts needed to create games but are struggling with how to put all those pieces together, this book is for you. For me, this book is just one a-ha moment after another. The code is clean and well documented and focuses on functionality rather than theory. This book is exactly what I needed to move to the next level, and expect to see my game on the Xbox Indie Marketplace soon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela