XNA 3.0 Game
Programming Recipes
A Problem-Solution Approach
Riemer Grootjans
XNA 3.0 Game Programming Recipes: A Problem-Solution Approach
Copyright © 2009 by Riemer Grootjans
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-1855-5
ISBN-13 (electronic): 978-1-4302-1856-2
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
Lead Editor: Ewan Buckingham
Development Editor: Joohn Choe
Technical Reviewer: Fabio Claudio Ferracchiati
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell,
Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper,
Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Project Manager: Richard Dal Porto
Copy Editors: Heather Lang, Kim Wimpsett
Associate Production Director: Kari Brooks-Copony
Production Editor: Elizabeth Berry
Compositor: Linda Weidemann, Wolf Creek Publishing Services
Proofreader: April Eddy
Indexer: Broccoli Information Management
Artist: April Milne
Cover Designer: Kurt Krames
CHAPTER 5 Getting the Most Out of Vertices 393
CHAPTER 6 Adding Light to Your Scene in XNA 3.0 521
CHAPTER 7 Adding Sounds to Your XNA 3.0 Project 583
CHAPTER 8 Networking in XNA 3.0 599
INDEX 631
vii
Contents
About the Author xxiii
About the Technical Reviewer xxv
Acknowledgments xxvii
Introduction xxix
CHAPTER 1 Getting Started with XNA 3.0 1
1-1. Install XNA Game Studio 3.0 1
1-2. Start Your First XNA 3.0 Project 2
1-3. Deploy Your XNA 3.0 Game on Xbox 360 5
1-4. Deploy Your XNA 3.0 Game on the Zune 8
1-5. Deploy Your XNA 3.0 Game on Another PC 10
1-6. Customize Game Loop Timing 12
1-7. Make Your Code Plug-and-Play Using GameComponents 14
1-8. Allow Your GameComponents to Communicate with
Each Other by Implementing GameServices
18
1-9. Save and Load Data to or from a File 23
CHAPTER 2 Setting Up Different Camera Modes in Your 3D World 29
2-1. Set Up the Camera: Position, Target, and View Frustum 30
2-2. Specify the Target of Your Camera 37
2-3. Create a First-Person Shooter Camera: A Quake-Style Camera 44
2-4. Create a Freelancer-Style Camera: Full 3D Rotation
Using Quaternions
50
3-10. Extend the Image Content Processor: Grayscale Conversion
and Processor Parameters
226
3-11. Make Your Scene More Impressive with Billboarding:
Render 2D Images in a 3D World So They Always Face
the Camera
231
3-12. Create a 3D Explosion Effect/Simple Particle System 253
3-13. Create a Mirror: Projective Texturing 266
CHAPTER 4 Working with Models 281
4-1. Load and Render a Model Using the BasicEffect Class 282
4-2. Set Different World Matrices for Different Objects,
Combining World Matrices
286
4-3. Find the Rotation Angle Corresponding to a Direction 293
4-4. Use Acceleration to Control Velocity 295
4-5. Construct the Global BoundingSphere Around a Model 299
4-6. Scale the Model to a Predefined Size 302
4-7. Render a Model Using Custom Effects and Custom Textures
(Easy Approach)
304
4-8. Visualize the Bone Structure of a Model 309
4-9. Make the Bones Move Individually: Model Animation 316
4-10. Use BoundingSpheres for Basic Model Collision Detection 321
4-11. Use Ray-Traced Collision Detection for Small/Fast Objects 327
The Problem 327
NCONTENTS
ix
4-12. Extend the Model Content Processor to Load Custom Effects
(Clean Approach)
VertexBuffer
429
5-8. Create a Terrain Based on a VertexBuffer and an IndexBuffer 436
5-9. Calculate the Exact Height of a Terrain Between Vertices
Using Bilinear Interpolation
446
5-10. Calculate the Collision Point Between the Pointer and
the Terrain: Surface Picking
452
5-11. Load Data from an XML File 460
5-12. Create Your Own Vertex Format 466
5-13. Work with Bump Mapping: Fixed Normal 476
5-14. Add Per-Pixel Detail by Bump Mapping in Tangent Space 481
5-15. Add an Ocean to Your 3D World 493
5-16. Apply Catmull-Rom Interpolation in 3D to Generate
Additional Vertices
507
5-17. Create the Vertices for a Racing Track 511
The Problem 511
NCONTENTS
x
CHAPTER 6 Adding Light to Your Scene in XNA 3.0 521
6-1. Define Normals and Use the BasicEffect. . . . . . . . . . . . . . . . . . . . . . . 522
6-2. Share Normals Between Vertices 528
6-3. Add Higher Detail to Your Lighting: Per-Pixel Lighting 533
6-4. Add Specular Highlights to Reflective Surfaces 536
6-5. Add HLSL Vertex Shading 538
6-6. Define a Point Light Using HLSL 545
6-7. Add HLSL Per-Pixel Lighting 547
6-8. Define a Spotlight Using HLSL 551
helping more than 1,500 people on their paths to XNA success every day.
In July 2007 and July 2008, he received the Microsoft MVP Award for his contributions to the
XNA community.
xiii
About the Technical Reviewer
A prolific writer on cutting-edge technologies, FABIO CLAUDIO FERRACCHIATI has contributed to
over a dozen books on .NET, C#, Visual Basic, and ASP.NET. He is a .NET MCSD and lives in
Milan, Italy.
xv
Acknowledgments
I would like to express my appreciation and thankfulness to the skillful group of professionals
at Apress who helped me complete this book.
Thanks to Regis Le Roy for the 3D models he provided me to play around with and test
the code on. Furthermore, I would like to thank Danc from dppl6++hkopc]n`aj*_ki for the 2D
artwork used in my book and code. There are some real gems to be found on your site!
And last but definitely not least, I thank Xan Tium from dppl6++t)o_aja*_ki for providing
me with the necessary hardware on which to test my code.
xvii
Introduction
When Microsoft released XNA in December 2006, it immediately became clear that this
new technology would have a major impact on the possibilities for game developers. XNA was
designed from the ground up with ease of use in mind, while not sacrificing performance or
capabilities to achieve this goal. As a bonus, any game you create in XNA for the PC also runs
on the Xbox 360 console! With the coming of XNA 3.0, you can even run your 2D game on the
Zune handheld device.
In the span of two years, a large user community has grown around XNA. You can find
code examples on a vast number of sites, ask your questions in one of the lively forums, or
even meet local people who share the same passion in one of the XNA user groups. Whether
you want to get up to speed with XNA quickly or you have tried some of the tutorial sites and
are looking for the next step, this book is for you. With almost 100 recipes dealing with various
s )NSTALL 8.! 'AME 3TUDIO
s 3TART 9OUR &IRST 8.! 0ROJECT
s #USTOMIZE 'AME ,OOP 4IMINGS
s $ISPLAY $ )MAGES ,OAD AND 2ENDER )MAGES 5SING THE 3PRITE"ATCH #LASS
s 2OTATE 3CALE AND -IRROR AN )MAGE
s 2ENDER 4RANSPARENT )MAGES 5SING ,AYERS
s #ONSIDER 0ERFORMANCE 7HEN 5SING THE 3PRITE"ATCH #LASS
s $ISPLAY 4EXT
If You’re Going from 2D to 3D
The step from 2D to 3D often seems much steeper than it actually is. If you go through the fol-
lowing recipes in the listed order, you’ll learn all about what’s needed to define your own 3D
worlds:
s 3ET 5P THE #AMERA 0OSITION 4ARGET AND 6IEW &RUSTUM
s 3PECIFY THE 4ARGET OF 9OUR #AMERA
s #REATE A &IRST0ERSON 3HOOTER #AMERA ! 1UAKE3TYLE #AMERA
s ,OAD AND 2ENDER A -ODEL 5SING THE "ASIC%FFECT #LASS
s 3ET $IFFERENT 7ORLD -ATRICES FOR $IFFERENT /BJECTS #OMBINING 7ORLD -ATRICES
s 2ENDER 4RIANGLES ,INES AND 0OINTS IN A $ 7ORLD
s !PPLY A 4EXTURE TO 9OUR 4RIANGLES
Start Using the Content Pipeline
If you’re interested in getting into the XNA content pipeline, I advise you to read the following
recipes in this order:
s %XTEND THE )MAGE #ONTENT 0ROCESSOR
s %XTEND THE )MAGE #ONTENT 0ROCESSOR 'RAYSCALE #ONVERSION AND 0ROCESSOR
Parameters
s 'AIN $IRECT !CCESS TO 6ERTEX 0OSITION $ATA BY %XTENDING THE -ODEL 0ROCESSOR
NINTRODUCTION
xix
s 'AIN $IRECT !CCESS TO 6ERTEX 0OSITION $ATA OF %ACH -ODEL-ESH BY %XTENDING THE
Model Processor
NINTRODUCTION
xx
Downloading the Code
The accompanying code for this book can be downloaded for free from this book’s page on the
Apress website (sss*]lnaoo*_ki+reas+^kkg+-0/, 411t) and sss*neaiano*jap.
Contacting the Author
You can ask any question and share all comments on my forum at sss*neaiano*jap+Bknqi,
which I visit as frequently as I can.
CHAPTER 1
Getting Started with XNA 3.0
The first part of this chapter will get you up and running with XNA 3.0 by guiding you through
the installation process and helping you get your code running on a PC and on the Xbox 360
console. The second part of this chapter contains some more advanced topics for those inter-
ested in the inner workings of the XNA Framework.
Specifically, the recipes in this chapter cover the following:
s )NSTALLING 8.! 'AME 3TUDIO AND STARTING YOUR FIRST 8.! PROJECT RECIPES
AND
s 2UNNING YOUR CODE ON THE 0# :UNE AND THE 8BOX CONSOLE RECIPES AND
s ,EARNING MORE ABOUT THE TIMING FOLLOWED BY THE 8.! &RAMEWORK RECIPE
s -AKING YOUR CODE PLUGANDPLAY USING C]ia?kilkjajp classes and C]iaOanre_ao
RECIPES AND
s !LLOWING USERS TO SAVE AND LOAD THEIR games using XNA’s storage capabilities
RECIPE
1-1. Install XNA Game Studio 3.0
The Problem
You want to start coding your own games.
The Solution
Before you can start coding your own games, you should install your development environ-
ment. XNA 'AME 3TUDIO ALLOWS YOU TO CREATE YOUR WHOLE GAME PROJECT USING A SINGLE
that when you experience trouble when connecting your game over other PCs or consoles, the
problem might be caused by incorrect or third-party firewall settings.
&INALLY HIT THE )NSTALL BUTTON TO INSTALL 8.! 'AME 3TUDIO .
1-2. Start Your First XNA 3.0 Project
The Problem
9OU WANT TO START CODING A NEW 8.! GAME )N ADDITION THE DEFAULT STARTUP CODE ALREADY
contains a few methods, so you want to know what these are for and how they help make your
life easier.
The Solution
/PENING A NEW PROJECT IS THE SAME IN MOST 7INDOWS PROGRAMS )N 8.! 'AME 3TUDIO GO TO
the File menu, and select New
° 0ROJECT
CHAPTER 1 N GETTING STARTED WITH XNA 3.0
3
How It Works
Starting XNA Game Studio 3.0
3TART 8.! 'AME 3TUDIO BY CLICKING THE 3TART BUTTON AND SELECTING 0ROGRAMS &IND -ICROSOFT
8.! 'AME 3TUDIO CLICK IT AND SELECT -ICROSOFT 6ISUAL 3TUDIO OR -ICROSOFT 6ISUAL #
%XPRESS %DITION IF YOU INSTALLED THE FREE VERSION
Starting a New XNA 3.0 Project
)N 8.! 'AME 3TUDIO OPEN the File menu, and select New ° 0ROJECT )N THE LIST ON THE
LEFT 8.! 'AME 3TUDIO UNDER 6ISUAL # SHOULD BE HIGHLIGHTED BY DEFAULT AS SHOWN IN &IG-
URE /N THE RIGHT HIGHLIGHT 7INDOWS 'AME 'IVE YOUR NEW PROJECT A FANCY NAME AND
hit the OK button.
Figure 1-1. Starting a new XNA 3.0 project (Visual Studio 2008 Express Edition)
Examining the Predefined Methods
7HEN YOU START A NEW 8.! PROJECT YOU WILL GET A CODE FILE ALREADY containing some code.
#OMMENTS SHOWN IN GREEN MAKE UP MORE THAN PERCENT OF THE CODE TO HELP YOU GET STARTED
)N A FEW MOMENTS YOU WILL FIND THAT THE METHODS YOURE PRESENTED WITH REALLY ARE QUITE
useful, because they greatly reduce the time you would otherwise spend doing basic stuff. For
the @n]s method.
LoadContent Method
7HENEVER YOU START A GAME YOU WILL WANT TO LOAD ART SUCH AS IMAGES MODELS AND AUDIO FROM
disk. To speed things up and allow a lot of flexibility, XNA manages this art through the con-
tent pipeline.
All art loading should be done in the Hk]`?kjpajp method. This method is called only once
AT THE BEGINNING OF YOUR PROJECT
! DETAILED EXAMPLE ON HOW TO LOAD A $ IMAGE INTO YOUR 8.! PROJECT IS GIVEN IN RECIPE
The same approach can be used to load any kind of art.
UnloadContent Method
)F SOME OF THE OBJECTS USED IN YOUR GAME REQUIRE SPECIFIC DISPOSING OR UNLOADING THE
Qjhk]`?kjpajp method IS THE IDEAL SPOT TO DO THIS )T IS CALLED ONCE BEFORE the game exits.
CHAPTER 1 N GETTING STARTED WITH XNA 3.0
5
Adding an .fx HLSL File
)F YOU WANT TO GO ONE STEP FURTHER AND ADD AN (,3, FILE TO YOUR PROJECT SIMPLY FIND THE #ONTENT
ENTRY IN YOUR 3OLUTION %XPLORER AT THE TOPRIGHT OF YOUR SCREEN 2IGHTCLICK IT AND SELECT !DD
°
.EW )TEM 3ELECT h%FFECT FILEv AND GIVE IT A NAME OF YOUR CHOICE
You’ll get some default code, which you’ll want to extend or replace with code you find
ELSEWHERE IN THIS BOOK !FTER THAT YOU NEED TO IMPORT IT LIKE ANY OTHER CONTENT OBJECT BY CREAT-
ing a suitable variable and linking this file to that variable.
Add this variable to the top of your main C]ia class:
Abba_p iuAbba_p7
Then link it to your code file in the Hk]`?kjpajp method:
lnkpa_pa` kranne`a rke` Hk]`?kjpajp$%
w
iuAbba_p 9 ?kjpajp*Hk]`8Abba_p:$abba_pBeha%7
y
NNote You’ll have to change the name of the asset, abba_pBeha in this case, to the name of your
Obtaining the Creators Club License
)F YOU ARE A STUDENT CHANCES ARE YOU CAN OBTAIN A FREE LICENSE FROM THE -ICROSOFT $REAM3PARK
program. You can access this from dppl6++`ksjhk]`o*_d]jjah4*io`j*_ki ,OG IN WITH YOUR STU-
DENT CREDENTIALS TO OBTAIN A CODE WHICH YOU CAN ENTER BY GOING TO THE -ARKETPLACE TAB IN YOUR
8BOX DASHBOARD AND CHOOSING h2EDEEM CODEv
/THERWISE YOU CAN SIMPLY LOG YOUR 8BOX CONSOLE ON TO THE 8BOX ,IVE -ARKETPLACE
AND THEN NAVIGATE TO 'AMES
° !LL 'AME $OWNLOADS )N THE LIST FIND 8.! #REATORS #LUB AND
select it.
4HEN SELECT -EMBERSHIPS AND YOU CAN BUY A LICENSE FOR FOUR MONTHS OR FOR ONE YEAR
Alternatively, you can also enter a code that you can find on a Creators Club voucher card.
Installing XNA Game Studio Connect on Your Xbox 360
This program makes your Xbox 360 listen for any incoming connections from your PC.
9OU CAN DOWNLOAD THIS FOR FREE BY GOING TO THE 8BOX ,IVE -ARKETPLACE AND BROWSING TO
'AME 3TORE
° -ORE ° 'ENRES ° Other. Start the program after you’ve finished installing it.
Connecting Your Xbox 360 and PC
Before your PC can stream data to the Xbox 360, the two devices need to be connected by a
,!. AND TO THE )NTERNET )F BOTH YOUR 8BOX AND 0# ARE ATTACHED TO A ROUTER SWITCH OR HUB
this should be OK.
Nowadays, more and more home networks are relying on a wireless network. This might
be a problem, because the Xbox 360 doesn’t ship with a wireless adapter by default. One solu-
TION IS TO HAVE A 0# WITH BOTH A WIRELESS AND A WIRED %THERNET NETWORK WHICH IS COMMON
FOR MOST NEW LAPTOPS #ONNECT THE 0# TO YOUR WIRELESS NETWORK AT HOME AND ADD A PATCH
cable between your Xbox 360 and PC. Finally, on your PC, click the Start button, and navigate
to Settings
° .ETWORK #ONNECTIONS (IGHLIGHT BOTH YOUR WIRELESS AND %THERNET ADAPTERS RIGHT
click one, and select Bridge Connections AS SHOWN IN &IGURE 7AIT FOR A FEW MINUTES AND
BOTH MACHINES SHOULD BE CONNECTED TO THE )NTERNET and to each other!
CHAPTER 1 N GETTING STARTED WITH XNA 3.0
&IGURE
CHAPTER 1 N GETTING STARTED WITH XNA 3.0
8
Figure 1-3. Generating an Xbox 360 project
Figure 1-4. Selecting the Configuration Manager
)N THE DIALOG THAT APPEARS CLICK THE h!CTIVE SOLUTION PLATFORMv LIST AND SELECT .EW
Next, select Xbox360, and close all dialogs.
&ROM NOW ON THE LIST SHOWN IN &IGURE SHOULD CONTAIN AN 8BOX ENTRY WHICH YOU
SHOULD SELECT WHENEVER YOU WANT TO DEPLOY TO YOUR 8BOX CONSOLE -AKE SURE YOUR 8BOX IS
RUNNING 8.! 'AME 3TUDIO #ONNECT AND IS WAITING FOR A CONNECTION 7HEN YOU HIT & YOUR
files will be uploaded to and executed on your Xbox 360 console!
1-4. Deploy Your XNA 3.0 Game on the Zune
The Problem
Once you HAVE CREATED AND TESTED YOUR $ GAME ON THE 0# YOU WANT TO UPLOAD YOUR GAME TO
YOUR :UNE AND RUN IT
The Solution
/NE OF THE MAIN NEW FEATURES OF 8.! IS :UNE SUPPORT FOR $ GAMES 3INCE THE :UNE OBVI-
ously can’t compare to the power of the graphics card inside your computer, you cannot
EXECUTE ANY 8.! $ APPLICATION ON THE :UNE (OWEVER THE COMPLETE Olnepa>]p_d !0) IS AVAIL-
ABLE ON THE :UNE ALLOWING YOU TO CREATE MOBILE $ GAMES
CHAPTER 1 N GETTING STARTED WITH XNA 3.0
9
How It Works
!S WITH THE 8BOX CONSOLE YOU DONT HAVE TO MAKE ANY ADJUSTMENTS TO YOUR CODE TO MAKE
IT RUN ON THE :UNE *UST CONNECT THE :UNE TO YOUR 0# SET IT AS THE ACTIVE TARGET AND DEPLOY
your game.
Connecting the Zune to Your PC
#ONNECT THE :UNE TO YOUR 0# USING THE 53" CABLE THAT SHIPPED WITH THE :UNE AND POWER IT
ON .EXT OPEN THE 8.! 'AME 3TUDIO $EVICE #ENTER BY CLICKING THE 3TART MENU AND SELECT-
ing Programs
AND HIT & TO INITIATE THE DEPLOYMENT
/NCE YOUR :UNE SCREEN INDICATES THE DEPLOYMENT HAS BEEN COMPLETED RESTART YOUR :UNE
SELECT 'AMES IN YOUR :UNES MAIN menu, and start your game!