# Question
Title: Is there a better term for a thing that hosts a game story script than "game engine?"
When I recently entered the field of game development, I actually assumed that “game engine” meant something with which you can make your game story script run in an environment where non-player characters have a state, and so you can test running your story as the bare bones of a game. A typical example of a tool for this is Chat Mapper. This in my perspective is the core of your game, around which you build animations, sounds, etc. using say a 3D engine. A 3D engine can also be used for ends which have little to do with games. Let’s temporarily call what I mean a game-story engine.

But this does not seem the intended meaning – I guess it depends on the focus and stage of your game. Possible meanings of “game engine” seem to be:

* An environment which supports creating and running a complete game; this too is quite ambiguous definition, consider Unity, http://unity3d.com/unity/engine/, Vassal http://www.vassalengine.org .
* The term “game engine” is actually a shortcut for “game 2D engine” or “game 3D engine”

Now what I am asking is not to become uselessly precise with words, but just whether there is a better term used for “game-story engine” which experienced game developers use. Thanks.

*P.S. And no, I’m not heading towards (nor advising to) creating “game engines” before creating games. In my startup we actually created a very simple JavaScript “game-story engine” for our browser games (it was strictly necessary) which we would like to share and am now wondering how to present it.*

# Answer
> 8 votes
The industry doesn't have these terms nailed down well yet, but I'd say your concept is pretty far from colloquial use.

"Game Engine" usually refers to a piece of software that is meant to be extended by a game developer with their own specific logic to make a unique game. The Game Engine would provide all or nearly all of the generic services a game might need; e.g. audio playback, asset management, a renderer, physics simulation, AI framework, special effects systems, etc.

Usually a good Game Engine will also have a heavy tool component, where the Game Engine will ship with one or more tools to facilitate creating assets for use with the Game Engine; e.g. a 3D model and texture converter, a level editor, a sound back editor, etc.

The general idea is that a game dev should only have to bring their own unique work to the project (their logic, their art, their flair for lack of a better term), avoiding reinventing the wheel by leaving the common stuff to the Game Engine.

The murky part usually is how much needs to come with a Game Engine to consider it complete. That's a shifting target, both by who's looking at the question and what's currently fashionable. It's not at all uncommon that a project will use only a portion of the Game Engine they're purportedly using, patching in other components they find desirable/necessary. These other components (usually referred to as libraries) are also often bought in rather than written in house.

To throw in one more related common term: both the individual systems (Libraries) and comprehensive collections of integrated systems and tools (Game Engines) are collectively referred to as Middleware.

Note: here we're talking about Game Engine, as in a specific case of engine. The term engine alone is commonly (at least in my experience) used synonymously with library, module, system and even manager, and in that context would refer to a logical unit of code that provides a service, as per the components of a Game Engine above. I guess you could say all these nouns serve to form the sentence "the X that does Y" for the form YX; e.g. "the engine that does games", "the library that does pathfinding", "the module that does dialogue trees".

# Answer
> 5 votes
I would use the term "story engine" for what you're describing. It's a code module to handle the story, just like a physics engine is a code module to handle the physics. You'll also see terms like "tile engine" for a code module that handles graphics tiles; basically, a code module that handles a single aspect of a complete game will often be referred to as a engine. It's used more or less in the same way as "library" (as in "audio library.")

Both your possible definitions for the term "game engine" apply. For example, Unity is a 3D game engine.

# Answer
> 1 votes
Prototype Environment is probably a good phrase to use, not that it's standard or anything, but if your talking about a place to set up AI characters and play with the mechanics of the game, that's a layer above the game engine.

game engine usually refers to things like the graphics renderer, which calculates lighting, etc. and some basic components important to the game like collision detection, how state is tracked, for the game, characters, level etc.

An environment set up where you have all of these components together in a usable way implies that a layer has been created which brings them all together. what that layer is called is a slippery term, because it brings so much together, sometimes it's referred to as the gameplay engine, sometimes it's just coordinating the gameplay, and then what do you call it. the thing or the thing that it acts upon.

---
Tags: terminology
---


title: How to get elapsed time of keypress?

text:
# Question
Title: How to get elapsed time of keypress?
I need to be able to determine how long a key has been held down with high accuracy. For example if they key tapped really fast it could report a time that is less than the time for each update frame.

# Answer
> 4 votes
You could capture the input by using the System.Windows.Forms.NativeWindow class. You'll get a notification when an input event occurs. That way you'll be notified as fast as possible right when it occurs, letting you record the time to a higher precision. It gets kind of messy (native/unsafe code), but it works.

I think this only works on windows, but I think that's the platform your targeting (no need for this on Xbox and WP7).

