34,79 €
XNA Game Studio enables hobbyists and independent game developers to easily create video games, and now gives that power to Visual Basic developers. XNA lets you bring your creations to life on Windows, the Xbox 360 and the Windows Phone platforms. The latest release of XNA has added support to Visual Basic and therefore, Visual Basic developers now have the power to give life to their creativity with XNA.This book covers both the concepts and the implementations necessary to get you started on bringing your own creations to life with XNA. It presents four different games, including a puzzler, space shooter, multi-axis shoot 'em up, and a jump-and-run platformer. Each game introduces new concepts and techniques to build a solid foundation for your own ideas and creativity.This book details the creation of four games, all in different styles, from start to finish using Visual Basic and the Microsoft XNA framework. Beginning with the basics of drawing images to the screen, the book then incrementally introduces sprite animation, particles, sound effects, tile-based maps, and path finding. It then explores combining XNA with Windows Forms to build an interactive map editor, and builds a platform-style game using the editor-generated maps. Finally, the book covers the considerations necessary for deploying your games to the Xbox 360 platform.By the end of the book, you will have a solid foundation of game development concepts and techniques as well as working sample games to extend and innovate upon. You will have the knowledge necessary to create games that you can complete without an army of fellow game developers at your back.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 524
Veröffentlichungsjahr: 2011
Copyright © 2011 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: December 2011
Production Reference: 1161211
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN: 978-1-84969-240-3
www.packtpub.com
Cover Image by Vinayak Chittar (<[email protected]>)
Author
Kurt Jaegers
Reviewers
Michael Schuld
Pedro Daniel Güida Vázquez
Acquisition Editor
Wilson D'souza
Development Editor
Wilson D'souza
Technical Editors
Lubna Shaikh
Ankita Shashi
Manasi Poonthottam
Project Coordinator
Kushal Bhardwaj
Proofreaders
Jonathan Todd
Lesley Harrison
Indexers
Tejal Daruwale
Hemangini Bari
Rekha Nair
Graphics
Conidon Miranda
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Kurt Jaegers is a database and network administrator, and a long-time hobbyist game developer, having built games for everything from the Commodore 64 to the Xbox 360. He is the owner of xnaresources.com and the author of the C# version of XNA Game Development by Example.
I would like to thank my parents George and Julie Jaegers for investing in a newfangled Atari 400 computer back in the 80s and encouraging my interest in computer programming from a very early age. As with my first book, thanks go to my wife Linda for proofreading, as well as my brother Jason for providing most of the graphics for the games.
Michael Schuld started his foray into game development using Managed DirectX 9, and after playing with the framework for a few months, decided that there wasn't enough beginner content out in the world to help people new to game development get started.
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 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 Game Informer 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 11 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.
Pedro Daniel Güida Vázquez is the owner of Pulsar Coders, an indie company that develops video games for many platforms. He enjoys working daily on everything related to video game development. Economist, System Analyst, Professor, Microsoft MVP for DirectX and XNA are some of the accomplishments obtained by him throughout his life. 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 biography of this reviewer at http://www.linkedin.com/in/pedroguida.
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.
The Microsoft XNA Framework provides a powerful set of tools to allow development teams of any size, from the individual developer to larger independent teams, to rapidly develop high-performance quality games for multiple Microsoft-related platforms.
This book will present a series of video games, utilizing Visual Basic and the XNA Framework, to delve into the world of 2D game development, targeting the Microsoft Windows environment. We will utilize XNA's 2D graphics capabilities to present our games to the player, and we will also look at the fundamental systems behind several game design challenges, such as pathfinding, collision detection, special effects, and more.
Each of the four games in this book cover a new gaming style and introduce progressively more advanced techniques and systems to provide a foundation for bringing your own creations to life.
Chapter 1, Introducing XNA Game Studio, begins by looking at the history of the XNA Framework and its predecessors and installing the Windows Phone SDK package that includes the version 4.0 release of the XNA tools. We wrap up this chapter by looking at the building blocks of an XNA game and putting together an XNA mini-game called SquareChase.
Chapter 2, Flood Control – Underwater Puzzling, introduces a board-based puzzle game called Flood Control. We introduce the XNA Content Pipeline and build a recursive function to determine the state of the game board while playing.
Chapter 3, Flood Control – Smoothing Out the Rough Edges, refines and completes the Flood Control game, adding animated rotation, movement, and fading of game pieces. We will implement a scoring system and cover displaying text to the screen.
Chapter 4, Asteroid Belt Assault – Lost in Space, begins by developing our second game. This time we put together a space-based shooter. We will create a basic moving star field, using a simple particle system, and introduce frame-based sprite animation. We will add moving asteroids to our star field and examine how to detect collisions between asteroids and make them respond realistically. We add a player-controlled spaceship and enemies that can fly across the screen following pre-defined waypoints.
Chapter 5, Asteroid Belt Assault – Special Effects, wraps up Asteroid Belt Assault. We implement collision detection between the player, enemies, asteroids, and bullets, and create particle-based explosions. Finally, we will look at loading and playing sound effects to bring life to our in-game events.
Chapter 6, Robot Rampage – Multi-Axis Mayhem, begins the construction of a tank-based game in which the player can move and fire independently using either an Xbox 360 controller or the keyboard. We build a tile-map-based game world and a camera class to view a screen-sized area of the larger world, and we implement player collision with the walls of the tile map.
Chapter 7, Robot Rampage—Lots and Lots of Bullets, completes Robot Rampage by expanding on our particle-based explosion system and adding enemies, player goals, and weapon upgrades to our tile map. We allow the player to fire at the enemies with several different weapons. Finally, we create an implementation of the A* pathfinding algorithm to allow the enemy tanks to track down the player.
Chapter 8, Gemstone Hunter - Put on Your Platform Shoes, introduces a side-scrolling, jump-and-run platform game. We start by evolving our tile-based mapping system to allow multiple layers of tiles, and we look at combining XNA and Windows Forms to produce a map editor for Gemstone Hunter. As part of this process, we will look at building more complex solutions that contain multiple projects, and we separate our game's tile engine into a Game Library project.
Chapter 9, Gemstone Hunter—Standing on your Own Two Pixels, concludes the Gemstone Hunter project by examining an alternative method for frame-based sprite animation, using player and enemy graphics from the XNA Platform Starter Kit. We implement platform physics and bring the game together by loading levels and reacting to their embedded code values.
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 who wants to take a shot at creating games for the Microsoft Windows platform with the XNA Framework, then this book is for you. Using this book, you can get started with creating games without any game development experience. Some knowledge of Visual Basic would be helpful to kick-start your game development experience.
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Instructions often need some extra explanation so that they make sense, so they are followed with:
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:
These are short multiple choice questions intended to help you test your own understanding.
These set practical challenges and give you ideas for experimenting with what you have learned.
You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Click on the Register. Now link to go to the Visual Studio Express registration page".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 via 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 and the colored images 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 errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
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.
Since its initial release in 2006, the Microsoft XNA Framework has allowed C# developers to harness the power of DirectX to create video games that can be targeted to Windows, the Xbox 360, and Microsoft-based mobile devices such as the Zune or the Windows Phone 7 platform.
XNA consists of the XNA Framework, which is a set of code libraries to perform common graphics, sound, and other game-related tasks, and XNA Game Studio, which is an extension of the Visual Studio interface that includes a number of project templates to make use of the XNA Framework.
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.
With the summer 2011 release of the XNA 4.0 Refresh, Microsoft has provided what has been cited as both the most requested feature for XNA and the most requested feature of Visual Basic developers: the ability to use Visual Basic as the backend for coding XNA projects.
What does XNA stand for, anyway?
According to the developers, XNA is an acronym for "XNA's Not Acronymed".
In this introductory chapter, you will:
Many beginning developers make the mistake of attempting to tackle far too large a project early on. Modern blockbuster video games are the result of the efforts of hundreds of programmers, designers, graphics artists, sound effects technicians, producers, directors, actors, and many other vocations, often working for years to create the game.
That does not mean that the efforts of a solo developer or small team need to be dull, boring, and unplayable. This book is designed to help you develop a solid understanding of 2D game development with XNA Game Studio. By the time you have completed the projects in this book, you will have the necessary knowledge to create games that you can complete without an army of fellow game developers at your back.
In this chapter, you will build your first XNA mini-game, chasing squares around the screen with your mouse cursor. In subsequent chapters, the following four more detailed games are presented:
The games are each presented over two chapters. In the first chapter, the basics are implemented to the point where the game is playable. In the second chapter, features and polish are added to the game.
Each game introduces both new concepts and expands on topics covered in the previous games. At the end of each game chapter, you will find a list of exercises challenging you to use your newly-gained knowledge, to enhance previous games in the book.
We will focus on Windows as our platform for the games presented in this book. That said, the code presented in this book requires very little in the way of changes for other XNA platforms, generally only requiring implementation of platform-specific controls (gamepads, touch screen, and so on), and consideration of the differences in display sizes and orientation on non-Windows devices.
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 listed in the following table:
Component
Minimum requirement
Notes
Operating System
Windows Vista SP2 or Windows 7 (all editions except Starter)
As of XNA 4.0, Windows XP is no longer officially supported.
Graphics Card
Shader Model 1.1 support and 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 similarly require Shader Model 2.0 support.
Development Platform
Visual Studio 2010 or Visual Studio 2010 Express
You will install Visual Studio 2010 Express as part of the XNA installation later in this chapter.
Optional requirements
Windows Phone
Windows Phone Development Tools, DirectX 10 or later, Compatible Video Card
Development tools include a Windows Phone emulator to test applications, without deployment to a physical device.
Xbox Live
Xbox Live Silver membership and XNA 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.
To get started developing games in XNA, you will need to download and install the software. You will need both Visual Studio and XNA extensions. With the release of XNA 4.0, the install packages have been consolidated, and both required components are included in the Windows Phone SDK package. The SDK was previously known as the Windows Phone Developers Tools prior to the release of the XNA 4.0 Refresh as part of the Windows Phone SDK 7.1 update.
XNA and the Windows Phone SDK
The October 2010 release of the Windows Phone 7 platform marked a shift in Microsoft's direction for XNA. Prior to Windows Phone, XNA was a separate download that included Visual C# Express. While still supporting the Windows and Xbox platforms as well as the Windows Phone, XNA is no longer available separately, and has been rolled into the Windows Phone SDK.
Other versions of Visual Studio and XNA
Different versions of Visual Studio and XNA can be installed on the same PC, without interfering with each other. If you wish to target the Zune platform, you will need to install Visual Studio 2008 Express and XNA 3.1 (which only supports the C# language). Additionally, Visual Studio Express and Visual Studio Professional can co-exist on the same PC, and XNA will integrate with both of them, if the Windows Phone SDK is installed after Visual Studio.
You have now successfully installed the Windows Phone SDK, which includes Visual Studio 2010 Express, the XNA Extensions for Visual Studio, and the re-distributable Font Pack provided by Microsoft for XNA developers.
XNA attempts to simplify many of the basic elements of game development by automatically handling things, such as the game update loop and presenting the current frame of graphical information to the display. To illustrate just how much of the background work is integrated into the XNA project templates, let's jump in straight away and create your first game within a few minutes of finishing the installation.
Visual Basic versus C# - tutorials and samples on the web
With a five-year headstart on Visual Basic developers, there are a host of XNA tutorials, code samples, and forum posts written for C# out on the Internet. In the interest of being able to utilize these resources, I will occasionally point out topics or sections of code and their equivalent in C# notation.
In SquareChase, we will generate randomly positioned squares of different colors while the user attempts to catch them with their mouse pointer before they disappear. While building the project, we will discuss each of the major code sections pre-defined by the XNA templates.
Each of the XNA project templates is a series of files and settings that get copied to your new project folder. Included in this set of files is the Game1.vb file, which is the heart of your XNA game.
Back up your projects
When you create your project, the Location field specifies where it will be saved. By default, Visual Studio creates a folder in your user documents area called Visual Studio 2010 to store both programs and configuration information. Under this folder is a Projects folder that contains subfolders for each new project you create. Make backups of your projects on a regular basis. You do not want to lose your hard work to a disk failure!
The most basic XNA game will have all of its code contained in the file called Game1.vb. This file is generated when you create a new project and contains override declarations for the methods used to manage your game. In addition to the Game1 class' declarations area, there are five primary methods that you will customize for any XNA project.
Right below the class declaration for Game1 is the class level declarations area. By default, this area contains two variables:
The graphics object provides access to, not surprisingly, the system's video card. It can be used to alter the video mode, the size of the current viewport (the area that all drawing work will be clipped to if specified), and retrieve information about Shader Models the video card supports.
XNA provides the SpriteBatch class to allow you to (very quickly) draw 2D images (called sprites) to the screen. The spriteBatch variable is an instance of this class, which we will use for all of our drawing purposes in SquareChase.
The declarations area is the spot for any variables that need to be maintained outside of any of the individual methods discussed next, such as LoadContent, Update, and Draw. In practice, any data that you need to keep track of throughout your game will be referenced in some way in your declarations section.
Any time you use a SpriteBatch object to draw to the display, you need to wrap the calls inside a Begin() and End() pair. Any number of calls to spriteBatch.Draw() can be included in a single batch, and it is common practice to simply start a Begin() at the top of your Draw() code, use it for all of your drawing, and then End() it right before the Draw() method exits. While not benefiting our SquareChase game, batching sprite drawing calls greatly speeds up the process of drawing a large number of images, by submitting them to the rendering system all at once instead of processing each image individually.
The SpriteBatch.Draw() method is used to draw a Texture2D object to the screen. There are a number of different options for how to specify what will be drawn. In this case, the simplest call requires a Texture2D object (squareTexture), a destination Rectangle (currentSquare), and a tint color to apply to the sprite. The expression "playerScoreMod3" takes the player's score, divides it by 3, and returns the remainder. The result will always be 0, 1, or 2. This fits perfectly as an index to the elements in the colors array, allowing us to easily change the color of the square each time the player catches one.
Finally, the spriteBatch.End() tells XNA that we have finished queuing up sprites to draw and it should actually push them all out to the graphics card.
You just finished your first XNA game, that's what!
Granted, it is not exactly the next blockbuster, but at only around 30 lines of code, it implements a simple game mechanic, user input, score tracking and display, and clock-based timing. Not bad for a few minutes' work.
As simple as it is, here are a couple of enhancements you could make to SquareChase:
