XNA 4 3D Game Development by Example: Beginner's Guide - Kurt Jaegers - E-Book

XNA 4 3D Game Development by Example: Beginner's Guide E-Book

Kurt Jaegers

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Move beyond the world of flat 2D-based game development and discover how to create your own exciting 3D games with Microsoft XNA 4.0. Create a 3D maze, fire shells at enemy tanks, and drive a rover on the surface of Mars while being attacked by alien saucers."XNA 4 3D Game Development by Example: Beginner's Guide" takes you step-by-step through the creation of three different 3D video games with Microsoft XNA 4.0. Learn by doing as you explore the worlds of 3D graphics and game design.This book takes a step-by-step approach to building 3D games with Microsoft XNA, describing each section of code in depth and explaining the topics and concepts covered in detail. From the basics of a 3D camera system to an introduction to writing DirectX shader code, the games in this book cover a wide variety of both 3D graphics and game design topics. Generate random mazes, load and animate 3D models, create particle-based explosions, and combine 2D and 3D techniques to build a user interface."XNA 4 3D Game Development by Example: Beginner's Guide" will give you the knowledge to bring your own 3D game creations to life.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 406

Veröffentlichungsjahr: 2012

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

XNA 4 3D Game Development by Example Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Instant Updates on New Packt Books
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Time for action – heading
What just happened?
Pop quiz – heading
Have a go hero – heading
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introduction to XNA
System requirements
Installing the Windows Phone SDK
Time for action – installing Windows Phone SDK
What just happened?
Speller – Our first XNA game
Time for action – creating an XNA project
What just happened?
Managing content
Time for action – creating content assets
What just happened?
Member variables
Time for action – declaring new member variables
What just happened?
The Game1 constructor
Initialization
Time for action – customizing the Initialize() method
What just happened?
Loading content
Time for action – creating a square texture
What just happened?
Updating
Time for action – customizing the Update() method
What just happened?
The Draw() method
Time for action – drawing Speller
What just happened?
Helper methods
Time for action – words and letters
What just happened?
Time for action – completing the Speller project
What just happened?
Have a go hero
Summary
2. Cube Chaser – A Flat 3D World
Designing the game
3D coordinates
Creating the project
Time for action – creating the Cube Chaser project
What just happened?
Our view of the world
Time for action – beginning the Camera class
What just happened?
The Projection matrix
Looking at something
Time for action – implementing a look-at point
What just happened?
The View matrix
Time for action – the View matrix
What just happened?
From the ground up
Time for action – creating the Maze classes
What just happened?
Drawing the floor
Time for action – drawing the floor
What just happened?
Moving around
Time for action – expanding the Camera
What just happened?
Time for action – letting the player move
What just happened?
Summary
3. Cube Chaser – It's A-Mazing!
Maze generation
Time for action – defining a MazeCell
What just happened?
Time for action – generating the Maze class
What just happened?
Constructing the walls
Time for action – building walls
What just happened?
Time for action – drawing the walls
What just happened?
Solid walls
Time for action – bouncing off the walls
What just happened?
Have a go hero
Summary
4. Cube Chaser – Finding Your Way
The cube
Time for action – placing the cube
What just happened?
Rotating the cube
Time for action – rotating the cube
What just happened?
Matrices – big scary math things?
The translation matrix
The rotation matrix
The scale matrix
Combining matrices
What does it all mean?
Positioning the cube
Time for action – randomly positioning the cube
What just happened?
Catching the cube
Time for action – catching the cube
What just happened?
Have a go hero!
Summary
5. Tank Battles – A War-torn Land
Creating the project
Time for action – creating the Tank Battles project
What just happened?
An arc-ball camera
Time for action – the ArcBallCamera class – part 1
What just happened?
Time for action – finishing the ArcBallCamera class
What just happened?
Building the playfield
Height maps
Generating the terrain
Time for action – generating the terrain
What just happened?
Height data
Time for action – adding the ReadHeightMap() method
What just happened?
Building vertices
Time for action – adding the BuildVertexBuffer() method
What just happened?
Building the indices
Time for action – the buildIndexBuffer() method
What just happened?
Let's see the terrain already!
Time for action – drawing the terrain
What just happened?
Adding texture – a gentle introduction to HLSL
Declaring variables
Time for action – HLSL declarations
What just happened?
The vertex shader structures
Time for action – Vertex Shader Input and Output definition
What just happened?
The vertex shader
Time for action – the vertex shader
What just happened?
The pixel shader
Time for action – the pixel shader
What just happened?
Time for action – utilizing Terrain.fx
What just happened?
Moving the camera
Time for action – moving the camera with the mouse
What just happened?
Summary
6. Tank Battles – The Big Guns
Adding the tank model
Time for action – adding the tank model
What just happened?
Building tanks
Time for action – building the Tank class
What just happened?
Bringing things down to earth
Time for action – terrain heights
What just happened?
Animating the tank
Time for action – tank animation
What just happened?
The combatants
Time for action – positioning tanks
What just happened?
Summary
7. Tank Battles – Shooting Things
Interface components
The UIWidget class
Time for action – creating the UIWidget class
What just happened?
UITextblocks
Time for action – creating UITextblocks
What just happened?
UIButtons
Time for action – creating buttons
What just happened?
Working with our UI objects
Time for action – adding the UIHelper class
What just happened?
Creating the user interface
Time for action – creating the UI
What just happened?
Responding to interface events
Time for action – responding to events
What just happened?
Firing shots
Time for action – ShotManager-part 1
What just happened?
Particles in 3D
Billboarded particles
Time for action – the Particle class-part 1
What just happened?
Time for action – finishing the Particle class
What just happened?
Managing particles
Time for action – the ParticleManager class
What just happened?
HLSL for our particles
Time for action – building Particles.fx
What just happened?
Adding particles
Time for action – implementing particles
What just happened?
Summary
8. Tank Battles – Ending the War
Managing game states
Time for action – implementing a title screen
What just happened?
From Playing to GameOver
Time for action – detecting hits
What just happened?
Managing turns
Time for action – managing turns
What just happened?
Visual improvements
Lighting
Time for action – computing normals
What just happened?
Diffuse lighting
Time for action – HLSL for lighting
What just happened?
Ambient lighting
Time for action – using ambient light
What just happened?
Multitexturing
Time for action – multitexturing
What just happened?
Have a go hero!
Summary
9. Mars Runner
Design of Mars Runner
Getting started with the GSM sample
Time for action – creating the Mars Runner solution
What just happened?
The GameScreen abstract class
Customizing the default ScreenManager screens
Time for action – customizing the BackgroundScreen class
What just happened?
Time for action – updating the menu
What just happened?
Adding a new screen
Time for action – creating the MarsRunnerPlayScreen class
What just happened?
A new camera
Time for action – the stationary camera
What just happened?
Creating the background
Time for action – creating a skybox
What just happened?
Building the Martian surface
Simplified heightmaps
Time for action – beginning the MarsTrack class
What just happened?
Time for action – generating the track
What just happened?
Drawing the track
Time for action – drawing the track
What just happened?
Summary
10. Mars Runner – Reaching the Finish Line
Abstracting support for 3D models
Time for action – the GameEntity class
What just happened?
Building the rover
Time for action –building the rover
What just happened?
Time for action – accepting user input
What just happened?
Animating the planet
Time for action – moving the world
What just happened?
Animating the rover
Time for action – animating the rover
What just happened?
Crashing into craters
Time for action – detecting craters
What just happened?
Adding an enemy
Time for action – the basic flying saucer
What just happened?
Time for action – flying the saucer
What just happened?
Shots and collisions
Time for action – Shot classes
What just happened?
Time for action – the ShotManager class
What just happened?
Enemy shots
Time for action – enemy shots
What just happened?
Time for action – player shots versus aliens
What just happened?
Time for action – enemy shots versus the rover
What just happened?
Scoring
Time for action – scoring
What just happened?
Time for action – the GameOver screen
What just happened?
Sound effects
Time for action – building the SFXManager class
What just happened?
Triggering sounds
Time for action – playing sound effects
What just happened?
Have a go hero!
Summary
Index

