# Game Creation with XNA/Print version

Preface

Introduction
Setup
C#
Game Loop
Input Devices

## Game Creation / Game Design

Introduction
Types of Games
Story Writing and Character Development
Project Management
Marketing, Making money, Licensing

## Mathematics and Physics

Introduction
Vectors and Matrices
Collision Detection
Ballistics
Inverse Kinematics
Character Animation
Physics Engines

## Programming

Introduction
Visual Studio
Git and Subversion
Reusable Components
Frameworks

## Audio and Sound

Introduction
XACT
Creation
Synthesizer
Finding free Sounds

## 2D Game Development

Introduction
Texture
Sprites
Finding free Textures and Graphics

## 3D Game Development

Introduction
Primitive Objects
3D Modelling Software
Finding free Models
Importing Models
Camera and Lighting
Skybox
Landscape Modelling
3D Engines

## Networking and Multiplayer

Introduction
Split-Screen
Network and Peer-to-peer
Network Engines

## Artificial Intelligence

Introduction
Artificial Intelligence in Games
AI Engines

## Kinect

Introduction
Use Kinect to create Models

Introduction
Level Editors

## Appendices

Game_Creation_with_XNA/Glossary/
Game_Creation_with_XNA/Resources/
Game_Creation_with_XNA/Authors/

## Preface

To start writing games for Microsoft's XBox360, one usually has to read many books, web pages and tutorials. This class project tries to introduce the major subjects, get you started and if needed point you into the right direction for finding additional material.

The idea behind this class project came from a colleague who suggested that most class projects produce really nice results, but usually disappear in some instructors' drawers. After reading on the possibility of using Wikibooks for class projects, we just had to give it a try.

### Getting Started

If you are new to Wikibooks, you might first want to look at Using Wikibooks. Details for creating a class project can be found at Class_Project_Guidelines.

### Other Wikibooks

There are also other wikibooks on subjects related that are quite useful:

### Other Class Projects

Inspiration from successful class projects can be drawn here, which by themselves are also quite interesting and maybe helpful for this project:

# Basics

## Introduction

Game development is neither easy nor cheap, instead it is a multi-billion dollar, fast growing industry. It is challenging in terms of hardware and software, always using cutting edge technology.

The XBox 360 contains gaming hardware which is among the most sophisticated available. It has a PowerPC-based CPU with 3 cores running at 3.2 GHz with 2 threads each. For graphics it uses a custom ATI Graphics (Xenos) card running at 500 MHz with 48-way parallel floating-point shader pipelines.

Hence, in game development we have already made the paradigm shift away from the single-core single-threaded application, because in the XBox we are dealing with 6 threads running in parallel on the CPU, with 48 threads running in parallel on the GPU and with hundreds of GFLOPS computing power. Therefore, game programming is parallel programming!

So how can we learn about game development, how can we get started? Microsoft with the XNA Game Studio and the XNA Framework has made it pretty easy to get started. With openly available components, even a 4th semester student can start writing a 3D race car simulation. A very nice feature of the XNA Game Studio is the fact that you can run the programs not only on the Xbox, but also on the PC, which is very nice for development.

Before we can get started writing code, we need to get our environment set up, install necessary software, including Visual Studio, learn a little about C# and the basics of game programming. Also handling of input devices is covered here.

## Setup

For this book we will use Visual Studio 2008 and the XNA Framework 3.1. Although there are newer versions available, for many reasons we will stay with this older version.

### Preparation

You should first make sure that you have a newer version of Windows, such as XP, Vista or 7, with the appropriate service packs installed. In general, it is a good idea to use the US version of the operating systems. In addition, since at least DirectX 9 compatibility is needed, you may not be able to use a virtual machine (such as Parallels, VMWare or Virtual Box) for doing XNA programming.

Make sure that no older or newer version of Visual Studio is installed on your computer. Especially with older version there are always issues. It is good advise not to have several versions of Visual Studio running on one computer.

### Install Visual C# 2008 Express Edition

First download the C# 2008 Express Edition from Microsoft. You can also use the Visual Studio Express version. Installation is straightforward, simply follow the wizard. After installation, make sure you run Visual Studio at least once before proceeding to the next step.

### Install the DirectX Runtime

Download and install the 9.0c Redistributable for Software Developers. This step should not be necessary on newer Windows version. First, try to get away without it, if in a later part you get some funny error message related to DirectX, then execute this step.

### Install XNA Game Studio 3.1

After having run Visual Studio at least once, you can proceed with the installation of the XNA Game Studio. First, download XNA Game Studio 3.1. Execute the installer and follow the instructions. When asked, allow communications with XBox and with network games.

To see if our installation was successful, let's create a first project.

1. start Visual C# 2008 Express Edition
2. select File->New Project under 'Visual C#->XNA Game Studio 3.1' you should see a 'Platformer Starter Kit (3.1)', click OK to create the project
3. to compile the code use either 'Ctrl-B', 'F6' or use 'Build Solution' from the Build menu
4. to run the game use 'Ctrl-F5', enjoy
5. take a look at the code, among other things, notice that a 'Solution' can have several 'Projects'

### Next Steps (optional)

We will only develop games for the PC, if you want to develop games for the XBox also, you need to become a member of XBox LIVE and purchase a subscription (in case your university has a MSDN-AA subscription, membership is included).

You need to be attentive of which XNA version you have to install.

compatible versions:

Visual Studio XNA Game Studio
2005 2.0
2008 3.0, 3.1
2010 4.0

Sarah and Rplano

## C-Sharp

