39,59 €
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:
Seitenzahl: 406
Veröffentlichungsjahr: 2012
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]>)
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
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.
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.
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.
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.
Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.
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.
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.
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.
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.
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
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.
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.
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.
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 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.
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.
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:
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.
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.
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.
To install Windows Phone SDK , perform the following steps:
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.
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:
That is quite a bit of ground to cover in a very small game, so we had better get started!
To create an XNA project, perform the following steps:
The Speller game's Game1.cs file, when opened in Visual Studio, would look like the following screenshot:
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.
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.
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.
To create content assets, perform the following steps:
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.
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.
Just after the Game1class declaration in the Game1.cs file there are two class member declarations:
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 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.
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.
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.
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.
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.