XNA 4 3D Game Development by Example Beginner's Guide

XNA 4 3D Game Development by Example Beginner's Guide

Copyright © 2012 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2012

Production Reference: 1180912

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84968-708-9

www.packtpub.com

Cover Image by Sandeep Babu (<[email protected]>)

Credits

Author

Kurt Jaegers

Reviewers

Kenneth Dahl Pedersen

Michael Schuld

Newton Sheikh

Pedro Daniel Güida Vázquez

Acquisition Editor

Dilip Venkatesh

Lead Technical Editor

Ankita Shashi

Technical Editors

Prashant Salvi

Ankita Shashi

Copy Editor

Alfida Paiva

Project Coordinator

Joel Goveya

Proofreaders

Aaron Nash

Chris Smith

Indexer

Tejal Soni

Graphics

Aditi Gajjar

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

About the Author

Kurt Jaegers is an Oracle Database Administrator and Windows Network Administrator, as well as a long-time hobbyist game developer. He has built games for everything from the Commodore 64 to the Xbox 360. He is the owner of xnaresources.com, and the author of XNA 4.0 Game Development by Example: Beginner's Guide (C# edition) and XNA 4.0 Game Development by Example: Beginner's Guide – Visual Basic Edition, both of which were published by Packt Publishing.

As always, I would like to thank my wife Linda for proofreading my original drafts. I would also like to thank the visitors to my website and the readers of my first two XNA books for their support, encouragement, and thought provoking questions. Finally, I would like to thank the team at Packt Publishing. This is my third book with them, and the experience has always been wonderful.

About the Reviewers

Kenneth Dahl Pedersen now aged 35, has been programming since he got his first computer at age 6, starting on the Commodore 64 with small programs that could do next to nothing. It quickly evolved when he migrated to the much more powerful Amiga 500, developing some demos and light applications, and finally culminated when he got his first PC.

Since then, game development has held his interest in a vice grip and Kenneth has since then studied numerous programming languages and APIs for that purpose, his repertoire includes C/C++, OpenGL, DirectX, C#, WPF, WCF, MDX, and XNA.

With the appearance of readily available high-end engines, such as Unreal Development Kit, Kenneth had found another interest to keep him well sated in his thirst for game development knowledge. UnrealScript provided another mountain top to climb.

Kenneth has an education as a Systems Analyst and Developer. Originally from Denmark, where he still works, he now lives in Sweden with his wife and baby daughter.

Other than his wife and daughter, he uses his spare time for game development, seeking new knowledge, and dabbling in 3D visual arts in applications such as 3D Studio Max and ZBrush. And of course, Kenneth is an avid gamer – after all, you cannot make a game if you don't enjoy playing them!

First of all, I would like to thank my wife, Nina, for the patience she's shown while I was doing this review—I have probably not been as helpful around the house as I should have been while this has been going on.

My beautiful daughter, Nadia, for always giving me a reason to smile 
and laugh.

Michael Schuld started his foray into game development using Managed DirectX v9; after playing with the framework for a few months, he decided there wasn't enough beginner content out in the world to help those people who are new to game development.

To fix this problem, he immediately set out writing a tutorial series that he kept up to date with the change from Managed DirectX to XNA and all the updates to the XNA Framework since then. Along with these tutorials, he has hosted a popular XNA Game Development forum and has helped hundreds of programmers new to game development get their feet wet. The site and tutorials have been listed by Microsoft and GameInformer as one of a select list of community resources for anyone wanting to learn the XNA Framework.