When coding for the XBox with the XNA framework, we will be using C-Sharp (C#) as programming language. C-Sharp and Java are quite similar, so if you know one, basically you know the other. A good introduction to C-Sharp is the Wikibook C_Sharp_Programming.

C# has some features that are not available in Java, however, if you know C++ some may look familiar to you:

• properties
• enumerations
• boxing and unboxing
• user-defined conversion (casting)
• structs

The biggest difference between C-Sharp and Java probably are the delegates. They are used for events, callbacks and for threading. Simply put, delegates are function pointers.

### Properties

This is an easy way to provide getter and setter methods for variables. It has no equivalent in Java, except if you consider the automatic feature of Eclipse to add these methods. Simply consider the following example, notice the use of the value keyword.

### Enumerations

In Java you can use interfaces to store constants. In C# the enumeration type is used for this. Notice that it may only contain integral data types.

### Boxing and Unboxing

This corresponds to Java’s wrapper types and also is available now in Java. Interesting to notice is that the original and boxed are not the same. Also notice that unboxed stuff lives on the stack, whereas the boxed stuff lives in the heap.

This is a feature that you may know from C++, or you might consider the overloading of the ’+’ operator for the Java String class. In C# you can overload the following operators:

• unary: +, -, !, +, ~, ++, --, true, false
• binary: +, -, *, /, %, &, |, ^, <<, >>, ==, !=, <, >, <=, >=

For instance for vector and matrix data types it makes sense to overload the '+', '-' and the '*' operators.

### User-Defined Conversion

Java has built-in casting, so does C#. In addition, C# allows for implicit and explicit casting, which means you define the casting behavior. Usually this makes sense between cousins in a class hierarchy. However, there is a restriction: conversions already defined by the class hierarchy cannot be overridden.

### Structs

Structs basically allow you to define objects that behave like primitive data types. Different from objects, which are stored on the heap, structs are actually stored on the stack. Structs are very similar to classes, they can have fields, methods, constructors, properties, events, operators, conversions and indexers. They can also implement interfaces. However, there are some differences:

• structs may not inherit from classes or other structs
• they have no destructor methods
• structs are passed by-value not by-reference

When we were discussing the keyword const the difference to Java’s final was that you had to give a value to it at variable declaration time. A way around this is the readonly keyword. However it still has the restriction, that a readonly variable has to be initialized inside the constructor.

### Delegates

Usually, in Java when you pass something to a method, it is a variable or an object. Now in C# it is also possible to pass methods. This is what delegates are all about. Note that delegates are also classes. One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.

In addition to normal delegates there are also multicast delegates. If a delegate has return type void, it can also become a multicast delegate. So if a delegate is the call to one method, then a multicast delegate is the call to several methods, one after the other.

### Callbacks

Callback methods are used quite often when programming C or C++ and they are extremely useful. The idea is instead of waiting on another thread to finish, we just give that thread a callback method, that it can call once its done. This is very important when there are tasks that would take a long time, but we want the user in the meanwhile to do other things. To accomplish this, C# uses delegates.

### Inheritance

Object-oriented concepts in C# are very similar to Java’s. There is a few minor syntax related differences. Only with regard to method overwriting in an inheritance chain, C# provide more flexibility than Java. It allows for a very fine-grained control over which polymorphic method actually will be called. For this it uses the keywords 'virtual', 'new', and 'override'. In the base class you need to declare the method that you want to override as virtual. Now in the derived class you have the choice between declaring the function 'virtual', 'new', or 'override'.

## Game Loop

Programming a game consoles (GC) is not quite the same as programming a regular PC. Whereas PC's have sophisticated operating systems such as Windows, Linux or Mac OS, on a game console we are much closer to the hardware. This has to do withe the special requirements of games. We must consider the following differences between PC’s and GC's:

• on a GC usually only one (multithreaded) program is running, thus there is no real OS
• on a GC raw graphics power is needed, but there is no GUI with windows and widgets
• a GC usually has no keyboard, console, sometimes not even a harddisk

Hence, you will find no classes with names like Window, Form, Button or TextBox. Instead you find classes with names such as Sprite, Texture2D and Vector3. We talk about Content Pipeline, Textures and Shaders.

Usually, programs for PC's are event driven, meaning the user clicks somewhere something happens. If the user doesn't click anywhere, nothing happens. On game consoles (GC) this is a little different. Here we often find the so-called Game Loop. For the Xbox 360, or rather the XNA framework, it consists of three methods:

• Update( GameTime time )
• Draw( GameTime time )

LoadContent() is called once at the start of the game to load images, sounds, textures, etc. Update() is used for getting user input, updating the game state, handling AI and sound effects. Draw() is called for displaying the game. (MVC Pattern). The Game Loop then consists of the two methods Update() and Draw() being called by the engine. They are not neccessarily called in sequence!

## Input Devices

### Introduction

Input Devices is one of the most important chapters in a handbook for game creation. A computer (or Xbox) game subsists on interaction with the user - that is why there needs be to a method to check the user input and to let game react on this input.

XNA makes it very easy to control the user devices. It offers an easy-to-use and understandable API for access to mouse, keyboard and gamepad. Using this it is possible to write an user-interaction scheme in a short time. Basically XNA offers easy access to:

• Mouse
• Keyboard

The basic concept is the same for all controller types. XNA provides a set of static classes (one for each type) which can be used to retrieve the status and all properties (e.g. pressed buttons, movements, ...) of the input device.

This detection is usually located in the Update()-method of the game loop to retrieve the status as often as possible. Storing the states of all input devices in class variables allow it to check the status in other methods and classes. It is a common solution to have an array of boolean variables in the class which represent the status of all controllers - namely the pressed buttons on the controller, the mouse movements and clicks and the pressed keys on the keyboard.

protected override void Update(GameTime gameTime)
{
KeyboardState kbState = Keyboard.GetState();
// ...
}


### Windows vs. Xbox

Windows and Xbox games are usually played in a different way. In general a Windows computer is controlled by a mouse and a keyboard, whereas an Xbox is often controlled by a gamepad. Therefore it needs a control structure to decide whether the code is executed on Windows or Xbox to set a default controller for the game.

#if XBOX
// this code is embedded only in xbox project
#endif


But it is also possible to connect a mouse or keyboard to an Xbox as well as to connect an Xbox controller to a Windows computer. So in most of the cases it is better to check for example if a gamepad is connected. Another way of dealing with that problem is to store the user's controller of choice in a variable. So the user may decide which controller he likes to use to play your game.

### Mouse

Wireless Mouse

At first you have to get an instance of the mouse state by calling the static GetState()-method of the Mouse class. This object now gives you access to a lot of public attributes from the connected mouse.

MouseState mouse = Mouse.GetState();
bool leftButton = (mouse.LeftButton == ButtonState.Pressed); // left mouse button
bool middleButton = (mouse.MiddleButton == ButtonState.Pressed); // middle mouse button
bool rightButton = (mouse.RightButton == ButtonState.Pressed); // right mouse button
int x = mouse.X; // horizontal mouse position
int y = mouse.Y; // vertical mouse position
int scroll = mouse.ScrollWheelValue; // scroll wheel value


The state of the mouse buttons is read through the attribute "xxxButton" (where xxx stands for the type - left, middle, right). If you compare this value with ButtonState.Pressed or ButtonState.Released you can retrieve the state of this button. In the example above it stores the state of each button in a boolean variable that is true if the associated button is pressed.

The mouse position on the screen is stored in the X and Y attribute of the mouse object. This value is always positive (as it starts with 0,0 in left upper corner) and may be compared to further mouse positions (in a game logic) to detect a specific movement of the mouse. A simple example would be:

MouseState mouse = Mouse.GetState();
int x = mouse.X;
int y = mouse.Y;
deltaX = oldX - x; // difference of horizontal positions
deltaY = oldY - y; // difference of vertical positions
oldX = x;
oldY = y;


Most of the modern mouse also have a scroll wheel that is often used in games, for example to zoom, to scroll or to switch between different weapons. The attribute ScrollWheelValue is an integer that represents the scroll state of the mouse.

To recognize the movement of the scroll wheel it is necessary to store some older values and compare them with each other. The sign of this difference indicates the scroll direction and the absolute value indicates the speed of scroll movement.

### Keyboard

Cherry Keyboard

To check the state of the keys on a keyboard is very simple. At first you have to get an KeyboardState object by calling the static method GetState from the Keyboard class. This instance now lets you retrieve the state of specific keys.

KeyboardState keyboard = Keyboard.GetState();
bool keyB = keyboard.IsKeyDown(Keys.B); // key "B" on keyboard
bool keyArrowLeft = keyboard.IsKeyDown(Keys.Left); // arrow left on keyboard


The boolean variables keyB and keyArrowLeft now store "true" if the specific key is pressed right now or "false" if it is not pressed. This method can be repeated for each key that is of interest for the application or game.

It is also possible to directly get an array of all keys of the keyboard that are currently pressed. A call of the method GetPressedKeys returns an array of Keys that can be traversed key by key.

KeyboardState keyboard = Keyboard.GetState();
Keys[] keys = keyboard.GetPressedKeys(); // array of keys


The gamepad is the most convenient way to play a game on the Xbox. Despite XNA is designed to develop games for Windows as well as for Xbox, the default API only supports the original Xbox controller. Based on that fact you have to decide whether you want to force your user to use (and maybe buy) the Xbox gamepad or if you want to support any other gamepads for example from Logitech.

That might be more comfortable for the user, though it means more coding effort for the developer. In this chapter I want to describe the implementation for both the Xbox controller and all other controllers.

Xbox 360 Wireless Controller

Accessing this input device is nearly as easy as checking the state of mouse or keyboard. One (and important) difference is that XNA makes it able to connect up to four different gamepads to the Xbox or Windows computer.

So it is (often) necessary to implement a loop over all gamepads that are connected to check their states individually. How this (and more) can be done is explained in the following paragraphs.

GamePadState[] gamePad = new GamePadState[4];
for(int i = 0; i < 4; i++) { // loop over up to 4 gamepads
}
}


In this loop you can access all attributes like the buttons (front and shoulder), the digital pad and the two analog sticks. Here is how you do it:

bool aButton = (gamePad[0].Buttons.A == ButtonState.Pressed); // button A
int leftStick = gamePad[0].ThumbSticks.Left.X; // horizontal position of left stick


The rumble effect lets the gamepad vibrate and gives the player a special feedback to his actions in the game. For instance a hit by an opponent in a shooter game or a crash in a racing game could cause such feedback. The second and third parameter control the intensity of the rumbling effect.

GamePad.SetVibration(int controllerNr, float leftRumble, float rightRumble); // make the controller rumble


Other gamepads than the original Xbox controller are not supported by XNA. But it is possible to integrate a support for them with a free library which is called SlimDX.

In addition you need a helper class that can be found here - it uses SlimDX to check the gamepad state of controllers that are not the original Xbox controller.

If you have downloaded, installed and integrated both the SlimDX library and the helper class you can use the following code to check the gamepad states - like you have done with the Xbox controller in XNA.

controller = new GameController(this, 0); // number of gamepad
GameControllerState state = controller.GetState();
bool button1 = state.GetButtons()[1]; // button 1 pressed


### Kinect

Xbox 360 Kinect Standalone

Kinect is a revolutionary video camera for the Xbox that recognizes your movement in front of the television. This can be used to control games just with your body. Developers can use the Kinect framework to integrate this into their game.

# Game Creation / Game Design

## Introduction

Here we first consider what types of games there are, basics behind story writing and character development. Also project management, marketing, making money, and licensing are issues briefly touched upon.

Lore ipsum ...

## Types of Games

BlaBla about what kind of games are out there, maybe some history. Also include non-computer games, maybe there are some genres.

• role playing
• card games
• chess, go
• browser games / 2nd Life...
• Nintendo
• Playstation/XBox etc
• 2D
• 3D
• strategy

... Write a little chapter about each, giving examples and references, maybe with links where to play them online.

# Story Writing and Character Development

A good game lives and dies with its characters and its story. A good story is what catches the player, keeps him interested and makes him want to continue. The story is the frame for all the action which is taking place, wrapping everything together. But story alone will never keep the player going. There is no good story without good characters and vice versa. The characters in the story are just as important. Not only the main character, but all characters he is interacting with, all characters who motivate him or influence him to do the things he does. Therefore its most crucial, for a good story, to create the story and all characters within in a way so they form a coherent unity. Imagine a Spacetrooper crossing Frodos way in The Lord of the Rings. That simply wouldnt fit and would definitly ruin the story. But what exactly is a good story? And what exactly are good characters, fitting this very story? As always, whether or not a story and its genre are interesting, is a question of taste and lies in the eye of the beholder. Whereas whether a story is written in a good or a bad way, follows certain mechanics. Same applies for the characters in the story. Its personal taste whether you like the good guy or prefer the bad guy. But creating a character which is “self-contained” and well made, again follows certain mechanics. However you write a story or chreate your character, is totally up to you. But looking at what other authors and game developers do, makes it easier. There are certain tools and ways how to write the story and create the character for your game. The more detail you want to put in the more research you should do. There are many books out there that might help you to dive deeper int o the matter of Story Writing and Character Development. Covering it all would simply be to much. This article will give you a basic insight into Character Development and Story Writing for Games.

## Character Development

On the following pages I will describe techniques to develop/create a character for a game or a story. Character development in terms of progress while playing, gaining expirience, increasing level, learning skills and so on, is not part of this article, will be referred to by certain links though. Focus of this article is character creation prior to the game.

### Preliminary Work

The probably most important thing when creating a character is to know its purpose. Are you creating the main character of the story, the villain, a sidekick, a servant, a random companion or something else? Knowing the role of the character makes it easier to define his behaviour, his actions, his way of thinking and his overall appearance. After you have choosen the scope of your character, the actual work begins. Inform yourself! Read as much about the type of the character as you can. Ask yourself questions to define the character.

• Do characters like this already exist in other games or stories?
• What has been written by other authors?
• Are there already stereotypes of this charakter and do they fit to your creation?
• Is he a servant? How does it feel to serve?
• Is he a soldier? How does it feel to be in battle?
• Is he a priest? How does it feel to pray to god?

Learn as much about the character as you can. Check all available resources. Talk to friends. Keep asking questions. If you dont find exactly what your looking for, stick to your own imagination and feelings. In the end its your creation. There are certain things to consider though. Do you create a character who is part of an already existing universe (like an orc or a dwarf or a human)? If so think about the characteristics already applied to them. Like, orcs are green, dwarfs a small and humans can’t breath underwater. Do you want to stick to these basic characteristics that are already present in the players imagination, or do you want to create something totally new? However you decide, keep in mind how the player could react on your creation.

### Point of View and Background

In order to make your character authentic, try to look through his eyes. Try to be your character and keep your eyes open to the world and how the character perceives it. How do things look? Why do they look like this? How do things feel? Why do they feel that way? What feels good? Why does it feel good? The WHY of things sometimes is more important than the things themselves. To understand the WHY, it is necessary to understand the background of your character. A real person develops a certain understanding of the world and has an individual point of view on things, depending on his own expirience, on his way of growing up and on all the things that happened in his life. And probably only he can tell how he became the person he is today. Since your character is a creation of your fantasy, you are the only one that can tell how he became the character he is. The more specific you describe the characters background the easier it will be for the player to understand him and feel with him. The player must not necessarily agree with the characters attitude, but he will more likely understand it, if you provide a detailed explanation for his behaviour. The more you think in detail the more realistic your character will be. You are the one to decide how much detail your character needs. But in general the main characters in your game should posses more detail and depth, than any character in a supporting role.

### Motivation & Alignment

Understanding the WHY of things is a good start to understand the motivation behind decisions your character makes. Motivation is the force that drives all of your characters, may it be good or evil. What is the motivation of the plumber Mario to take all the efforts? To rescue the princess and stop Bowser. What is Bowsers motivation? To take over the Mushroom Kingdom. Both of them are driven by their motivation. To understand the motivation of a character, and eventually agree with it, you need to know as much about the character as possible. Giving your character an alignment will help to understand his actions and might even help to understand and clarify his motivation. SuperMario wants to save the princess, never does any bad things and therefore is easily classified as good. So is Bowser. He embodies everything which is considered bad, so he is the bad guy, period. But saying “Well, he is a bad guy, and that’s why he is doing bad things.” won’t do the trick for more detailed characters. The more detailed a character gets, the more complicated it is to classify him as good or evil. Some people do the right things for the wrong reasons and some do the wrong things for the right reasons. Who is the good and who is the bad guy? To help you align your character to a side, you should look at his intention. When he is doing a good thing and furtermore intended to do a good thing, he is probably a good guy. But no one is entirely good or purely evil. Most characters are neutral until their actions proove them to be good or evil. Here is a list of the three stereotypes and their attributes to help you classify your character:

#### Good

• does the right things for the right reasons
• loves and respects life in every form
• tries to help others
• puts others interests over its own
• sticks to the law
• is driven by the wish to do the right thing even when not knowing what the right thing is

Be careful when creating your Hero. There would be no fun running through the game being invincible, being too strong or beeing too clever. If things are too easy, players will loose interest very fast. To make him interesting a hero must not be perfect. He should have some weaknesses and flaws the player can identify with. Most heros don’t even know they are heros. They can be just like you and me, living their lives and doing their daily work. Suddenly something happens and they simply react. Driven by their inner perception of what is right and wrong, driven by their alignment, they react in a way which slowly transforms them into what we would call a hero. Frodo for example never chose to be a hero, he was chosen and became a hero while fullfilling the task he was given. A hero needs to grow with his challenges. And exactly that is what makes the hero so interesting for the player. The change that happens and the fact that the player witnesses the transformation from the normal guy to the saviour of the world. While creating your character, keep in mind that every hero has skills and talents that enable him to fullfill his task. Some of them are special or even unique which make the hero appear special. But what really makes the hero interesting and appealing to the player are his flaws and merits. A knight in shiny armor, a huge sword and a big shield who slays dragons seems impressive and adorable. But giving him flaws and merits like, beeing afraid of small spiders make him much more realistic and bring him closer to the player.

#### Neutral

• sometimes does the right things
• sometimes behaves selfish and does the wrong things
• hard to say on which side they are - sometimes they dont know themselves
• even though they call themselves neutral their actions sometimes prove otherwise
• good alignment for sidekicks of hero and villain - Devils advocat
• Anti-Heros can be neutral and pushed from one side to the other

Neutral characters dont choose a side per se. They base their decisions and actions on their mood at a apecific point. Most characters are neutral until they have to decide which way to go. And after that descision they can still change their mind again. Whatever suits them best.

#### Evil

• is selfish
• greedy, insane or pure evil
• shows no interest for others
• puts his own goals infront of everything else
• must have a strong motive
• the reader must love to hate him simply cuz he embodies everything we hate or never would consider doing

For more detailed information about archetypes, their features and use in stories check Archetypes.

## Story Writing / Story Telling

Writing a story often begins with an idea. Where that idea comes from may differ though. Either you want to make a game out of a movie or a book you like, you want to create something totally new, or you want to make a sequel of an existing game. Depending on the source of your idea, different things are to be considered when writing. In general one can say, writing a story and creating a game should go hand in hand. It’s never a good idea to clamp a story to an already existing game design and vice versa. Both, Design and Story grow and therefore it’s a good idea to make them grow parallel.

### Adapting a movie or a book

When adapting a movie or a book you necessarely need to take things from the movie. Either the story, the main characters, the setting or all of it. Otherwise it would’nt be an adaptation. If you want to adapt the whole movie you need to be clear of certain things. Yo need to stay true to the original material. When doing so you need to be aware of that not everything that is working good in a movie works for a game. Some parts of the story are moving on without the character even being present. You have to fill in that information with cutscenes or videos which take the player out of the game. That’s no big deal in a movie because you sit and watch it anyway and don’t interact with it. It can be frustrating for a player though, to not be able to interact in a specific situation. Another point to think about is the fact that the player might know the end of the game already due to the fact he knows the movie. This could take away some thrill but on the other hand could make the player identify with the hero because he is doing all the things the hero does in the movie.

### Creating a whole new story

When creating a whole new story you are quite free to do whatever you want. Keep in mind certain things though. If you want to create a game which shall be successful and should sell good you need to know what kind of games are played at the moment and why. You should consider how the players think and what they want. Next thing to consider is what kind of story do you want and then choose an appropriate game-style to match your story. Decide for a genre (Game Genres / Types of Games). Not all genres are able to transport the story of your game. Already existing genres might have content which serve your needs and are already established. On the other hand genres do have boundaries which are not easy to cross. Whatever genre and style you choose for your game, stick to it throughout the whole game.

### How to actually write a story

Every story needs a title, a prolog, a main part and an epilog. Furthermore a story needs characters, because no story without character and no character without story. This seems a bit flat but that’s all there is to it. Lets dive a bit deeper into the single parts.

#### Title

The title should fit your story. It should create an interest to play the game. It should partially reveal what the game is about but not say to much to keep the thrill.

#### Prologue

The prologue usually starts with a description of the game world as it is. The player becomes a first impression and a feeling for the setting. A good prologue rouses the players desire to explore. Actually everything is in order. Furthermore the prologue gives background details needed to understand what is going on.

#### Main part

The main part usually starts with a call to adventure or a reason to start playing. Whatever that my be in your story. Either the princess gets kidnapped, your character’s village gets destroyed by Dark Riders, or your character simply wants to break out of his world. Referring to Joseph Campbell's Monomyth the hero refuses this first call to adventure and needs further persuasion to finally start his journey. But as for games the player wants to play, he wants to explore and wants to take the journey. That’s why he plays the game. So the call of adventure gets our character going. On this journey the character is faced with multiple challenges he has to overcome in order to come a step closer to his final goal. (Whatever that is…). With every challenge the character passes he will grow stronger and will come closer to his goal. But every challenge which is overcome, is followed by an even greater challenge. Lee Sheldon writes in his book Character Development and Story Telling for Games:

“We have our crisis then. A major change is going to occur. Only one? No. As we move through the story, crisis follows crisis, each one escalating tension and suspense.
Every one of these crises needs an additional element a climax. Egri says, “crisis and climax follow each other, the last one always on a higher plane than the one before…
…Resolution is simply the outcome of the climax that is a result of the crisis. The story is built from this three-step dance. Every one of these crises has reached a
climax and has been resolved, only to have the stakes raised higher, and the next crisis always looming as even more profound.“

But challenges should not always be slaying evil creatures or escape from a trap. Personal sacrifice, or the loss of a loved companion can be a challenge as well. Most of you might remember Gandalf falling to his assumed death in the Mines of Moria while fighting the Balrog. But Frodo and his fellowship decided to keep their eyes on the goal, grow with the challenge and move on. Challenges can also be to collect certain things, learn how craft or solve puzzles. And each challenge has a small reward, may it be experience, a new weapon, a new companion or just something that makes your character stronger and prepares him for his “final battle”. Small challenges or quests keep the player motivated. Furthermore the character should meet several other characters. All of them will have their own intend and influence on him. Some want to help him advance on his journey and some of them want to hinder or even destroy him.

Usually the main part ends with the final encounter and the ultimate reward. May it be the Lord Deamon you slay, the princess you rescue or the world you save. Again referring to Joseph Campbell's Monomyth this is attended by a personal sacrifice your character has to make. The hero is willing to give away his life to save the princess and to complete his task.

#### Epilogue

The epilogue describes how the character receives the The ultimate Boon, his way home and how the story ends. Sometimes games leave an open end in order to be continued some day. Some games like MMORPG do not even have a “real” end. The story itself may end or pause until the next expansion is released, but the game continues.

Thonka

## Books

Character Development And Storytelling For Games by Lee Sheldon(Premier Press 2004)
Die Heldenreise im Film by Joachim Hammann (Zweitauseneins)

## Project Managment

BlaBla about project management and how important it is. Should include basics of project management, including milestones, risk analysis, etc. Especially, also tools like MS Project, Zoho, Google Groups or similar should be compared and described how to use them.

### Authors

to be continued... thonka

also interested: juliusse

# Introduction

After finishing to develop your Xbox game, your aim will be to make as many people as possible to buy and enjoy your game to get at least the money back which you have invested into the game and at best some reward. Microsoft itself offers a platform for downloading games which can be used to distribute games - it contains two sections, where independent developers can submit their creations. This Book gives information about the whole platform, the special independent developers sections, describe the ways how to publish a game successfully and provides some informations how Microsoft generally promotes the Xbox to attract more users.

# Xbox Games + Marketplace

## General

The Xbox Marketplace is a platform, where users can purchase games, download videos, game demos, Indie Games (will be treated in a separate chapter) and some additional content like mappacks or themes for the XBox 360 Dashboard. It was launched in November 2005 for Xbox and 3 years later, in November 2008, for Windows OS. Since 11th August 2009 it's possible to download Xbox 360 Games. The content will be saved on the Xbox 360's hard drive or an additional memory unit.

# AppHub

AppHub is a specific website and community for Xbox Live Indie Games (and Windows Phone) developers. AppHub offers free tools like XNA Game Studio and DirectX Software Development Kit, provides community forums where users can ask questions, give advice, or just discuss the finer points of programming. Code samples provides developers with a jump-start to implementing new features, and the Education Catalog is packed with articles, tutorials, and utilities to help beginners and experts alike. An App Hub annual subscription for $99 USD provides you with access to the Xbox LIVE Marketplace, where you can sell or give away your creation to a global audience. For students the membership is free if you register at MSDNAA. They also provide a developer dashboard so developers can manage all aspects of how the game appears in marketplace, monitor downloads, and track how much money they've earned. So the AppHub membership is required to publish an Indie Game. Per year, members can submit up to 10 Indie Games, peer review new Indie Games before they get released and get offered premium deal from partners. # Xbox Marketing Strategies 53 million Xbox Consoles have been sold world wide, the Xbox Live community has more than 30 million members and it's getting harder for Microsoft to attract new customer. So they try to gain user from a new target audience and develop some new strategies to get the Xbox into as many homes as possible. Microsoft uses a lot of viral marketing and tries to let users to interact as much as possible in their own Xbox Live community. ## Xbox Party The usual Xbox gamer is male, so there are a lot of women who can be won as new customers. Inspired by "Tupperware Parties", Microsoft offers the possibility to get an Xbox pack to throw a home party to present the Xbox. Hosts got an Xbox party pack of freebies that included microwaveable popcorn, Xbox trivia game "Scene It? Box Office Smash," an Xbox universal media remote control, a three-month subscription to Xbox Live, and 1600 Microsoft Points. The aim is to spread the Xbox and get into a new target audience, everyone wants to have the console all friends are on.[11] ## Special offers Another strategy is to reach even the last ones of the main target audience who haven't an Xbox yet. A main reason are the costs of an Xbox, a special offer for college students now offers an Xbox 360 to all U.S. college students who buy a Windows 7 PC. By targeting college kids, Microsoft is going after the sexiest demographic. College students ages 18 to 24 spend more than 200 billion dollars a year on consumables. The average student has about$600 a month in disposable income from part-time work, work-study or scholarships. They also typically don’t have mortgages or car payment. Because of this, they are able to spend their money less conservatively than an adult who has those expenses on top of paying back college loans and possibly providing for their families. [12]

To promote the marketplace and connect the users of Windows Phones and Xbox closer to each other, Microsoft offers a free Xbox 360 game to developers of Windows Phone Apps, the best App also wins a Windows 7 Phone. It's just available for the first 100 Apps and calles Yalla App-a-thron comeptition.[13]

## Promote Indie Game

Indie Games are developed usually by independent developers with low costs. The best strategy to advertise for an Indie Game is spreading it as much as possible. Users can rate games in the Marketplace, games with a good rating get downloaded more often. If someone plays an Indie Game, friend in the Xbox Live are able to see that and maybe the game gets spread more and more into the community. Websites like IndieGames.com constantly present popular Indie Games, the aim of every developer should be to get as much attention as possible and to trust into viral marketing.

# Mathematics and Physics

## Introduction

Unfortunately, every good game, especially the 3D kind, needs a basic knowledge of vectors and matrices. Also collision detection, especially when dealing with thousands of objects requires special data structures. Ballistics and Inverse Kinematics are also topics covered here, as well as character animation. Last but not least, a couple of physics engines are introduced.

Lore ipsum ...

## Vectors and Matrices

We need to recall some basic facts about vector and matrix algebra, especially when trying to develop 3D games. A nice introduction with XNA examples can be found in the book by Cawood and McGee. [1]

A right triangle showing the relation between opposite, adjacent and hypotenuse.

### Right Triangle

Once upon a time there was little Hypotenuse. He had two cousins: the Opposite and his sister the Adjacent. Both were usually just known by their nick names 'Sine'[2] and 'Cosine'[3]. They lived together in a right triangle close to the woods. They were related through his mother's sister, aunty Alpha. His father, who was a mathematician, used to say that:

${\displaystyle \sin \alpha ={\frac {\textrm {opposite}}{\textrm {hypotenuse}}}={\frac {a}{h}}}$
${\displaystyle \cos \alpha ={\frac {\textrm {adjacent}}{\textrm {hypotenuse}}}={\frac {b}{h}}.}$

Sometimes he also referred to uncle Tangent (who was married to aunty Alpha) and said that

${\displaystyle \tan \alpha ={\frac {\textrm {opposite}}{\textrm {adjacent}}}={\frac {a}{b}},}$

so in a sense uncle Tangent of aunty Alpha was Sine divided by Cosine. To us that didn't make any sense, but Hypotenuse's father said that was how it always was.

### References

1. S. Cawood and P. McGee (2009). Microsoft XNA Game Studio Creator’s Guide. McGraw-Hill.
2. Wikipedia:Sine
3. Wikipedia:Cosine

# Collision Detection

Collision detection is one of the basic components in a 3D game. It is important for a realistic appearance of the game, which needs fast and rugged collision detection algorithms. If you do not use some sort of collision detection in your game you are not able to check if there is a wall in front of your player or if your player is going to walk into another object.

No collision
Collision detected

## Bounding Spheres

First we need to answer the question "What is a bounding sphere?" The bounding sphere means a ball which has nearly the same center point as the object which is enclosed by the ball. A bounding sphere is defined by its center point and its radius.

In collision detection the bounding spheres are often used for ball-shaped objects like cliffs, asteroids or space ships.

Two spheres are touching

Let's take a look at what happens when two spheres are touching. The image shows , the radius of each sphere now also defines the distance its center to the opposite sphere's skin. The interspace between the centers would be equal to radius1 + radius2. If the distance would be greater, the two spheres would not touch but if it would be less, the spheres would intersect.

A feasible way to determine if a collision has occurred between two objects with bounding spheres you can simply find the distance between their centres and see if this is less than the sum of their bounding sphere radius.

Another way to use bounding spheres is to use the balance point of the object as the center point of the bounding sphere. Thereby you use the midpoint of all vertices as the centre of the bounding sphere. This algorithm gives you a more exact midpoint than the first way.

### XNA Bounding Spheres

Microsofts XNA offers a model for you to use by developing your own game called "BoundingSphere". XNA provides this for you so that there is no need to calculate it. Models in XNA are made up of 1 or more meshes. When doing collisions you will want to have one sphere that borders the whole model. That means at model load time you will want to loop through all the meshes in your model and expand a main model sphere.

foreach (ModelMesh mesh in m_model.Meshes)
{
m_boundingSphere=BoundingSphere.CreateMerged(base.m_boundingSphere, mesh.BoundingSphere);
...


To see if two spheres have collided Xna provides us to use:

bool hasCollided=sphere.Intersects(otherSphere);


## Bounding Rectangles or Bounding Box

Bounding box

In collision detection handling with rectangles you want to see whether two rectangular areas are in any way touching or overlapping each other. Therefor we need to use the bounding box. A bounding box is simply a box that encloses all the geometry of a 3D object. We can easily calculate one from a set of vertex by simply looping through all the vertices finding the smallest and biggest x, y and z values.

To create a bounding box around our model in model space you need to calculate the midpoint an the four corner point of the rectangle we want to enclose. Then you need to build a matrix and rotate the four point about the midpoint with the given rotation value. After that we need to go through all the vertices in the model keeping a track of the minimum and maximum x, y and z positions. This gives us two corners of the box from which all the other corners can be calculated.

### XNA Bounding Box

Because each model is made from a number of mesh we need to calculate minimum and maximum values from the vertex positions for each mesh. The"ModelMesh" object in XNA is split into parts which provides access to the buffer which is keeping the data of the vertex (VertexBuffer) from which we can get a copy of the vertices using the GetData call.

public BoundingBox CalculateBoundingBox()
{

// Create variables to keep min and max xyz values for the model
Vector3 modelMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 modelMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);

foreach (ModelMesh mesh in m_model.Meshes)
{
//Create variables to hold min and max xyz values for the mesh
Vector3 meshMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 meshMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);

// There may be multiple parts in a mesh (different materials etc.) so loop through each
foreach (ModelMeshPart part in mesh.MeshParts)
{
// The stride is how big, in bytes, one vertex is in the vertex buffer
int stride = part.VertexBuffer.VertexDeclaration.VertexStride;

byte[] vertexData = new byte[stride * part.NumVertices];
part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, 1); // fixed 13/4/11

// Find minimum and maximum xyz values for this mesh part
// We know the position will always be the first 3 float values of the vertex data
Vector3 vertPosition=new Vector3();
for (int ndx = 0; ndx < vertexData.Length; ndx += stride)
{
vertPosition.X= BitConverter.ToSingle(vertexData, ndx);
vertPosition.Y = BitConverter.ToSingle(vertexData, ndx + sizeof(float));
vertPosition.Z= BitConverter.ToSingle(vertexData, ndx + sizeof(float)*2);

// update our running values from this vertex
meshMin = Vector3.Min(meshMin, vertPosition);
meshMax = Vector3.Max(meshMax, vertPosition);
}
}

// transform by mesh bone transforms
meshMin = Vector3.Transform(meshMin, m_transforms[mesh.ParentBone.Index]);
meshMax = Vector3.Transform(meshMax, m_transforms[mesh.ParentBone.Index]);

// Expand model extents by the ones from this mesh
modelMin = Vector3.Min(modelMin, meshMin);
modelMax = Vector3.Max(modelMax, meshMax);
}

// Create and return the model bounding box
return new BoundingBox(modelMin, modelMax);
}


## Terrain Collision

Un-even terrain

Collision detection with a terrain and an object is different than the collision between objects.

First of all you have to detect the coordinates of your current player (object). The height map of your terrain gives you a "gap value" which identifies the distance between two sequenced vertices. When dividing your coordinate position through those "gap values" you can detect the vertices at your position. You can get from your heightmapbuffer the 4 vertices squares where you are. Using these datas and your position in this square, you can calculate the best interspace to the terrain so that there is no collision with it.

## Collision Performance

Sometimes collision detection slows down a game. It is the most time-consuming component in an application. Therefor there are data structures as quadtree and octtree.

A quadtree is a tree structure using a principle called ‘spatial locality’ to speed up the process of finding all possible collisions. Objects can only hit things close to them. To advance the performance you should avoid the testing again objects which are far away.

Octtree

The easiest way to check for collision is to divide the area which is going to be checked into a consistent grid and declare each object with all intersecting grid cells. The quadtree tries to overcome this weakness by recursively splitting the collision space into smaller subregions. Every region is divided exactly into 4 smaller regions of the same size, so you end up having multiple grids with different resolutions, where the number of cells in a region goes go up by a power of two every time the resolution is increased. So every object resides in the cell (called quad node or quadrant) with the highest possible resolution. A search is made by starting at the object’s node and climb up to the root node.

### Octtree (3D)

Octtrees work the same way as quadtree. It is used for collision detection in 3D areas.

## References

3D Collision Detection

Bounding Volumes and Collisions

Bounding Spheres

Bounding Sphere Collision Detection

Bounding Sphere

XNA Model Collision

sarah

# Ballistics

If one thinks about ballistics the first couple of things that come to mind are guns and various deadly bullets. But especially in games ballistics can be concerned with the movement of any kind of projectile, from balls to bananas and from coconuts to rockets. Ballisitcs help determine how these projectiles behave during movement and what their effects are[1]. This chapter will show and explain what a game programmer needs to know when programming anything related to projectiles.

## Basic Physics

The movement of any projectile will be heavily influenced by its surroundings and the physical laws it should abide by. However, it is important to remember that games do not need to be set on earth and the experience on an alien planet may be completely different from what we know to be valid. Therefore the here listed formulas and explanations may need adjustment to what ever world your are intending to let projectiles move around in.

#### Mass and Weight

It is a common misunderstanding that mass is the same thing as weight. But while the weight of an object can change depending on the environment it is placed in, the mass of an object will stay the same[2]. Weight (denoted by W) is defined as a force that exist when gravity effects a mass[3]:

${\displaystyle W=mg\,}$ , where g is the gravity present and m denotes the mass of the object

#### Velocity and Acceleration

Velocity describes the distance covered by an object through movement over a certain amount of time and the direction of such movement. It is the speed and direction at which your car travels along the Highway or at which a bullet whizzes through the air . Probably the most commonly seen units to denote speed are km/h and m/s. h and s represent a certain amount of time, where h stands for an hour and s for a second, km and m mean kilometer and meter, the distance traveled during this time interval. Velocity is defined by a vector which specifies the direction of movement and its absolute value is the speed.

Imagening a ball that is thrown, it will not have the same speed through its whole flight. It will speed up after leaving the hand and it will slow down eventually. This is called acceleration. It is the rate by which the speed of an object changes over time. Newton's second Law of motion shows that acceleration depends on the force that is exercised on an object (e.g the force from the arm and hand that throw the ball) and the mass of such object (eg. the ball): ${\displaystyle F=ma\,\implies a={\frac {F}{m}}}$
The acceleration of such object will be in the same direction as the applied force. The unit for acceleration is distance traveled over time squared, for example km/s².

#### Gravity

Universal gravitation is a force that takes effect between any two objects, drawing them torwards each other. This force depends on the objects' masses as well as their distance to each other.[4] The general formula to calculate this force looks like this:
${\displaystyle F=G{\frac {m_{1}m_{2}}{r^{2}}}}$ ,where ${\displaystyle m_{1}}$ and ${\displaystyle m_{2}}$ are the objects' masses, r is the distance and G the universal gravitational constant
The universal gravitational constant is:[5] ${\displaystyle G=6.67428\times 10^{-11}\ {\mbox{m}}^{3}\ {\mbox{kg}}^{-1}\ {\mbox{s}}^{-2}=6.67428\times 10^{-11}\ {\rm {N}}\,{\rm {(m/kg)^{2}}}}$

When talking about the gravity of earth, the acceleration experienced by a mass because of the existing attractive force, is meant. So gravity is nothing other than acceleration torwards the earth's mid point. This is why an object, dropped from a high building, will continue to be in free fall until it is stopped by another object, for example the ground. The gravity of earth is defined as follows: ${\displaystyle g=G{\frac {m_{earth}}{r^{2}}}}$ , where g is the gravity of earth, m the earth's mass and r its radius
The earth's gravity on the surface equals approximately 9.8 meters/second².

#### Drag

Drag influences the velocity of objects moving through fluids and gases. This force is opposite to the direction of the object's movement and it hence reduces the object's speed over time. It depends on the objects mass and shape as well the density of the fluid. Because the flight path computation is usually simplified you might not end up needing the drag force. You should however consider the fluid and gases your projectile moves in and fiddle around with the scaling factors to get an appropriate flight path.

## Projectile Movement

In games the world a player acts in is never really a hundred percent accurate representation of the real world. Therefore when programming movement of projectiles it is easier to simplify some of the physics while creating the illusion that the projectile is at least somewhat behaving like a human player would expect it to do. No matter if throwing a ball or shooting a torpedo under water there are two general and simplified patterns how projectiles move in games. These movements can be adapted and refined to match the expected movement of a specific projectile.

### Projectile Class

It is advisable to make your own projectile class that includes all projectile specific variables like velocity as well as functions to manipulate and calculate the flight path. The class' basic framework could look something like this:

public class Projectile{

private Vector3 velocity;   //stores the direction and speed of the projectile
public Vector3 pos;         //current projectile position
private Vector3 prevPos;    //previous projectile position
private float totalTimePassed;         //time passed since start
public bool bmoving = false;        //if the projectile is moving

///Constants
private const float GRAVITY = 9.8f;

public void Start(Vector3 direction,int speed, Vector3 startPos){
this.velocity = speed*Vector3.Normalize(direction);
this.pos = startPos;   //in the beginning the current position is the start position
bmoving = true;
}

public void UpdateLinear(GameTime time){
if(bmoving) LinearFlight(time);
}

public void UpdateArching(GameTime time){
if(bmoving) ArchingFlight(time);
}
}


To start with something needs to trigger the movement of the projectile, for example the players mouse click. On that event you create a new instance of your projectile class and call Start() to launch the projectile. You will need to keep a reference to this object because the projectiles position is going to be updated every frame and the projectile is redrawn. The update is done be calling either the UpdateLinear or UpdateArching function, depending on the flight path that's wanted. The new position will have to be part of the transformation matrix that is used to draw the projectile in your game world.

In the Start method the direction vector is normalized to ensure that when multiplied by the speed the result is a velocity vector with the same direction as the initial vector and the absolute value of the desired speed. Remember that the direction vector passed to the Start function is the aim vector of whatever made the projectile move in the first place. Its absolute value can basically be anything when we assume the aim is changeable. Hence, this would not guarantee projectiles of the same kind moving at the same speed, nor would it allow for the player to decide on the force that is excersiced on the projectile before its release, changing its speed accordingly.

If your projectile is of a form that has an obvious front, end and sides it will become necessary to change the projectiles orientation according to its flight path. Following Euler's rotation theorem, vectors of a rotation matrix have to be unit vectors as well as orthogonal[6]. For a linear flight path we could simply take the normalized velocity vector as forward vector of the orientation matrix and construct the matrix's right and up vector accordingly. However, because the projectile's flight direction constantly changes when using an arching flight path it is easier to recalculate the forward vector each update by subtracting the projectile's current position from the position held an update earlier. To do so put the following function in your projectile class. Remember to call it before drawing the projectile and put the result matrix into the appropriate transformation matrix following I.S.R.O.T sequence. This sequence specifies the order by which to multiply the transform matrices, namely the Identiy Matrix, Scaling, Rotation, Orientation and Translation.

public Matrix ConstructOrientationMatrix(){
Matrix orientation = new Matrix();

// get orthogonal vectors dependant on the projectile's aim
Vector3 forward = pos - prevPos;
Vector3 right = Vector3.Cross(new Vector3(0,1,0),forward);
Vector3 up = Vector3.Cross(right,forward);

// normalize vectors, put them into 4x4 matrix for further transforms
orientation.Right = Vector3.Normalize(right);
orientation.Up = Vector3.Normalize(up);
orientation.Forward = Vector3.Normalize(forward);
orientation.M44 = 1;
return orientation;
}


### Linear Flight

Shows the linear movement of a ball with the velocity of (5,3,2)

A linear flight is the movement along a straight line. This kind of movement might be observed when a ball is thrown straight and very fast. Obviously, even a ball like that will eventually fall to the ground if not stopped before. However, if it is for example caught quite early after leaving the throwers hand its flight path will look linear. To simplify this movement, acceleration and gravity are neglected and the velocity is the same at all time. The direction of movement is given by the velocity vector and is the same as the aim direction of the gun,hand etc.

If you have active projectiles in your game, the XNA Update function needs to call a function that updates the position for every active projectile object. The projectile's new position is calculate like this:
${\displaystyle pos=pos+velocity\times {timePassed}}$[7] , where timePassed is the time that has passed since the last update.

All this function needs as a parameter is the game time that has passed since the last update. Cawood and McGee suggest to scale this time by dividing it by 90 because otherwise the positions calculated for every frame will be to far apart.

private void LinearFlight(GameTime timePassed){
prevPos = pos;
pos = pos + velocity * ((float)timePassed.ElapsedGameTime.Milliseconds/90.0f);
}


### Arching Flight

Shows the simplified arching flight path of a ball

The arching flight path is a bit more realistic for most flying objects than the linear flight because it takes gravity into account. Remember that gravity is an acceleration. To calculate the position of a projectile with constant acceleration and at a certain point in time the formula is:
${\displaystyle pos={\frac {1}{2}}{a}{t}^{2}}$ ,where a is the acceleration and t the time that has passed
Because gravity pulls the projectile towards earth only the y-coordinate of your projectile will be effected. The projectile's ascenting rate will decrease over time until it stops its climb and turns to fall. However, the x and z coordinates remain uneffected by this and are calculated just the way they are with the linear flight path. The following formula shows how to compute the y-position:
${\displaystyle {pos_{y}}=({pos_{y}}+{velocity_{y}}\times {timePassed})-{\frac {1}{2}}\times {gravity}\times {totalTimePassed}^{2}}$
, where totalTimePassed is the time passed since the projectiles started
The minuend is equal to the linear flight formula, the subtrahend is the downwards acceleration due to gravity. It becomes obvious that the lower the projectile's speed and the further the velocity's direction is pointed towards the ground, the faster gravity will win over. This function will update the projectile's flight path:

private void ArchingFlight(GameTime timePassed){
prevPos = pos;
// accumulate overall time
totalTimePassed += (float)timePassed.ElapsedGameTime.Milliseconds/4096.0f ;

// flight path where y-coordinate is additionally effected by gravity
pos = pos + velocity * ((float)timePassed.ElapsedGameTime.Milliseconds/90.0f);
pos.Y = pos.Y - 0.5f * GRAVITY * totalTimePassed * totalTimePassed;
}


I scaled the time that is added to the overall time down again so the gravity does not take immediate effect. For a speed of 1 scaling by 4096 produces a nice flying path. Also, the compiler hopefully does something sensible and optimises the division by 4096 because it is a multiple of two. You might want to play around with the scaling factors. If your game is not set on earth you should also think about if the gravity constant is different.

## Impact

Once your projectile is on the move you might want to do some collision checking if you expect it to hit anything. For more information and details on how to do collision detection check out the chapter about Collision Detection. In case a collision is detected it is time to think about what is going to happen to the projectile and the object that was hit. What the impact will look like is highly dependent on what your projectile is. A ball can bounce back, a really fast and small bullet might penetrate the object and keep on moving, a big torpedo on the other hand would probably explode. It is easier to decide in the hit object's class what the appropriate reaction will be when hit and maybe play specified sounds or animation. Otherwise you have to keep track in the projectile class of all effects that the projectile can have on each object in the game. To keep things simple just include some functions in your projectile class that define a possible behaviour of your the projectile and call the appropriate one from the hit object class when you detect a collision. For example, when a ball hits the ground it would probably simply bounce of. To simulate this behaviour use the following function in your projectile class and call it when you detect the ball reaching the ground. All it does is reflect the incoming direction and reduce the speed. When the speed is zero or smaller the ball has stopped moving and there is no need to keep its flight path updated. The 'reflectionAxis' Vector contains only ones except for the axis along which the direction needs to be inversed, this value will have to be a -1.

public void bounce(Vector3 incomingDirection, Vector3 reflectionAxis){
//reflect the incoming projectile and normalize it so it's "just" a direction
Vector3 direction = Vector3.Normalize(reflectionAxis* incomingDirection);
speed -= 0.5f;                   // reduces the speed so the arche becomes lower
velocity = speed * direction;    // the new velocity vector
totalTimePassed= 0;                     // gravity starts all over again
if (speed <= 0)bmoving= false;   // no speed no movement
}


A call to this function could look something like this when the ball is supposed to bounce back from the ground, hence its y-direction needs to be inversed:

ball.bounce(ball.position - ball.previousPosition, new Vector3(1, -1, 1));


## Inverse Kinematics

Inverse Kinematics (IK) is related to skeletal animation. Examples are the motion of a robotic arm or the motion of animated characters. Inverse Kinematics for Humanoid Skeletons Tutorial and Inverse kinematics on Wikipedia.

An example could be the simulation of a robotic arm with the XNA framework. This chapter should worry more about the mathematical background, whereas the chapter Character Animation will deal more with the models coming from 3D modellers.

If you want to move an arm of robotics or animated characters to a certain direction this entity is mostly modeled as a rigid multibody system consisting of a set of rigid objects which are called links. These links are connected by joints. To control the movement of this rigid multibody and get it into the destined direction inverse kinematics is often used.

The goal of inverse kinematics is to place each joint at its target. For that the right settings for the joint angles need to be found. The angles are represented by a vector [1].

Inverse kinematics is very challenging since there may be several possible solutions for the angle or none. In case of a solution complex and expensive computations could be required to find it [2]. Many different approaches for solving that problem exist:

• Jacobian transpose method
• Pseudoinverse method
• Damped Least Squares (DLS)
• Selectively Damped Least Square (SDLS)
• Cyclic Coordinate Descent

It is a big effort to implement the Jacobian based methods because they require enormous mathematical knowledge and many prerequisites like classes for matrices with m columns and n rows or singular value decomposition. An Example for implementation can be found here. It was created by Samuel R. Buss and Jin-Su Kim.

All methods mentioned above except the Cyclic Coordinate Descent are based upon the Jacobian matrix which is a function of the joint angle values and used to determine the end position. They discuss the question of how to choose the angle. The values of the angles need to be altered until a value approximately equal to the target value is reached.

Updating the values of the joint angles can be used in two ways:

1) Each step perform a single update of the angle values (using equation) so that joint follows the target position.
2) The angles are updated iteratively until it is close to a solution [1]

The Jacobian can only be used as an approximation near a position. The process of calculating the Jacobian must therefore be repeated in small steps until the desired end position is reached.

Pseudo Code:

while (e is too far from g) {

Compute J(e,Φ) for the current pose Φ

Compute J-1 // invert the Jacobian matrix

Δe = β(g - e) // pick approximate step to take

ΔΦ = J-1 • Δe // compute change in joint DOFs

Φ = Φ + ΔΦ // apply change to DOFs

Compute new e vector // apply forward kinematics to see where we ended up

}[2]

The following methods deal with the issue of choosing the appropriate angle value.

### Jacobian transpose method

The idea of the Jacobian transpose method is to update the angles by equation using the transpose instead of the inverse or pseudoinverse (since an inversion is not always possible)[1] . With this method the change to an angle can be computed directly by looping through it. It avoids expensive inversion and singularity problems but converges towards a solution very slowly. The motion of this method closely matches the physics unlike other inverse kinematics solutions which can result in an unnatural motion [3].

### Pseudoinverse method

This method sets the angle values to the pseudoinverse of the Jacobian. It tries to find a matrix which effectively inverts a non-square matrix. It has singularity issues which tend to the fact that certain directions are not reachable. The problem is that the method first loops through all angles and then needs to compute and store the Jacobian, pseudoinvert it, calculate the changes in the angle and last apply the changes [4].

### Damped Least Squares (DLS)

This method avoids certain problems of the pseudoinverse method. It finds the value of the angle that minimizes the quantity rather than just the one finding the minimum vector. The damping constant must be chosen carefully to make the equation stable [1].

### Selectively Damped Least Square (SDLS)

This method is a refinement of the DLS method and needs fewer iterations.

### Cyclic Coordinate Descent

The algorithms based on the inverse Jacobian Matrix are sometimes unstable and fail to converge. Therefore another method exists. The Cyclic Coordinate Descent adjusts one joint angle at a time. It starts at the last link in the chain and works backwards iteratively through all of the adjustable angles until the desired position is reached or the loop has repeated a set number of times. The algorithm uses two vectors to determine the angle in order to rotate the model to the desired spot. This is solved by the inverse cosine of the dot product. Additionally, to define the rotation direction the cross product is used [5]. A concept demonstration of the method can be watched here

Here is a sample implementation:

First we need an object that represents a joint.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace InverseKinematics
{
/// <summary>
/// Represents a chain link of the class BoneChain
/// </summary>
public class Bone
{
/// <summary>
/// the bone's appearance
/// </summary>
private Cuboid cuboid;

/// <summary>
/// the bone's last calculated angle if errors occure like not a number
/// this will be used instead
/// </summary>
public float lastAngle = 0;

private Vector3 worldCoordinate, destination;

/// <summary>
/// where the bone does point at
/// </summary>
public Vector3 Destination
{
get { return destination; }
set { destination = value; }
}

/// <summary>
/// the bone's source position
/// </summary>
public Vector3 WorldCoordinate
{
get { return worldCoordinate; }
set { worldCoordinate = value; }
}

/// <summary>
/// Generates a bone by another bone's end
/// </summary>
/// <param name="lastBone">the bone's end for this bone's source</param>
/// <param name="destination"></param>
public Bone(Bone lastBone, Vector3 destination) : this(lastBone.Effector, destination)
{
}

/// <summary>
/// Generates a bone at a coordinate in
/// </summary>
/// <param name="worldCoordinate"></param>
/// <param name="destination"></param>
public Bone(Vector3 worldCoordinate, Vector3 destination)
{
cuboid = new Cuboid();
this.worldCoordinate = worldCoordinate;
this.destination = destination;
}


These are the fields and constructors which we need for our bone class. The field cuboid is the 3D model which represents our bone. The destination and worldCoordinate describe the joints. The worldCoordinate shows the position of the bone. The destination is the targeted position. The first constructor contains the settings for both vectors. The second constructor takes the world position and the target position (also called end effector) and generates a new world position for the new bone from them.

        /// <summary>
/// calculate's the bone's appearance appropiate to its world position
/// and its destination
/// </summary>
public void Update()
{

Vector3 direction = new Vector3(destination.Length() / 2, 0, 0);

cuboid.Scale(new Vector3(destination.Length() / 2, 5f, 5f));
cuboid.Translate(direction);

cuboid.Rotate(SphereCoordinateOrientation(destination));
cuboid.Translate(worldCoordinate);

cuboid.Update();
}


The update method scales the cuboid with the length of the destination vector with the width of 5 and depth of 5. It translates the cuboid by its half length to get the rotation pivot and rotates it by the sphere coordinate angles of the destination vector and translates it to its world coordinate.

        /// <summary>
/// Draws the bone's appearance
/// </summary>
/// <param name="device">the device to draw the bone's appearance</param>
public void Draw(GraphicsDevice device)
{
cuboid.Draw(device);
}


The draw method draws the updated vector.

        /// <summary>
/// generates the bone's rotation by unsing sphere coordinates
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
private Vector3 SphereCoordinateOrientation(Vector3 position)
{
float alpha = 0;
float beta = 0;
if (position.Z != 0.0 || position.X != 0.0)
alpha = (float)Math.Atan2(position.Z, position.X);

if (position.Y != 0.0)
beta = (float)Math.Atan2(position.Y, Math.Sqrt(position.X * position.X + position.Z * position.Z));

return new Vector3(0, -alpha, beta);
}

        /// <summary>
/// the bone's destination is local and points to the world's destination
/// so this function just subtract's the bone's world coordinate from the world's destination
/// and gets the bone's local destination vector
/// </summary>
/// <param name="destination">The destination in the world coordinate system</param>
public void SetLocalDestinationbyAWorldDestination(Vector3 destination)
{
this.destination = destination - worldCoordinate;
}

/// <summary>
/// the bone's source plus the bone's destination vector
/// </summary>
/// <returns></returns>
public Vector3 Effector
{
get
{
return worldCoordinate + destination;
}
}
}
}


The rest of the bone class is getters and setters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace InverseKinematics
{
/// <summary>
/// The BoneChain class repressents a list of bones which are always connected once.
/// On the one hand you can add new bones and every bone's source is the last bone's destination
/// on the other hand you can use the cyclic coordinate descent to change the bones' positions.
/// </summary>
public class BoneChain
{
/// <summary>
/// The last bone that were created
/// </summary>
private Bone lastBone;

/// <summary>
/// All the concatenated bones
/// </summary>
private List<Bone> bones;

/// <summary>
/// Creates an empty bone chain
/// Added Bones will be affected by inverse kinematics
/// </summary>
public BoneChain()
{
this.bones = new List<Bone>();
}


The BoneChain class repressents a list of bones which are always connected once. On the one hand you can add new bones and every bone's source is the last bone's destination on the other hand you can use the cyclic coordinate descent to change the bones' positions. The class works with a list which contains the bones their coordinates. The class has two modes. The first is the creation mode where one bone is created after another and they keep connected. The other mode is the CCD (described further below).

        /// <summary>
/// Draws all the bones in this chain
/// </summary>
/// <param name="device"></param>
public void Draw(GraphicsDevice device)
{
foreach (Bone bone in bones) bone.Draw(device);
}


        /// <summary>
/// Creates a bone
/// Every bone's destination is the next bone's source
/// </summary>
/// <param name="v">the bone's destination</param>
/// <param name="click">if true it sets the bone with its coordinate and adds the next bone</param>
public void CreateBone(Vector3 v, bool click)
{
if (click)
{
//if it is the first bone it will create the bone's source at the destination point
//so it need not to start at the coordinates(0/0/0)
if (bones.Count == 0)
{
lastBone = new Bone(v, Vector3.Zero);
}
else
{
Bone temp = new Bone(lastBone, v);
lastBone = temp;
}
}
if (lastBone != null)
{
lastBone.SetLocalDestinationbyAWorldDestination(v);
}

}


This is the method for creating the bones (creation mode)

        /// <summary>
/// The Cyclic Coordinate Descent
/// </summary>
/// <param name="destination">Where the bones should be adjusted</param>
/// <param name="gameTime"></param>
public void CalculateCCD(Vector3 destination, GameTime gameTime)
{

// iterating the bones reverse
int index = bones.Count - 1;
while (index >= 0)
{
//getting the vector between the new destination and the joint's world position
Vector3 jointWorldPositionToDestination = destination - bones.ElementAt(index).WorldCoordinate;

//getting the vector between the end effector and the joint's world position
Vector3 boneWorldToEndEffector = bones.Last().Effector - bones.ElementAt(index).WorldCoordinate;

//calculate the rotation axis which is the cross product of the destination
Vector3 cross = Vector3.Cross(jointWorldPositionToDestination, boneWorldToEndEffector);

//normalizing that rotation axis
cross.Normalize();
//check if there occured divisions by 0
if (float.IsNaN(cross.X) || float.IsNaN(cross.Y) || float.IsNaN(cross.Z))
//take a temporary vector
cross = Vector3.UnitZ;

// calculate the angle between jointWorldPositionToDestination and boneWorldToEndEffector
// in regard of the rotation axis
float angle = CalculateAngle(jointWorldPositionToDestination, boneWorldToEndEffector, cross);
if (float.IsNaN(angle)) angle = 0;

//create a matrix for the roation of this bone's destination
Matrix m = Matrix.CreateFromAxisAngle(cross, angle);

// rotate the destination
bones.ElementAt(index).Destination = Vector3.Transform(bones.ElementAt(index).Destination, m);

// update all bones which are affected by this bone
UpdateBones(index);
index--;
}
}


This is one possible version of the CCD Algorithm.

        /// <summary>
/// While CalculateCCD changes the destinations of all the bones,
/// every affected adjacent bone's WorldCoordinate must be updated to keep the bone chain together.
/// </summary>
/// <param name="index">when the bones should updated, because CalculateCCD changed their destinations</param>
private void UpdateBones(int index)
{
for (int j = index; j < bones.Count - 1; j++)
{
bones.ElementAt(j + 1).WorldCoordinate = (bones.ElementAt(j).Effector);
}
}

/// <summary>
/// Updates all the representation parameters for every bone
/// including orienations and positionsin this bonechain
/// </summary>
public void Update()
{
foreach (Bone bone in bones) bone.Update();
}

/// <summary>
/// This function calculates an angle between two vectors
/// the cross product which is orthogonal to the two vectors is the most common orientation vector
/// for specifing the angle's direction.
/// </summary>
/// <param name="v0">the first vector </param>
/// <param name="v1">the second vector </param>
/// <param name="crossProductOfV0andV1">the cross product of the first and second vector </param>
/// <returns>the angle between the two vectors in radians</returns>
private float CalculateAngle(Vector3 v0, Vector3 v1, Vector3 crossProductOfV0andV1)
{
Vector3 n0 = Vector3.Normalize(v0);
Vector3 n1 = Vector3.Normalize(v1);
Vector3 NCross = Vector3.Cross(n1, n0);
NCross.Normalize();
float NDot = Vector3.Dot(n0, n1);
if (float.IsNaN(NDot)) NDot = 0;
if (NDot > 1) NDot = 1;
if (NDot < -1) NDot = -1;
float a = (float)Math.Acos(NDot);
if ((n0 + n1).Length() < 0.01f) return (float)Math.PI;
return Vector3.Dot(NCross, crossProductOfV0andV1) >= 0 ? a : -a;
}

}
}


Nexus' Child

### References

1. a b c d
2. a b Steve Rotenberg: Inverse kinematics (part 1)
3. Mike Tabaczynski: Jacobian Solutions to the Inverse Kinematics Problem
4. Jeff Rotenberg: Inverse kinematics (part 2)
5. Jeff Lander: Making Kine More Flexible

## Character Animation

Here we have to distinguish between skeletal and keyframed animation. The main point is to show how to get both types of animation working with XNA. Special attention should be places on contraints given by the XNA framework (e.g. the shader 2.0 model does not allow more than 59 joints).

## Introduction

Animation is just an illusion- it is created by a series of images. Each is a little different from the last. We just feel such a group of images as a changing scene.
The most common method of presenting animation is as a motion picture or video program, although there are other methods. [1]
In Computer based animation there are two forms of it: The little more "classical", from flip-books known keyframe animation and the skeletal animation, which is by default known from 3d-animation.

## Keyframed Animation

Keyframe animation is an animation technique, that originially was used in classical cartoons. A Keyframe defines the start- and endpoint of an animation. they are filled with so called interframes or inbetweens.

In the traditioal keyframe animation, which e.g. was used for hand-drawn trickfilms, the senior artist (or key artist) would draw the keyframes. (Just the important pictures of an animation) After testing of the rough animation, he gives this to his assistand, and the assistand does the necessary "inbetweens and the clean up.

### Computergraphics

In Computergraphics it is the same concept like in cartoon: The keyframes are created by the user and the interframes are supplemented by the computer. The "Keyframe" saves parameters such as position, rotation and scale of an object The following inbetweens are interpolated by the computer.

#### Example

An Object will move from one corner to an other. The first keyframe shows the object in the top left corner and the second keyframe shows it in the bottom right corner. Everything in between is interpolated.

## Interpolation methods

The preceding sections mentioned that some key-frame animations support multiple interpolation methods. An animation's interpolation describes how an animation transitions between values over its duration. By selecting which key frame type you use with your animation, you can define the interpolation method for that key frame segment. There are three different types of interpolation methods: linear, discrete, and splined.
[2]

#### linear

The individual segments are pass with constant speed.

#### Discrete

With discrete interpolation, the animation function jumps from one value to the next without interpolation.

#### Spline Interpolation

http://msdn.microsoft.com/uk-en/library/ms742524.aspx

#### Keyframe Animation in XNA

to be edited die einzelnen Parameter werden in einer Liste gespeichert. Wenn man nun die Länge der Timeline und die anzahl der elemente hat, kann man hier draus schließen, auf welchen Keyframe man zu welcher Zeit zugreifen kann. (in dem der Timeline- Zähler hochgezählt wird und dann der entsprechende keyframe aufgerufen wird, ist es, als ob man z.b. bei einem daumenkino, bei dem 1 seite 1 keyframe ist, auf die enstsprechende Seite blättern würde).

Folgend ist eine klasse dargestellt, mit welcher dies umgesetzt werden kann. Die Quelle ist hier drunter zu finden.

A little keyframe animation class

using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace PuzzleGame
{
/// <summary>
/// Keyframe animation helper class.
/// </summary>
public class Animation
{
/// <summary>
/// List of keyframes in the animation.
/// </summary>
List<Keyframe> keyframes = new List<Keyframe>();

/// <summary>
/// Current position in the animation.
/// </summary>
int timeline;

/// <summary>
/// The last frame of the animation (set when keyframes are added).
/// </summary>
int lastFrame = 0;

/// <summary>
/// Marks the animation as ready to run/running.
/// </summary>
bool run = false;

/// <summary>
/// Current keyframe index.
/// </summary>
int currentIndex;

/// <summary>
/// Construct new animation helper.
/// </summary>
public Animation()
{
}

/// <summary>
/// Add a keyframe to the animation.
/// </summary>
/// <param name="time">Time for keyframe to happen.</param>
/// <param name="value">Value at keyframe.</param>
public void AddKeyframe(int time, float value)
{
Keyframe k = new Keyframe();
k.time = time;
k.value = value;
keyframes.Sort(delegate(Keyframe a, Keyframe b) { return a.time.CompareTo(b.time); });
lastFrame = (time > lastFrame) ? time : lastFrame;
}

/// <summary>
/// Reset the animation and flag it as ready to run.
/// </summary>
public void Start()
{
timeline = 0;
currentIndex = 0;
run = true;
}

/// <summary>
/// Update the animation timeline.
/// </summary>
/// <param name="gameTime">Current game time.</param>
/// <param name="value">Reference to value to change.</param>
public void Update(GameTime gameTime, ref float value)
{
if (run)
{
timeline += gameTime.ElapsedGameTime.Milliseconds;
value = MathHelper.SmoothStep(keyframes[currentIndex].value, keyframes[currentIndex + 1].value
(float)timeline / (float)keyframes[currentIndex + 1].time);
if (timeline >= keyframes[currentIndex + 1].time && currentIndex != keyframes.Count) { currentIndex++; }
if (timeline >= lastFrame) { run = false; }
}
}

/// <summary>
/// Represents a keyframe on the timeline.
/// </summary>
public struct Keyframe
{
public int time;
public float value;
}
}
}


ARei

## Skeletal Animation

Skeletal animation is the technique in computer animation which is represented in two parts, the skin part (called mesh) and the skeleton part (called rig). The skin is represented as a combination of surfaces and the skeleton is a combination of bones. These bones are connected to each other like real bones and part of a hierarchical set. The result is, you move one bone and the bones which should interact move too. The bones animate the mesh (the surfaces) in the same way. While this technique is often used to animate humans or more generally for organic modeling, it only serves to make the animation process more intuitive and the same technique can be used to control the deformation of any object, a building, a car, and so on.

Bones(green)

This technique is quite useful for the animators because in all animation systems is this simple technique a port of. So they don't need any complex algorithms to animate the models. Without this technique it is virtually impossible to animate the mesh in combination with the bones.
http://en.wikipedia.org/wiki/Skeletal_animation

### Rigging

Skeleton-Legs)

Rigging is the technique to create a skeleton to animate a model. This skeleton consists of bones(rigs) and joins which are the connetion between the bones. Regularly you associates this bones and joins with the property of an real skeleton. For example you create first the upper leg as a bone and afterwards you build the knee as a join.
http://de.wikipedia.org/wiki/Rigging_%28Animation%29

### Skinning

Skin and Bones

Skinning is the technique to create a skin which is assigned to a wired frame (the bones) and the movement of the skin is like the movement of the bones.The skinning comes intuitive after the rigging. The differences between skinning and rigging is,skinning is the visual deformation of the body(your model). Useful is the fact that it is possible to setup every single sufaces, this is very helpful in situations like the motion of an arm. Even you move your arm (or the arm of the model), your skin (the surfaces of the model) interact with the motion differently, determined by the position like at the inside of your elbow or at the outside of your elbow. It is also possible to simulate muscular movement in this context. http://de.wikipedia.org/wiki/Skinning

#### The bones and polygons of your model have a limit in XNA:

1. Bones: 59 up to 79 in 4.0
2. Polygons: depends on the hardware

### Animations in XNA

The simplest way to get animations from your model in XNA is to create animations in your 3d development tool. These animations are automatically a part of your exported .x flile or .fbx file.

A simple way to show the handling with animations in XNA is a nice demo from http://create.msdn.com/en-US/education/catalog/sample/skinned_model.

First we need a model and a animation:

Model currentModel;
AnimationPlayer animationPlayer;


The next step is to update the LoadContent() method:

protected override void LoadContent()
{

// Look up our custom skinning information.
SkinningData skinningData = currentModel.Tag as SkinningData;

if (skinningData == null)
throw new InvalidOperationException
("This model does not contain a SkinningData tag.");

// Create an animation player, and start decoding an animation clip.
animationPlayer = new AnimationPlayer(skinningData);

AnimationClip clip = skinningData.AnimationClips["Take 001"];

animationPlayer.StartClip(clip);
}


If you setup your clib variable as an array you can save a lot of different animations:

AnimationClip clips= new AnimationClip[skinningData.AnimationClips.Keys.Count];
clips[0] = skinningData.AnimationClips["moveleft"];
clips[1] = skinningData.AnimationClips["moveright"];
clips[2] = skinningData.AnimationClips["jump"];


After that is is easy to call the different animations, for example by dragging the jump key.

animationPlayer.StartClip(clip[2]);
`

The same applies to all the others animations.

FixSpix

## Summary

### What we learnt in this chapter

In this chapter we learned, how to animate our character in two different ways. First the keyframe-animation and than the skeleton-animation. These two techniques are the most important in xna.

### But which one is better?

Better in this context is the wrong word, lets replace the word "better" with the words "better in which situation". Its simple... use the skeleton-animation in 3D and the keyframe-animation in the 2D area.

fixspix

## Authors

A.Rei and FixSpix

## Physics Engines

Should introduce, and discuss some physics engines, compare and evaluate them, best with examples. Also show capabilities, maybe compare with non-XNA physics engines.

Other examples can be found here: http://forums.create.msdn.com/forums/t/7574.aspx

XNA physics engine list can be found here: http://www.xnawiki.com/index.php?title=Physics_Engine

# Programming

## Introduction

Game development needs good programming skills. Here we introduce you to Visual Studio, and how to get Git and Subversion working, as well as some other skills required. Also we want to give a list of good reusable components and where to find more, as well as a brief introduction to some existing frameworks, supposedly making the life of the developer easier.

### More Details

Lore ipsum ...

to be edited by iSteffi Visual Studio , created and providing by Microsoft, is an IDE for developers who want to evolve different applications based on Windows and the .NET platforms. It supports developers/programmer with a widespread accumulation of development programmes for generating different kinds of applications e.g. Windows applications, ASP.NET applications or Web services. Professional programmers as well as free coders like to use Visual Studio for developing because the IDE supports many different programming languages: Visual Basic, C, C++, C++/CLI, C# and F#.

We are going to use Visual Studio throughout our exercise course, to create a small 3D game. To develop those games we apply Visual Studio including the XNA- framework. An instruction on how to install Visual Studio including XNA is declared on WikiBook: Setup.

## Features

Visual Studio supports the developer with helpfull features which are useful in every development step.

### The Code Editor

Visual Studio allocates a useful code editor which supports the user during writing the source code by highlighting the syntax and suggesting code complements. The code editor tries to complete methods and functions. It is also usefull when the developer wants to have quick access to his defined variables e.g. by entering the first letter, the code editor proposes all variables beginning with it.

### Designers

Visual Studio offers different visual designer which help the coder during developing their applications:

Web designer/development
Visual Studio offers another editor for creating and designing web pages. The Web designer supports the user during the development of an ASP.NET application.
Windows Forms Designer
This designer can be used to add control devices to a form and code the specific functions behind it.
WPF Designer
The WPF (Windows Presentation Foundation) Designer also behaves like the Forms Designer but is used to build WPF control devices and applications.
Class designer
The Class designer is a tool that makes it possible to model a class diagram of the developed application. The Class Designer models the connection and structure of it. It is not only used for classes but also for structures, delegates and interfaces.
Mapping designer
This designer mappes the classes and the database schemas that seal the data.

### Debugging

Visual Studio comes along with its own debbuger. The debugger supports by securing that the application operates in a logical way and as you want it to operate. It makes it possible to stop on different code positions to check the building.

### Expandability

The developer using Visual Studio has the chance to expand the functions of the standard Visual Studio.

### Browser and Explorer

Object Browser
The Object Browser makes it possible to appraise the available symbols for use in Visual Studio. The Browser uses three panes: the Objects pane, the Members Pane and the Description pane.
Open Tabs Browser
The Open Tabs Browser displays als open tabs and switches between them.
Properties Editor
Used to see all available properties for all objects and other items. Furthermore it is used to edit them.
Solution Explorer
The Solution Explorer is used for the arrangement of item management tasks in a project/solution. It is possible to handle with items outside a project.
Data Explorer
The Data Explorer is used to administrate databases. The administration provides the creation and creation and modification of database tables.
Team Explorer
The Team Explorer accesses the Team Foundation Server and the revision control.
Server Explorer
The Server Explorer establish the connection to the server. It offers the task to edit the ressources.
Text Generation Framework
The Text Generation Framework, also called t4, is a code generator which uses textfiles from templates.

## Version history

Visual Studio offers the possibility to develop different applications
Application Description
Console Application Program to use as a command-line appliance
Windows forms application Used to build a graphical user interface
Windows services Progam that works back-cloth as a self executable statement
ASP.NET applications + web services Web applications based on the Microsoft .NET Framework
Windows Mobile/Phone applications Used to build appliances for mobile devices(Windows Mobile or Windows Phone) with the .NET Compact Framework.
MFC/ATL/Win32 applications Applications for Windows
Visual Studio add-ins Programms that are used within Visual Studio to extend the functionality of Visual Studio.
Windows Store applications Used to build apps specifically for the Windows Store in Windows 8 and Windows 8.1
Product Launched .NET Framework
version
Release date Editions
Visual Studio N/A Spring 1995
Visual Studio 97 N/A 1997 Professional , Enterprise
Visual Studio 6.0 N/A 1998-06
Visual Studio .NET (2002) 1.0 2002-02-13
Visual Studio .NET 2003 1.1 2003-04-24 Academic, Professional, Enterprise Developer, and Enterprise Architect
Visual Studio 2005 2.0 2005-11-07 Express , Standard , Professional and Team System
Visual Studio 2008 3.5 2007-11-19
Visual Studio 2010 4.0 2010-04-12 Express , Professional , Premium , Ultimate and Test Professional
Visual Studio 2012 4.5 2012-09-12
Visual Studio 2013 4.5.1 2013-10-17
Visual Studio 2015(pre-release currently) 4.6

### Windows versions on which it runs⁴

Product History Windows 95/98/Me Windows NT 4 Windows 2000 Windows XP Windows Vista Windows 7 Windows 8 Windows 8.1
Visual Studio Yes
Visual Studio 97 Yes
Visual Studio 6 Yes
Visual Studio .Net 2002 No Yes
Visual Studio .Net 2003 No Yes
Visual Studio 2005 No Yes
Visual Studio 2008 No Yes
Visual Studio 2010 No Most¹ Yes
Visual Studio 2012 No No³ Desktop only² Yes
Visual Studio 2013 No No³ Desktop only Yes

¹ - Windows Phone 7 applications cannot be developed in Windows XP.

² - Windows 8 required to create and develop Windows Store apps.

³ - Even through Visual Studio 2012 and higher will not run on Windows Vista , the latest version of NET Framework works on Windows Vista however. This means that even through you cannot develop programs using Visual Studio 2012 in Windows Vista , you can run them on Windows Vista using the default configuration.

⁴ - For server based versions of Windows , use the corresponding client Windows version for reference.

### Supported default languages/tools(available by default)⁵

Product version Visual Basic Visual C# Visual C++ Visual F# Visual J++ Visual J#⁶ Visual FoxPro Visual SourceSafe Visual InterDev ASP.NET Windows Mobile Windows Phone Windows Store apps⁹
Visual Studio Yes No Yes No Yes No
Visual Studio 97 Yes No Yes No Yes No Yes No
Visual Studio 6 Yes No Yes No Yes No Yes No
Visual Studio NET 2002 Yes No Yes Yes⁷ No Yes Partial⁸ No
Visual Studio NET 2003 Yes No Yes No Yes Partial⁸ No
Visual Studio 2005 Yes No Yes No Yes No
Visual Studio 2008 Yes No Yes No Yes No
Visual Studio 2010 Yes No Yes No Version 7.x only No
Visual Studio 2012 Yes No Yes No Yes
Visual Studio 2013 Yes No Yes No Yes

⁵ - Languages beginning from Visual Studio NET 2002 use the NET Framework as their language base.

⁶ - It is the NET Framework version of Visual J++. It can only target the NET Framework , not the Java Virtual Machines which others target.

⁷ - From this version , it follows its own development cycle.

⁸ - Full support was available only with Visual Studio 2005 , including a full emulator.

⁹ - Windows Store apps can be developed only in Windows 8 and higher.

• Cobra_w

## References

Microsoft Visual Studio on Wikipedia