Tải bản đầy đủ (.pdf) (30 trang)

Microsoft XNA Game Studio Creator’s Guide- P1 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (624.72 KB, 30 trang )

Microsoft

XNA

Game Studio
Creator’s Guide
Second Edition
A
BOUT THE AUTHORS
Stephen Cawood is a former Microsoft employee and recovering Halo fan. Stephen
has written a number of books including Augmented Reality: A Practical Guide,
Microsoft Content Management Server 2002: A Complete Guide, The Unauthorized
Halo 2 Battle Guide: Advanced Combat Techniques, The Black Art of Halo Mods,
and Halo 2 Hacks. Stephen currently works for Metalogix Software and lives in Hal-
ifax, Nova Scotia, with his wife Christa and two well-behaved kittens.
Pat McGee is a former games programmer and has worked on the Clifford the Big
Red Dog video game series. In addition to writing the first edition of the Microsoft
XNA Game Studio Creator’s Guide, Pat has also written a book called Games Pro-
gramming in C++ and DirectX. Since 2001, Pat has developed and taught several
courses in games programming at the British Columbia Institute of Technology. Pat
is an Instructor in the Software Systems Developer program at the British Columbia
Institute of Technology. Pat lives in North Vancouver, British Columbia, with his
wife Yumi and their son Owen.
Nick Gravelyn is a two-time Microsoft MVP in the DirectX/XNA category. He has
written countless articles and blog posts relating to XNA, and has recorded many
hours of video tutorials. He is currently the owner and lead programmer of
Metacreature, an indie software company.
Microsoft

XNA



Game Studio
Creator’s Guide
Second Edition
Stephen Cawood
Pat McGee
New York Chicago San Francisco Lisbon London Madrid Mexico City
Milan New Delhi San Juan Seoul Singapore Sydney Toronto
Copyright © 2009 by The McGraw-Hill Companies. All rights reserved. Except as permitted under the United States Copyright Act of
1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval sys-
tem, without the prior written permission of the publisher.
ISBN: 978-0-07-161407-8
MHID: 0-07-161407-9
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-161406-1, MHID: 0-07-161406-0.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked
name, we use names in an editorial fashion only, and to the sbenefit of the trademark owner, with no intention of infringement of the
trademark. Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate
training programs. To contact a representative please visit the Contact Us page at www.mhprofessional.com.
All trademarks or copyrights mentioned herein are the possession of their respective owners and McGraw-Hill makes no claim of
ownership by the mention of products that contain these marks.
Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or
mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of
any information and is not responsible for any errors or omissions or the results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work.
Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one
copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, trans-
mit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the
work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be

terminated if you fail to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS
TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,
INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE,
AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not
warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or
error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless
of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information
accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special,
punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised
of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause
arises in contract, tort or otherwise.
I dedicate this book to my father, John Cawood. To
protect his children from a future that would have
included military service under an oppressive regime,
my dad left our home in 1978 and moved to Canada.
That decision provided me with the sort of
opportunities that led to this book project. In 1994,
when South Africa became a truly democratic country,
my father once again did the right thing and returned.
His goal was lofty—to help South Africa reach its
potential—but that’s what he worked for every day. I
miss him and so does the rest of our family, but it is
his homeland that misses him most of all.
—Stephen Cawood
To my wife Yumi for supporting me on this project
and to my parents Jack and Donna McGee for
assistance along the way.
—Pat McGee

This page intentionally left blank
v
Contents At A Glance
1 Set Up an XNA Development Environment 1
2 Developer Basics 7
3 Behind the Game Window 21
4 2D Games 31
5 Introduction to 3D Graphics Programming 55
6 Shaders 69
7 Animation Introduction 91
8 Character Movement 103
9 Texturing Your Game World 119
10 Adding Skies and Horizons to Your Levels 143
11 Index Buffers 155
12 Combining Images for Better Visual Effects 165
13 Score Tracking and Game Stats 191
14 3D Models 201
15 Vectors 233
16 Matrices 247
17 Building a Graphics Engine Camera 267
vii
18 Collision Detection 285
19 Ballistics 305
20 Particle Effects 323
21 Keyframe Animations 343
22 Lighting 353
23 Input Devices 377
24 Content Pipeline Processors 401
25 Terrain with Height Detection 419
26 Animated Models 437

