Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

XNA 4 3D Game Development by Example: Beginner's Guide
XNA 4 3D Game Development by Example: Beginner's Guide
XNA 4 3D Game Development by Example: Beginner's Guide
Ebook735 pages10 hours

XNA 4 3D Game Development by Example: Beginner's Guide

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book is a step-by-step tutorial that includes complete source code for all of the games covered. It adopts an engaging style to teach all the game development concepts. Each block of code is explained, and game development concepts are diagrammed and covered in detail. Each game begins with a concept description and concludes with suggestions for expanding on the finished game. This book is intended for readers who want to create 3D games using the XNA Framework. Basic knowledge of the C# programming language and 2D XNA concepts are helpful, but not required.
LanguageEnglish
Release dateSep 25, 2012
ISBN9781849687096
XNA 4 3D Game Development by Example: Beginner's Guide
Author

Kurt Jaegers

Kurt Jaegers is a database administrator by day, 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, one of the earliest XNA-focused tutorial websites.

Read more from Kurt Jaegers

Related to XNA 4 3D Game Development by Example

Related ebooks

Programming For You

View More

Related articles

Reviews for XNA 4 3D Game Development by Example

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    XNA 4 3D Game Development by Example - Kurt Jaegers

    Table of Contents

    XNA 4 3D Game Development by Example Beginner's Guide

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers and more

    Why Subscribe?

    Free Access for Packt account holders

    Instant Updates on New Packt Books

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Time for action – heading

    What just happened?

    Pop quiz – heading

    Have a go hero – heading

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Introduction to XNA

    System requirements

    Installing the Windows Phone SDK

    Time for action – installing Windows Phone SDK

    What just happened?

    Speller – Our first XNA game

    Time for action – creating an XNA project

    What just happened?

    Managing content

    Time for action – creating content assets

    What just happened?

    Member variables

    Time for action – declaring new member variables

    What just happened?

    The Game1 constructor

    Initialization

    Time for action – customizing the Initialize() method

    What just happened?

    Loading content

    Time for action – creating a square texture

    What just happened?

    Updating

    Time for action – customizing the Update() method

    What just happened?

    The Draw() method

    Time for action – drawing Speller

    What just happened?

    Helper methods

    Time for action – words and letters

    What just happened?

    Time for action – completing the Speller project

    What just happened?

    Have a go hero

    Summary

    2. Cube Chaser – A Flat 3D World

    Designing the game

    3D coordinates

    Creating the project

    Time for action – creating the Cube Chaser project

    What just happened?

    Our view of the world

    Time for action – beginning the Camera class

    What just happened?

    The Projection matrix

    Looking at something

    Time for action – implementing a look-at point

    What just happened?

    The View matrix

    Time for action – the View matrix

    What just happened?

    From the ground up

    Time for action – creating the Maze classes

    What just happened?

    Drawing the floor

    Time for action – drawing the floor

    What just happened?

    Moving around

    Time for action – expanding the Camera

    What just happened?

    Time for action – letting the player move

    What just happened?

    Summary

    3. Cube Chaser – It's A-Mazing!

    Maze generation

    Time for action – defining a MazeCell

    What just happened?

    Time for action – generating the Maze class

    What just happened?

    Constructing the walls

    Time for action – building walls

    What just happened?

    Time for action – drawing the walls

    What just happened?

    Solid walls

    Time for action – bouncing off the walls

    What just happened?

    Have a go hero

    Summary

    4. Cube Chaser – Finding Your Way

    The cube

    Time for action – placing the cube

    What just happened?

    Rotating the cube

    Time for action – rotating the cube

    What just happened?

    Matrices – big scary math things?

    The translation matrix

    The rotation matrix

    The scale matrix

    Combining matrices

    What does it all mean?

    Positioning the cube

    Time for action – randomly positioning the cube

    What just happened?

    Catching the cube

    Time for action – catching the cube

    What just happened?

    Have a go hero!

    Summary

    5. Tank Battles – A War-torn Land

    Creating the project

    Time for action – creating the Tank Battles project

    What just happened?

    An arc-ball camera

    Time for action – the ArcBallCamera class – part 1

    What just happened?

    Time for action – finishing the ArcBallCamera class

    What just happened?

    Building the playfield

    Height maps

    Generating the terrain

    Time for action – generating the terrain

    What just happened?

    Height data

    Time for action – adding the ReadHeightMap() method

    What just happened?

    Building vertices

    Time for action – adding the BuildVertexBuffer() method

    What just happened?

    Building the indices

    Time for action – the buildIndexBuffer() method

    What just happened?

    Let's see the terrain already!

    Time for action – drawing the terrain

    What just happened?

    Adding texture – a gentle introduction to HLSL

    Declaring variables

    Time for action – HLSL declarations

    What just happened?

    The vertex shader structures

    Time for action – Vertex Shader Input and Output definition

    What just happened?

    The vertex shader

    Time for action – the vertex shader

    What just happened?

    The pixel shader

    Time for action – the pixel shader

    What just happened?

    Time for action – utilizing Terrain.fx

    What just happened?

    Moving the camera

    Time for action – moving the camera with the mouse

    What just happened?

    Summary

    6. Tank Battles – The Big Guns

    Adding the tank model

    Time for action – adding the tank model

    What just happened?

    Building tanks

    Time for action – building the Tank class

    What just happened?

    Bringing things down to earth

    Time for action – terrain heights

    What just happened?

    Animating the tank

    Time for action – tank animation

    What just happened?

    The combatants

    Time for action – positioning tanks

    What just happened?

    Summary

    7. Tank Battles – Shooting Things

    Interface components

    The UIWidget class

    Time for action – creating the UIWidget class

    What just happened?

    UITextblocks

    Time for action – creating UITextblocks

    What just happened?

    UIButtons

    Time for action – creating buttons

    What just happened?

    Working with our UI objects

    Time for action – adding the UIHelper class

    What just happened?

    Creating the user interface

    Time for action – creating the UI

    What just happened?

    Responding to interface events

    Time for action – responding to events

    What just happened?

    Firing shots

    Time for action – ShotManager-part 1

    What just happened?

    Particles in 3D

    Billboarded particles

    Time for action – the Particle class-part 1

    What just happened?

    Time for action – finishing the Particle class

    What just happened?

    Managing particles

    Time for action – the ParticleManager class

    What just happened?

    HLSL for our particles

    Time for action – building Particles.fx

    What just happened?

    Adding particles

    Time for action – implementing particles

    What just happened?

    Summary

    8. Tank Battles – Ending the War

    Managing game states

    Time for action – implementing a title screen

    What just happened?

    From Playing to GameOver

    Time for action – detecting hits

    What just happened?

    Managing turns

    Time for action – managing turns

    What just happened?

    Visual improvements

    Lighting

    Time for action – computing normals

    What just happened?

    Diffuse lighting

    Time for action – HLSL for lighting

    What just happened?

    Ambient lighting

    Time for action – using ambient light

    What just happened?

    Multitexturing

    Time for action – multitexturing

    What just happened?

    Have a go hero!

    Summary

    9. Mars Runner

    Design of Mars Runner

    Getting started with the GSM sample

    Time for action – creating the Mars Runner solution

    What just happened?

    The GameScreen abstract class

    Customizing the default ScreenManager screens

    Time for action – customizing the BackgroundScreen class

    What just happened?

    Time for action – updating the menu

    What just happened?

    Adding a new screen

    Time for action – creating the MarsRunnerPlayScreen class

    What just happened?

    A new camera

    Time for action – the stationary camera

    What just happened?

    Creating the background

    Time for action – creating a skybox

    What just happened?

    Building the Martian surface

    Simplified heightmaps

    Time for action – beginning the MarsTrack class

    What just happened?

    Time for action – generating the track

    What just happened?

    Drawing the track

    Time for action – drawing the track

    What just happened?

    Summary

    10. Mars Runner – Reaching the Finish Line

    Abstracting support for 3D models

    Time for action – the GameEntity class

    What just happened?

    Building the rover

    Time for action –building the rover

    What just happened?

    Time for action – accepting user input

    What just happened?

    Animating the planet

    Time for action – moving the world

    What just happened?

    Animating the rover

    Time for action – animating the rover

    What just happened?

    Crashing into craters

    Time for action – detecting craters

    What just happened?

    Adding an enemy

    Time for action – the basic flying saucer

    What just happened?

    Time for action – flying the saucer

    What just happened?

    Shots and collisions

    Time for action – Shot classes

    What just happened?

    Time for action – the ShotManager class

    What just happened?

    Enemy shots

    Time for action – enemy shots

    What just happened?

    Time for action – player shots versus aliens

    What just happened?

    Time for action – enemy shots versus the rover

    What just happened?

    Scoring

    Time for action – scoring

    What just happened?

    Time for action – the GameOver screen

    What just happened?

    Sound effects

    Time for action – building the SFXManager class

    What just happened?

    Triggering sounds

    Time for action – playing sound effects

    What just happened?

    Have a go hero!

    Summary

    Index

    XNA 4 3D Game Development by Example Beginner's Guide


    XNA 4 3D Game Development by Example Beginner's Guide

    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 (<sandyjb@gmail.com>)

    Credits

    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

    About the Author

    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.

    About the Reviewers

    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.

    www.PacktPub.com

    Support files, eBooks, discount offers and more

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

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print and bookmark content

    On demand and accessible via web browser

    Free Access for Packt account holders

    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.

    Instant Updates on New Packt Books

    Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.

    Preface

    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.

    What this book covers

    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.

    What you need for this book

    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.

    Who this book is for

    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.

    Conventions

    In this book, you will find several headings appearing frequently.

    To give clear instructions of how to complete a procedure or task, we use:

    Time for action – heading

    Action 1

    Action 2

    Action 3

    Instructions often need some extra explanation so that they make sense, so they are followed with:

    What just happened?

    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:

    Pop quiz – heading

    These are short multiple-choice questions intended to help you test your own understanding.

    Have a go hero – heading

    These practical challenges 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: You may notice that we used the Unix command rm to remove the Drush directory rather than the DOS del command.

    A block of code is set as follows:

    # * Fine Tuning

    #

    key_buffer = 16M

    key_buffer_size = 32M

    max_allowed_packet = 16M

    thread_stack = 512K

    thread_cache_size = 8

    max_connections = 300

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    # * Fine Tuning

    #

    key_buffer = 16M

    key_buffer_size = 32M

    max_allowed_packet = 16M

     

    thread_stack = 512K

    thread_cache_size = 8

    max_connections = 300

    Any command-line input or output is written as follows:

    cd /ProgramData/Propeople rm -r Drush git clone --branch master http://git.drupal.org/project/drush.git

    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: On the Select Destination Location screen, click on Next to accept the default destination..

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    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 <feedback@packtpub.com>, 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.

    Customer support

    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.

    Downloading the example code

    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.

    Errata

    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 to our website, or added to any list of existing errata, under the Errata section of that title.

    Piracy

    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 <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors, and our ability to bring you valuable content.

    Questions

    You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.

    Chapter 1. Introduction to XNA

    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:

    Review the system

    Enjoying the preview?
    Page 1 of 1