1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft XNA game studio

561 3K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Microsoft XNA Game Studio
Tác giả Stephen Cawood, Pat McGee
Người hướng dẫn Pat McGee Instructor in the Software Systems Developer program at the British Columbia Institute of Technology
Trường học British Columbia Institute of Technology
Chuyên ngành Game Development, Programming
Thể loại Creator’s guide
Năm xuất bản 2009
Thành phố New York, Chicago, San Francisco, Lisbon, London, Madrid, Mexico City, Milan, New Delhi, San Juan, Seoul, Singapore, Sydney, Toronto
Định dạng
Số trang 561
Dung lượng 4,36 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Microsoft XNA game studio

Trang 2

MicrosoftXNA

Game Studio

Creator’s Guide

Second Edition

Trang 3

A BOUT THE AUTHORS

Stephen Cawood is a former Microsoft employee and recoveringHalo 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 theClifford 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 ColumbiaInstitute of Technology Pat lives in North Vancouver, British Columbia, with hiswife 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 manyhours of video tutorials He is currently the owner and lead programmer ofMetacreature, an indie software company

Trang 4

New York Chicago San Francisco Lisbon London Madrid Mexico City

Trang 5

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 tem, without the prior written permission of the publisher.

sys-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.

Trang 6

I dedicate this book to my father, John Cawood Toprotect his children from a future that would haveincluded military service under an oppressive regime,

my dad left our home in 1978 and moved to Canada

That decision provided me with the sort ofopportunities 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 itspotential—but that’s what he worked for every day Imiss him and so does the rest of our family, but it is

his homeland that misses him most of all

Trang 7

This page intentionally left blank

Trang 8

10 Adding Skies and Horizons to Your Levels 143

12 Combining Images for Better Visual Effects 165

Trang 10

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

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

Trang 11

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

Creating the XNA Game Foundation, 22

Initializing the Game Application, 23 GraphicsDeviceManager, 24 SpriteBatch, 24

Closing the Game Application, 26 Basic XNA Game Window Example, 26 Chapter 3 Review Exercise, 28

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

Trang 12

C O N T E N T S

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

Drawing a Line Strip, 65

Adding a Line List, 66

Adding a Point List, 67

Chapter 5 Review Exercises, 68

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

Trang 13

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

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

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

Trang 14

C O N T E N T S

Using Terragen to Create a Skybox, 146

Chapter 10 Review Exercises, 153

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

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

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

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

Trang 15

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

Chapter 16 Review Exercises, 265

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

Trang 16

C O N T E N T S

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

Fine-Tuning Your Collision Detection Systems, 286

Early Warning Systems, 287

Linear Projectiles Example, 309

Arcing Projectiles Example, 319

Chapter 19 Review Exercises, 321

Point Sprites, 324

Custom Vertex Declarations, 330

Fire Example Using Point Sprites, 331

Chapter 20 Review Exercises, 341

Interpolation, 344

Curves, 344

Trang 17

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

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

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

Height Maps, 420

Creating a Height Map Using Terragen, 421

Trang 18

C O N T E N T S

Height Map Code Example, 425

Chapter 25 Review Exercises, 436

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

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

Trang 19

Zune Audio Example, 487 Chapter 27 Review Exercises, 489

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

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

xviii

Trang 20

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 are very 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:

Trang 21

This page intentionally left blank

Trang 22

Source code for all examples in this book can be downloaded from

http://www.mhprofessional.com/ and http://www.xnachinchilla.com

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 exex-amples 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

Trang 23

This page intentionally left blank

Trang 24

CHAPTER 1

Set Up

an XNA Development Environment

Trang 25

THE release of the XNA platform—and specifically the ability for any-one to write Xbox 360 console games—was truly a major sion in the game-programming world Before XNA, it was simply too complicatedand costly for a student, software hobbyist, or independent game developer to gainaccess to a decent development kit for a major console platform With the release ofXNA Game Studio, the ground rules changed Suddenly, anyone with a PC that has adecent graphics card can use the XNA platform to develop games not only for Win-dows, but also for the Xbox 360