27 Adding Audio to Your Game 459
28 Multiplayer Gaming 491
29 Networking 505
Index 527
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE
viii
ix
ix
Contents
ACKNOWLEDGMENTS, xix
INTRODUCTION, xxi
1 Set Up an XNA Development Environment 1
Set Up an XNA Development Environment, 2
Install the Software, 3
Join the Xbox 360 Creators Club, 3
Using XNA Game Studio Connect, 3
Connect Your PC to Your Xbox 360, 3
Deploying a Game to Your Zune, 4
Selling Your Games with LIVE Community Games, 5
Download the Examples for This Book, 5
XNA and Your PC Video Card, 6
2 Developer Basics 7
Managing the Code Project, 8
Opening Microsoft XNA Game Studio, 8
Creating a Game Studio Project, 8
Opening an Existing Game Studio Project, 8
Coding Differences Between Windows, the XBox 360,
and the Zune, 9
Creating a Windows Game Project, 9
Creating an Xbox 360 Game Project, 10

Creating a Zune Game Project, 11
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE
x
Editing Your Code, 12
Adding and Removing Code Files to and from the Project, 12
Compiling and Running Game Studio Projects, 12
Saving the Game Studio Project, 13
Deploying an Xbox 360 Game Project, 14
Debugging, 15
Error List, 15
Errors, 15
Warnings, 16
Pausing the Program to View Logic and Variable Values
at Run Time, 16
Watch Lists, 18
Chapter 2 Review Exercises, 19
3 Behind the Game Window 21
Creating the XNA Game Foundation, 22
Initializing the Game Application, 23
GraphicsDeviceManager, 24
SpriteBatch, 24
ContentManager, 24
Initialize(), 25
LoadContent(), 25
Drawing and Updating the Game Application, 25
Draw(), 26
Update(), 26
Closing the Game Application, 26
Basic XNA Game Window Example, 26
Chapter 3 Review Exercise, 28

4 2D Games 31
The Two-Dimensional Coordinate System, 32
Using Image Files in 2D Games, 33
Content Pipeline Overview, 33
Loading and Storing Images, 33
Textures, 33
Animated Sprites, 34
Enabling Transparency, 35
Drawing and Animating Your Sprites, 35
Title Safe Region, 37
xi
CONTENTS
Adding Collision Detection, 37
Rectangle Collision Checking, 37
Transformation Matrices, 37
Per Pixel Collision Checking, 39
Handling User Input Devices, 40
Keyboard Input, 40
GamePad Input, 41
Porting your 2D Games to the Zune, 41
A Starter 2D Game Example, 42
Adding the Images, 42
Animating the Asteroid, 43
Controlling the Ship, 45
Adding in Collision Detection, 48
Completing the 2D Game, 52
Chapter Exercises, 53
5 Introduction to 3D Graphics Programming 55
Primitive Objects, 56
Drawing Syntax, 57

Primitive Object Types, 57
Vertex Types, 58
VertexDeclaration, 59
DrawUserPrimitives, 59
Drawing Primitive Objects Example, 59
Triangle Strip, 61
Triangle List, 63
Drawing a Line Strip, 65
Adding a Line List, 66
Adding a Point List, 67
Chapter 5 Review Exercises, 68
6 Shaders 69
Graphics Pipeline, 70
Shaders, 70
Shader Structure, 71
High Level Shader Language, 72
XNA’s BasicEffect Class, 86
Setting Properties Within the BasicEffect Class, 87
Chapter 6 Review Exercises, 89
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE
xii
7 Animation Introduction 91
Right Hand Rule, 92
Matrix Logic, 93
Transformation Order, 94
XNA Matrix Syntax, 94
Identity Matrix, 94
Scaling Matrix, 95
Rotation Matrices, 95
Translation Matrices, 95

Steps for Drawing a Primitive Object or a 3D Model, 96
Declaring and Initializing Individual Matrices, 96
Building the Cumulative World Matrix, 96
Setting the Shader Values, 96
Drawing the Object, 97
Applying Transformations: Earth and Moon Example, 97
Chapter 7 Review Exercises, 101
8 Character Movement 103
Direction, 104
Calculating Direction Using Trigonometry, 104
Calculating Direction Using Speed, 105
Calculating Direction Using Vectors, 107
Scaling Animations with Time Lapse Between Frames, 108
Character Movement Example, 109
Chapter 8 Review Exercises, 118
9 Texturing Your Game World 119
Texture Introduction, 120
UV Coordinates, 120
C# Syntax for Textures, 120
Shader Implementation for Textures, 122
Transparent Textures, 127
Alpha Channel, 127
Texture Tiling, 127
Texture Coloring, 128
Texture Example, 129
Billboarding Example, 140
Texture Coloring Example, 140
Chapter 9 Review Exercises, 141
10 Adding Skies and Horizons to Your Levels 143
The Skybox, 144