More recently, he has expanded his work into DirectX v11 and reviewing books in the game development arena. His recent work, tutorials, and reviews can all be found on http://www.thehazymind.com.

I would like to thank David Bonner, Charles Humphrey, and Michael Quandt for their early interest and assistance with my tutorial series, both in reviewing the content for ease of use and helping out with the forums. I'm glad to have you guys around to keep things from getting too crazy.

Newton Sheikh, is a software engineer working on Cloud applications for Windows Azure platform. Newton has been working with .NET technologies for the last 4 years and loves programming both in C# and VB. Newton's hobbies include web development and web designing. He is a casual game programmer for Android and Windows. When not programming, Newton loves to hang out with his friends.

Newton made a very humble start of his career with a company named Inyxa LLC based in Faridabad, India. Currently Newton is working with Hanu Softwares in Gurgaon, India.

Pedro Daniel Güida Vázquez is an Economist, System Analyst, Professor, and Microsoft MVP for DirectX and XNA, which are some of the accomplishments obtained throughout his life. Owner of Pulsar Coders, an indie company that develops videogames for many platforms, he enjoys working daily on everything related to videogame development. His skills cover many areas in the field, both technical and artistic, and he is always looking for interesting challenges to extend his personal and professional goals. You can find a comprehensive bio of Pedro at http://www.linkedin.com/in/pedroguida.

Pedro has worked on XNA 4.0 Game Development by Example: Beginner's Guide – Visual Basic Edition (Book) and XNA Game Development Video Training Screencast (Video tutorial), both of which are endeavors by Packt Publishing.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Instant Updates on New Packt Books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.

Preface

Microsoft's XNA Framework provides C# developers with a robust and efficient method of utilizing the DirectX and Direct3D Application Programming Interfaces (APIs) in order to build 3D games for the Windows, Xbox 360, and Windows Phone platforms.

This book will present a series of video games, utilizing the XNA Framework to create 3D environments and objects. The games we build in this book will be targeted to the Windows platform, though they can be compiled to run on both the Xbox 360 and Windows Phone with minor changes to accommodate input methods on those devices.

Each of the games presented will build on the 3D concepts of the previous games, and finally wrapping up with a game built around the Game State Management system sample code available from the Microsoft XNA website.

What this book covers

Chapter 1 , Introduction to XNA, begins by installing the Windows Phone Development Tools package that includes the Version 4.0 release of the XNA tools. We will examine the basic building blocks of an XNA game and create a 2D mini game called Speller to establish a baseline of 2D techniques that will be needed while building 3D games later.

Chapter 2, Cube Chaser – A Flat 3D World, introduces basic 3D concepts such as cameras and projections. We will build a floor for our 3D maze using colored triangles and allow the player to walk around on it.

Chapter 3, Cube Chaser – It's A-Mazing!, explores the generation of a random maze layout using the Depth-first search method. We will construct walls based on the generated maze and restrict player movement within those walls.

Chapter 4, Cube Chaser – Finding Your Way, guides us through the construction of the cube we will be chasing, including mapping textures to the faces of an object. We will randomly position the cube and rotate it to perform a simple animation. We will take a closer look at matrix math in order to understand just what is happening when we move, rotate, and scale objects.

Chapter 5, Tank Battles – A War-torn Land, embarks on the building of a tank combat game. In this chapter we will build a new type of 3D camera and generate a terrain based on a heightmap image. We will explore the fundamentals of High Level Shader Language (HLSL) used to create shader effects that describe the surfaces of the objects we will be rendering.

Chapter 6, Tank Battles – The Big Guns, adds 3D models to our game, importing a tank model and positioning it appropriately on the game's terrain. We also delve into bone-based animation for 3D models, allowing the tank's turret and cannon to be moved by the player.

Chapter 7, Tank Battles – Shooting Things, combines our existing 3D elements with a 2D interface, allowing us to accept input from the user via onscreen buttons. We will create and track shots fired by the players and implement billboard-based particle explosions.

Chapter 8, Tank Battles – Ending the War, wraps up the Tank Battles game by incorporating a simple game flow structure to surround game play and establishing a sequence of turns between two players, modifying the state of our user interface elements appropriately. We will determine the result of fired shots, allowing players to score hits on the enemy tank and win the game. Additionally, we will return to HLSL to implement lighting and multitexturing effects on our terrain to improve the graphical quality of the game.

Chapter 9, Mars Runner, begins a new game – a side-scrolling, jumping game on the surface of Mars. We will work with the Game State Management sample code provided by Microsoft to build the structure of our game. The backdrop for Mars Runner will be implemented as a 3D skybox that surrounds the stationary camera. Finally, we will revisit the heightmap-based terrain by generating terrain tiles that can be joined together to create a track for the player's rover to drive on.

Chapter 10, Mars Runner – Reaching the Finish Line, completes the Mars Runner game by enhancing our handling of 3D models and adding both the player's Mars rover and an enemy alien saucer to the game. We allow both the player and the enemy to fire shots at each other and use bounding box collision detection to determine when one of the entities has been hit. To finish up, we will implement a basic sound effect system, allowing us to play audio clips based on the events taking place in the game.

What you need for this book

In order to install and use the Microsoft XNA 4.0 tools, you will need a Windows PC with either Microsoft Windows Vista or Microsoft Windows 7, and a video card supporting DirectX 9 or later. Shader Model 1.1 is required for XNA, but it is highly recommended that your video card support Shader Model 2.0 or later, as many of the XNA samples available online require 2.0 support.

Who this book is for

If you are an aspiring game developer, looking to get started with XNA, or to expand your 2D XNA knowledge into the 3D realm, this book is for you. A basic knowledge of C# is helpful to kick start your game development, but is not essential.

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions of how to complete a procedure or task, we use:

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title through the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Introduction to XNA

Microsoft's XNA Framework provides a powerful set of tools for building both 2D and 3D games for Windows, the Xbox 360, and the Windows Phone platforms. As an extension of the Visual Studio development environment, XNA provides developers with a set of free tools for these environments.

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 this introductory chapter, we will do the following:

Review the system requirements for XNA developmentInstall the Windows Phone Tools SDK, which includes Visual Studio Express and the XNA 4.0 extensionsExamine the basic structure of an XNA game by building a simple 2D gameExplore a fast-paced rundown of 2D techniques that will provide a foundation for moving forward into 3D with XNA

Starting out a book on 3D game development by building a 2D game may seem like an odd approach, but most 3D games use a number of 2D techniques and resources, even if only to display a readable user interface to the player.

If you already have an understanding of 2D game development in XNA, you may want to glance over this chapter and proceed to Chapter 2, Cube Chaser – A Flat 3D World, where we begin building our first 3D game.

System requirements

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

Component

Minimum requirements

Notes

Operating System

Windows Vista SP2

or

Windows 7 (except Starter Edition)

Windows XP is not 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 also require Shader Model 2.0 support.

Development Platform

Visual Studio 2010

or

Visual Studio 2010 Express

Visual Studio 2010 Express is installed along with the XNA Framework.

Optional

Windows Phone

Windows Phone Development Tools, DirectX 10 or later, compatible video card

The Windows Phone SDK includes a Windows Phone emulator for testing.

Xbox Live

Xbox Live Silver membershipXNA 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.

Installing the Windows Phone SDK

Originally developed as a separate product, XNA is now incorporated in the Windows Phone SDK. You can still develop games for Windows and the Xbox 360 using the tools installed by the Windows Phone SDK.

If you have an existing version of Visual Studio 2010 on your PC, the XNA Framework templates and tools will be integrated into that installation as well as the Visual Studio 2010 Express for Windows Phone installation that is part of the Windows Phone SDK, which we are going to install now.

Time for action – installing Windows Phone SDK

To install Windows Phone SDK , perform the following steps:

Visit http://create.msdn.com/en-us/home/getting_started and download the latest version of the Windows Phone SDK package. Run the setup wizard and allow the installation package to complete.Open Visual Studio 2010 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 2010 Express and enter the registration number into the registration dialog box.Close Visual Studio 2010 Express.Launch Visual Studio 2010 Express, and the Integrated Development Environment (IDE) will be displayed as shown in the following screenshot:

What just happened?

You have now successfully installed the Windows Phone SDK, which includes Visual Studio 2010 Express, the XNA Extensions for Visual Studio, and the Redistributable Font Pack provided by Microsoft for XNA developers.

Speller – Our first XNA game

If you have never used XNA before, it would be helpful to review a number of concepts before you dive into 3D game design. In most 3D games, there will be at least some 2D content for user interfaces, Heads-up display (HUD) overlays, text alerts, and so on. In addition, many 3D game constructions are really evolutions of 2D game concepts.

In order to provide both an overview of the XNA game template and to build a foundation for moving forward into 3D development, we will construct a simple game called Speller. In Speller, the player controls a small square using the keyboard. During each round we will generate a random set of letters, including the letters needed to spell a particular word. The player's job is to navigate through the forest of letters and hit only the correct ones in the right order to spell the indicated word.

By building this game, we will be:

Performing initialization when our game is executedAdding graphical assets to the game and loading them at run timeDisplaying 2D images with the SpriteBatch classDrawing text to the screen with the SpriteFont classColorizing images and fontsHandling keyboard input and calculating player movement adjusted for the frame rateBounding box collision detectionKeeping and displaying the scoreGenerating random numbers

That is quite a bit of ground to cover in a very small game, so we had better get started!

Time for action – creating an XNA project

To create an XNA project, perform the following steps:

In the Visual Studio window, open the File menu and select New Project....Under Project Type, make sure C# is selected as the language and that the XNA Game Studio 4.0 category is selected.Under Templates, select Windows Game (4.0).Name the project Speller (this will automatically update the Solution Name).Click on OK.

The Speller game's Game1.cs file, when opened in Visual Studio, would look like the following screenshot:

What just happened?

We now have the skeleton of a project upon which we can build the Speller game. Each of the major XNA methods is declared, usually with no additional code except the execution of the method's base. We will examine each area of the XNA game template as we create the pieces necessary for Speller.

Managing content

Two separate projects get created when you start a new XNA Game Studio project in Visual Studio. The first is your actual game project, and the second is a special type of project called a content project. This is shown in the following screenshot:

Any non-code pieces of your game, including graphical resources, sounds, fonts, and any number of other item types (you can define your own content interpreters to read things such as level maps) are added to the content project. This project gets built along with the code in your primary project and the two are combined into a single location with everything your game needs to run.

When the content project is built, each item is examined by a content importer—a bit of code that interprets the raw data of the content file, a .jpg image for example, and converts it into a format that can be passed into a content processor. The content processor's job is to convert this file into a managed code object that can be stored on a disk and read directly into memory by XNA's ContentManager class. These compiled binary files carry the .xnb file extension and are located, by default, in a subdirectory of your game's executable folder called Content.

Tip

ContentManager

Though its primary job is to load the content resources into memory at runtime, ContentManagerdoes more than that. Each instance of ContentManager maintains a library of all of the content that has been loaded. If multiple requests to load the same content file are sent to a ContentManager instance, it will only load the resource from the disk the first time. The remaining requests are supplied with a reference to the item that already exists in memory.

Out of the box, XNA contains importers/processors for 3D meshes, images, fonts, audio, shaders, and XML data. We will create the content used for Speller with an image editor and the tools built into XNA Game Studio.

Time for action – creating content assets

To create content assets, perform the following steps:

Open Microsoft Paint, or your favorite image creation program, and create a new 16 x 16 image. Fill the image with white color and save the file to a temporary location as SQUARE.BMP.Switch back to Visual Studio and right-click on the SpellerContent (Content) project in Solution Explorer.Select Add | Existing Item... from the pop-up menu and browse to the SQUARE.BMP file. Select it and click on Add to add it to the content project.Again, right-click on the content project in Solution Explorer and this time select Add | New Item....In the Add New Item window, select Sprite Font from the window's center pane.Enter Segoe14.spritefont as the name of the file and click on Add.Close the XML document that appears after Sprite Font has been added to the project.

What just happened?

We have now added both an image and a font to our content project. We will see how we load these assets into the game at runtime and how we can use them during gameplay.

Tip

Alternatives when adding content

You can also drag-and-drop files directly from Windows Explorer into the Solution Manager pane in Visual Studio to add them to your content project. If you have the full version of Visual Studio, you can add a new bitmap object by selecting Add | New Item... from the project's pop-up menu and selecting Bitmap as the type. The free version of Visual Studio does not support creating bitmaps from within Visual Studio.

The SpriteFont file that we created in step 6 and the XML document mentioned in step 7 actually load an XML template that describes how the content pipeline should create the resulting .xnb file. In this case, the default values for the SpriteFont template are sufficient for our game. This resulted in the Segoe UI Mono font (added to your system when the Windows Phone SDK is installed), with a value of 14 points being used. As we will only be using the standard A to Z character set, we do not need to make any changes to this template for Speller.

Member variables

Just after the Game1class declaration in the Game1.cs file there are two class member declarations:

GraphicsDeviceManager graphics; SpriteBatch spriteBatch;

These two members will provide access to the system's video hardware (graphics) and an instance of a class that can be used to draw 2D images and text (spriteBatch). We can add our own member variables here for things we need to keep track of while our game is running.

The Game1 constructor

The Game1 class has a simple constructor with no parameters. An instance of this class will be created by the shell contained in the Program.cs file within the project when the game is launched.

Tip

The Program.cs file

When your XNA game starts, the Main() method in the Program.cs file is what actually gets executed. This method creates an instance of your Game1 class and calls the Run() method, which performs the initialization we will discuss shortly. It then begins executing the game loop, updating and drawing your game repeatedly until the program exits. In many games, we will not have to worry about Program.cs, but there are some instances (combining XNA and Windows Forms, for example) when it is necessary to make changes here.

By default, the constructor has created an instance of the GraphicsDeviceManager class to store in the graphics member, and has established the base directory for the Content object, which is an instance of the ContentManager class.

When we build our project, all of the items in the content project are translated into a format specific to XNA, with the .xnb file extension. These are then copied to the Content folder in the same directory as our game's executable file.

Our Speller game will not need to make any changes to the class constructor, so we will simply move on to the next method that is called when our game starts.

Initialization

Once the instance of the Game1 class has been created and the constructor has been executed, the Initialize() method is executed. This is the only time during our game's execution that this method will execute, and it is responsible for setting up anything in our class that does not require the use of content assets.

The default Initialize() method is empty and simply calls the base class' Initialize() method before exiting.

Loading content

After the Initialize() method has run, the LoadContent() method is called. Here, we initialize any items in our game that require the content assets we included in the content project.

Updating

Our game will now enter an endless loop in which the Update() and Draw() methods are called repeatedly until we exit the application. By default, this loop attempts to run 60 times per second on the Windows and Xbox platforms, and 30 times per second on the Windows Phone platform.

The Update() method is used to process all of our game logic, such as checking for and reacting to player input, updating the positions of objects in the game world, and detecting collisions. The Update() method has a single parameter, gameTime, which identifies how much real time has passed since the last call to Update(). We can use this to scale movements smoothly over time to reduce stuttering that would occur if we make the assumption that our update will always run at a consistent frame rate, and code on other system events impacted by the update cycle.