progres-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 ZuneMP3 Player Also, XNA game developers may submit their games for distribution inthe Xbox LIVE Community Games marketplace We are pleased to offer this secondedition 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 enjoyreading 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 dents, hobbyist game developers, small game shops—and you Of course, commer-cial developers have larger budgets, teams of paid artists, and abundant resources ontheir side—however, commercial game developers are going to be taking notes andlearning from the independent XNA developers who find new and interesting ways

stu-to warp the virtual world There is a niche for you stu-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) forXNA It is an add-on for Visual C# Express Edition or Visual Studio Although somepeople 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 fromthe price of your PC, and possibly your Zune

However, if you want to write games for the Xbox 360, this is obviously not thecase There is an additional subscription charge for the Xbox 360 Creators Club(http://creators.xna.com) A Creators Club subscription allows you to deploy gamesfrom your Windows PC to the Xbox 360

ENVIRONMENT

Follow these instructions to prepare your system for XNA development on the PC,Xbox 360, and Zune

Trang 26

Install the Software

Before you can develop any games with XNA, you will need to download some freesoftware from Microsoft.com You will need to install Visual C# Express or VisualStudio with C# and then XNA Game Studio

After you have installed the required software, you will be able to develop XNAgames for Windows or the Zune However, if you want to develop for the Xbox 360,you will need to complete the rest of the instructions in this section

Join the Xbox 360 Creators Club

Before you are able to do any Xbox 360 game development, you will have topay for a subscription to the Xbox 360 Creators Club Fortunately, this isthe only fee you will have to pay; everything else is free To join the club, go tothe XNA Creators Club website and sign up for a premium membership(http://creators.xna.com/en-us/membership)

Using XNA Game Studio Connect

After you have purchased a Creators Club premium membership, you will be able tosign in to Xbox LIVE and download the free XNA Game Studio Connect application

To use the XNA Game Studio Connect utility, navigate to the Games blade onyour Xbox 360, and then to the Demos and More section Once there, select XNAGame Studio Connect and press A to launch the application Next, press A to startthe XNA Game Studio Connect

When you have the launcher running, you will see three options: My XNA Games,Connect to Computer, and Settings The My XNA Games option shows a list ofgames Selecting a game gives you the options Play Game and Delete Game Connect toComputer (which requires an active Xbox LIVE connection to verify your subscrip-tion) puts the Xbox 360 in the correct mode for deploying or debugging Xbox 360Game projects in GS The last option, Settings, allows you to generate a connectionkey Select this option and you will receive instructions for how to add the connectionkey inside GS (under Tools | Options | XNA Game Studio and Xbox 360 Console)

Connect Your PC to Your Xbox 360

Before you can develop Xbox 360 games, you must set up a connection betweenyour GS development PC and your Xbox 360 Follow these steps to establish theconnection:

1. Make sure that your Xbox 360 is connected to Xbox LIVE, that you have

a membership to the Xbox 360 Creators Club, and that you have downloadedthe XNA Game Studio Connect application

Trang 27

2. Ensure that you have Visual C# Express Edition (or Visual Studio) and GSinstalled on your development PC.

3. The Connect to Computer option is disabled the first time you run XNAGame Studio Connect To enable it, you must go to Settings and selectGenerate Connection Key At this point, you will see a connection keydisplayed After you have added the connection key to GS (under Tools |Options | XNA Game Studio and Xbox 360 Console), your PC can deployXNA projects to your Xbox 360

4. From the XNA Game Studio Connect options, choose Connect to Computer.You must have the Xbox waiting in this mode before you try to debug ordeploy from GS

That’s it! Now you will be able to develop XNA games for the Windows platform

or the Xbox 360

Deploying a Game to Your Zune

With the recent XNA 3.0 release, you can now deploy your XNA games to aMicrosoft Zune device Although the Zune does not support 3D graphics, you canstill write your own games and play them on the small screen The process of deploy-ing games to the Zune is remarkably straightforward

Once you have installed XNA GS, you simply need to plug in your Zune, add it as

a recognized device, and then create an XNA game with the Zune game template Totest your ability to deploy games to the Zune, try downloading a Zune game projectfrom the Creators Club website, deploying it to your Zune, and then playing thegame

Here is the process to deploy your own Zune games:

1. Open GS and create a game by choosing File | New Project | ZuneGame (3.0)

2. Build the game as usual

3. Physically connect your Zune to your PC (Note that you should havealready connected your device at least once and thereby updated to thelatest version of the Zune firmware.)

4. Add your Zune to GS using Tools | XNA Game Studio Device Center.Set your Zune as the default

5. Use the Deploy to Zune option to send your game to the device

6. Play your Zune game!

4

Trang 28

Here are some points to remember when creating a Zune game:

 The Zune currently only plays 2D games

 Screen resolution on all Zunes is 240× 320 pixels

 Game size should be restricted to a maximum of 2GB

 Be wary of memory limitations when developing games for the Zune; keep

your texture and audio content lean

 The Zune does not implement 3D audio content created in the Cross PlatformAudio Creation Tool (XACT) Instead it implements mp3 and WAV file

playback using the SoundEffect, SoundEffectInstance, and Song classes

 The Zune input device handling uses a subset of the input device library usedfor the game controller

Selling Your Games with LIVE Community Games

Starting with the full release of GS 3.0, XNA game developers have the option ofmaking their games public on the Xbox LIVE marketplace When you submit yourgame, you have the option of choosing between a few different price levels Microsofthas announced that XNA developers will retain up to 70 percent of the profit fromthe sale of community games on the Xbox 360

To publish your game, you simply have to:

1. Develop a game Note that there is a size limitation for games published onLIVE Community Games, so check how big your game can be before you

start development

2. Submit your game for peer review Other Creators Club members will

make sure your game follows the rules for publishing (for example, no

copyright infringement, no unacceptable content, and the game actually

works), and then they will either approve or reject your game

3. Sell your game You will need to refer to Microsoft’s XNA Creators Club

site for current detailed instructions

Download the Examples for This Book

You can find all of the resources and solutions for the examples in this book availablefor download from the book’s catalog page at www.mhprofessional.com and atXNAChinchilla.com (see the Introduction for more details)

Trang 29

X NA AND YOUR PC VIDEO CARD

Before you start installing the software required for XNA development, you shouldensure that your PC meets the basic requirements for GS One consideration is yourvideo card; if your card does not meet the requirements, you will not be able to run

Now that you have your development environment ready to go, the next chapterwill walk you through some of the most important features of the GS IDE

6

Trang 30

CHAPTER 2

Developer Basics

Trang 31

IF you’re itching to get coding, but are not familiar with Microsoft’s inte-grated development environment (IDE), this chapter will help you useMicrosoft XNA Game Studio (GS) to program, debug, and deploy your gameprojects Once your PC, Zune, and Xbox 360 have been prepared as outlined inChapter 1, “Set Up an XNA Development Environment,” you are ready to codewith GS

GS is a first-class integrated development environment (IDE) that leverages the C#language Although Microsoft Visual Studio and Microsoft Visual C# Express areboth supported Microsoft Visual C# Express is a free coding studio and it is verysimilar to Microsoft Visual C# NET, enabling you to program, edit, debug, and de-ploy your C# applications Compared to other freeware developer tools, GS is a RollsRoyce Using this software, you can code in comfort and allow the IDE to improveyour efficiency

Opening Microsoft XNA Game Studio

To launch GS, from the Start menu select Programs and choose Microsoft XNAGame Studio or Microsft Visual C# 2008 GS will open the Start Page, which pres-ents your recent projects, links to tutorials, and links to online articles, discussions,and events related to C# development

Creating a Game Studio Project

A GS project will store references to all of your code files and resources that are used

by your game application There are currently three types of stand-alone XNA gameprojects: the Windows Game project, the Zune Game project, and the Xbox 360Game project

Each type of project references a slightly different instruction set For example,the Windows Game project can be run on a PC, but the Xbox 360 Game projectcannot because it uses a reduced instruction set that is required by the Xbox 360console

Opening an Existing Game Studio Project

A GS project can be opened by double-clicking the solution file Solution files have an.sln extension The project will launch GS and show the code editor, Solution Ex-

Trang 32

THE XBOX 360, AND THE ZUNE

The base code that is automatically generated by GS for the Xbox 360 Game project

is identical to the code generated for a Windows Game project Some slight ences exist between the two instruction sets available, such as mouse support, which

differ-is only available in Windows However, in the majority of cases, you can write yourcode in one project type and then copy your source files and resources to the otherproject type and you will still be able to run your project The Xbox 360 is slightlystricter in enforcing variable default declarations, but even if you forget the differ-ences, GS provides excellent debug information to inform you of any issues and how

to resolve them when testing your code in one environment or the other

You can have confidence that almost all the code you write for a Windows Gameproject is going to work in an Xbox 360 Game project, and vice versa In mostcases, platform compatibility will not be an issue because XNA is designed to work

in both environments Of course, you still need to test in both environments, butplan for an excellent level of compatibility between platforms

The most important distinction for Zune programming is that the Zune does notcurrently support 3D graphics When creating games for the Zune, you’ll have towork with simpler 2D graphics Also, the Zune does not implement 3D audio forprojects created using the Cross Platform Audio Creation Tool Instead the Zuneuses a much lighter audio library for playing WAV and mp3 files which loads youraudio content directly in code Finally, the input device handling on the Zune is im-plemented using a subset of instructions used for device handling with the Xbox 360game controller Aside from including one extra instruction to regulate the frequency

of updates between frames, the Zune Game project template code is identical to theXbox 360 Game and Windows Game project templates

Creating a Windows Game Project

You can create a project by selecting File and then New Project At this point, severaloptions are available to you If you want your project to run on Windows, thenchoose the Windows Game icon that appears in the New Project dialog (see Figure2-1) To proceed, you need to fill in each of the text boxes at the bottom of the NewProject dialog These values include the name of the project and the file path for thedirectory where you would like your project to be created

Trang 33

When you first create a project, a code-editing window will open on the left (seeFigure 2-2) The Solution Explorer in the right panel shows a listing of code files andmay display resources such as a project icon and other items you have selected TheError List at the bottom of the page displays error messages for lines of code that willnot compile, warning messages such as information about variables that are notused, and instructions that are deprecated but have been allowed to compile

If the code editor, Solution Explorer, or Error List do not appear, these optionscan be enabled from the View menu

Creating an Xbox 360 Game Project

The creation of an Xbox 360 Game project is similar to creating a Windows Gameproject But before you can actually run an Xbox 360 Game project, you will need tosign in to Xbox Live and download the XNA Game Studio Connect, as outlined inChapter 1, “Set Up an XNA Development Environment.” Once you have this in-stalled, you will have to connect your PC to your Xbox 360 Connecting your PC toyour Xbox 360 will be explained later in this chapter

F I G U R E 2 - 1

Selecting a project type and entering the file path and project name

Trang 34

Creating a Zune Game Project

Creating a new project for the Zune is exactly the same as for the other project types:File | New project | Zune Game

Trang 35

The GS code window offers a friendly environment for writing and editing yourcode The latest IDE editing features enable you to write code quickly and accurately.For example, code coloring allows for easy readability by distinguishing comments

in green, C# structures and functions in blue, and user-defined code in black Also,incomplete lines of code are marked with red lines Furthermore, AutoComplete isreadily available to assist you in completing your instructions with methods and vari-ables for your classes ToolTips, which display descriptive summaries, appear whenyou hover the mouse over variables and instructions that are referenced fromMicrosoft’s code libraries

The other windows also provide features that will make your programming rience more enjoyable For example, the Solution Explorer enables you to quicklynavigate from page to page In short, GS is rich with editing features that are waitingfor you to discover them

expe-Adding and Removing Code Files to and from the Project

By default, when you create a new game project, GS will generate a Game1.cs file, aProgram.cs file, and a Game.ico file (for a Windows Game project) You’ll see thesefiles listed in the Solution Explorer Options are available to add files to (or removethem from) the project by right-clicking the project name in the Solution Explorer

To add new source files to the project, right-click the project name in the SolutionExplorer, choose Add, and then select New Item In the New Item dialog that ap-pears, a C# file can be created by selecting Code File You must specify a name for theC# file in the Name box before the file can be added Once you have provided a file-name, click the Add button to have the file added to the project

To add existing source files to the project, right-click the project name in the tion Explorer, choose Add, and then select Existing Item; an Add Existing Item dia-log will appear By default, the Add Existing Item dialog displays all files listed in thesource folder of the current project When you left-click the source files to be addedand click Add, GS will load the files into the project; after they have been added, theywill be listed in the Solution Explorer

Solu-Compiling and Running Game Studio Projects

You can use the Start Debugging action to compile your code, generate debugging formation, and run the project in one step In the case of an Xbox 360 Game project,

Trang 36

pro-in Figure 2-3.

Saving the Game Studio Project

When compiling, GS will automatically save all edits to the game project Betweenbuilds, you can manually save changes to the *.cs file that is currently showing inthe code editor, or you can save changes to the entire project Under the File menu,three different options are available for saving the project: Save *.cs, Save *.cs As,and Save All

Trang 37

D EPLOYING AN XBOX 360 GAME PROJECT

When you have a project that is ready to run on your Xbox 360, you can use GS to ploy it to your Xbox The first step of deployment requires that you go to your Xbox

de-360 and configure it to connect it to your PC On the Games blade of the Xbox de-360Dashboard (under Demos and More), launching XNA Game Studio Connect willdisplay the XNA Game Studio Connect main page (see Figure 2-4)

The Connect to Computer option is disabled the first time you run XNA GameStudio Connect To enable it, you must go to Settings and select Generate Connec-tion Key After you generate the key, but before you accept it, you must enter the keynumber into GS on your PC From GS, under Options | Tools, select XNA Game Stu-dio Xbox 360 and click Add to launch the Add Xbox 360 Name and Connection Keydialog In this dialog, you must enter a computer name so you can identify your PCconnection and the connection key that was just generated Once you complete thistask, select Accept New Key from the Connection Key dialog on your Xbox 360 to fi-nalize the process After you have accepted the key, you will be brought back to theSettings dialog, which will now report [key set] to notify you that you were successful

in applying the key on your Xbox 360 You can now select the Back button to return

to the XNA Game Studio Connect page

On the XNA Game Studio Connect page, select the Connect to Computer optionand press the A controller button to make the connection

14

F I G U R E 2 - 4

XNA Game Studio Connect main page

Trang 38

There is no silver bullet when it comes to debugging techniques However, havingmany techniques in your arsenal will aid your ability to examine (or trace) code, and

it will help you write robust code quickly and efficiently

Microsoft’s development suites have earned a reputation for delivering tional debugging tools In short, the debugging tools rock It is no wonder that biggame companies such as Electronic Arts use Microsoft’s Visual Studio NET for theircoding environment Most of the common debug features available in Visual Studio.NET can be also found in GS

excep-Error List

The Error List at the bottom of the project page is probably the first debugging toolyou will encounter, and it will quickly become your best friend If your code fails tocompile, the Error List will show error messages alerting you to reasons why Also, ifthe compiler finds an issue that isn’t serious enough to cause a build error, the ErrorList will show a warning message

Errors

When your project does not compile, the Error List will show all lines of code thatfailed—with an explanation of why each did not compile Figure 2-5 shows the ErrorList reporting a missing semicolon You can double-click the error message in the Er-ror List to automatically move your cursor to the line that failed to compile; this fea-ture is a huge timesaver

Trang 39

Warnings highlight code that compiles but should either be modified or removed.The warning in Figure 2-6 shows a variable that has been declared but is unused.Keep in mind that expert developers pay attention to the warnings and aim to shiptheir code with zero warnings Paying heed to warnings can also improve the read-ability and scalability of your code projects Warnings will also help you identify dep-recated methods and blocks of code that are unused Finding replacements fordeprecated methods will ensure your code is current with the latest code libraries,and it will also ensure that you’re using the most secure code available Removing un-used variables will reduce the clutter in your project

Pausing the Program to View Logic and Variable Values at

Run Time

Microsoft’s development environments, including GS, offer excellent tools for ping your program in midstream so that you can check variable values and logic Ifyou are not already aware of these features, you should add them to your debuggingprocedures

stop-16

F I G U R E 2 - 5

Error message in the Error List

Trang 40

in-in action—the program has been paused at the breakpoin-int At this poin-int, you can

Ngày đăng: 11/03/2014, 19:44

TỪ KHÓA LIÊN QUAN