Terragen Photorealistic Scenery Rendering Software, 145
xiii
CONTENTS
Using Terragen to Create a Skybox, 146
Chapter 10 Review Exercises, 153
11 Index Buffers 155
Index Buffers, 156
Managing Vertex Data with Index Buffers
and Vertex Buffers, 158
Chapter 11 Review Exercises, 163
12 Combining Images for Better Visual Effects 165
Sprites, 166
Image Frame Swapping for 2D Animations, 166
SpriteBatch, 166
Restoring 3D Drawing Settings After Drawing
with a SpriteBatch, 167
Image Frame Animations, 169
Sprite on the Heads-Up-Display Example, 169
Animated Texture Example, 174
Multitexturing, 178
Multipass Rendering from the Shader’s Technique, 178
Calling a Pass in the Shader, 179
Water Using Multitexturing Example, 179
Water Using Multitexturing Example, Continued:
Adding Waves, 187
Chapter 12 Review Exercises, 190
13 Score Tracking and Game Stats 191
Font Example: Displaying Text in the Game Window, 193
Loading the Font Type Data, 193
Ensuring Your Fonts Are Drawn in the Visible Portion of the

Window, 196
Drawing the Font, 197
Font Example: Displaying a Frames-per-Second Count, 198
Chapter 13 Review Exercises, 200
14 3D Models 201
3D Modeling Tools, 202
MilkShape 3D Intro Example: Creating a Windmill, 203
Loading the Model in XNA, 214
Loading the Models, 214
Drawing the Model In XNA, 215
Loading and Animating the Windmill in Code, 216
Adding a Car as a Third-Person Object, 219
Chapter 14 Review Exercises, 232
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE
xiv
15 Vectors 233
Vector Types, 234
Vector Addition, 234
Vector Subtraction, 236
Vector Scaling, 236
Vector Scaling, Example 1, 236
Vector Scaling, Example 2, 237
Normal Vectors, 238
Cross Product, 238
Cross Product Example, 239
Normalization, 240
Pythagorean Theorem, 241
Using the Pythagorean Theorem to Calculate
the Vector Length, 241
Using Normalization to Compute the Unit Vector, 242

Using the Normalize( ) Method to Compute the Unit
Vector, 243
Dot Product, 243
Dot Product Method, 244
Dot Product Example, 244
Chapter 15 Review Exercises, 246
16 Matrices 247
Matrix Multiplication, 248
Matrix Types, 248
Transformation Matrices, 253
Translation Matrix, 254
Scaling Matrix, 256
Rotation Matrix X Axis, 258
Rotation Matrix Y Axis, 260
Rotation Matrix Z Axis, 262
Identity Matrix, 263
Chapter 16 Review Exercises, 265
17 Building a Graphics Engine Camera 267
Camera Vectors, 268
Camera Matrices, 268
World Matrix, 269
View Matrix, 269
Projection Matrix, 269
Camera Example, 271
Creating the Camera Class Shell, 271
Initializing the Camera from Your Game Class, 272
xv
CONTENTS
Moving and Strafing, 274
Rotating the View, 277

Triggering Changes to the View from the Game Class, 282
Building the Base Code from Scratch Example, 284
Chapter 17 Review Exercises, 284
18 Collision Detection 285
Fine-Tuning Your Collision Detection Systems, 286
Early Warning Systems, 287
ContainmentType, 287
BoundingSphere, 288
Initializing the Bounding Sphere, 288
Intersects(), 288
Contains, 288
BoundingBox, 288
Intersects(), 289
Contains(), 289
Collision Detection Example: Initializing and Drawing Bounding
Spheres, 290
Collision Detection Example: Implementing BoundingSphere Collision
Checking, 299
Collision Detection Example: Implementing BoundingBox Collision
Checking, 302
Chapter 18 Review Exercises, 304
19 Ballistics 305
Linear Projectiles, 306
Arcing Projectile, 306
Linear Projectiles Example, 309
Arcing Projectiles Example, 319
Chapter 19 Review Exercises, 321
20 Particle Effects 323
Point Sprites, 324
Custom Vertex Declarations, 330

Fire Example Using Point Sprites, 331
Chapter 20 Review Exercises, 341
21 Keyframe Animations 343
Interpolation, 344
Curves, 344
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE
xvi
Keyframe Animation Example, 345
Chapter 21 Review Exercises, 351
22 Lighting 353
Lighting Methods, 354
Source Lights, 354
Reflective Lighting Properties of Materials, 355
Implementing Directional Lighting Using XNA’s BasicEffect
Class, 356
BasicEffect Default Lighting, 356
Directional Lighting Example, 357
Implementing Point Light Using the Phong Reflection Model, 362
Calculating Point Light, 364
Point Light in the Pixel Shader Example, 365
Point Light in the Vertex Shader Example, 373
Chapter 22 Review Exercises, 375
23 Input Devices 377
Handling Keyboard Input, 378
Handling Mouse Input, 379
Handling Controller Input, 379
Game Pad States, 380
Handling Pressed and Released States, 381
Thumbsticks, 381
Triggers, 382

Adjusting the Input Device Responsiveness, 382
Adding a Rumble, 382
Input Example, 383
Zune Input Handling, 396
Zune Input Device Example, 397
Chapter 23 Review Exercises, 399
24 Content Pipeline Processors 401
Content Processors, 402
ContentImporter, 403
ContentTypeWriter, 403
ContentTypeReader, 404
Custom Content Processor Example, 404
Building a Custom Content Processor in Windows, 405
Chapter 24 Review Exercises, 417
25 Terrain with Height Detection 419
Height Maps, 420
Creating a Height Map Using Terragen, 421
xvii
CONTENTS
Height Map Code Example, 425
Chapter 25 Review Exercises, 436
26 Animated Models 437
The Quake II Format, 438
A Closer Look at the .md2 Data, 439
Textures with .md2 Format, 440
Animating Models in Milkshape, 440
Creating the Quake II Model, 441
Loading Your Quake II Model in Code, 446
Loading and Controlling Quake II Models in Code, 451
Loading the Quake II Weapon, 454

Chapter 26 Review Exercises, 457
27 Adding Audio to Your Game 459
About XACT, 460
The Song and SoundEffect Alternative, 460
Programming XACT Audio, 460
XACT Audio Project File, 461
Audio Engine, 461
Global Settings, 462
Wave Banks, 462
Sound Banks, 462
Space Audio Example: Part A, 464
Launching the XACT Authoring Tool, 465
Creating a Wave Bank, 465
Adding a Sound Bank, 465
Referencing the Spaceship Engines, Firing Sound, and Beeping
Sounds, 466
Setting the Category Property for Beep0, 466
Creating an Infinite Loop, 467
Adding a Finite Loop, 467
Testing Your Audio, 468
Cue Instance Variables, 468
Creating a New RPC Preset, 469
Enabling Volume Attenuation, 471
Saving Your Audio Project, 473
Space Audio Example: Part B, 473
Loading, Drawing, and Animating the Spacecraft, 473
Space Audio Example: Part C, 477
Adding Audio, 477
Space Audio Example: Part D, 482
Adding 3D Audio, 482

Zune Audio Example, 487
Chapter 27 Review Exercises, 489
28 Multiplayer Gaming 491
Viewport, 492
Creating Separate Cameras for Each Player, 493
Adjusting the View, 493
Adjusting the Projection, 493
Handling the User Input, 494
Split-Screen Code Example, 494
Chapter 28 Review Exercises, 503
29 Networking 505
Peer-to-Peer Networks, 506
Client/Server Networks, 506
Efficient Bandwidth Use, 506
XNA’s Code Framework, 507
GamerServicesComponent, 507
NetworkSession, 507
Session Events, 508
Local Network Gamer, 509
Updating the Session, 509
PacketWriter, 510
PacketReader, 510
Updating the Network, 511
Network Example: Peer to Peer, 511
Setting Up the Network Class, 511
Adding Network Capability to the Game Class, 514
Network Example: Client/Server, 521
Chapter 29 Review Exercises, 526
Index 527
MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE

xviii
x
xix
Acknowledgments
Thank
you to people at Microsoft for a great game platform and for ad-
vocacy of our project. Thank you Andy Dunn (the ZMan) and
Shawn Hargreaves for excellent community contributions. Nick Gravelyn has been an
incredible resource for this project—Nick, we arevery grateful for your help and input.
For guidance and assistance from the British Columbia Institute of Technology,
thank you to Kevin Cudihee, Medhat Elmasry, Jason Harrison, and Dr. Benjamin Yu.
Thank you to a publishing team who are an excellent group to work with: Roger
Stewart, Joya Anthony, Rachel Gunn, Carly Stapleton.
—Pat McGee
Big thanks go to Nick Gravelyn for his technical expertise. I’d also like to thank
my agent Neil J. Salkind, Roger Stewart (our Editorial Director) from
McGraw-Hill, and the rest of the MGH team: Joya Anthony, Rachel Gunn, and
Carly Stapleton. It has been great working with MGH again and I look forward to
our next project together. In the last, but not least, category, thanks go to my wife
Christa for her support.
—Stephen Cawood
Credits:
CF-18 model, Eric Bancroft
Hotrod model, Sheila Nash
Zarlag model, Phillip T. Wheeler
For use of Terragen images, John McLusky:
/>For support on MilkShape, Mete Cirigan:
/>Permission to use Quake II model format granted under the GPL from id Software:

This page intentionally left blank

x
Source code for all examples in this book can be downloaded from
and
This book shows how to build complete 2D and 3D games with all essential com-
ponents from scratch; shapes, image effects, animation, 3D model creation and use,
graphics math, collision detection, 3D audio, split-screen, and networked games. All
code examples are presented in an easy-to-follow, step-by-step format. This book
targets development for the PC and Xbox 360 and introduces development for the
Zune.
With the exception of the Quake II model loader code, all source code for all ex-
amples and solutions is presented on the pages of this book. All examples either begin
with the minimal Microsoft XNA game template or they begin with a single base
code project that is used throughout this entire book. Chapter 17 shows how to build
this base code project from start to finish so you have a full understanding of the
structures behind it.
This book is suited for readers with basic to advanced knowledge in a C-style pro-
gramming language but who have not necessarily programmed 3D games. This book
is also suited for readers who just want to cover a lot of ground in games program-
ming fast with an easy-to-understand tutorial-style guide.
xxi
This page intentionally left blank
CHAPTER
CHAPTER
1
1
Set Up
Set Up
an XNA
an XNA
Development

Development
Environment
Environment
2
THE
release of the XNA platform—and specifically the ability for any-
one to write Xbox 360 console games—was truly a major progres-
sion in the game-programming world. Before XNA, it was simply too complicated
and costly for a student, software hobbyist, or independent game developer to gain
access to a decent development kit for a major console platform. With the release of
XNA Game Studio, the ground rules changed. Suddenly, anyone with a PC that has a
decent graphics card can use the XNA platform to develop games not only for Win-
dows, but also for the Xbox 360.
The XNA platform has continued to evolve, and with the release of XNA 3.0,
XNA developers have provided the ability to write games for the Microsoft Zune
MP3 Player. Also, XNA game developers may submit their games for distribution in
the Xbox LIVE Community Games marketplace. We are pleased to offer this second
edition to update our book for the latest developments in the XNA development plat-
form. We have also taken the experience from writing our first edition to add im-
provements, making this our strongest XNA guide to date. We hope you enjoy
reading it and that you find it helpful for learning XNA.
It will be fun to watch as a new strain of games springs forth from the labs of stu-
dents, hobbyist game developers, small game shops—and you. Of course, commer-
cial developers have larger budgets, teams of paid artists, and abundant resources on
their side—however, commercial game developers are going to be taking notes and
learning from the independent XNA developers who find new and interesting ways
to warp the virtual world. There is a niche for you to fill and an opportunity for you
to sell your games at the LIVE Community Games marketplace.
XNA Game Studio (GS) is the integrated development environment (IDE) for
XNA. It is an add-on for Visual C# Express Edition or Visual Studio. Although some

people prefer to use the full version of Visual Studio, Visual C# Express is free. Based
on this, it is possible to develop Windows XNA games without any cost—aside from
the price of your PC, and possibly your Zune.
However, if you want to write games for the Xbox 360, this is obviously not the
case. There is an additional subscription charge for the Xbox 360 Creators Club
(). A Creators Club subscription allows you to deploy games
from your Windows PC to the Xbox 360.
S
ET UP AN XNA DEVELOPMENT
ENVIRONMENT
Follow these instructions to prepare your system for XNA development on the PC,
Xbox 360, and Zune.

×