A Beginners Guide to XNA - Game From Scratch

21 downloads 67 Views 666KB Size Report
This is aimed at the game programming beginner. Most people with a lot of game programming experience will look at the contents of this document and laugh.
A Beginners Guide to XNA By Mike Fleischauer [email protected] Hosted at http://www.learnxna.com/pages/XNABook.aspx

Introduction When Microsoft announced XNA some two years ago I was at first excited, then somewhat confused and finally I settled on underwhelmed. The talk was big about making games easier to write, stream lining the asset creation pipeline,etc… H ow ever,in the end,it turned out to be m ostly a couple video demos and a lot of talk. Now tw o years later it’s a concrete,usable product that has a lot of potential. It really does simplify a project, although still not to the level the average 13 year old is going to be creating games with ease. It’s still a truly amazing first step and once the asset management stuff is released, I think it will create a huge indie developer community for both Windows and Xbox 360. So then,w hat’s this docum ent? Iam going to attem pt to explain how to use XN A so the “average person” should be able to create a fullgam e. Since of course,XN A is in beta,don’t expect too m uch just yet.

What you need to know C#. Frankly a programming primer is beyond the scope of this book. Besides there are a ton of resources available for learning C#,Ihighly recom m end you explore those options. You don’t need to be a C# guru but the better you understand the language the more you will get out of this book. However, if you have experience with Java, C++, Python or a great many other modern programming languages,C# w on’t be hard to pickup.

M ath. D on’t w orry,there isn’t a ton,but you w illneed to know basic math to get by. Game programming is a math heavy subject. That said, XNA does a good job of making much of the tough stuff invisible to you. This is aimed at the game programming beginner. Most people with a lot of game programming experience will look at the contents of this document and laugh. I am not aiming this document at you. However, if you do see things that are incorrect, could be done better or simply have a suggestion, I would love your input. Email suggestions to [email protected]

W hatyou w on’tlearn Iw on’t be covering as Isaid earlier,C# program m ing. Additionally Iw on’t be covering asset ( graphic/sound/texture/etc ) creation. I will cover how to deal with all of these things from a programming perspective, but again creating graphics and sound is a completely different beast. I will however cover how to deal with each of these assets in game. If the content pipeline assets are delivered soon,Im ay cover these… fingers crossed.

What you need to begin First off, you need Visual Studio Express 2005. You can download at the following link: http://msdn.microsoft.com/vstudio/express/visualcsharp/ Once VC# is installed, you will need XNA Studio Express: http://msdn.microsoft.com/directx/xna/gse/ The following two items are rather large downloads, so I hope you have a fair bit of patience. Microsoft Direct X SDK ( currently August ), which can be downloaded from this link: http://msdn.microsoft.com/directx/sdk/ Finally, the source code for Mech Commander 2, which Microsoft made freely available: http://www.microsoft.com/downloads/details.aspx?FamilyID=6D790CDE-C3E5-46BE-B3A5729581269A9C&displaylang=en I will be using assets for sound and graphics from the MC2 release. If you wish to substitute your own art and audio files, feel free, it will save you close to a gig of download time!

NOTE: XNA is actually a set of assemblies and templates that install into Visual C# Express. Visual C# Express is a full blown C# integrated development environment (IDE) while XNA are the libraries and such that are gaming specific. You do require both to continue though. Additionally, even if you have a full copy of Visual Studio (Pro) installed, you will still need to install the Express version. No worries though, they will run side by side without issues.

Chapter 1: Getting Started

At this point I will assume you have been able to download and install Visual Studio Express, XNA, the D irectX SD K and hopefully the M ech Com m ander 2 sources. N ow it’s tim e to get started.

Load up Game Studio Express, it should look something like the following:

Now, time for your first game. Select the menu File -> N ew Project… The following dialog will appear:

Select W indow s G am e from the tem plates and give it the nam e “M yFirstG am e”,then press OK. Congratulations, you have created your first windows game. Select Build -> Build Solution, then press F5 ( or menu Debug ->Start Debugging ) and your new game will launch. You will see the following:

Not very exciting so far, I agree. Lets take a quick look at what code the template created for us. Double click Program.cs in the solution explorer. This contains the following code: using System; namespace MyFirstGame { static class Program { /// /// The main entry point for the application. /// static void Main(string[] args) { using (Game1 game = new Game1()) { game.Run(); } } } }

Pretty simple really. Every program needs a starting point, and this is your programs starting point. In main, all it does is creates a new version of your Game1 class, and calls its run method. Lets check out Game1, this is where the heavy lifting is going to be done. Right click Game1.cs in the solution explorer and select View Code. You will see the following: using using using using using using using using

System; System.Collections.Generic; Microsoft.Xna.Framework; Microsoft.Xna.Framework.Audio; Microsoft.Xna.Framework.Components; Microsoft.Xna.Framework.Graphics; Microsoft.Xna.Framework.Input; Microsoft.Xna.Framework.Storage;

namespace MyFirstGame { /// /// This is the main type for your game /// partial class Game1 : Microsoft.Xna.Framework.Game { public Game1() { InitializeComponent(); } protected override void Update() {

// The time since Update was called last float elapsed = (float)ElapsedTime.TotalSeconds; // TODO: Add your game logic here // Let the GameComponents update UpdateComponents(); } protected override void Draw() { // Make sure we have a valid device if (!graphics.EnsureDevice()) return; graphics.GraphicsDevice.Clear(Color.CornflowerBlue); graphics.GraphicsDevice.BeginScene(); // TODO: Add your drawing code here // Let the GameComponents draw DrawComponents(); graphics.GraphicsDevice.EndScene(); graphics.GraphicsDevice.Present(); } } }

Again, fairly straight forward code. Game1 is inheireted from Microsft.Xna.Framework.Game, which is the skeleton code of a game application. This object itself free’s you from having to create a ton of boilerplate code to create the main window, set up the graphics card and a number of other mundane actions. Additionally, it links in all the various XNA assemblies, regardless to if you need them or not. Eventaully, you will use every piece so leave all the using statements alone. Other then that, it implemented a default Constructor, the Update method and the Draw method.

Let’s look at each piece individually. protected override void Update() { // The time since Update was called last float elapsed = (float)ElapsedTime.TotalSeconds; // TODO: Add your game logic here // Let the GameComponents update UpdateComponents(); }

Update() is called over and over as your game is run. Think of this as your “game loop”. This is where all the action happens… if you have artifical intelligence, player movement, input controller, etc, you will handle it here. For now all this code does is updates a counter saying who long it has been since the last call to Update(). Finally it calls UpdateComponents() which will call the Update() function of all the child components your game owns. This will be important later.

protected override void Draw() { // Make sure we have a valid device if (!graphics.EnsureDevice()) return; graphics.GraphicsDevice.Clear(Color.CornflowerBlue); graphics.GraphicsDevice.BeginScene(); // TODO: Add your drawing code here // Let the GameComponents draw DrawComponents(); graphics.GraphicsDevice.EndScene(); graphics.GraphicsDevice.Present(); }

This is the heart and soul of your game application so far. This is the actual function that puts graphics on the screen. Again, it is fairly straight forward. When your game was created an object called graphics was created. Graphics pretty much abstracts away all the video card specific functionality. In plain English the Draw() function does the following: -

Makes sure the graphics device is still valid, otherwise exits the function Clears the screen background color to a Cornflower Blue ( is Corn Flower blue?? ). Tells the graphics card you are about to draw the scene Tells all child components to draw themselves Tells the graphics card you are done drawing the scene Finally, tells the graphics card to go ahead and show the results.

Pretty simple so far, no?

You may have a question at this point. How did the game know what size to make my window? How do I make the graphics go full screen? For answers to both of these questions, in Solution Explorer right click G am e1 and choose design. Select the “graphics” com ponent. As Itold you earlier,a graphics component was already created for you when you created your game. The drawing call if (!graphics.EnsureDevice()) is a call to this component.

If you look at the properties window for the graphics component you will see the following

These are the default public properties the graphics component exposes. For example, if you wanted your game to run full screen, you could set IsFullScreen to True, or back in your Game1 constructor, you could have put the line graphics.IsFullScreen = true;

Components themselves are one of the key concepts of XNA. Your game is a component, which in turn, contains a number of components. You can think of Components like lego blocks that can be put together to create a game. You will notice that during your games update and draw methods, it called update and draw on each component within. This effect can cascade down through further components which can update and draw all their child components. In the future, components could be used for

such things as menus, terrain and helper methods like a FPS counter. We will cover components in greater depth later on. There you go,you just created your first gam e! G ranted,it doesn’t do anything,its rather ugly and extremely boring. We will work on that in the following chapters.

Your final action is to save your project. Select the menu File -> Save All… Just remember to save the project to somewhere you can remember, as we will be building on it in following chapters.

Legal Stuff Now for some closing legal bits. All respective terms and copyrights are those of their owning companies. I, Mike Fleischauer, do make this document available to the public domain. Feel free to host this file and distribute it in any manner you desire. However, do not make any modification without prior written consent. Reselling or profiting from this document is strictly prohibited, with the exception of advertising related revenues of the hosting site(s). As a courtesy, please cite the author when posting. I reserve the right to revoke this license at any time.

Additionally, the Mech Commander 2 sources are provided under the following EULA. Please adhere to these requirements as well or abstain from using the Mech Commander related assets!

Mech Commander 2 EULA Shared Source Limited Permissive License for use of MechCommander® 2

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions The term s “reproduce,” “reproduction” and “distribution” have the sam e m eaning here as under U .S. copyright law. “You” m eans the licensee ofthe softw are.

“Licensed patents” m eans any Microsoft patent claims which read directly on the software as distributed by Microsoft under this license.

2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, Microsoft grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce the software, prepare derivative works of the software and distribute the software or any derivative works that you create.

(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, Microsoft grants you a non-exclusive, worldwide, royalty-free patent license under licensed patents to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the software or derivative works of the software.

3. Conditions and Limitations (A) Limitation on Commercial Distribution- Notwithstanding the rights granted in section 2(A) above, you are not granted any rights to com m ercially distribute any artw ork from the softw are (“Art Assets”)in any derivative work or otherwise. Microsoft grants you a limited, non-exclusive, worldwide, royalty-free copyright license to use, reproduce and distribute the Art Assets on a non-commercial basis only.

(B) No Trademark License- This license does not grant you any rights to use Microsoft’s name, logo, or trademarks.

(C) If you begin patent litigation against Microsoft over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.

(D) If you distribute copies of the software or derivative works, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

(E) If you distribute the software or derivative works in source code form you may do so only under this license (i.e., you must include a complete copy of this license with your distribution), and if you

distribute the software or derivative works in compiled or object code form you may only do so under a license that complies with this license.

(F) The softw are is licensed “as-is.” You bear the risk ofusing it.Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

Non Legal ( and non legally binding ) Summary In a nutshell,don’t profit from this docum ent directly or the contents ofthe M ech Commander 2 source release and you will be fine. The sole exception ( to this document ) is advertising based revenue from hosting websites ( aka, banner adds ). That said, subscription based access to this content is forbidden. In plain English, you cannot charge a subscription fee to read this content.

About the Author I have been a professional programmer since graduating college in 1996. I started in e-commerce before the term was coined. Since then, I have worked in a number of industries using a number of technologies, from gaming to manufacturing. Gaming has been a hobby of mine since I first bought an Intellivision, far too many years back for me to desire counting! Since my first few lines of BASIC code on my Atari 800XL computer, I have been hooked on game programming. Please keep in mind, I am learning XNA at the same time you are, so I am bound to make a few mistakes here and there. Also please point the mistakes out to me but do go gentle! Also, this book is as much an experiment in writing and teaching others. I am new to this as well and please point out my errors! You can contact me at [email protected].

Source Code Availability This chapter is available for download at: http://www.learnxna.com/pages/XnaBook.aspx As a mirror, you can download at: http://www.netsalesmanager.com/xna/Chapter1.pdf

Project source code is available at: http://www.learnxna.com/pages/XNABook.aspx

Again, as a mirror you can download at: http://www.netsalesmanager.com/xna/Chapter1Src.zip

Special Thanks Special thanks goes out to the folks at http://learnxna.com for hosting this book! Also, I would like to thank any people on the MSDN forums that gave feedback.