Here is a good example (from nuclex framework): WindowInputCapturer (note: this code might have been updated recently and I didn't code it)

Edit: This also allows you to get at the character code of the key press. This could be useful for taking text input (especially things like latin characters) I'm not sure why you would need to get input at such a high precision, but this would be a good way to do it in my opinion.

# Answer
> 2 votes
XNA is a looped based framework, not an event based framework. If you need the exact time an event occurred, consider a winforms project (an event based project) and connect XNA to a control if necessary for rendering.

# Answer
> 1 votes
Store key state into a variable and compare on the next loop to current key states. Create a `DateTime` object to hold the start and you can compare with `DateTime.Now` when the previous key state doesn't match.

Very simple example of what I mean:

```
   if(currentKeyboardState.IsKeyDown(Keys.Space)
      && !previousKeyboardState.IsKeyDown(Key.Space))
      { DateTime startTime = DateTime.Now; }
    ...
    if(!currentKeyboardState.IsKeyDown(Keys.Space)
      && previousKeyboardState.IsKeyDown(Key.Space))
      { TimeSpan elapsedTime = DateTime.Now - startTime; }

```

# Answer
> 0 votes
I'm not aware of any official way of doing this, you could run a second thread in a very tight loop just to check the input and send this of to a circular buffer sufficiently large to require very little synchronization between threads.

(Store some kind of increasing number in each slot of the buffer and update that AFTER the thread wrote all the data, then continue reading slots with data from the buffer until the number decreases (don't forget to check for overflowing numbers!))

# Answer
> 0 votes
If you update thirty times per second, a human will not be able to press keys faster than you can sample the keyboard state. If you update more slowly than a human can type, then you may need one thread for rendering graphics, and another thread for reading and responding to the keyboard / mouse.

But, if you update more slowly than a human can type, then you can't provide visual feedback for each key press either. This doesn't matter if the idea is to display aggregate feedback, such as average time between key presses.

---
Tags: xna, input
---


# Question
Title: Kepler orbit : get position on the orbit over time
I'm developing a space-simulation related game, and I am having some trouble implementing the movement of binary stars, like this:

The two stars orbit their centroid, and their trajectories are ellipses.

I basically know how to determine the angular velocity at any position, but not the angular velocity over time. So, for a given angle, I can very easily compute the stars position (cf. http://en.wikipedia.org/wiki/Orbit\_equation).

I'd want to get the stars position over time. The parametric equations of the ellipse works but doesn't give the correct speed : `{ X(t) = a×cos(t) ; Y(t) = b×sin(t) }`.

Is it possible, and how can it be done?

# Answer
> 4 votes
Following a few links from the Wikipedia page you reference leads to Position as a function of time.

# Answer
> 0 votes
You seem to have had enough data to produce the handy animation above. Your simulation may need more accuracy than provided by my solution:

For each frame of your animation above, record the pixel positions of the centers of each star. Enter these values into two arrays in your program. For a given time t, find the corresponding four consecutive entries in each array and do a bicubic filter on them to produce the position of each star.

# Answer
> 0 votes
I've found numerical integration to be the easiest way. The inverse square law (F=GM/r^2) works pretty well. And Runge Kutta order four often called RK4 is easy to implment and works quiet well. You start out by writing a routien which takes first order time derivative, for instance for a single object in 2D space, you have X and Y coordinates, and X and Y velocities. The output is the time derivative, the time derivative of of position is simply velocity, so half of it is just copying values, then the acceleration is just the gravational attraction. Then you follow the Runge Kutta prescription. The error of a single time step is proportional to the time step to the fifth power. You adjust the time step to make the result accurate enough. One advantage on numerical integration is if you want to play with the system to make it more interesting, add extra orbiting bodies, or add friction, or whatever, you alreday have the machinery.

---
Tags: mathematics, physics
---


# Question
Title: SWiSH alternative Flash animator for AS3
In the past I've used SWiSH to create small animations that I could use for Flash projects, however, I'm now trying to move to writing AS3 which SWiSH doesn't support.

Whilst I have access to Flash CS5 through work, it doesn't have much in the way of in-built effects & animations, compared to SWiSH's 400+, and I want to be able to create various effects quickly and easily. (I'm a coder, not a graphics kind of guy!)

So, does anyone know of a good alternative to SWiSH (Flash Animator) that I could get/purchase that has a lot of stock animations/effects built into it, but is fully compatible with AS3, allowing me to export symbols in SWF and embed/use them in FlashDevelop?

# Answer
> 3 votes
As long as the animations are frame-based (not scripted), you can embed AS2 SWF assets into an AS3 project.

The best way is probably to embed symbols from your SWF files, like this:

```
[Embed(source='SWFFileName.swf', symbol='symbolName')]

```

If you just create animations and maybe have some frame-labels to jump to, this is going to work fine. It won't work if you have scripted animations, since all AS2 code will be lost when embedding.

It's probably good practice anyway to have plain animations without scripting and let the actual game code control the animations.

---
Tags: actionscript-3, animation, flashdevelop, flash-cs5
---


# Question
Title: Where can I find 3d models of equipment for supermarket?
Where can I find 3d models of equipment for supermarket? I will use them in XNA.

UPD. I need equipment like this http://www.the3dstudio.com/product\_details.aspx?id\_product=419747 without products.

# Answer
> 2 votes
You could try turbosquid.com.

# Answer
> 2 votes
first of all, i don't know any particular website for this, but i can help you out.

What file types does you current 3d environment support? search Google sketch-up library online, it has lots of 3d models.

if you found what you need, then check if you 3d apps file type is supported in Google sketch-up.

if yes download Google sketch-up, download the model from Google site and do the conversion manually.

the reason i suggest this is that Google sketch-up has lots of models you can download free, depending on the owners terms.

if you have any problem converting, let me know i have done lots of conversion like these when doing 3d games

---
Tags: models
---


title: Unity MouseWheel weapon change

text:
# Question
Title: Unity MouseWheel weapon change
I am trying to make a simple weapon change in Unity3D. The best way to do this is with the mouse scroll wheel, as far as I can see.

I googled on how to do this and found that I have to use `Input.GetAxis("Mouse ScrollWheel")`; I use this piece of code and print it. Still, I always get an value of 0. any ideas? I just need to solve how to get the value first, I'll figure out the rest myself.

Code idea:

```
function Update () {
    print(WeaponNumber);

    if(Input.GetAxis("Mouse ScrollWheel")){
    WeaponNumber += Input.GetAxis("Mouse ScrollWheel");
    }
}

```

# Answer
> 3 votes
In addition to using the code you have above you need to configure the axis in the input manager and name it correctly.

The accepted answer here may be of help: http://answers.unity3d.com/questions/6106/implementing-the-scrollwheel

---
Tags: unity, javascript, input, mouse
---


# Question
Title: Game companies - Involvement of programmers in the design process
This is a question basically to programmers with experience working in game companies.

How common is it that game coders participate in the design process of the game? Both gameplay design, and content design. Do you participate in related meetings and such, or do you have some other (formal/informal) opportunities to sound your opinions of game features / levels / even story, and for them to be actually considered?

Another question, not completely unrelated - is it possible for a programmer with interest in the field to move from the technical job to a gameplay design related job (or do both in smaller companies)? Does that happen?

# Answer
Frequently coders are called upon to figure out if designs are possible, and also help order new features in schedules, but when it comes to actively providing creative input, each company varies wildly. Some don't have many dedicated designers and the coders are meant to "add value" while developing the features. In other companies there is a very strict "if it's not in a design doc, it's not going in".

So, choose who you work for carefully.

Also, it's very possible for a coder to move to being a producer, which can lead to some more creative control, but I've not yet seen a good designer start out as a professional coder. (being a computer games enthusiast turned bedroom coder doesn't count, as many games designers have to start trying their ideas out somewhere)

This distinction of mine seems to have stirred up some feelings, so let me elaborate:

Games developers that are first and foremost coders, the ones that started out by coding, then realising that they liked computer games and then started to develop them became games developers, those games developers I would say are probably a bit hit or miss for being games designers.

The ones that started out by loving games then attacking SDKs with gusto, the ones that make mods, generate a lot of random stuff in game creation kits, only finally getting into a job where they code much later, those are games designers that can code. These ones, often, have the feel for games design that makes them good games designers.

Admittedly, I'm one of the former, I do love coding games, but for the joy of developing the game, and in the case of my home projects, for seeing the reaction from my family when they play the games I make for them. I am, however, aware of my shortcomings when it comes to games design. I have to try really hard not to be blinkered into thinking like a coder when designing games. I have to stop myself from adding features just because they're simple, and stop myself from trying to avoid adding features just because they're hard.

The coders that started out by designing annoy me with their tolerance for shabby code, but when I take a step back and see what they've done with the code, I have to be humble and admit that they made the game better, regardless of how annoying they might be to work with when it comes to code cleanliness.

I found a rare one at my last job that was the combination of both and wish him much luck in the future.

So, although coders can be involved in the design process, add their own creativity to the mix, I think it's probably better to sum it up differently: Design meetings can include coders and designers, sometimes they even have the right job description.
> 10 votes

# Answer
**There's no rules, sometimes**

There was no rules in the game company I worked at. *Sure, I don't think it's uncommon for coders to do design*. I'll share my examples.

Regarding,
While I was hired as a programmer, but I did design and music. It's not that I wanted to do the creative stuff, they just had no structure and needed my design.

*Yes, moving from a technical job to design/gameplay is possible in an unstructured company.* You need to bring some real skill, and be careful about territorial issues and egos.

Because I came from the multi-media industry and was just doing programming as a hobbie, I had the confidence to move into game design. That was my break, but instead of lacking experience with design, I lacked experience in the programming.

I hope you get a break in the industry if that is what you're after. *I recommend getting some experience with design in a gaming company, but stay within your job title.* You can always go to an other company with the experience you've gained, without ruffling egos at your current company.
Good Luck,
> 5 votes

# Answer
In our company game designers are separated from other developers. But we have special page on our internal wiki where we can post our thoughts about different aspects of game and of course we can talk to them directly. But the last word always have game designers and we are not allowed to do anything outside the specs. And it is great, actually. Division of labor.
> 4 votes

# Answer
First: your mileage will vary depending on both you and the company you work for.

That being said, let's look at some job titles:

**Technical designer** \- These individuals straddle design and programming. Often times, the ones I've encountered have started off as programmers and then heavily migrated to design. Responsibilities often involve working closely with both the design team and programming team to build technically challenging design elements.

**Gameplay programmer** \- I've been a gameplay programmer on a triple-A FPS. Typically, our responsibilities involve translating a designer's dreams into realities. Depending on the studio, you can be given a great deal of latitude in how your implementation functions and what if offers the designer. I've seen more than one gameplay programmer's initial values be used in the shipped product. Additionally, being a gameplay programmer gives you a close dialogue with the design team, potentially allow you to comment or influence their designs.

**Other programmers** \- Engine programmers and tools programmers typically have very little sway in any design decisions beyond "can it be done". Though, this depends on the studio. My current studio (a social/casual house) expects everyone to provide input for design, including all programmers.

So, basically, it all depends on the company and your position within the company.

I hope that helps!
> 3 votes

# Answer
> How common is it that game coders participate in the design process of the game?

I've had experience of 3 companies:

* One had no designers at all. All design was done by programmers and artists, typically the most senior.
* One had designers, and programmers had virtually no input into the process. The lead programmer might be brought in to provide a feasibility check on the design after it was made and adjustments made accordingly, but they did no design as such.
* One has separate programmers and designers, but programmers are encouraged to contribute high level design just as much as the designers are - the division of labour takes place more on the implementation side.

So, no standard there!

> is it possible for a programmer with interest in the field to move from the technical job to a gameplay design related job (or do both in smaller companies)? Does that happen?

Yes, and yes. I think it's actually quite common, and I would argue it's preferable - I would much rather have a designer who has (a) experience of the game making process and (b) understanding of the medium's limitations.
> 2 votes

# Answer
One question I'd like to answer even if you didn't ask directly: SHOULD game designers involve programmers in their design meetings? (As others have said, whether they actually do or not varies from team to team.)

I think this is an emphatic YES. A programmer's job is, essentially, to turn the designer's ideas into working code. For that to happen, the programmer needs to have buy-in to the design, whether this comes from feeling like they have creative input, or merely that they are "in the loop" in terms of the current state and direction of the game.

Especially in teams where the designers are not strong coders, it is also vital that programmers have "veto power" over any designs that would be more difficult or time-consuming to code than they are worth... especially if they can suggest trivial-to-implement alternatives. Programmers also tend to be good at finding holes in the design, because they are thinking in terms of "how do I code this" so a missing detail will stick out to a programmer easier than it will to a designer.
> 1 votes

---
Tags: game-design, software-engineering, career, jobs
---


# Question
Title: Game/Level Design Career translations in other fields
Although I would love to get a job in the gaming industry I can't help but feel I should have a backup plan. What I wanted to ask is game/level design a marketable skill that translates to other industries?

For example if your a programming in game development, you can be a software engineer in business, health care, finance, scientific etc, industries

If your an artist in game development, you can be an graphic artist, web designer, animator, advertisement, etc.

Do game/level designers have other industries they can get into other than gaming? If you think so, what are some industries that level design (or game design) would be marketable for?

# Answer
There is the ever-growing field of serious gaming to consider, if you get a formal game design training.

It has many variants now :

* edutainment: learning games for kids (an old and very profitable business), getting a lot of attention with iPad/tablets right now.
* corporate training: currently not very big, but there are growing possibilities there. Might be more popular than 'survival'-type 'seminars'.
* institutional training: military forces in several countries now use serious gaming as a way to train their officers.
> 4 votes

# Answer
"Game design" is an incredibly broad field that likes to include level design, systems design, and story writing (among many others) under its umbrella.

When I think of game designers, though, I think of systems designers: the people who write the specs that get implemented by programmers. And yes, spec-writing is a skill that is used in the greater software industry (these people are sometimes called "systems analysts" or "program managers" or lots of other names) - just look at all of the "design" articles on joelonsoftware! This goes triple for designers who specialize in UI, since the principles of designing a good UI are still largely the same whether you're making a game or a business application. So, yeah, the skills transfer quite nicely.

One caveat: not everyone in the software industry knows what it's like to work in game development. There is still the stigma of "oh, you used to get paid to just sit around and play games all day? We actually do Real Work here" that has to be overcome in some companies, so you may have to convince people that a game developers is actually one of the hardest workers and most skilled labor they are likely to find. This might mean, for example, carefully crafting your resume and cover letter to focus on job responsibilities that sync well with a given posting, and downplaying the "games" aspect.
> 2 votes

# Answer
I am in a very similiar situation regarding occupation. In my opinion, I believe Architecture (Which in itself is a very broad subject containing many practical fields.) is a really nice choice for you. That is if you want to apply yourself to real world principles. Architecture is used in housing, landscaping, large scale city projects, etc. Now, mabye you think "Oh, but architecture is more hands on and physical and less digital." Not true, Architecture nowadays uses CAD programs for modeling ideas and projects. Not to mention you also make 2D drafts.
> 1 votes

---
Tags: game-design, level-design, jobs
---


title: XNA with SQLite

text:
# Question
Title: XNA with SQLite
Does anyone have experience using SQLite with XNA?

Or using any other DB with XNA?

# Answer
> 7 votes
SQLight does work with XNA, just don't expect any store procedures or functions. Any flat file will work to store data (XML, JSON etc). I prefer XML, though if I was using lots of data I would switch to SQLite

# Answer
> 5 votes
You should have no issues Accessing SQLite from a Windows XNA Game. On Windows, XNA Project is just like any other project and you can do anything that C# can do. On Xbox or WP7 this isn't completely the case; however, there is also a C# version of SQLite written to run on fully managed environment (Xbox, WP7): see the ZMan's post here: http://xboxforums.create.msdn.com/forums/p/47127/282261.aspx

---
Tags: xna, databases
---


# Question
Title: Surface of Revolution with vertex shader
Is it possible to render a surface of revolution with using a vertex shader?

I have NxM vertices, and I would like to transformate them accordingly to the function I have to draw.

Is it possible, or i can not change the vertex position with a vertex shader?

Thanks ahead!

# Answer
Sure this is possible, for a given value of possible. It's somewhat unclear to me exactly what you're looking to do, but the basic principle of a vertex shader is to take a stream of inputs, execute a homogenous function for every vert, and produce a set of outputs.

In your case of a surface of revolution, I assume you mean you want to end up with a mesh like a lathed surface, given an input profile curve? If so, what you're intending to do is more commonly done on the CPU, written into a vertex buffer as a finished surface, and then displayed like any other mesh. Usually the vertex shader would only be used to apply a linear transformation + projection matrix to get a perspective render of the surface.

It's not entirely uncommon though to move some calculations to the vertex shader where you know that they will be heavy for the CPU to perform, and you intend to do them often, or you could save resources in some way by parametrizing the same input data over and over again. E.g. you wanted to draw 1000 similar lathed objects where only the radius varies.

If that's the case, then your first problem is that you cannot generate vertices in a vertex shader. There are two inputs into a vertex shader: varying/stream and uniform/constants. Varying inputs vary for each vertex, while uniform ones only change between draw calls.

All vertices you will draw will need to be present in the input stream. What this means is that you'll need to identify a common input stream pattern to all your possible instances. Let's say, for instance, that you'll be making lathed surfaces where:

* There are N segments around the axis of rotation (let's call it Y)
* You have a function that given a T value between 0 and 1 can give you the distance from the axis, and the distance along the axis for a vertex; i.e. the x and y of the profile curve.

So, you'll need to setup an input vertex buffer that provides for each vertex:

* An A value, which determines segment it is on, so that you can calculate how far around the axis it should be. Let's say we store this in radians.
* The T value, so that you can calculate where on the profile curve it should be. We'll store this as a value between 0 and 1.

So for an instance that had 3 segments, and 3 steps along the curve, your stream would look like: 0, 0, 0.5, 0, 1, 0, 0, 2/3pi, 0.5, 2/3pi, 1, 2/3pi, 0, 4/3pi, 0.5, 4/3pi, 1, 4/3pi. *Note: with that vertex stream you'll need an index buffer to describe how to stitch those points into triangles.*

You would then make a custom vertex declaration that described the two floats you need.

You would then make your vertex shader take these two inputs, and:

* Calculate the X/Y position using the T input.
* Rotate that point around the Y axis using the A value, creating a 3D point.
* Apply your view/projection transform.

Now, based on what you're trying to do, you can figure out what uniform inputs you'll need here, i.e. whatever your function that takes T to produce XY needs.

Once that's all done, you can now make individual draw calls reusing the same stream inputs, but varying the uniform inputs to create different lathed surfaces. You could also vary the vertex shader its self to apply different functions. You could also create multiple streams with varying amounts of tessellation. Swapping between these would allow you to cheaply adjust the level of detail for each instance.

That's the simplest usage of the GPU at this time. Different architectures offer alternative features that may contribute a different solution to your goal, but without knowing more about your goal or what your environment is, I can't speak to those.
> 4 votes

# Answer
***Yes you can change the vertex position with a vertex shader***. The vertex shader is specifically intended for this purpose.

In this basic OpenGL example, the shader reads in the vertex - in the `gl_Vertex` variable - and writes the final vertex position to the `gl_Position` variable:

```
void main(void) {
   vec4 a = gl_Vertex;
   ... custom code here
   gl_Position = ... * a;
}

```

Determining the surface of revolution is, however, not really a rendering problem.
> 1 votes

---
Tags: graphics-programming
---


title: What is Minecraft's database?

text:
# Question
Title: What is Minecraft's database?
I was wondering, what kind of database does Minecraft use? Is it a relational database, maybe something common like MySQL? Do we even know what he's using?

And maybe even a better question, SHOULD he be doing it that way? What type of database should be used?

# Answer
> 12 votes
Minecraft saves the world data and the player data. Saving the world data is done in multiplayer and singleplayer with the same method. It saves everything in a single `.mcr` file.
Previous versions of minecraft saved the data in a file structure with many files, which was slower, I think.
I don´t know this exactly, but I guess that a database for world saving would be not the best, because the data is saved in intervals of 15 minutes or so and a database is not designed for saving all data at the same time.

The player data on multiplayer servers is saved in a `.dat` file. I don´t think that this player data is saved in a SQLite database or something similar, because using a database for requesting once and saving every 5 minutes or so is also not the best.

**To sum it up:**
I think Notch doesn´t even use any database, because it does not make sense since every data is kept in memory and only saved in intervals of minutes.

---
Tags: databases, minecraft-modding
---


# Question
Title: Suggestion for C++ reinforcement learning library to control flocking algorithm
I am looking to use reinforcement learning to adaptively modify the weights involved in a flocking algorithm (i.e. 'boids').

Searching google revealed several libraries, but I don't know anything about any of them.

I am far from being an expert in reinforcement learning, though I have perused Sutton and Barto's classic book on the subject, so I understand some of the concepts.

A little background, in case it helps. I have a few steering behaviours (seperation, alignment, cohesion, forward, and wall avoidance), which each generate a 'force' vector and compete to tell the agent(s) where to move. Each force vector is combined in, basically, a weighted sum. I would like to 'learn' these weights adaptively so as to cause e.g. more/less clustering, reduce/increase the flock's speed, etc.

Can anyone recommend a good library to use?

I would also need some kind of linear classifier, or something, to interface the learning with the (float valued) weights for each of the flocking steering behaviours. So a library that provides a one-stop solution for this problem would be good?

# Answer
> 1 votes
As Daniel pointed out, the difficult part is the reward function. If you got that figured out what it comes to to is this:

1. You create a flocking simulation taking N parameters (where N is the number of coefficients to tune) returning a single value (the "fitness/error/reward").
2. Afterwards you plug that function into a reinforcement-learning algorithm as a black-box error-function.
3. The algorithm will then try more or less random values for the N parameters, evaluating their error (by launching your simulation), and stop when good values are found.

A very fast and stable reinforment learning algorithm is the CMA-ES. Papers and source code are available at http://www.lri.fr/~hansen/cmaesintro.html

Be warned though:

* Building a reward function that actually does what it should is often more difficult than solving the initial problem manually.
* The reward function should return the same output value for same input values, therefore "then alter the reward function" is probably a bad idea.

# Answer
> 1 votes
During my software agents module, I searched high and low for a decent RL learning. Unfortunately, I didn't find anything that was a) useful for my uses and b) well documented.

However, something like Q-Learning isn't too difficult to implement. Artificial Intelligence for Games has a simple implementation of Q-Learning that would probably be of use to you. What's more is the source is packaged on the CD. I would have suggested the website for the book to get the source code but it seems to be down or just gone.

Also, here is a reinforcement learning simulator (open source and written in Java) which is fairly straightforward to understand the underlying concepts. http://www.cs.cmu.edu/~awm/rlsim/

But as said above, the reward function you use is key to getting a decent result.

Personally, when it comes to tweaking weights, I'd probably use a genetic algorithm, but similarly you'll need the appropriate fitness function for what you're trying to create.

---
Tags: c++, ai, movement, character, reinforcement-learning
---


# Question
Title: Which would a game development company prefer; UDK experience or C++ game projects?
Which would a game development company prefer, a developer with experience in UDK engine, or a developer with projects made entirely in c++ with a graphics engine like Ogre3D?

I think that a coder can demonstrate better his abilities with games made in c++, because it requires a knowledge deeper in many fields. However, currently there is a lot of companies that develop games with UDK. Now I don't know if it's better specialize in a game engine like UDK or not.

# Answer
Depends on the job spec, if the company have set out the requirements for proficiency in C++, then you're gonna want to have some decent C++ projects in your portfolio that you can show off.

If they specifically ask for UnrealScript examples, then you'll want to have some UDK samples to show off.

It really depends on the games company, what they're after, what the role is, etc.

At the end of the day, it comes down to experience. Whilst it is very good for a programmer to be competent in many different technologies (and desirable in some cases), if you're looking at a specialist role I'd expect the potential candidate to focus more of their submitted portfolio to the specialism (for example, if you're applying for an AI role, I wouldn't really expect a whole portfolio full of awesome physics demos).

Hope that helps.

Ray
> 12 votes

# Answer
Speaking as a programmer (to be more specific than 'developer') at a company that has used UE3 for multiple projects, I can emphatically say that we would consider C++ knowledge essential, and a candidate with experience in the UDK but no C++ coding knowledge would almost certainly not be considered for a programming position.

To expand on this a bit: while we were using the Unreal Engine for our titles, only a small fraction of the game was written in UnrealScript, for a plethora of reasons that I won't get into here. Meanwhile, the implicit consideration was that coders with solid C++ knowledge could pick up UnrealScript relatively straightforwardly (indeed, I don't think more than one or two people on the devteam had any experience with it before starting the project), whereas someone whose only skills were Unrealscript would likely have a harder time learning all the ins and outs of C++ and a larger codebase. Since programmers needed to be able to shift specific roles over the course of a project and slot in as needed (particularly during bug crunches), carrying UnrealScript-specific programmers would make next to no sense for us.

I don't know if the calculation of what can be more easily learned would be the same for other companies, but I do know that we weren't the only UE3 developer to almost completely forgo UnrealScript; and more to the point, there are far more developers out there who *aren't* using UE3 than who are (and any way you slice it, virtually all of the studios using UE3 are also using C++) - so if the question is 'what skill is more likely to make me employable as a programmer in the games industry?' then the answer is C++ hands-down.
> 7 votes

# Answer
A good coder is a good coder regardless of their specific background. It's really just a matter of how much time the company is willing to spend on training/learning for a new coder to become familiar with whatever tech they're working on.

Some companies hire to fill positions. In that case if you have experience in X and they're looking for somebody who can do X, you'll be bumped to closer to the top of the queue. Other companies look for targets of opportunity and realize that learning new software and languages is easy for any mid/senior programmer worth his salt and would fit in with the company for other reasons (i.e. culture). It depends.

That being said, not having any C++ experience can be a red flag companies doing at least some C++ work, as "getting pointers" is pretty fundamental.
> 4 votes

# Answer
I'd say C++ as it is a more general skill. UDK is written in C++ as are many game engines. Code your own little engine in C++ and you'll learn skills that are relevant everywhere. And then learn how to use the UDK as well.
> 3 votes

# Answer
> What prefer a game developer company? A developer with experience in UDK engine ? or, a developer with projects made entirely in c++ with a graphics engine like Ogre3D?

Too hard to say. Both skills are good to have, whether or not a company will prefer one over the other depends on what position(s) and skill set(s) they are looking for currently.

> I think that a coder can demonstrate better his abilities with games made in c++, because it requires a knowledge deeper in many fields.

I would challenge this assertion. A game made in C++ demonstrates the developers C++ skills more than a game made in some other fashion, but just because something was written in C++ does not mean it better demonstrates a developer's overall ability, nor does it necessarily demonstrate deeper knowledge about anything.
> 2 votes

# Answer
Companies that use a game engine like UDK also have programmers that write c++ code (and/or other languages). So learning either one is equally valid and relevant to get into the game industry.

The important thing here is for you to **find out what you really love doing and then do it**.

When you work on something that you really enjoy doing, you will probably produce your best work, and this will give you the best chance of convincing the company that you are worth hiring, regardless of what technology you decided to learn and implement.

If you don't yet know what motivates you to make games, the best way to find out is to experiment.
Try a small project with UDK. See how you like UnreaScript and programming game logic.
Find some examples in c++ and try them out, maybe physics, or graphics or even a small tool that converts data from one format to another.
You don't even have to settle on one technology or one area of expertise, in fact the more skills you have the better, especially early on in your career.

There are many different programming roles in a game developer. They are all needed to make the game. Find out which one you want to be.
> 1 votes

# Answer
I am a programmer at a game company and I would simply not consider someone who didn't have C++ experience; C++ programming is just too much of a pain to expect someone to totally pick it up on the job (and we don't even go that nuts using its more advanced features). However I would value someone with both C++ and UDK experience over someone with only C++ experience. So my advice would be to pursue your UDK interest if you have it, but don't neglect your baseline C/C++ skills.
> 1 votes

# Answer
It depends. But for developer should mostly present as much skills as possible. So yeah for c++ and UDK. But in my opinion, much better is have your own litle graphics engine in opengl or directx...
> 0 votes

# Answer
UDK is not UE3. AAA games are made with UE3, casual games are made with UDK. So your first question should be: which is my target company type? Nothing is going to get big paying 25% of its revenue in licensing, there are no examples yet, and I very much doubt there will be outside the occasional lucky single-developper AppStore hit (do not confuse with the huge success list of UE3, which has a different licensing scheme, but will likely require much more C++ knowledge if you're hired to work with it).

C++ knwoledge is universal and can get you a job working on the F35, for a global company for consumer electronics, in a hospital... UDK is getting you nowhere at all, except where it excels, which is a niche however interesting it may be for you at this time in your life. Are you that sure you want that bad to work for a (likely small) game company forever, when the game industry has changed so much in so little time?

Finally, C++ has been around for a long time, is there to stay under different incarnations (you'll be a lot more efficient learning C# from C++ than from UDK script), whereas UDK script is very very good at one thing: language support for asynchronous events. Essential in some environments, but talk about a hard-to-sell skill!
> 0 votes

# Answer
Companies want to hire technical artists these days, basically that means you must have skills both in art and programming in one. To serious people trying to break into the industry it's sad to report that the industry is simply not interested in the average Joe with some hands on game engine experience, its not dedication or even creating works of art that do wonder. It's all about time and money nothing else, 90% of your skills are wasted on what your art directors or coordinators want to see. You get passed concept work and you work to complete that and bring it into reality then you get messy and put the art into the technology that will be running it, that is practically all a game artist does in the industry. If you believe otherwise then you are sadly mistaken, try spending the 40 to 60 years in the industry you will see what its like creating art for a living on a shoe string budget.

UDK is not Unreal Engine 3 and vise versa they are contemporary engines which are a superset of the unreal technology, UDK is simply a lesser umbilical child of the Unreal Engine thus its state is in constant evolution. Whereas Unreal engine is the complete source code licensed under an NDA sort of agreement and unless you can pay millions chances are STFU. That is not to say UDK isn't powerful, however it is limiting in a number of ways which are both technical and license model based, what does make UDK interesting is that it employs a technology share type program. Where various technology partners have contributed to the needed success of UDK for example "Speedtree" without it our lives would be miserable. UDK is nothing but a cheap shot at the market because Epic has lost Epic revenue and court battles, so they decided to build a license model that targets the average market in the hopes of revitalizing their losses.

ID Software as much as I hate their direction and lack of aesthetics, were the first to open source their previous generation technology to the public. That is something no game development company has done thus far, UDK comes close but loses the stretch by a mile.
> 0 votes

---
Tags: c++, udk
---


# Question
Title: What approach would you take to develop an old school game?
> Possible duplicate: What technology should I use for a web-based game?

I have agreed to show my child how to develop software. He wants me to help him develop a game.

**If you were me then what approach would you take to develop an old school game?**

I was thinking about an old school game that you can pick up and play them straight away, where there is no "learning curve". This is because we prefer playing these types of games. On top of that I want to be able to say things like "I made the game engine, the AI, he did the scoring system and .. and .. and ..".

I intend to run it in a browser, to target a broad range of platforms. I was thinking to use mainly C# and Silverlight.

So, if you were me then what approach would you take to develop an old school game?

**EDIT**

Could I use XNA? Is it free? Does it plug into Visual Studio 2010?

# Answer
C# makes best combo for home development. There are two great platforms which are well suitable even for beginers. I expect that "old school game" means something like SNES games.

* XNA \- is buid over directx and can ran on PC,XBOX and win7 phone. It is easy to use and learn. It uses shaders but you can evercome it by use basic effect classes which does the work for you and you don't need to touch GPU. And of course you can make simple 2D old school games which will run on todays hw with xna.
* Unity \- Is today's "everybody-love" game development platform. You can write code in c# or javascript and it will run on almost everything (PC, web browser, mac, iphone, android, xbox and ps3). It is however not that good for simple 2D development as XNA is. But someone may disagree.

edit: if running in web browser is your "must have":

* Using java applets is also possibility to run games in browsers. If you use only canvas to which you can draw geometric primitives, it will be pretty near to the old school. However you can also use JOGL or similar to have access to the OpenGl functions.
* Flash - It is well used possibility for game development in a browser. It uses action script, which is similar to javascript.
* Javascript and html5 - Html5 canvas and javascript opens new ways to create games in browsers. You can control directly what you draw into the canvas and it will run with no need on of installation of any plugin in every browser (in near future). No hw acceleration seems like no problem for you.
> 6 votes

---
Tags: c#, web
---


# Question
Title: Pathfinding with multiple random paths in a Tower Defense game
I thought about random pathfinding for my Tower Defense game. A\* would not work for my puposes, because I specifically need **random** pathfinding.

Imagine a map with routes, a starting point and a destination. I have multiple routes, which all lead from the starting point to the destination, one way or another. It could look like this:

---

*Color description: red - starting point; black - destination; grey - route; white - free space<br>(The numbers are used in the text as a reference to some tiles)*

---

I first thought about just calculating the next waypoint randomly, when an entity passes a tile. But that would not work. When an entity passes tile 1 it either can go up or down. When it comes to 2 it can either go down/up (relative to it´s position) or right.
**If** it goes **down/up** it would go to tile 1, which means that it goes backwards. Bad...

I would really like to make it **dynamic**, but I can´t figure out what I can do now. Anyone with ideas or experience in this?

# Answer
> 4 votes
Instead of having all adjacent squares as possible next waypoints, only include squares that do not lead back to the beginning and randomly pick from those. If you did this, it would be impossible to go backwards because going back is not an option.

This is a directed graph problem with each waypoint as a vertex, and each path an edge. You just need to limit the number of cycles, perhaps removing them entirely.

# Answer
> 7 votes
You say random, but how much randomness do you want? Is it ok if the enemies pick a path that is 10 times as long as the shortest one? Is it ok if the enemies enter a dead end and have to backtrack? That is, random over what set of paths, and with which probability distribution?

Assuming you want the enemies to prefer short paths, you could use A\*, but randomly vary the edge weights fed to it. Then, enemies will always choose a random path that visits each node at most once, with a bias towards shorter paths. In particular, if without randomization there would be several paths of same length, each of these paths would be chosen with equal probability.

Alternatively, in A\*, you could iterate over neighbours in random order. In your eaxmple, when path finding reaches node 1, it would at random enqueue the top of bottom neighbour first, causing the top or bottom path to considered first. This solution would cause enemies to pick among all shortest paths at random. In your simple example, both shortest paths would be equally probable, but in a situation like:

```
start -+--------+
       |        |
       +--------+
       |        |
       +--------+- end

```

the top path would be chosen at probability 1/2, while the bottom ones would be chosen at probability 1/4 each.

# Answer
> 0 votes
Just a proof of concept:

1. Choose a random direction.
2. If this would cause us to go somewhere we've already been, pick another direction.
3. If we have run out of directions go back to the last square with a unexplored direction.

---
Tags: algorithm, path-finding, random, tower-defense
---


title: Top Down RPG Movement w/ Correction?

text:
# Question
Title: Top Down RPG Movement w/ Correction?
I would hope that we have all played Zelda: A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top-down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to. More specifically the kind of movement and correction I'm talking about is:

* Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion.
* If you're walking West and you come to a wall that is diagonal in a North East/South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions.
* If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall/door.

I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something?

I'm using the XNA Framework, is there anything in it to help with this?

# Answer
Well, the first bullet point is easy. You simply store and manipulate the character's position in world or pixel coordinates instead of tile-based coordinates. If you were having an issue with this, it might be due to a a confusing choice of representation for your world and tile space, so perhaps you should post more details about it / ask a separate, specific question.

For the second point, the most direct approach would be to take the player's (normalized) movement vector and add it to the wall's normal vector, then renormalize. The sign of the components of the resulting vector will indicate how the wall relates to the player's motion while the vector itself indicates which direction the player may now move.

For the third point, assuming you have collision rectangles for both the wall and the player, you should be able to determine how much of the player's collision rectangle contacts with the wall's collision rectangle. If, for example, the player is moving to the right and hits a vertical wall, you compare the Y axis extents of the collision rectangles -- if if the player's extent exceeds the wall's extent by some threshold, say 75% of the player's Y axis extent, then you "cheat" the player towards the door.

I've made a fair number of assumptions here in how your object model looks in your code and what techniques you've chosen -- largely due to the generality of your question. I've tried to suggest approaches that are simple (although perhaps not optimal) for the same reason. If you can provide more specific information, either in this question or in a new one, I can try to provide more details or a better idea.
> 22 votes

# Answer
As a possible answer for the second point is to project the player's movement vector along the wall vector using a dot product (a.b * normalized(b)). You then get a vector that tells you how far to move the player in the direction of the wall, and if you move the player by that vector, you get a 'slide' along the wall. Worked well for me in a previous game project.
> 4 votes

# Answer
Great answer for Josh, but I'll add a few suggestions: \- For more info on sliding against walls, check out my question \- from this answer I managed to get it working really nicely. \- If I'm not mistaken, when walking up the screen Link will ease to align to the closest whole horizontal grid square. This way when you get to the doors you're more likely to be properly lined up (might be wrong). \- To make it easy to get through doors, make sure the collision box of your character is way smaller than the width of the door.
> 3 votes

# Answer
For correction of entering doors, you could make the collision object for the door slightly larger than the image of the door. This would result in the same effect proposed by Josh, but without having to calculate the proximity to the wall's collision rectangle.
> 2 votes

---
Tags: xna, 2d, rpg, movement
---


# Question
Title: pixel shader and vertex shader problem in visual studio 2008
I have just installed XNA for VB2008 professional, now i try to run my first game development and i get this error,

any way around this, am using windows xp sp3

my system configuration

```
Host Name:                 USER-PC
OS Name:                   Microsoft Windows XP Professional
OS Version:                5.1.2600 Service Pack 3 Build 2600
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Workstation
OS Build Type:             Uniprocessor Free
Registered Owner:          user
Registered Organization:   user-pc
Product ID:                55274-640-1011873-23081
Original Install Date:     1/26/2011, 7:00:52 PM
System Up Time:            0 Days, 10 Hours, 31 Minutes, 22 Seconds
System Manufacturer:       Hewlett-Packard
System Model:              HP d330 uT(DC579AV)
System type:               X86-based PC
Processor(s):              1 Processor(s) Installed.
                           [01]: x86 Family 15 Model 2 Stepping 9 GenuineIntel ~
2593 Mhz
BIOS Version:              COMPAQ - 20031003
Windows Directory:         C:\WINDOWS
System Directory:          C:\WINDOWS\system32
Boot Device:               \Device\HarddiskVolume1
System Locale:             en-us;English (United States)
Input Locale:              en-us;English (United States)
Time Zone:                 N/A
Total Physical Memory:     1,527 MB
Available Physical Memory: 689 MB
Virtual Memory: Max Size:  2,048 MB
Virtual Memory: Available: 2,008 MB
Virtual Memory: In Use:    40 MB
Page File Location(s):     C:\pagefile.sys
Domain:                    WORKGROUP
Logon Server:              \\USER-PC
Hotfix(s):                 10 Hotfix(s) Installed.

```

# Answer
> 3 votes
Doing a quick google search on your PC model number led me to this page: http://h18000.www1.hp.com/products/quickspecs/11647\_na/11647\_na.html

The important bit is this:

> Intel 865G chipset with Integrated Intel Extreme Graphics 2

Which, according to a few sources I found, seems to not support shaders.

You need a new graphics card.

---
Tags: shaders, .net
---


title: What libraries/engines should I use?

text:
# Question
Title: What libraries/engines should I use?
I have some pretty decent general programming skills and elementary C/C++ skills. I am a complete noob in game/graphics programming and I would like to start.

I want to gradually learn, starting off by something like Pong, and gradually making more difficult stuff for learning. My ultimate goal is to make some COD:BO zombies clone (I **love** this game).

So what libraries/engines can you guys recommend, first to even start drawing stuff on the screen, and later more sophisticated stuff for getting a FPS going.

# Answer
> 3 votes
Try to keep your first attempts as simple as possible. Pong is a good start. You can use a 2D library such as SDL or (better) SFML to bring your graphics onto the screen.

For 3D, there's for example OGRE, which is pretty powerful. But keep in mind that making 3D games is much more time-consuming and difficult than 2D, so you should definitely practice with the former.

**Alternative**: You may want to have a look at Unity3D or Unreal Development Kit (UDK) if you want to get as quick as possible to a playable prototype. Albeit those are rather 'game makers' than low-level libraries and don't require you to code in C++ or Java, you still have to code respectively script your game logic.

# Answer
> 2 votes
I wouldn't recommend either Java or C++ unless you are already very familiar with those languages. The language I would recommend is Python, and the most obvious game library for that language is PyGame: http://www.pygame.org/news.html

Another game development tool I am thinking of starting to use is Love2D, mostly because I have started programming in Lua: http://love2d.org/

That's for 2D games; if you want to develop 3D games then going with Unity is a great place to learn: http://unity3d.com/

And then while I have no personal experience with C# a lot of people say good things about learning game development using XNA.

# Answer
> 0 votes
First you should choose your programming language.

I can recommend **Java**, not only because of it's ease, or **C++**. You should choose the language, which is most familiar for you. Don't worry about performance. Java and C++ are extremely performant, if you keep some performance rules.
I like java more so I use it. I can't recommend engines in C++, because I have no experience there.

For learning drawing and other basics I would start with java2D or the equivalent C++ engine. This way you understand the basics of game development such as the main loop, rendering and input. These tasks are normally taken by the game engine.

---

Open Source Game Engines in Java:

**2D:**
*libGDX* \- nice and fast library for developing games simultaneously for PC and android
*Slick* \- Also good and easy to learn
*Java2D* \- built in java 2d graphics engine

**3D:**
*jMonkeyEngine* \- famous 3d engine

# Answer
> 0 votes
Check this site for a long list of libraries. The best thing is that these libraries are categorized under Physcis, AI, GUI, Networking.

He provides descriptions and sometimes examples or at least from where you can get the library.

Also, you can check this site for free open source libraries.

---
Tags: education
---


title: Surface of Revolution with 3D surface

text:
# Question
Title: Surface of Revolution with 3D surface
I have to use this function to get a Surface of Revolution (homework).

```
newVertex = (oldVertex.y, someFunc1(oldVertex.x, oldVertex.y), someFunc2(oldVertex.x, oldVertex.y));

```

As far as I know (FIXME) Surface of Revolution means rotations of a (2D)curve around an axis in 3D. But this vertex computing gives a 3D plane (FIXME again :D), so rotation of this isn't obvious.

Am I misunderstanding something?

# Answer
> 1 votes
I guess the 2D "curve" is given as a polyline with `oldVertex` vertices. Rotating the curve around an axis should result in appropriate 3D vertices where each old vertex creates a loop of new vertices given an angle-step.

The other possibility I imaging is rotating given 3D vertices according to their x/y components, ignoring z. That would involve some dot- and crossproducts but you example code doesn't make a lot of sense in that case.

Are you sure you got all those x/y/z parts right?

---
Tags: mathematics
---


title: Are there any open source CCG projects?

text:
# Question
Title: Are there any open source CCG projects?
I'm having trouble finding any well-developed open source Collectible Card Game projects.

I want to find projects to learn from and port to a mobile platform.

# Answer
I'm one of the devs behind WTactics.org and would of course recommend our project over Forge as it's open, while the other is written to play Magic: The gathering against an A.I.

Art wise we have plenty and more to come since we hire artist(s). Code wise we have plenty of things cooking, like for example local client, a browser based version and card also online development tools.

Personally I wouldn't ever recommend anyone to play a CCG on a small mobile device, but I guess that's just my own preferences.

Anyways, a safe bet would be Wagic, if you, again, don't care much about it being a MtG centric AI. The good thing with it is that it even runs on a PSP, which I think is already more mobile than *perhaps* Forge is.
> 7 votes

# Answer
http://wtactics.org/ Has nice card art assets already
> 4 votes

# Answer
I've found nice one - Forge card game
> 3 votes

---
Tags: open-source, card-game
---


title: A few questions about entity states

text:
# Question
Title: A few questions about entity states
This is the first time I'm trying to make a 2D game, so I'm having quite a few difficulties in getting things right. Right now I'm trying to figure out exactly how the entity state machine should work.

**1. I noticed entity states are... well, stateless.** Basically, they just act on the data in the entity accordingly, they hold no data of their own. When an entity forwards events to its states it does it like this:

```
void Entity::handleEvent(const Event& event)
{
     // We pass this to the state so it could act upon the data in
     // the entity in a manner appropriate for the given event.
     state_->handleEvent(event, this);
}

```

That means that I don't really ever need more than one instance of a particular entity state; doing something like `entity.setState(new StandState)` is therefore highly wasteful. Then again, making each entity state a singleton hardly seems appropriate. What do you suggest I do?

(*The same can be said about game states, so whatever the solution to this is, I guess it can be applied to game states as well.*)

**2. The state of the entity sprite.** Most of the time, whenever the state of the entity changes, the sprite that is used to represent it must change as well. How should the entity representation be notified of the change in state?

Then again, should it be notified at all? It seem that if the representation needs to be made aware the entity has changed, then it (the representation) starts having an internal state. I would much rather have it stateless so that I require only one instance of every representation (just as before).

---

**Edit:** How the Entity and its sprite interact in my current setup.

```
class Entity
{
  public:
    void handleEvent(const Event& event);
    void render(Surface* surf, unsigned long currentTime);
    // void update(unsigned long currentTime);

  private:
    // The representation holds the actual sprite.
    EntityRepresentation* representation_;
};

void Entity::handleEvent(const Event& event)
{
    // The representation changes its internal state depending on the event.
    // This means a representation can only be used for a specific entity,
    // and thus may be wasteful.
    representation_->handleEvent(event);
}

void Entity::render(Surface* surf, unsigned long currentTime)
{
    representation_->render(surf, currentTime);
}

```

# Answer
Well, for the first one, you could just make a state that has a static public member function handleMessage(), and then you don't really need to define any internal data. That would make states exceedingly cheap to allocate, as they would basically just be wrapped function pointers. For that matter, you could just have a global array of function pointers for those states (very C-ish way of handling this issue).

As for the second, it sounds like you have things backwards: the *entity* should notify the *sprite*, not the other way around. So, just have a setAnimationFrame() or whatever function exposed by the sprite, and let the entity call that as needed.
> 2 votes

---
Tags: c++, state, entity-system
---


title: Where should input be used?

text:
# Question
Title: Where should input be used?
I'm working on an input system (in C#) and now I'm wondering, what is the best place to put input functionality?

Currently what I was coding was a bunch of delegates which act as callbacks (i.e. onkeypress, onmouseclick, etc) and the idea is when the input manager checks for input it invokes these delegaetes.

However this means that input is updated when the input manager updates and not when a game class has its own update function called.

The way I see it is moving input functionality out of a classes update function and deferring them would forecefully reduce the codes complexity (particularly the update function) but on the other hand I'm thinking it might be a better idea to move update and input to the same place as it would give the coder more freedom to work with the input systems.

Anyone have any ideas on this matter?

# Answer
> 3 votes
This answer implies using the xna framework with c#.

I generally create an input manager class that has its own update method to update the current state of the keyboard/mouse/gamepads. I create an instance of this class and register it as a service so it's available to any class in the game.

At the beginning of the game's update, I call the inputManager's update. At this point the current & previous states of the keyboard, mouse, & gamepads are available to all classes that can access services.

My input manager also has stand alone methods to check for key or button presses and/or clicks which can also be accessed from anywhere and can pass in whatever key/button they are concerned about.

# Answer
> 4 votes
I'd recommend a good clear separation of input and the rest of your game. I'd also recommend a layer that allows you to map different inputs onto different results (i.e. press key A maps to Left, S to Right). If you tightly couple the game with the input you won't easily be able to handle people remapping keys to suit their tastes, you also would have trouble adapting to maybe using a controller (i.e. 360 pad) instead of the keyboard later, or even being able to use something like Kinect to control input with enough abstraction.

In a driving game for example, I would have something that parses the current input state from the device currently in use (i.e. keyboard, pad, wheel, etc) and use the values I retrieve to build up a structure more suitable to my specific need, i.e. turn the values I parse into a steering value, an accelerator pedal, a brake pedal, etc. This structure could then be passed around to systems without having to worry about what input method had generated these values or whether they used analogue sticks, d-pad or keyboard.

---
Tags: game-design, c#, architecture, input
---


# Question
Title: Blender books for advanced character animation and modeling?
I've been messing with Blender on and off for over a year, and am now ready to put a lot of sweat into making a great model for an iPhone app I'm working on. I want to learn tips and tricks on how to make great looking models and how to animate them as well.

I know how to do key-frame animation, I just want to learn how to do it well. For instance, I have made a model that walks, but I want to improve it. I want to learn how make its movements realistic.

Does anyone have any resources that could help me with this?

# Answer
http://www.blendercookie.com/2010/05/13/game-enginecharacter-part-1/

This was very educational for me...
> 3 votes

# Answer
There's a book soon to be released for 2.5: Blender 2.5 Character Animation Cookbook

For 2.4 there is Introducing Character Animation with Blender:

but @stephelton recommendation is very good also.
> 1 votes

# Answer
I'm agree with the books recommended in other answers. I want to encourage to learn animation concepts that are universal and there aren't linked to no specific tool.

Animation is the process to give life to things. The movement is very bound to the life. The things that are dead not move. The unanimated things not move. The animation process is very hard and need a lot of experience to achieve good results. There are some small concepts that are essential to begin animating. The books of a tool normally forgive these concepts and focuses only in the use of the tool.

I recommend the book: "The Animator's Survival Kit" from Richard Williams that is a "must have" to every animator, that teach these concepts.
> 0 votes

---
Tags: animation, books, models, blender
---


# Question
Title: How to use XML files as content files in XNA?
I have an XML file representing different car manufactures that will be available in my game. The file looks like this:

```
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <Asset Type="List[string]">
    <car>Audi</car>
    <car>BMW</car>
    <car>Nissan</car>
    <car>Volvo</car>
  </Asset>
</XnaContent>

```

When adding it into my content folder, the compiler return this error:

```
There was an error while deserializing intermediate XML. Cannot find type "List`1"

```

How can I create a list of strings, put it into XML and read it from XNA?

# Answer
> 14 votes
I haven't tried to find out exactly what is wrong with your XML - it's probably the lack of a namespace. **But here is the correct XML:**

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Generic="System.Collections.Generic">
  <Asset Type="Generic:List[string]">
    <Item>Audi</Item>
    <Item>BMW</Item>
    <Item>Nissan</Item>
    <Item>Volvo</Item>
  </Asset>
</XnaContent>

```

Under the hood the `XmlImporter` uses the `IntermediateSerializer` class. So a small program like the following can be used to determine what your XML *should* look like:

```
var test = new List<string>(){ "Audi", "BMW", "Nissan", "Volvo" };
var sb = new StringBuilder();
using(XmlWriter writer = XmlWriter.Create(sb))
{
    IntermediateSerializer.Serialize(writer, test, null);
}
Console.Write(sb.ToString());

```

(You can even convert the output to a stream, pass it to the `Deserialize` method, and reconstruct the object - just to be doubly-sure it's working. Also it is probably worth putting the right encoding in the header - eg: `StringBuilder` is utf-16.)

For some in-depth information about `IntermediateSerializer`, take a look at Shawn Hargreaves' blog, starting with this post and continuing through the archives until August 2008.

# Answer
> 0 votes
If you want to see how to do it by code example, here is a sample that uses xml like you want to http://create.msdn.com/en-US/education/catalog/sample/collision

If you want to read articles explaining whats going on and gain insight on how to work with xml & the content processor, go to this link, scroll down to the intermediate serializer section and read the 8 or 9 articles there. http://www.talula.demon.co.uk/blogindex.html

---
Tags: xna, xml
---


title: 2d Ray intersection

text:
# Question
Title: 2d Ray intersection
I've recently picked up a class which creates 2D Rays and detects if the ray is intersecting any bounding boxes passed through it.

```
public struct Ray2D
    {
        private Vector2 startPos;
        private Vector2 endPos;
        private readonly List<Point> result;

        public Ray2D(Vector2 startPos, Vector2 endPos)
        {
            this.startPos = startPos;
            this.endPos = endPos;
            result = new List<Point>();
        }

        /// <summary>
        /// Determine if the ray intersects the rectangle
        /// </summary>
        /// <param name="rectangle">Rectangle to check</param>
        /// <returns></returns>
        ///
        public Vector2 Intersects(Rectangle rectangle)
        {
            Point p0 = new Point((int)startPos.X, (int)startPos.Y);
            Point p1 = new Point((int)endPos.X, (int)endPos.Y);

            foreach (Point testPoint in BresenhamLine(p0, p1))
            {
                if (rectangle.Contains(testPoint))
                    return new Vector2((float)testPoint.X, (float)testPoint.Y);
            }
            return Vector2.Zero;
        }

        // Swap the values of A and B

        private void Swap<T>(ref T a, ref T b)
        {
            T c = a;
            a = b;
            b = c;
        }

        // Returns the list of points from p0 to p1

        private List<Point> BresenhamLine(Point p0, Point p1)
        {
            return BresenhamLine(p0.X, p0.Y, p1.X, p1.Y);
        }

         // Returns the list of points from (x0, y0) to (x1, y1)

        private List<Point> BresenhamLine(int x0, int y0, int x1, int y1)
        {
            // Optimization: it would be preferable to calculate in
            // advance the size of "result" and to use a fixed-size array
            // instead of a list.

            result.Clear();

            bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
            if (steep)
            {
                Swap(ref x0, ref y0);
                Swap(ref x1, ref y1);
            }
            if (x0 > x1)
            {
                Swap(ref x0, ref x1);
                Swap(ref y0, ref y1);
            }

            int deltax = x1 - x0;
            int deltay = Math.Abs(y1 - y0);
            int error = 0;
            int ystep;
            int y = y0;
            if (y0 < y1) ystep = 1; else ystep = -1;
            for (int x = x0; x <= x1; x++)
            {
                if (steep) result.Add(new Point(y, x));
                else result.Add(new Point(x, y));
                error += deltay;
                if (2 * error >= deltax)
                {
                    y += ystep;
                    error -= deltax;
                }
            }

            return result;
        }
    }

```

Based off this class I'm cycling through every tile in the level to determine if the ray has indeed intersected with any of the boxes and then move on from there

```
camToChar = new Ray2D(lensPosition, level.Player.Position);
            // For each potentially colliding tile,
            for (int y = tileMap.GetHeight(); y <= tileMap.GetHeight(); ++y)
            {
                for (int x = tileMap.GetWidth(); x <= tileMap.GetWidth(); ++x)
                {
                    TileCollision collision = Level.GetCollision(x, y, tileMap);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);

                        Vector2 depth = camToChar.Intersects(tileBounds);

                        if (depth != Vector2.Zero)
                        {
                            clockwise = true;
                        }
                    }
                }
            }

```

The problem is that despite the fact the ray should be passing through bounding boxes, the intersect method never gives this result. I'm trying to determine if it is an issue with either the 2DRay class or the way I've constructed method to use it.

Any help with this would be greatly appreciated.

# Answer
> 2 votes
There may be a bug in this line:

```
for (int y = tileMap.GetHeight(); y <= tileMap.GetHeight(); ++y)

```

Maybe it should have been:

```
for (int y = 0; y < tileMap.GetHeight(); ++y)

```

# Answer
> 1 votes
Bresenham line algorithm is not intended to collision detection tests. It is intended to discretize and achieve an aproximation to draw lines on the screen. With bresenham accuracy is being lost.

To collision tests you can use geometric equations. In this case the bounding box can be separated in four segments and check if any of the segments intersects with the ray ( other segment ).

I write you a code to this test in C++, sorry but I'm not familiarized with C# but the conversion must be very easy.

```
float signedTriangleArea( const vector2df& pointA,
                          const vector2df& pointB,
                          const vector2df& pointC
                        )
{
    return ( pointA.X - pointC.X ) * ( pointC.Y - pointB.Y ) - ( pointC.Y - pointA.Y ) * ( pointB.X - pointC.X );
}

bool testSegmentsIntersection( const vector2df& pointA,
                               const vector2df& pointB,
                               const vector2df& pointC,
                               const vector2df& pointD
                             )
{
    float a1 = signedTriangleArea( pointA, pointB, pointD );
    float a2 = signedTriangleArea( pointA, pointB, pointC );

    if ( a1 * a2 < 0.f )
    {
        float a3 = signedTriangleArea( pointC, pointD, pointA );
        float a4 = a3 + a2 - a1;

        if ( a3 * a4 < 0.f )
            return true;

        return false;
   }

```

The triangle area is useful because the sign of the function can determine if a point is on the left or on the right of a segment.

# Answer
> 1 votes
Another alternative is to use XNA's built in Ray class and BoundingBox class. Although they are typically used in 3d, often (as in this case) you can simply set their Z components to zero and utilize them in 2d as needed. It seems to me that that would achieve a dramatic simplification to your code.

---
Tags: xna, c#, collision-detection
---


# Question
Title: How can I make space recognizable and easy to orient in?
I'm thinking about making a game set in space, that would feature very large, procedurally-generated game world (many stars, planets and what have you). However, I foresee a big problem: cosmic space is mostly featureless. It's almost the same everywhere - the same black emptiness with stars. This is obviously bad. A large game world must be different in different places, so that the player can understand where she is, and how to get where she needs. What can I do to make different, recognizable places in space?

The game I'm envisioning is 2D (a bit like Space Rangers), with space pictures used only in background. However, I'm interested in any techniques, 2D or 3D.

**Clarification** What I need here is not just ability to orient in game space, but rather having *different* places so that the game feels more interesting. Here's an example: imagine any space-trading game (like Elite or X or whatever). You visit different star systems, but they're all generally alike: a dock to repair/refuel, a shop to trade, a bar to take missions/contracts... Some Tau Ceti III differs from KZ'ish VI mostly by name.

I believe that every place, or at least most places that player visits should be different from each other, and immediately recognizable, so that player has a sense of wonder and discovery as she explores the universe. Of course, making every star system a full-fledged 3D level with its own visual style would work, but that's prohibitively expensive even for a big-budget game. Are there any other ways to achieve this wonder and discovery?

# Answer
Unfortunately, I can't remember where I read or heard this rule, so apologies to whoever gave it to me, but what I learned was *give the player at least three points of reference*.

The simplest form is a point for where the player was coming from, a point for where they're going, and a point elsewhere to help orient the other two points. If you want to encourage more exploration or have the player participate more in orienteering, they can be three arbitrary points. These features should be big - a distant nebula, a black hole, an asteroid cloud - and dominate the camera when the player is looking at them.

Three is a lower limit. You can go higher, but not much higher. If there's points of interest everywhere, they're no longer interesting. I suspect the ideal number is 3-5.

Play any open world game and you should be able to see this rule in action - Fallout 3, GTA, Assassin's Creed, WoW - from any given point on the map you'll see 3-5 major landmarks.
> 19 votes

# Answer
If differentiating your player locations is important to your game, perhaps you need consider alternative perspectives on the world.

The games you reference, and most common for the genre, are out-of-starship third-person perspectives. One alternative would be to take a first-person perspective at the trade depot, allowing the biology, culture (architecture, language, etc.) and surrounding environment (atmosphere, star light, etc.) take a more dominate role in your game.

In other words, if it is the space between is the boring/repetition parts, eliminate that and associated travel time from the player's experience.

If you're not willing to jump that far out of genre, some games have had success with color (star light and nebulous backdrops) and sound (radio noise from local culture, with possible interference from local celestial bodies).

---

**Edit:** Since you already mentioned "a dock to repair/refuel, a shop to trade, a bar", let me elaborate with some questions * How does star type and planet orbit relate to the habitable zone?
* How does this affect the planet's biosphere?
* How did the local species evolve in this environment?
* Did the traders evolve here? If not what in the environment brings them to this world?
* How does the biology affect the culture?
    + How large are the inhabitants, and how does that change the player's perspective.
    + What would they eat and drink? (Or more aptly, how would the player observe locals being served, since eating is probably not in the player's scope of interaction?)
    + How segregate or ingrained is the surround biology into the urban/trading post environment?
    + How is the biology adapted to the environment and the climate or weather?
* What is the architecture like?
    + What is the scale of the architecture? Caves or hobbit holes? Skyscrapers? Castles? Arcologies? Ring worlds?
    + What colors and shapes define cultural artifacts and architectural details?
    + What materials and technologies are available for buildings? Carved in rock? Built from glass or gold? Grown out of trees or crystal nanites?
    + What environmental protection/exposure is the architecture supposed to provide? Extreme weather? Radiation? Meteorites? Ocean-going access?
* What is the dominant economy, and how does this reflect in the values of the culture?
    + Mining? Agriculture? Trade? Science & Technology?
    + Are there different classes/castes/genders in the culture, and if so, who would the player be interacting with?
* How would local culture or customs influence communication, trade, contracts, and the surround social environment?
    + How do they feeling about outsiders, like the player?
    + How close is the player allowed to everyday citizens, and what obstacles are presented along the way? Security outposts? Quarantine isolation? Guarded at gun point? Or just invited to the local bar for drinks? Possibly showered with gifts to smooth business relations?
    + Is the culture more formal or informal? Does the player trade with an accountant like book-keeper, or to they haggle with a dock-hand at the space dock?
    + How is trade conducted? Free trade between private parties? Government run customs checkpoint?
    + Are the NPCs prone to gossip? Do they expect bribes? Are they supportive of the local authority, or prone to rebellion?
* In any of the above questions, is there any variety exposed to the player?
    + Are there multiple locations on a planet or in a system open to foreign trade? Are they located in different climates? Do they represent different nations? Do they share a world or social outlook?

These are just a handful of questions you can consider to differentiate the player experiences. Obviously it would be a huge undertaking to address all of them in a single procedural system, but a textual prototype might help you navigate them for what is important for your vision of the player's experience.

The beauty about using culture and biology to differentiate locations, is that you can also use it to ties different places together. A starfaring civilization will bring it heritage with it, which will allow a player to recognize the similarities, as well as the differences.
> 6 votes

# Answer
Most interesting places in space are in the middle of a galaxy. Most galaxies are flattened in some way and thus have a clear band of densely-packed stars forming a ring around the viewer's position. This will hold true for almost all positions within that galaxy. You can see plenty of examples from our own galaxy on Google Image Search.
> 4 votes

# Answer
What i'd use in a basic set:

* different background
* "landmarks"
* effects

I don't know how realistic it should be and which "dimensions" it should have, so you need to clarify most for yourself.

Ad background) I you say you're inside one galaxy, then you'll have

* some other galaxies flying around - add them to mark different "sectors" - galaxies can look pretty different from each other (form & color)
* The angle of galaxies can change (they're mostly flat, so it's a difference if you look at them front top/bottom or some side)
* If you're closer to the middle of your own galaxy, you'll have more densitiy when i comes to star systems and more brightness for light.
* close planets & suns from star system(s)

Ad "landmarks") You could use

* asteroids
* asteroid fields
* destroyed/abandoned ships or stations

Ad effects) You could take a basic set of colors and lightning effects (puls, etc.) and use different combination sets for

* unknown space animals (swarms) like whales in the sea
* satelites
* patroull or scientific drones
* plasma fields
* nebulars

This would allow a lot of combinations, so you wouldn't get into the trouble of having doublettes too soon. In every case i'd sketch your world down on paper and make soft transitions on the background/surroundings for places which are next to each other. So if solar system *a* is next to system *b* and *a* has green nebulars and blue pulsing plasma fields, i'd give system *b* one of both so it feels more "next to *a*".
> 4 votes

# Answer
I think that the best way to keep player's orientated is an on-screen mini-map.

All the RTS games that I play have mini-maps in a corner e.g. the top left corner.

The map typically stays "pointing north" and the angle of the user is shown with an arrow indicating direction etc.

In RTS games you can often navigate to somewhere hidden by the fog of war, which means the screen is blank. Yet users can use the mini-map, which is always visible, to understand where they are in relation to all the landmarks they know. Users don't get lost.

Elite had a map at the bottom, if I remember.
> 1 votes

---
Tags: game-design
---


title: Managing Game Entity coordinates

text:
# Question
Title: Managing Game Entity coordinates
In my Game I'm currently have "Scene Coordinates" which are the X,Y coordinates relative to a Game Scene.

In that Scene there are Game Entities, let's say there's a GameEntity **A** in x=100.0, y=100.0 ( scene coordinates )

Which is the best way to have "Entity Coordinates" so that from GameEntity **A** point of view, he's standing at x=0.0, y=0.0 with OpenGL transformations?

In that way if I apply something like

```
glRotatef(angle, 0, 0, 1)

```

The entity will rotate around it's own origin and not the scene "global" origin.

# Answer
The order of transformations in OpenGL is the opposite order than for DirectX. For DirectX its the SRT-Rule: Scale, Rotate, Translate - for OpenGL its: Translate, Rotate, Scale

```
glPushMatrix();
    // move entity to its position
    glTranslate(...);
    // rotate entity around its origin
    glRotate(...);
    // drawn entity
    DrawEntity();
glPopMatrix();

```

DrawEntity must render the entity using its local space coordsystem, they are fixed if there is no animation.

If that doesnt answer your question, please rephrase it and elaborate.
> 4 votes

---
Tags: opengl, matrix, entity-system
---


# Question
Title: Why are my 2D positions "off" after adding a camera transformation in XNA?
My game's source is on github.

I am following this tutorial to create a 2D camera. After I adding the transformation to the SpriteBatch, all of my positions seem to be "off" when I move the ship (and hence camera) away from the screen center.

Any idea what might be wrong?

# Answer
Since my other answer was incorrect, I deleted it, pulled your source and traced down the actual solution.

The issue is that your particle renderer never gets your camera's transform matrix. Here's how you can fix it:

Update your `ParticleManager.Draw` method to be the following (very slight change, just the passing of the matrix:

```
public void Draw(Matrix transform)
{
    foreach (KeyValuePair<string, ParticleEffect> effectPair in particleEffects)
    {
        particleRenderer.RenderEffect(effectPair.Value, ref transform);
    }
}

```

Then within your `ActionScreen.Draw` method, make sure to pass along the transformation matrix:

```
particleManager.Draw(cam.get_transformation(game.GraphicsDevice));

```

You might want to grab the matrix from the camera earlier in this method, so you don't end up calculating it more than once.

Now comes the annoying part - this alone didn't work for me. I'm guessing it's a bug in the Mercury Particle Engine 3.1. I ended up pulling the source of the current version of Mercury (from their trunk) and compiled it myself. After dropping those assemblies in, the trails and explosions were placed correctly.

For reference, I used Mercury Particle Engine.

I just looked into the mouse aiming issue and found a quick fix (may want to modify it long-term). In `Player.Update`, change this:

```
direction = position - mousePosition;

```

To this:

```
direction = new Vector2(Game1.SCREEN_WIDTH * 0.5f, Game1.SCREEN_HEIGHT * 0.5f) - mousePosition;

```
> 3 votes

---
Tags: xna, 2d, camera
---


# Question
Title: Which API for cross platform mobile audio?
This question focuses on the API's available on phones.

I'd been planning to use OpenAL in my game for maximum portability. It runs great on Linux so I can quickly iterate while developing as well as leverage the desktop's superior debugging tools.

However I've recently heard that Android doesn't support OpenAL well. Instead they've gone with an OpenSL ES library.

What I'm looking for is a free Audio library that I can use with minimal custom code on iPhone, Android, and my Linux desktop. Does such a library exists?

Some extra details:
The game is written in C++ with custom minimal front ends, e.g. ObjC for iPhone, Java for Android, and SFML for desktops. I'm using OpenGL ES for portability as iPhone doesn't support the more advanced OpenGL APIs.

# Answer
> 4 votes
I find OpenAL pretty convoluted for small things. What are your feature requirements? Because mine are pretty simple:

* load/close samples and music
* play/pause/stop music
* play samples
* dynamically change per-channel volume for each item being played

If your requirements are that simple, too, I suggest you consider sticking with whatever’s more convenient on the platform, at the cost of a few `#ifdef`’s. I usually use SDL\_mixer (despite its numerous shortcomings) on desktop systems, and the OS audio layer on mobile platforms.

You should have a look at ALmixer, which is basically SDL\_mixer done right on top of OpenAL.

# Answer
> 4 votes
You might want to check out fmod.

# Answer
> 3 votes
I have found it easier myself to put the playing of audio in the platform-specific code rather than trying to use a works-portably library to wrap it.

The discussion then comes what format to use. MP3 works well everywhere.

---
Tags: iphone, android, cross-platform, audio
---


# Question
Title: Is it OK to release the source code for your own Xbox Live indie game?
Between not being sure how to phrase my question for Google and not being a lawyer, I thought it might be easier to ask you guys. Specifically, I want to know if it's OK to sell an Xbox Live indie game while simultaneously distributing the source code and other assets via GitHub or something.

Edit: The Communist Duck asked "why not?" One reason I can think of is that Microsoft has a small stake in a game's sales. They are hosting the demo/full game, they might be dedicating an advertising slot to the game in their "latest" section, etc. It's true they get a cut of each sale, **but** they get nothing if everyone just goes and downloads the free version.

Anyway, it's not a matter of what is reasonable and logical, it's a matter of what the terms and conditions allow. I'm going to read through them regardless, but I was hoping someone already knew.

# Answer
> 6 votes
The only part of the FAQ I could see that came close to answering this is here. It states:

**Who owns the IP rights to the game I create? Can I distribute my game on non-Microsoft services?** You own the complete IP rights to your game, and you're free to distribute through any service of your choosing. However, we may provide incentives for exclusive distribution through Microsoft services.

Looking through the App Hub community forums it seems others have asked the same question and consensus seems to be it won't be a problem. For example, one person is already giving away the code for their game here.

As others have said, if you're still not sure on reading all of this then stay on the side of caution or consult a lawyer.

# Answer
> 3 votes
I'm not a lawyer, but why not? It's your code. Generally the reason people don't distribute commercial source code is because they lose profit.

Unless there's some weird part of Microsoft's licensing. **I would have a look at their terms and conditions on this.** I put this in bold because there could be some esoteric condition; see Joe Wreschnig's comment below.

# Answer
> -1 votes
If it's an IP(intellectual property) submitted on XBox Live it has to conform to the rules of submission, when you agree to a contract online to submit a game you are accepting and abiding by the bindings of that contract. If you change the terms of the contract **after** the fact, your basically violating the contract.

You can resolve this issue by:

1. not submitting the game to XBox Live.
2. writing a "similar" game ( in a language other than C#) and posting it on a site with no affiliations to XBox Live

---
Tags: xna, open-source, licensing
---