title: Atmospheric Scattering

text:
# Question
Title: Atmospheric Scattering
I want to add some nice atmospheric scattering to my 3D game engine but I am very concerned with conserving resources. I am not very familiar with how its done but can someone please give me some suggestions how to achieve this effect without using too many resources? For example, should I use precomputed or real time atmospheric scattering. Also is the effect worth it without HDR or is it practically needed.

# Answer
> 2 votes
HDR isn't always necessary. A lot of the time you can get away with compressing your output values in the pixel shader. Essentially you're just doing the tone-mapping in a single pass, so you have HDR rendering without a wide pixel buffer. This makes it trickier to know what values you should use for the tone-mapping, and certainly makes it tough to do a localised effect. However if you use feedback from the previous frame, you can adjust the values over time, and that can actually aid the visual effect as it looks like an eye adjusting to the brightness changes over time.

Doesn't work well with anything multi-pass, including alpha-blending, unless you special case those (if you're using alpha-to-coverage, it's not too bad, though you'll be linearly blending values which have been non-linearly mapped into RGB space).

# Answer
> 8 votes
GPU Gems 2 has a chapter about atmospheric scattering. It's available online at
https://developer.nvidia.com/gpugems/gpugems2/part-ii-shading-lighting-and-shadows/chapter-16-accurate-atmospheric-scattering
I have no experience with it so can't really answer your question further :o
Edited to add: GPU gems 1,2 and 3 (and the CG programming guide, which ain't bad either) are available in their entirety over at NVidia's site. They're pretty nice.

---
Tags: c++, opengl, software-engineering, rendering
---


title: Graphics for non-Graphics Designers

text:
# Question
Title: Graphics for non-Graphics Designers
Are there resources for programmers with little to no graphics design talent, but still want to make good-enough graphics for their own programs? I'm interested in both 2d and 3d computer generated graphics techniques, as well as free graphics repositories.

# Answer
> 11 votes
You just need to read this: http://www.lostgarden.com/2007/12/how-to-bootstrap-your-indie-art-needs.html

# Answer
> 4 votes
If you have the money, invest in yourself: buy a **drawing tablet**. Personally, I am a terrible artist, I just can't make good graphics, but it sure didn't help that I was stuck trying to do things with my mouse, sloppily drawing lines or clicking pixel-by-pixel. I can at least roughly sketch something that works, and my Wacom Intuos4 is amazing for that (but surely overkill if you ask a professional). The Wacom Bamboo tablets are "entry-level" consumer models with slightly less accuracy, but they start at $69 (Wacom store; you want one with a pen, not the $49 touch model) and would be just great. So if you are able to somewhat draw things by hand, try getting a tablet - it won't improve your art skills unless you work at it but it can at least make it easier for you to make crappy programmer art. :)

# Answer
> 2 votes
Seems to be a little vague.
You have 3 main options, I think.

1. Learn. The best idea in the long term.
2. Get someone to do it for you. The most flexible idea.
3. Get free off the net. The quickest idea.

1 is probably the best if you have plenty of time. It gives you an advantage for any future projects you do, and gives you a wider skillset.

2 is better if you need them to be higher quality, but exactly what you want. May take a while to find someone, without paying them.

3 is the quickest by far, but it isn't great because you have to make do with what you find.

# Answer
> 1 votes
If the game is good enough and web-based, you can release it without "proper" graphics and no-one will complain.

Desktop Tower Defense is a good example of this.

If it makes enough money you will be able to hire a team of professional artists to revamp it. But you might find the users still prefer the original version.

# Answer
> 0 votes
For 2D I know there are people that use existing spritesheets and pixel over their own graphics. Whether it's ethical is a debate in its own, whether your pixeling skills will make it look halfway decent is another, but you at least got your animation cycles covered.
If you do know any artists it sometimes works too show them a prototype with programmer art - it'll hurt their eyes so much that they actually offer to pixel you some assets.
A third option for 2D is to use a 3d model and render it with cartoon rendering. But there's still a lot of artistic skill involved getting the models looking and animating the way you want to. Not aware of any real shortcuts in that area.
A fourth option, that seems to work well is to go for a decidedly abstract or amateur look. Milk the fact that you can't draw and make it the theme of your game. The hard part is to be consistent in your chaos, which makes it a skill again.
I feel your pain - I can't draw my way out of a paper bag.

---
Tags: graphics, 3d, art
---


title: How to make a BattleShips game?

text:
# Question
Title: How to make a BattleShips game?
How do I make a Battleships game for the Iphone?

I'm new to programming, I've done some tutorials and I feel I'm making progress with this but I would like to make a full game like battleships.

Can anyone help me out with this?

I'm trying to learn cocos2d-Iphone so I would like to use that if possible. David

# Answer
Since you already started learning, why not go ahead and try to implement something? Maybe start with a simpler game-concept (like Tic-Tac-Toe) to get a grip of all the things involved (code, graphics, sound, etc.). Then post more specific questions here as you move along. Since your question is a bit "broad" to say the least.
> 4 votes

---
Tags: cocos2d-iphone
---


# Question
Title: How can non-indie devs stop reinventing the wheel?
It seems like the status quo in the games industry is to write most software in-house, maybe excluding the engine if you use one of the dozen or so big ones. Before working here I was mostly an open-source developer, so this mindset seems downright crazy to me. Is there any good way we can all stop building things like log viewers, network diagnostics, and patching systems?

# Answer
> 15 votes
We can stop reinventing the wheel by... ceasing to reinvent the wheel. Use external libraries, game engines, etc.

I get the sense that people *do* reinvent the wheel to:

* Avoid copyrights, royalties, etc on libraries or borrowed code
* Avoid paying for a game engine (for a full on AAA game, this can be enormously expensive)
* Maintain intimate familiarity with the entire codebase--adding external libraries, linking to game engines, etc just means more code to become familiar with and possibly maintain
* Writing all your code yourself means that you can optimize it specifically for your game
* That code can then be licensed to others if desired, reuse it for other projects, etc while you maintain proprietary control

# Answer
> 1 votes
It depends. I think there is actually a fair amount of middle-ware out there, that gets used, ... if you are willing to pay of it.

At the same time sometimes it is easy to hack something to get really fast without that many external dependencies, if the scope is small.

I think on the highend, you have to compare companies like EA and Ubisoft to other large software companies, like Apple, Google, Facebook, what have you.

They all write a very large amount of custom code, when there are existing alternatives, because they want to get a competitive advantage.

As @Sean James said there are legal reasons and host of other reasons, but I think even if there were no road blocks, inventive software companies would still develop custom alternatives to common existing software components if they thought they could make them better.

However I also agree that there is always room to start some projects we all could benefit from. For instance, I think we need to replace COLLADA with something much simpler that is JSON based. Maybe something that only handles arbitrary meshes, but nothing else. I think we really need a better mesh format.

# Answer
> 1 votes
> Is there any good way we can all stop building things like log viewers, network diagnostics, and patching systems?

In my experience, these things are treated as simple extras that can be bolted on alongside your 'real' programming. Of course, they turn out to be far from simple and far from 'extra', being complex and important parts of the system, but by then there's already too much investment in the bespoke version.

Are there good open-source or commercial libraries that provide this type of functionality? I am not sure there are, and until someone steps up and provides one, it'll stay this way. The business developers often aren't able to produce libraries that are suitable for games ("*what, you mean you can't completely remove all the calls in a Release build?!*") and game developers are often uninterested in making this sort of thing as a standalone package when they have a game to be getting on with.

---
Tags: open-source
---


# Question
Title: Where can I find articles/books on 2D graphics (how it works etc.)?
After I have been through more intensive C++ studies, I am thinking of giving it a start in my practices of computer game programming. Therefore, I think 2D knowledge (processing images, animating frames, etc.) would be a good place to start. However, I don't seem to find many articles on 2D (mostly 3D), and if found one, it is mostly stuffs like how to use a 2D game engine. I would really want something much more low-level, or "from scratch" ideas.

I want articles/books that would answer something like:

How would I import images into C++? (Let's say, if I want to import jpeg/bmp/etc. file into raw C++ code, what would I do?)

Basically, I just want to have enough low-level knowledge about computer graphics to be able to create something like 2D game engine from scratch.

# Answer
SDL would be a good place to start. Here is a link to some general articles on beginning 2D game design: http://lazyfoo.net/articles/index.php

On that same site they have a pretty complete tutorial set that will show you everything you need to know to program a basic 2D game. http://www.lazyfoo.net/SDL\_tutorials/index.php

The reason I really like this tutorial is that it really breaks it down for you into readable code. It also introduces how to incorporate OpenGL which is a much more powerful library.
> 2 votes

---
Tags: graphics, 2d
---


# Question
Title: How would one determine the position of a participant in a racing game?
Now, for the record, I'm currently not implementing any racing game whatsoever, but this problem just popped into my mind and now I'm curious.

So how would one go about finding out which participant of a race is currently the first one? It can't be something trivial like just sorting by distance to the finish line because that would be highly inaccurate on most courses. I've thought about doing something like separating the route into straight segments, each of which has a direction vector. The game would then check for when someone outruns somebody else by projecting their positions onto that vector and checking which one is ahead. If the position has changed, the game would increment/decrement them appropriately. But that does seem a little too complicated.

Does anybody know of any established methods or has any experience in implementing some?

# Answer
> 12 votes
Shawn Hargreaves describes how MotoGP used a special track-relative position system. Ignoring the vertical y position, the x/z Cartesian coordinates are translated to a track-relative system. This had many benefits for calculations involving the relative positions of participants in a racing game (for example for the AI):

> A common simplification is to collapse 3D into 2D. Even though rendering and physics may be truly 3D, decision making logic need not treat all three axes equally. MotoGP tracks have few hills, so our AI was able to ignore the y component.
>
> Next, we switched from x/z cartesian coordinates to a track-relative system. Positions were represented by a pair of values:
>
> int distance = how far around the track, stored in 16.16 fixed point format
>
> * 0 = starting line
> * 0x8000 = half way around
> * 0x10000 = looped back to the start
> * 0x1C000 = three quarters of the way through the second lap
>
> float cross = how far sideways across the track 0 = on the center line
>
> * -1 = left edge of racing surface
> * 1 = right edge of racing surface
>
> To convert between this and the cartesian coordinates used by our physics and rendering code, we stored a list of segments defining the shape of the racing surface: struct TrackSegment { Vector CenterPoint; float DistanceToLeftEdge; float DistanceToRightEdge; }
>
> We created several hundred of these structures, spaced evenly around the track, by tessellating the Bezier curves from which the tracks were originally created. This gave us enough information to write the necessary coordinate conversion functions.
>
> With track-relative coordinates, many useful calculations become trivially simple:
>
> ```
> if (abs(cross) > 1)
>     // You are off the track and should steer back toward the center line
>
>
> if (this.distance > other.distance)
>     // You are ahead of the other player (even though you may be
>     // physically behind in 3D space if you have lapped them)
>
>
> short difference = (short)(this.distance - other.distance);
>
> if (abs(difference) < threshold)
>     // These two bikes are physically close together,
>     // so we should run obstacle avoidance checks
>
> ```
>
> Because of the fixed point data format, casting the distance counter from 32 to 16 bits was an easy way to discard the lap number, so we could pick and choose which computations cared if two bikes were on different laps, versus wanting to know if they were close in physical space. Thanks to the magic of two's compliment, treating the difference as signed 16 bit gives the shortest distance regardless of which bike is in front (remember that in a modulo arithmetic system such as a looping racetrack there are two possible distances, as you can measure in either direction around the track). This works even when the two bikes are on opposite sides of the starting line, a situation which would require error prone special case logic in most other coordinate systems.
>
> Flattening and straightening out this virtual gameplay area made it easy to reason about things like "am I on the racing line?" or "I'm coming up fast behind this other bike: do I have more room to pass them on the left or right?" which would have been tricky to implement in a full 3D world space. Once we decided to pass on the left, we would convert the resulting track-relative coordinate back into world space, at which point the curvature of the track gets taken into account, showing how we should steer to accomplish our chosen goal.

# Answer
> 3 votes
I guess I would use the fact that the road is generally built up by using splines, therefore every edge of the road has a corresponding spline position, and using that you could determine (approximately, or fine grained if you subdivide further) what the current spline position of each car is, and thus who is in the lead. So more or less the way you suggest, just using the spline.

# Answer
> 3 votes
You've more or less answered your own question, I think. Divide the track up into segments, track which segment each car is in, and project the cars onto a line through the middle of the appropriate segment (mathematically it's a simple dot-product, so not complicated at all). Very simple to give each car a "distance" which you can sort for position.

The segments give you some additional benefit - you can ensure that cars don't cut-corners (or general take short-cuts), go backwards, or other cheats.

---
Tags: algorithm, racing
---


# Question
Title: How can I improve the "smoothness" of a 2D side-scrolling iPhone game?
I'm working on a relatively simple 2D side-scrolling iPhone game. The controls are tilt-based. I use OpenGL ES 1.1 for the graphics. The game state is updated at a rate of 30 Hz... And the drawing is updated at a rate of 30 fps (via NSTimer). The smoothness of the drawing is ok... But not quite as smooth as a game like iFighter. What can I do to improve the smoothness of the game?

Here are the potential issues I've briefly considered:

* I'm varying the opacity of up to 15 "small" (20x20 pixels) textures at a time... Apparently varying the opacity in this manner can degrade drawing performance
* I'm rendering at only 30 fps (via NSTimer)... Perhaps 2D games like iFighter are rendered at a higher frame rate?
* Perhaps the game state could be updated at a faster rate? Note the acceleration vales are updated at 100 Hz... So I could potentially update part of the game state at 100 hz
* All of my textures are PNG24... Perhaps PNG8 would help (due to smaller size etc)

# Answer
I'd recommend using CADisplayLink to manage your loop rather than NSTimer. It's synchronized to the screen refresh.

Are you updating your graphics positions on the screen at a fixed interval or is their movement based on the time elapsed since the last update? Occasionally the iPhone stutters, if you don't take account of it the animation can look jittery.
> 4 votes

# Answer
30fps is probably your problem?

Some/many people will try to tell you that 30fps is just fine. But really, it's not. While 30fps is certainly 'playable', it's never going to be 'smooth', especially for a fast-moving 2D scroller, and especially to any games enthusiast that's had a taste of 60fps.

2D games on 16bit consoles and arcade machines ran at 50/60Hz for a very good reason — it looks far, far smoother than 25/30, *especially* for 2D scrolling games. Back then, 60fps was almost the definition of 'arcade quality'. These days, many developers are prepared to sacrifice that smoothness for better image quality (better screenshots) or shorter development time (less time-consuming optimization work).

Unfortunately, I can't help with the iPhone specifics. I get the impression that 60fps on iPhone/Android isn't easy to achieve — although a few do manage it. (The iPhone port of Pinball Dreams being one example.)
> 4 votes

# Answer
I hate to be nitpicky but....wouldn't trying your suggestions answer them? Like PNG8 vs 24....give it a shot? Convert them after loading and see if things improve?
30fps should be smooth enough for a game, but my experience has shown that you have to be very careful (at least on my 2G testphone) to actually maintain 30fps....I'd get a spike every half a second or so throwing me one frame off, so it is crucial that your code is framerate independent. Have you verified that you don't have those spikes?
> 2 votes

# Answer
Another thing to watch out for with 2D scrolling games:

Are you scrolling a nice constant number of pixels per frame?

If you're scrolling 2 pixels one frame, then 3 the next, then 2, for example, that will add a bit of judder. If you're working with a 3D API, and scrolling some arbitrary speed, like 2.73 pixels per frame, that may add sub-pixel 'wobble'

If you are able to target a fixed framerate, try to ensure that the character's walk/run speeds are a whole number of pixels-per-frame.
> 1 votes

# Answer
Don't trust the 60Hz hype - it is partly misinformstion. 30fps is perceived as smooth by the human brain (anything over 18fps is perceived as motion) - movies have been shot at 24 fps for the majority of the past century without people thinking they were not smooth. There is one caveat though - the interpolation has to be correct. If your timestep is not compensated properly the glitvch will break the illuision, even at 60fps - this is something that movies obviously never suffer. The only difference between 30fps and 60fps (given proper interpolation) is streakiness, since the brain will internally also try to blend the frames, and compensation for the fact (less of an issue with LCD) that the frame slowly fades between every redraw out and thus you see a wobble. Regarding the streaking: An eagle's eye registers frames at 2Hz, so when it sees a mouse running on the ground it sees a dot at place a, a dot at place b and the brains interpolate this to a line, which is why it can see the mouse from such height - streaking.
The only thing that 60fps gives is that, if your interpolation is not done right, the glitch is less and thus less disturbing to the perception of smoothness.
> 0 votes

---
Tags: graphics, iphone, opengl-es
---


# Question
Title: What language was used to write Starcraft II?
Total newbie question, but what language was used by blizzard to create the Starcraft II gameplay? I've been playing it for the last couple of days, and I'm constantly astonished by the complexity and the performance of the game. Is it an in-house language, or do they use some flavour of a known language?

# Answer
> 4 votes
The actual game itself uses a combination of C, C++ and XML (for metadata).

The scripting language used called 'Galaxy'. It's a C-based language built into the game engine.
It's used in the campaign and in custom maps.

# Answer
> 11 votes
The Map Editor is where 'Galaxy' is coming from (Galaxy Editor). It's a data driven editor which allows you to put together actions from English statements which really opens up an insane amount of possibilities. For example, attaching Thor cannons to a hydralisk is easy cheesy.

* Create a Hydralisk object and modify attributes on it to give it the abilities you desire
* Trigger - 'Create 1 Hydralisk for player 1 using default facing'

Take a look at this video tutorial that show off the trigger editor. Here are some good tutorials to get you started.

The game itself was written in C/C++.

# Answer
> 8 votes
I assume you meant *scripting* language? (since programming language-wise, I'd be very surprised if they didn't use C++...)

A quick Google-ing turned this up:

> "StarCraft II uses an entirely new scripting language, which we’ve called Galaxy. This language is very similar to C, and anyone familiar with programming in C will have no trouble picking it up. "

---
Tags: software-engineering
---


# Question
Title: How can I improve or replace my programmer art?
Say I'm a programmer who has done his own sprites or 3d models which would fall into programmer-ish kind of art. What steps can I take in order to improve or replace my own art?

# Answer
1) If you want to improve try putting up your work on specialized sites like http://www.polycount.com/forum/

2) If you don't have time or *insert reason here* go to recruiting sites, here are a few to get you started:

http://forum.unity3d.com/viewforum.php?f=11

http://www.polycount.com/forum/forumdisplay.php?f=44

http://www.moddb.com/forum/board/recruiting-resumes
> 5 votes

# Answer
http://opengameart.org/ its a nice resource too.
> 6 votes

# Answer
The best way of having your programmer art replaced by real art is to carry on making a great game.

Pimp your game as often as you can - concentrate of game mechanics first - then I am sure that you'll attract some artist types - maybe even for free (join the team).

This approach is probably the only one if you're short of cash, and/or want to stay free.

Programmers art could make sure that you concentrate on the most important aspect of your game: the game itself.

There are of course places where you can grab models and art under an open license, but I would just carry on making a game if I were you.

Don't bother spending too much time trying to learn how to be an artist yourself.

That skill takes years..
> 5 votes

# Answer
You could try making more art. The saying 'practice makes perfect' is probably applicable here.
Or, you could advertise on a site such as Gamedev's Help Wanted Forum for an artist, saying that you've created such and such a game, with your programmer art, and looking for a improvment to the graphical quality.
The other way is to get free images, textures, and models from many sites on the internet. However, these aren't necessarily what you want. Option 2 is probably the best way, unless it's more of a learning project (not for release).
> 2 votes

# Answer
I would recommend you to search a skinner and/or 2D Artist who is skilled and can create that kind of art. This is a good forum i remember, where like just skilled artists are grouped :) You could search at Deviantart too, but there it's imo more complicated.

Or you try learning it in a professional way, but that is exhausting...
> 1 votes

# Answer
Go to forums. Artists need you as much as you need them.
> 1 votes

---
Tags: graphics, art
---


title: GLSL shader without a vertex array

text:
# Question
Title: GLSL shader without a vertex array
Ok so I have a idea for a neat GPU driven curve renderer, and I realised that the vertex shader can be hardwired to generate points of the curve segment (to be rendered as a line strip) without sending any vertex positions - `gl_Position` could be set completely procedurally.

That said I'd still need to specify a "t" value per point via vertex attributes.

Is it possible to specify attributes (ie via `glVertexAttribPointer`) without specifying vertices? Or does the GL need "space" in the buffers for vertices - even if they aren't initialized.

# Answer
Sure, modern GL doesn't have any such limitations, just pass the correct data to glVertexAttribPointer, 1D vertex attribute is supported.

Think about it, using glVertexAttribPointer, where do you say to the GL that this data are vertices? Nowhere, it's generic, any implementation should accept any data you pass.
> 5 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: Storing game objects in multiple containers
In the light of DRY, it seems desirable to store a collection of related game objects in one container only. However, one might need sub-collections of these objects in various contexts. It might be sensible store these specific sub-sets in specific more suitable containers. This increases the effort to track objects across containers, for instance when objects are removed from the game world.

What are possibilities to simplify such a design and what are the typical trade-offs?

**To illustrate:**

In a multiplayer role playing game, the server might hold a collection of game characters in a map suitable for lookup by id.

```
world
    map<id, Character> allCharacters

```

A character may also reside in a certain game level. In order to identify all characters being present in a level it may seem suitable to introduce a container for each level which holds the characters currently present on it. This way you can execute common logic for all characters in that level.

```
world
    map<id, Character> allCharacters

    [levels]
        level1
           vector<Character> charactersOnPlayfield
        level2
           vector<Character> charactersOnPlayfield
        ...

```

Going even further, when a character interacts with the world messages should only be routed to characters in range. This interest management could be achieved by dividing the each level into a grid of cells each of which in turn store the characters currently standing on it.

```
world
    map<id, Character> allCharacters

    [levels]
        level1
           vector<Character> charactersOnPlayfield
           [cells]
               cell1
                   vector<Character> charactersOnCell
               cell2
                   vector<Character> charactersOnCell
               ...
        level2
           vector<Character> charactersOnPlayfield
           [cells]
               cell1
                   vector<Character> charactersOnCell
               cell2
                   vector<Character> charactersOnCell
               ...
        ...

```

The Character objects at different levels of abstraction introduce the need to think carefully about object ownership and life-time.

Note that the Character objects stored in the containers would naturally be references, not copies. Also, I am assuming that no garbage collection is in place.

# Answer
I would advice against actually having multiple lists like that and instead use some kind of signal/slot library instead (which basically is the observer pattern) to make the "calling a function on all objects in this area/zone" pattern easier.

Objects could manage what signal they connect to themselves pretty easily, i.e. every time they move they disconnect from the signal representing their old slot and connect to the new one, if you're going to be that fine grained.
> 6 votes

# Answer
Every Character should, one way or another, know all the containers it's contained in. That can be explicit (an actual list of the containers that reference it), computable (the character coordinates are stored, from which the actual cell vectors can be derived), or unspoken ("characters might also be stored in any of these six lists and I'm not going to bother keeping track of which"). Or any combination of the three. The important part is that it's easy and efficient to find every location that looks at a character.

There should also be a canonical storage that stores every character in the game, such as your allCharacters map up there.

A character is alive if and only if it's contained in allCharacters. If you want to remove it from allCharacters, you remove it from every container that contains it also (which, as per first paragraph, should be reasonably efficient) and you're set.

This assumes you don't have garbage collection - if you do, you can mostly get away with letting the GC take care of it. If you end up with leaks, just make a weak-reference container holding every entity, and use that for analyzing which entities are leaking.
> 3 votes

# Answer
In answering my question from the experience I had so far, I basically see these options:

Extract your more specific collection of objects from the more general collection each time you need it

* pro: central object repository
* con: computational overhead

Store your more specific collection in specialized containers as provided in the example for this question

* pro: quick lookup / pre-sorted data
* con: more involved tracking of objects

Use caching for certain perspectives on / sub-sets of the game objects

* pro: middle-ground between 1 and 2
* con: need to devise caching strategy which can complicate matters

---

Factors for choosing one of these options include

* how often is the specific collection of objects required
* what is the cost for tracking the objects across the multiple containers (it might just be relevant in case of object removal)

The observer pattern can help to propagate the need to change the other sub-sets of objects.
> 2 votes

---
Tags: architecture
---


title: UI design examples?

text:
# Question
Title: UI design examples?
I am not asking the theory of UI design, or how to do one, I am asking for examples and resources, like... How to draw this fiddly stuff, or how to code another circular thing, or a gallery of game menus, etc...

I am seeking myself specifically sci-fi stuff, but no problem putting other stuff, references are never enough!

EDIT: I am neither looking logic code, neither software tutorials... I am looking for stuff like this:

"Oh, there are this cool GUI on castlevania: http://xbox360media.ign.com/xbox360/image/article/759/759732/castlevania-symphony-of-the-night-20070130115858695.jpg Where the gui looks like made of bone, and it is shown on on the screen by drawing a rectangle textured with the blue bar, and then a transparent bony image is drawn over it..."

Got it now?

# Answer
> 2 votes
Menu display for a RPG game tutorial
Tuning dial/knob in photoshop guide
Sci-fi type loading wheel thing :P

# Answer
> 0 votes
Gimp Tutorials will show you how to draw stuff.

---
Tags: graphics, gui, interface, ui-design
---


# Question
Title: Splitting into files - how much splitting?
If I say I have a hierarchal entity framework, rather than a component model. Something like:
(Yes, this is made up)

Weapon-\>Gun-\>AutomaticGun-\>MP44
Or, more of a classical example:
Entity-\>MovableEntity-\>Enemy-\>WalkingEnemy

How far would you split up the source/header files for readability and organization? Is it best to go something like Entity.cpp, MovableEntity.cpp, Enemy.cpp, etc. or would an approach like Entity.cpp \[containing Entity and MovableEntity\] and Enemy.cpp \[containing Enemy and WalkingEnemy\] be better? (Or in a more language agnostic way, an Enemy file and an Entity file vs a file for each class?)
Also, would this affect anything other than readability and organization?

# Answer
This is entirely a matter of preference. However, I personally believe it is best to err on the side of more files. **Java requires one class per file**, with the filename the same as the class name, for example; they do this by policy to enforce this good practice (though you can have subclasses which basically get around this).

Also, **source control systems** are pretty good at merging changes in a file, but it's less of a hassle if you're just working in totally separate files. You can also easier see who changed which class. Let's say another developer makes a change to the file AllEntities.h; you have no clue exactly what entity (or entities) he changed until you open the file and look at the diff output.

It's great to **group small structs and enums related to class within one class's file**, though. If you have an enum that's only used by a single class, why split it into its own file? Just put them together. But if it's used by another class (i.e. another class member is of this enum's type), that's when it is time to give it its own file.
> 12 votes

# Answer
Many languages outside of C/C++ impose constraints on files. Ricket mentioned Java's 'one class per file'; Python uses files as namespaces; other languages often copy the spirit of those.

If you are using C or C++, more included files generally means longer compile times per file; on the other hand, fewer means more to recompile when making small changes. Because enumerations cannot be forward-declared in C, you should always put them into header files containing only other enums, for dependency sanity.

Otherwise, Java's "one file per class" is reasonable, but for a long time Java has supported inner classes - like a container, and an inner class of its iterator. Similarly in any other language you'll probably want one dominant record/struct/class/type/interface/blorb per header, but may decide to include related helpers or containers as well.

(You don't need to use a component model, but if you have a deep and specific class hierarchy like that, you are going to hate yourself later.)
> 2 votes

---
Tags: c++, file
---


title: Procedural Generation of Infinite Level

text:
# Question
Title: Procedural Generation of Infinite Level
**What are some good approaches to procedurally generating an infinite 2d level?** The level could be constrained in either dimension but not necessarily.

The approach that makes most sense to me so far is using a grid-based radius. e.g. divide the play area into a grid with squares of a certain size and then load X squares in a radius around the player. Then when the player moves to another square build the next set and drop the farther (Persisting explored area is not necessary.) When a square is built, it contains a random arrangement of objects. When objects leave the outer ring of squares they are removed from the world. Are there better or different ways? Or if this is a good approach, what are potential issues?

For discussion's sake, you can think of the level as a top down asteroid field with power ups, etc scattered throughout.

# Answer
> 6 votes
A problem with "infinite" worlds is that your underlying coordinates might not be infinite. Sometimes, if the game slows down the player enough, it might not be a concern, because the time to reach the integer wrap around, for example, would be way too long to ever be reached. But if you allow for high differences in speed, you might need to be both very precise and very far reaching, that you would need to think about your coordinates. A reasonable fix would be to have two levels, such as the integer coordinates of your grid, and float coordinates in each grid referential.

As an aside, you might even be able to properly persist the layout of your world, by using the grid coordinates as a seed to create your random world in a given square. So, when the player leaves the area, you can drop it, and when the player comes back, you can regenerate it back from the seed.

---
Tags: 2d, procedural-generation
---


title: How to Create a Game?

text:
# Question
Title: How to Create a Game?
I'm a newbie. I like to play games, but I'd also like to program them too. I know it's difficult to create a game, but please share the basic info I need to get started creating my first game. What do I need to study to become a game developer? What is game AI? What is a Game Engine? What are the different types of game engine?

# Answer
The field of game design is a broad topic, but it's certainly possible for to get started with little prior experience. The first thing you need is an idea; you can find many good starting ones at this question.

From there, you should choose your platform and language/IDE. A good solid choice for PC development is XNA, and if you want to go web you can choose Flash (though that may cost money).

Then, you need to figure out the *design* of the game engine you'll write (i'd personally recommend an Asteroids clone). This includes figuring out how the main game loop is structured, what attendant classes to make, how you'll draw everything on the screen, etc. Your platform+language+ide choice may affect this, so make sure you know how to fit a design into the language you chose.

After that, you get to work. You map out the classes and start implementing features, using programmer art along the way. After a long time of this (if your design was good and you didn't give up), you should basically have a game.

Then you look for assets you can use, and tweak your game to use them. Finally, it's a good idea to get a few parties to playtest the game and get feedback (actually it's good to do this once you have something playable, not when it's done)

That's an overview of how you could do a 1-man simple 2d game, the process is much more complicated for larger teams and 3d games. The above is a good start for you though. For instance, if you hired an artist for your game, chances are you'd have him working at the same time you worked on programming the game, so you'd use his/her output as you get it.

As far as what Game AI and game engines are:

* Game AI is where you program the computer to play some part in the game, whether it's a computerized opponent in a strategy game, or the behavior of a space invader from Galaga.
* Game engine is a loose term used to refer to the collection of code which makes up the game and is compiled directly into a computer executable file (and possibly attendant DLLs).

and finally, Don't create an MMO till you're really good! :)
> 11 votes

# Answer
If you're completely new to game development and you just want to play around, I'd recommend starting with Game Maker.
> 6 votes

# Answer
Basically a game is composed of 3 things:

1. Game Design - your mecahnics, rules, goals and rewards
2. Game Assets - your graphics (2d or 3d) and sounds
3. Game program - program that consolidates everthing

Game AI- Artificial Intelligence, a program use to simulate control over actions of certain entities usually NPC's be it enemies or allies. This can be set by programmers or designers

Game engine - are a collection of tools (from frame works, middle ware etc.) to make games.

For better knowledge it would be good to check out articles at gamasutra.com as well
> 3 votes

# Answer
If you're new to game development but have programming experience I can really recommend Unity (http://www.unity3d.com).
It'll allow you to get something going pretty easily and as you settle in you can do more and more yourself, many things can be done very easily in Unity, but you can also get closer to the metal if you so desire. They have tutorials varying from Racing games to platformers and an awesome community.
It'll allow you to get going without grasping all the concepts and as you go you'll grasp more and more, and will have a tool to help you toy with them. As far as learning curves go, it's hard to get a smoother one than with Unity while still having the ability to create pretty much any kind of game.
> 2 votes

---
Tags: game-design
---


# Question
Title: How to deal with differences between 2D screen coordinates and Cartesian coordinates
* Most 2D screen/bitmap coordinate systems have the positive Y axis pointing *down* (with the the origin in the upper left corner).
* This is counter to how most people think geometrically with the positive Y axis pointing *up* (with the origin in the center).

**How do most games manage the two different 2D coordinate systems?** There are two main types of coordinates (screen vs. Cartesian), but there could be many different coordinate spaces: sprite space, world space, view space, screen space, etc...

**Background:**

I originally made the world coordinates in my game match the 2D screen coordinate convention. This made it very natural to use the graphics drawing routines, but subtle issues arose when using trigonometric functions like atan2(). The results of feeding atan2() 2D screen coordinates are very confusing because atan2() assumes the positive y axis points up.

So I changed my world coordinates to follow the classic Cartesian coordinate system (with the origin at the bottom left of the screen). Reasoning with atan2() is much more straight-forward, but now it is harder to do other types of reasoning:

* If I click the screen here, what sprite is underneath?
* Where did I click on that sprite?
* If a sprite is drawn in the wrong location, what was calculated incorrectly? The screen coordinates or the world coordinates?

I realize conversion from screen to Cartesian coordinates involves simply scaling the y value by -1 with an optional translation of both (x,y) values. I'm more interested in best practices for game design:

* Do most games just stick with the screen coordinate convention and change their thinking about how things like atan2() should work?
* When/how are coordinate system conversions done? (Using matrices, OOP abstraction, etc)
* Are sprite locations stored as the center of the sprite or one of the corners? The sprite's height/width going in the "wrong" direction seems to be a common problem when I draw them.

Although my question is mainly about 2D games, it seems OpenGL uses a coordinate system where the Y axis points up. OpenGL must eventually project those 3D coordinates onto a 2D screen coordinate system. Perhaps some guidance could be found in OpenGL's method...

# Answer
> 8 votes
Having tried every conceivable way of doing it, I have found if it's purely a 2D game, just use the screen drawing system, it will make your life much easier. Sin, Cos, and atan2 need to be used slightly differently, but this inconvenience is easily made up for by the simplicity of knowing which way up, down, clockwise and anti-clockwise are. I would also recommend working in pixels rather than meters for 2D games - it's much easier to think about on-screen distances, and the chances of you wanting to change the whole scale of your game are close to zero.

"How do most games manage the two different 2D coordinate systems?"

* most 2D games I've seen the source for use the screen system, but each entity should know its world space, let your drawing manager convert this to a screen position. At this point you'll do whatever matrix transformation you need.

"Are sprite locations stored as the center of the sprite or one of the corners?"

* If you work from the centre it makes rotation more straight forward, although you'll want to know the corners as well.

"Perhaps some guidance could be found in OpenGL's method..."

* 3D engines are a completely different case. As they have true cameras, the screen position can be wildly different from the world position. For a top-down game you'd be working in the X and Z axes, rather than the X and Y for one thing.

# Answer
> 1 votes
I may be oversimplifying things here, but my inclination would be to have any 2D/UI subsystem deal strictly in what you dubbed "screen" coordinates. You would have two matrices: ScreenToCartesianTransform and CartesianToScreenTransform. When mouse input events are received, the mouse coordinates would be transformed using CartesianToScreenTransform before being passed to the 2D/UI system's input manager. From there, the UI system would perform hit-testing using the screen coordinate system, and handle (or not handle) the event accordingly. If a mouse input event goes unhandled by the 2D/UI, it could be passed on to the 3D system (if one exists) using the original, untransformed coordinates.

Since the 2D/UI system would deal only in "screen" coordinates, its geometry would need to be transformed via ScreenToCartesianTransform before being processed by the rendering engine.

# Answer
> 0 votes
OpenGL, like DirectX, has the X and Z axes along the horizontal plane and Y facing upwards.
I have never had any issues with screen coordinates, and I think the easiest way would simply be to treat it how it is: if something, such as atan2, does not like it, then change parameters being fed.

If you're using relative or local coordinates, such as a scene graph, then a simple function such as ToGlobalCoords() is good. In fact, if you want to learn more about spatial positioning, scene graphs, and localToGlobal, the free extract from Game Engine Architecture is about that.

Sprites are drawn from the top left corner or (0,0) the origin. Reasons why are because of the top left origin of the window.

It seems a little silly to change the window coordinate system, and would make things like input, which plays a larger part to most games than trig does, significantly more difficult. It also alienates you from the norm and any users of your code.

# Answer
> 0 votes
I prefer using a display tree like in Flash. I'll have a root node (game view) which contains a child for the world (world node) and one on top for the HUD. Inside the world node will be the nodes for the objects in the game world.

I then simply transform the world node. Along with translation (camera panning) and proportional scaling (camera zooming) I also apply two other transformations:

* A -1 y-scale to flip the coordinate system.
* A scaling to convert world units (meters) to screen units (pixels)

I then use y-up / world coordinates in game object drawing code and y-down / screen coordinates in HUD drawing code, which both feel very natural.

To answer questions like "what object am I clicking on" I use display node methods to convert coordinates between coordinate systems (such as `globalToLocal` and its inverse in Flash).

By the way, `atan` doesn't really work differently when y is down, you just need to think of all angles as going clockwise instead of counter-clockwise.

---
Tags: 2d, screen, coordinates
---


# Question
Title: Two balls stick together in a pool game?
When multiple collisions occur between balls, sometimes they stick together. Mostly in cases of either of the balls having high velocity.

# Answer
> 3 votes
There's probably something on the balls causing them to stick together. Try cleaning them with a soft cloth or wet paper towel.

# Answer
> 1 votes
Can we see some physics code? How are you handling it? What do you mean by 'multiple collisions'? We're going to struggle helping without more detail.

Only reason I can think of is that the physics is treating it as a collision rather than an explosion (i.e. they stick together instead of flying apart).

EDIT: You could've said that in the original post. I also found this post on gamedev.net:

> wen multiple collision occurs between 2 or more balls..they tend to overlap...or sometimes rotate around themselves....cant figur out wy this is happening...

The problem is probably that your movement speeds mean the balls end up inside each other, and you do collision from there. A better option would be seeing if the objects intersect, and separating them before trying to move them.

---
Tags: physics, collision-detection
---


# Question
Title: What is the best way to make a main menu system?
I know that's it's easy to make buttons that highlight when you move your mouse over them, but when it comes to sub-menus I'm kinda stuck. Anyone got some tips on the best way to have a main menu with sub-menus? (like Singleplayer -\> Load Save -\> Save 1-5? -\> Start game etc.)

# Answer
> 12 votes
This is usually done using a stack of game states. For example, each item listed above would be pushed onto a stack as follows:

* Gameplay
* Select Save
* Single Player
* Main Menu

Where each state on the stack references its sub-items. When a button is clicked, it's corresponding state is pushed onto the stack, and becomes the top-most item which is drawn and interacted with. Usually, you would only draw that top state, unless there is some kind of transparency between layers, in which case you would draw from the bottom of the stack up until you draw the active state.

# Answer
> 6 votes
You should definitely implement it as either a Finite-state machine (FSM) or a Stack of states (sub-menus), depending on the exact requirements. Whichever sub-menu is the current one in the FSM or the top one on the stack, draws to the screen and handles input. And then when it detects the user clicks a button, it switches the FSM or pushes onto the stack the correct state to go to that next screen.

In your case I'm thinking a Stack is best, but if you had a more complex menu system that jumped around menus arbitrarily then you'd want to use a FSM.

# Answer
> 5 votes
"Best way" is entirely subjective. Look at the way other games do it and see if you find one that works well. The one thing you absolutely need is a way for the user to hit Cancel and get back to the previous level. You can give each menu object a reference back to the menu it was opened from, or implement it with a stack.

Aside from that, it all depends on what your game feels like and what you want your menus to feel like. Should each menu take up the entire screen, Final Fantasy style? Should they branch off of each other like Windows submenus? Should you go for something exotic like radial menus? It's up to you, really.

---
Tags: gui
---


title: doubts in circle circle collisions

text:
# Question
Title: doubts in circle circle collisions
> **Possible Duplicate:**
> two balls stick together in a pool game?

I have problems in circle circle collisions in a pool ball game..

The game has problems like the circles (or balls) stick together: they overlap after collision. I tried changing the directions after collisions and it works well, but when I arrange the balls real close and then the striker ball is shot at high velocity towards any of the balls, the balls start overlapping again, and also the striker ball slides over the hit balls.

What could be the reason for this and how could I fix it?

# Answer
Honestly, I would just use a physics library. It saves a lot of trouble in the long run, especially with respect to collision response.
> 2 votes

# Answer
Did you remember to abort moving the ball if you predict a collision when moving to the new location?

What you might be doing is that you're actually moving the ball first, then checking if it has collided.

If you check for collision, then move the ball you should avoid these overlapping cases.

Assuming you're checking for collision often enough.
> 1 votes

---
Tags: collision-detection
---


title: Game Engine framework or library

text:
# Question
Title: Game Engine framework or library
I'm on the planning stages for an internal game engine I am about to start creating, which will be used for all my games going forward. But I'm struggling a bit with how it should be built.

The choices come down to: framework or library.

My basic objective is to hide engine details as much as possible to keep high level game development on scripts and config files as much as possible. But also to reuse the core engine for any tools we might develop in the future.

Frameworks can make things nice and easy for development, but then you're locked in. Libraries are good if you're only interested in a specific subsystem. But we need to glue everything together in a game by game basis.

Well there is also another, building the engine as a standalone exe that handles all game resources, and all the subsystems. Game logic (and other per game dynamic stuff) is done exclusively on scripts with config files to configure each internal engine subsystem.

Which one will give me more flexibility in the future.

Thanks.

Edit: Thanks everybody, guess I was looking at this in the wrong perspective. We can't really plan something like this without a priori knowledge of what the games need, guess this is why there is no such thing as a general engine for all genres.

I'll focus first on the game proper then iteratively analyze at the end of each game how to make decent abstractions for libraries or frameworks depending on my work-flow (or possibly that of a future team).

# Answer
> 15 votes
Don't worry about the future quite yet. Worry about your current game, now. Otherwise you are not going to get anywhere because you are fretting on the details.

You should concentrate on building the game first and then later, if the game was successful enough, you can extract it out into something reusable for your next game. This will keep you from being locked in to something else and give you full control over your project.

# Answer
> 10 votes
### Build a framework.

I have experience with building both. I prefer to use libraries over frameworks. Frameworks feel very restrictive and *"bossy"*. So when I built my first game I wanted to build an engine that was composed of many libraries that could be easily reused in other projects.

It was a disaster. It spent half my time writing glue code between my various libraries. My libraries also tended to be bloated with extra abstractions, so that it became a huge chore to add features to the libraries/components.

Now, however my engines are built with the game I'm writing in mind. I still keep my eyes open for abstractions that will allow me to reuse it or the new features I'm adding in later games. I'm much more happy and productive.

For me the turning point was to decide to not publish my engine. I may still publish it, but for now knowing I don't need to justify my game specific hacks to other users has let me build an engine better suited to my games.

# Answer
> 4 votes
I see this way too often.
Why build an engine, to use in future games, when you don't know what games need?
Why not build the game first, and then another, and another, reusing as often as you can.
Then you have a library of code, probably unorganised, but all shown to be useful.
Then you can go about organising it.

And for 'framework vs library', I would base it off of how tired you get of writing a game loop over and over again and stuff. ;)

A framework doesn't necessarily need to lock you in. Look at XNA.

# Answer
> 4 votes
Keep it simple.

If you're not sure which way to go - just do whatever your game requires. Try to write small, basic libraries for stuff that you feel might be usable in the future. Look into data-driven software development. I suggest looking into component-based entity systems. Don't base the code around things that are unique such as a player. A player is just another object, just like anything else. An entity has components, perhaps a list of components.

By writing small, contained libraries that interact with each other, you can go ahead and determine which ones to re-use for your next game. Personally I have things like a "container" library for data-storage types. I have a math-library for such things. There are several things like these that you can sort out and write as modules. Camera, effects, input, entity, movement, physics, rendering, resource-handling, threading, the list goes on.

Writing small stand-alone components often increases readability and debugging possibilities of your code.

Mike Acton and insomniac games (www.insomniacgames.com) have written a lot of topics and discussions regarding game development, in particular data-driven. Look them up and see what kind of information that is too complex and which you find interesting and understandable. They're great developers with a ton of experience.

# Answer
> 3 votes
I think you're doing premature generalization. Don't get stuck too much on future-use questions right now. Pick an answer and run with it, learn from it. Flip a coin if you don't have a preference.

Start by building a game. When you build your second game you'll have a better idea what parts are re-usable and can be turned into robust library functions. When you build your third game you'll have a better idea what structure is re-usable and can be turned into a robust framework.

# Answer
> 2 votes
In terms of flexibility, I think you answered your own question: "Frameworks can make things nice and easy for development, **but then you're locked in**." This doesn't mean frameworks have to be inflexible; every game, for example, has a game loop. Microsoft's XNA framework is 99% library, but your game extends the Game class which just provides a few blank functions for the things which are guaranteed to be in every game: `LoadContent`, `Update`, `Draw`. It's a prime example of a nonrestrictive framework.

One might say a framework is nothing more than a library combined with a template class(es) that are hooked into the library, at least this has been my experience.

I tend to prefer libraries over frameworks. jMonkeyEngine, for example, is great but it's a framework and as a result I've noticed it receives tons of flak. SDL, on the other hand, is amazingly popular; it's just a library. It provides what you need but gets out of your way to do whatever you want with it.

With a library, there's not necessarily a lot of gluing to be done on a game-by-game basis -- especially if you write parts of your library to support each piece of the game loop; a Frames-Per-Second timer/counter, for example, would prevent that commonly-rewritten part from needing to be reinvented with every game.

Also, libraries can be as general or specific as you want to make them. If you're making a racing game and you want your library to have racing-specific features, that's fine. It's your creation and you get to choose exactly how flexible you want it. This would be very feasible in a situation where you're in a long-term contract with Nascar to develop numerous racing games, for example. You wouldn't necessarily want a framework to potentially tie you into a classic racing-in-a-circle game when Nascar comes up and asks for an offroad game, but you would want a racing-game-specific library since you know Nascar isn't going to ask for a shooter.

Here's a tip for development, too: if you write the library alongside a game, you will inevitably end up accidentally coupling the library to the game, or making it too inflexible, no matter how much planning you do. You'll figure it out as soon as you try to make a different game with it, and you'll spend time separating it; this isn't necessarily a bad thing and you might consciously decide to do this, since you'll have more free time after your first game is released. But if you're aiming for a stellar library from the get-go, **try making two totally different games at the same time, and extract the similar pieces into your library**. You'll get a LOT less coupling, it will be a lot more flexible, and your third game will probably still expose some weaknesses but your library will be much better in the end. It is, however, obviously much harder and more time-consuming to do.

---
Tags: architecture
---


# Question
Title: Simple scene graph in 2D, without matrices?
First of all, I think I roughly know how a scene graph works. Please correct me if I'm wrong.

It is a tree based structure, with each branch/leaf being a node. It means you can better organise children, like tyres on a car or something. I want to use a simple version of it, which makes me think matrices, but the graphics API I'm using (SFML) doesn't allow them. I would use GL here, but the project has to be done in a reasonable time frame.

---

Instead, I only have the ability to set 'absolute' window coords by default. Without anything, it would be something like:
`carBody.position(10,10);
carWheel1.position(9.5f, 8.7f);//etc. I think that's a badly placed wheel. :P`

How could I go about this? Have each object/renderable thing/entity be a node, obviously, but then how would I handle position changes? I would think passing down the branch, somehow.

Is there some kind of tree structure in the STL containers? Would I have to make my own?

---

There's one other thing that's hit me. Is all of this overkill? All I really need is some way to control more of 'local' positioning, which this does, but this seems OTT for what I need. So it's sort of organization + positioning vs the sheer complexity for a 2D side scroller.

# Answer
If you need to support rotation or scale of parent nodes I would use matrices. Even if they're not supported you can implement them yourself. If not, you could just, upon rendering, add the local translation to the parent node's translation? Transfer the tree from the top, when you enter a child you add it's translation, when you go back to a parent you either subtract it again (bad, as you will get small errors adding up) or restore the previous translation (use a stack and push the current translation when you go into a child, and pop it when you return.
I don't know if there's a tree structure in STL, but you can just use any vector and store the index of the first child of a node, and the index of the next sibling of a node. You can then traverse the tree by starting at the root, and do
If (firstChild) push translation - visit child; pop translation
If (firstSibling) visit firstSibling
This will do a depth-first traversal.
> 4 votes

# Answer
Matrices are the 'right' way to approach this - but if you really can't use them, you can still create a hierarchy of nodes (as a tree) and do something along the lines of:

```
scale    = parent_scale    * local_scale
rotation = parent_rotation + local_rotation
pos      = parent_pos + rotate( parent_rotation, local_pos )

```

(Where positions are 2D vectors, rotations/scales are scalars, and 'rotate' rotates a position vector by a rotation angle)

As you would with matrices, do a depth-first traversal of the hierarchy to update pos/rotation/scale of each node before rendering

However, without matrices, I think you'll struggle to handle non-uniform scaling?
> 0 votes

---
Tags: 2d, architecture, scene-graph
---


# Question
Title: What determines which key combinations register in a Flash game?
Many times when I'm working on Flash games I'll find that a particular combination of keys held at the same time doesn't register, e.g. LEFT, DOWN and SPACEBAR.

I know from my days playing Doom this can be caused by the keyboard hardware, but surely technology has moved on since those spongy beige PS2 keyboards?

So my question: are these problems caused by Flash, by the hardware, by the operating system, or something else?

# Answer
> 6 votes
it's still keyboard hardware limitations. http://en.wikipedia.org/wiki/Rollover\_%28key%29

# Answer
> 0 votes
The problem also occurs in Java games so I suspect it's on the OS level or lower.

# Answer
> -3 votes
What you want to do is to have Boolean variables and turn them on and off while they are pressed and un-pressed. Flash has a combination of just a couple of keys(i do not know why) but you can easily get around it by just keeping your variables up to date when they are pressed and released.

---
Tags: flash, keyboard, input
---


# Question
Title: Splitting profit - Equal share vs equity investment (work & money spent = share)
Coming up with an appropriate one-liner question was so hard I wrote the body before the header...

So we're a team of 4 developers; two designers, two coders to put it simply (naturally we don't tie ourselves up with labels). We've come up with a great game design together, and we're prepared to spend a great bulk of our time making a prototype.

Problem is, there's a major difference of opinion when it comes to sharing *potential* revenue made by the game.

### Investment = Share

Two of us would like to have everyone keep a rough log of hours spent. Converting that to a previously agreed upon per-hour salary, we could add it up with real money invested, and from that determine each developer's 'stake' in the game, i.e. their share.

### Equal Share

The other two do not agree with that, among other reasons because they think some pieces of work are worth more than others, like a really great idea for a feature. Because of such immeasurables, they think an equal share for all would be the easiest.

Another argument said: (paraphrasing) "logging hours would take away the fun. I'm serious about this project, but I want to work with it on hobbyist terms, not like a second job."

---

We need to formalize an agreement before development has gone too far, but how can we get past these core differences of opinion? Is this a common problem among first-time startups?

# Answer
> 8 votes
I prefer equality, because if it's time based then someone who works twice as efficient or is madly talented will be punished for doing twice the work per hour.
On the other hand, people might argue that someone talented puts in as much sweat as the less talented so the hours are of equal value.
I do know that not being based on equality might demotivate people, whereas you'd hope that everyone will be as motivated as can be.
You don't want the wrong sentiments to influence a process that is hard enough to pull off as is.
Besides, the coders can't draw, and the designers likely can't program so you're equally indispensable. As between the coders and the designers, if people feel the others don't work hard enough you have the wrong team. Being a company is hard, especially if you're friends. I've done it for 5 years (same setup) and we were on equal shares. Sometimes the designers had to work harder, sometimes the coders. Generally we all put in 80 hour weeks anyhow.

# Answer
> 5 votes
I would say it is a very interesting problem to have.

If all of you are already in the project, then I guess doing Equal Share would be the best thing to do. **You cannot quantify productivity in hours** and I know sometimes i spend a couple of hours thinking and then implement something complex in just a few hours(which is imposible without the thinking part, which seems imposible to measure).

That being said, if someone is putting money in or out, then its a different thing. If someone is **investing**, they probably want more shares, if someone is planning on charging money early on(which is fine, I mean maybe he wants to quit hes day job?) then he would get way less equity.

The most important thing would be to agree that you are **all the team making the game**, and that you **will put everything you can into the project**, if you all agree with that, why not go to the **equal share option**?

# Answer
> 2 votes
In our gamedev-studio we have a system of ten grades, you earn them for like working on the concept or spending time to code etc.

In our conferences everyone gives his self-assessment about his work done and then those will be discussed.

For just being active and doing some little concept stuff is a grade of 2 and coding the whole month is like an 8, so together they add up to a 10.(Just an example)

The money now is shared very simple: All points of all members are added up so they are 100% and therefore everyone of the team gets the money he worked for. Fair and simple.

---
Tags: legal, monetization, planning, project-management, publishing
---


# Question
Title: Tips for implementing MMO quest mechanics?
What tools, patterns, or best practices would you recommend to implement the quest mechanics given below listed requirements?

I am talking about software architecture (how generic should you be) and choices for object wiring, event subscription, and representation of conditions. Mentioning of tools / libraries you have successfully used are welcome. **Edit:** If you are using scripting, what setup do you recommend?

Requirements:

* simple 2D mmo(rpg)
* all the game data, including quests, is stored in a relational database
* any event in the game could trigger a new quest for players or advancement of existing quests
* a quest can have an arbitrary number of conditions that must be met before the quest is available to players
* a quest can consist of an arbitrary number of sub-quests / steps with arbitrary conditions
* quests would range from simple:

talk to A - kill 5 B - talk to A - permanently increase health
* to quite involved:

use item in area X - go to area Y - a bot will spawn - kill bot without taking more than 10% damage - bot drops item - pick up item - portal unlocks - deliver item to J behind the portal - receive gold and experience - allow to pass portal once more - lock portal for this player
* level instances are a possibility (players can complete certain quests in teams or isolation which will spawn the level location just for those participants)
* Quests should preferably be manageable using a world editor without scripting or programming knowledge (**Edit:** not advocating against scripting in general though)
* I assume C++ as the language of implementation

I was thinking that if I could combine any chain of events and conditions we could model more complex and thus possibly more engaging quests. I experimented with rolling my own ECA (Events-Conditions-Actions) engine but that might be overkill. It has been particularly difficult to model generic conditions without using any sort of scripting.

# Answer
> 8 votes
First a warning, then some advice.

The last time I needed to implement a system like this, I was not using an engine originally intended for MMO-like applications. The quest system it shipped with was geared for single-player endeavours, and could not be used.

I ended up having to stuff scripts on all the objects involved with the quests more or less by hand, like this (pseudocode):

```
Lever004_on_activate() {
    if isOnQuest(player, QUEST_0012) do_something();
    if isOnQuest(player, QUEST_0015) do_something_else();
}

```

This is a complete nightmare. There is no way to figure out how the quest works without scavenging all through the game. Do not do this.

I would recommend creating a system where the entire quest (line) is represented as a finite state machine, with events to check for transitions and scripts to react to said transition. That makes it easy to keep track of where you are in a given quest (line) and keeps all quest state neatly encapsulated.

If you want, you can make a library of scripts/script templates in your world editor for common occurrences (player talks to NPC, player kills mob, etc.)

I would not worry too much about script performance, as long as you do not fire your event scripts too often. As a rule of thumb, scripts should fire at least an order of magnitude less than the "core" game logic (animation, physics etc). They should react to events, instead of firing periodically to check if a condition has been met.

# Answer
> 3 votes
Our system basically involves running a an expression (custom mini scripting language but tcl/lua/python would work just as well, or make something yourself) each server frame for each mission step. This is for "personal missions" that are tied to a specific player. Each substep is then part of an FSM (finite state machine) for the mission itself (which might just be a substep of another mission). There are also "map missions" which have a single FSM and are tied to the map instead of a player (think WAR's public quests), but the substeps work basically the same.

What these expressions actually look at are events broadcast by the system like "NPC died" or "interaction complete". This means you can somewhat decouple the various parts, the gameplay systems just send out events as needed, which the mission scripts just listen to events and don't worry about where they come from. If you also layer on that you can have the mission FSMs interact with the world state (only show this contact when in mission state X) you can get a lot of power out of the system.

---
Tags: architecture, c++, mmo, scripting, quests
---


title: What game engine does Mega Jump use?

text:
# Question
Title: What game engine does Mega Jump use?
What game engine does the iphone game Mega Jump use? Im guessing it's unity 3d but it could be anything.

# Answer
> 5 votes
Cocos2D, judging by their development blog.

http://getsetgames.com/2009/08/21/cocos2d-and-uiscrollview/

---
Tags: iphone
---


# Question
Title: Best practices XML data files and xml compression for Flash Games?
I am working on a game, and the xml files are getting to be a few megs, and the final game might have a hundred megs of uncompressed xml. If I zip the xml files up I can get something that is about 3 megabytes to be under 100kb which shows that compressing the files will yield good results. **How can I get the XML files compressed, and how would I uncompress them on the client's game?**

I am planning to keep all my bullet patterns in one file, and planning to keep all the levels in one file. I am not to concerned about the files becoming undwieldy to edit, as I can add my own xml tags as categories to group data, and use a xml editor that can collapse tags. **Is there a better way to do this?**

# Answer
> 2 votes
Wow. That's a lot of data. As Ricket said: Try to split the files into smaller chunks. Loading these huge files into memory will cause problems otherwise.

As for compression of the data: The easiest way would be to simply enable *gzip* compression on the server. When using Apache, you would have to enable mod\_deflate and configure it, so that it also includes your xml files into compression. That way, all your files will be gzipped before sending to the client and automatically extracted by the client-browser.

If you can't modify the server settings (eg. enable *gzip* compression), then you could also zip your files manually and use ActionScript (AS3 Zip Library) to unzip the data. I used this on 3D data (Collada XML files) and it works a charm.

# Answer
> 3 votes
Switching to JSON rather than XML would also immediately save a lot of space. It's also a lot more readable, as a side effect.

Here's an AS3 library that includes JSON in/out: http://github.com/mikechambers/as3corelib

# Answer
> 2 votes
The question of how to compress and decompress data/files with ActionScript is a great candidate for asking at Stack Overflow; it's not game dev specific.

As for the question of is that a good idea, well you'll have to load, parse and keep the entire XML file in memory just to load one level. So I most certainly think **you should split the levels into one xml file per level** and then dynamically load and unload, so as not to waste valuable RAM.

I'm not sure what bullet patterns are. But you might run into the same issues with those.

However, I personally like XML, and I think it suits your usage very well. As you found, XML compression is extremely efficient (cancelling out the fact that it's human readable rather than binary) and I'm sure there are XML parsers in ActionScript for you to take advantage of.

---
Tags: flash, actionscript-3
---


# Question
Title: Generate levels in real-time with the Procedural CityEngine
Has anyone used the Procedural CityEngine to generate levels in real-time?

It seems to get used in production or pre-production due to its sizable overhead, but has anyone tweaked it to run in real-time either in a test or in a game?

**Edit:** Please include the person or group who did this, the game or test it was used in and a brief description of how it was done.

# Answer
my name's Matthias Buehler, i am content manager at procedural, inc.

to get an idea about the current way to implement the cityengine in a game pipeline, check out the following show case: http://www.procedural.com/showcase/showcases/destroyed-city.html

this is a game which was created from scratch by a few students. the guy responsible for the level layout used the cityengine to create all building geometries. the assets of course were of course modeled in an other 3d application.

...

you guys are referring to a methodology to create models (in different LODs) directly from within a game ("realtime"), (without having to start the CE and export the models) by directly calling the cga shape grammar engine. this is currently not possible, but we have been asked about this many times already. some of our current development goes in that direction, since one of our main focus is the game market.

the workflow so far is - of course - to create a pool of meshes in different LODs and load them in dynamically (proximity based, ..), as it's done in almost all games today.
> 10 votes

# Answer
(sarcasm here)

But in all seriousness, I think your best bet at this time would be to contact the company regarding this usage of their product. It has been my experience that companies are very willing to support their product, especially if you are a customer or potential customer, and you would get the best answers from the actual developers of the product.
> 2 votes

# Answer
Best option would involve asking the creators if it is possible or anyone has done it.

Why exactly would you want to run it in game? Doesn't seem to have much of a point. Even if you could run it in game, the amount of watering down would be huge. Thus rendering it mediocre or worse.
> 0 votes

---
Tags: graphics, procedural-generation, levels, procedural
---


# Question
Title: Connecting physics simulations with different coordinate-systems
I want objects to move between two physics simulations through a "window" and collide with those from both simulations in case they intersect the window plane.

The coordinate systems of the simulations don't have the same origin and may have a different orientation. Wrapping a simulation to itself isn't necessary, but would be a plus.

How do I connect the systems efficiently without cloning the individual objects?

**Edit:**

The calculations should be as accurate as possible, so objects don't get stuck if they cross the window at the same time from opposite sides.

# Answer
> 0 votes
I read up some infos on physics simulations and found a possible solution. It works by splitting each physics-step into three phases:

**1. Pre-Step:**

Each physics-step, a window creates four transformations, two for each side of the connection:

* an input transformation that transforms an object's position, velocity (and possibly size and weight) into the destination coordinate-system and
* an output transformation that transforms forces back into the object's original system.

(Static windows only need to do this once.)

Additionally, objects in each coordinate-system are split into three groups:

Physics Grouping http://content.wuala.com/contents/Tamschi/Stack%20Exchange/WindowGrouping.png

1. Objects in front of the window (green).
An object is also counted towards this group if it is intersecting the window plane or likely to cross it from behind the window (not shown).
2. Objects intersecting the window or likely to intersect it in this physics-step (orange).
3. Objects behind the window (blue). If an objects flies towards the back-side of the window, it is still marked as member of group three.

Grouping can be simplified if the window is at the simulation's border.

**2. Main-Step:**

Physics are calculated mostly as usual, with a few exceptions:

* Objects from the second group never collide with those from the third and vice-versa.
* The window's input transformation is used on the objects from the second group and the results are evaluated against the front- and intersecting objects from the destination system. The resulting force is transformed using the output transformation and applied to the original object.

(If an object is hit during the calculation, it must be regrouped!)

**3. Post-Step:**

If an object from the second group has crossed the window, it is moved into the destination system using the input transformation.

**Additional Thoughts:**

If the transformations are preserved after calculating the physics, they can be used to speed up rendering and for easier AI calculations. The grouping could be used to remove clip-planes from the rendering process.

The downside of this solution is that the windows have to be added directly into the physics-engine.

# Answer
> 2 votes
There's this cool project called Pseudoform, formerly known as 'Portalized', which handles physics simulations using portals in a groovie fashion:

Pseudoform

Check it out!

Especially the videos - it's staggeringly cool.

It's open source, so you get to see how they do it.

I bet that's what you want. :)

# Answer
> 0 votes
Okay - I do not know if this would work.
Based on the above info I would put triggers on the 'windows' so that I could detect when an object is going out of a world. Grab current velocity vector at time of collision. Calculate timestep left based on where it hit the trigger and where it ended up this frame (outside the world, your world would need a virtual border to allow for this). At this point you know the speed and the timestep left, so you can reposition it on the border of the world it's about to enter, and reproject the velocity. This would however require two physics updates in one frame, and there would be the bordercase of one object going from a to b while another goes from b to a at the same position - there would be no collision detected at all.
Kinda sketchy, but maybe it makes sense somehow?

---
Tags: physics, collision-detection
---


title: Game development and research

text:
# Question
Title: Game development and research
Game development is currently a largely non-academic enterprise. There are a lot of commercial developers of games, as well as a large hobbyist community. The academic community focusing on games seems to be small, and new. \[Or so it appears to me\].

Having said all that, are there some *must read* papers/books on game development from academics?

# Answer
> 2 votes
A professor at my school, Dr. R. Michael Young, was editor-in-chief of the Journal of Game Development. It had 9 issues before it apparently disappeared. I don't know the story, though I should ask him. The main website is down but here's a wayback machine result from June 2008 if you're interested. You should look around for the issues; they are probably pretty rare since it was discontinued.

So right now I think the closest you're going to get is the Game Developer magazine.

I like to keep up with the industry online. I highly recommend becoming a member of IGDA and keeping up with your local chapter. There's also Gamasutra, they have a lot of game industry news and articles, and of course Gamedev.net.

You might also search around for textbook lists. I'm not sure how many schools publicize them; mine doesn't. But for example, my game design class last Fall required the book Rules of Play: Game Design Fundamentals. If you can figure out what books are being required as textbooks by professors, it's a good bet they are great resources. (though I personally didn't like Rules of Play all too much, it's way too much theory and nothing concrete)

You may also find, scholars tend to be "lazy" and just use existing solutions. So whereas indie developers love to code their own engines, libraries, etc., the game development researchers and masters students at my school use the Unreal engine (and now the UDK) or the Unity engine. Being an aspiring game programmer, I find it to be extremely boring, but they are mainly interested in design and AI studies.

# Answer
> 2 votes
Some papers from a friend of mine: http://scholar.google.com/scholar?hl=en&q=%22marc+destefano%22&btnG=Search&as\_sdt=40000000&as\_ylo=&as\_vis=0

Most game-related research can't be labeled as such or funding (90% of which in the US comes from the Navy) will dry up in an instant. If you look for "cognitive modeling" or similar that might help.

# Answer
> 1 votes
I think everyone who is interested ought to find good resources on story telling. Most games have some story that drives the game play and creates the world that players are immersed in. I myself don't know any good story telling resources but a great place to start might be contacting a game development institute like DigiPen. I am sure there are others out there too that would put you in contact with an English professor or someone who is an expert in storytelling.

You could also ask what other resources the deans of the school think are important for their students to know.

# Answer
> 1 votes
For game designers, "MDA Framework" (Hunicke, LeBlanc, Zubek) is one of the most useful papers I've seen come out of academia. For books, "Art of Game Design: A Book of Lenses" (Schell) and "Game Design Workshop" (Fullerton) are good picks, both written by professors. (In fact, most game design books worth reading were written by professors, as they tend to have more time for book writing than your average working game developer. Most game design books that aren't worth reading were also written by professors, though.)

This question seems like it carries some kind of mistrust of academia (the whole "those who can, do; those who can't, teach" thing), but that ignores that especially these days, there's an awful lot of crossover between academia and industry. I worked in games for ten years before crossing over into teaching, and I still do industry contract work when I can; does that make me part of the game developer community, or the academic community? I could name a dozen others off the top of my head in the exact same situation. So I'm not sure that the distinction of "academic or industry" is even meaningful anymore.

# Answer
> 1 votes
This is a starting point:
http://webdocs.cs.ualberta.ca/~games/
as is:
http://grandtextauto.org/
also
http://aigamedev.com/
links a fair amount of papers on a fair amount of topics (check the forum too)
Of course in graphics there's a lot of research that makes it into games or is developed for games, so always keep up on what's going on in SigGraph circles.
And for AI there's
http://www.aaai.org/home.html

# Answer
> 1 votes
There is not and never will be any de-facto must-read; like *the book* that everyone agrees every self-respecting game developers should have read. Won't happen.

Everyone find their own must-reads from time to time. A complete game-changer for me could mean nothing to you, due to our different personalities, past experiences and so on. You'll find *your* must-reads as you get involved in the game development scene.

I started out by frequenting Gamasutra and GameCareerGuide because they had the best articles on what I was most interested in at the time; writing game design documents and 'breaking in'.

The beast readers tips come when you are actively engaged with other game developers. Conversation with your peers will always be in the context of game development, and suggestions to 'further reading' will be always relevant to what you are currently trying to achieve, e.g. learning a new toolset or researching good level design. It won't matter so much that you could have read a slightly better book, if the one you're reading in its stead makes it easier to collaborate/talk with your fellow developers because you have a resource in common that you can refer to.

# Answer
> 0 votes
One more book to add to the list: http://www.amazon.com/Software-Engineering-Game-Developers/dp/1592001556/ref=sr\_1\_1?s=books&ie=UTF8&qid=1281546762&sr=1-1

Software Engineering for Game Developers is an interesting approach to combining traditional software engineering to the typically chaotic process of game development. I have not gotten through the entire book yet, but the parts I have were pretty enlightening in respect to how to approach the chaotic nature of creative process with a orderly and structured process to approach the best of both worlds.

---
Tags: education
---


# Question
Title: Is there a better way of determining direction to turn?
You have an entity A that you want to turn towards another entity B. One way to determine the direction to turn is to compute the cross-product of the direction vector of A with the vector from AB. If the value of z is positive, then you turn right. If the value of z is negative, you turn left. Is this the only way of determining which way to turn?

# Answer
If you're storing your rotations as quaternions (which you probably should), you could use a quaternion lerp function to lerp from your initial rotation to the rotation you want to be at (i.e the rotation given by the vector AB with whatever your up vector is).
> 5 votes

# Answer
It sounds like this is essentially a 2D problem; if it's truly a 3D problem (one spaceship face another spaceship in free space) then you should definitely use quaternions. Traditional vectors will have odd turn patterns. But according to your question, you're just turning left or right. If you can simplify the problem down to two (x,y) positions and the angle that entity A is facing, then you can use simple 2D math:

tan((yB-yA)/(xB-xA)) is the desired angle (of A facing B). Turn towards that.

You need to account for crossing 0 degrees; for example, if the target angle is 359 degrees and you're currently looking at a 1 degree angle, you want to just turn 2 degrees clockwise rather than turning 358 degrees counterclockwise.
> 2 votes

---
Tags: mathematics
---


# Question
Title: What's a good data structure solution for a scene manager in XNA?
I'm playing with XNA for a game project of myself, I had previous exposure to OpenGL and worked a bit with Ogre, so I'm trying to get the same concepts working on XNA.

Specifically I'm trying to add to XNA a scene manager to handle hierarchical transforms, frustum (maybe even occlusion) culling and transparency object sorting.

My plan was to build a tree scene manager to handle hierarchical transforms and lighting, and then use an Octree for frustum culling and object sorting. The problem is how to do geometry sorting to support transparencies correctly. I know that sorting is very expensive if done on a per-polygon basis, so expensive that it is not even managed by Ogre. But still images from Ogre look right.

Any ideas on how to do it and which data structures to use and their capabilities? I know people around is using:

* Octrees
* Kd-trees (someone on GameDev forum said that these are far better than Octrees)
* BSP (which should handle per-polygon ordering but are very expensive)
* BVH (but just for frustum and occlusion culling)

Thank you

Tunnuz

# Answer
> 6 votes
Octtrees (or even just quadtrees) and Kd-trees are both good general purpose spatial partitioning schemes, and if your build pipeline and/or engine is generating them, then you will find they come in useful in all sorts of different ways for optimising queries/iterations. They work by sub-dividing a fixed volume in a hierarchical way, which makes queries like raycasting into your object space very cheap to query for (great for collision checks).

Bounding Volume Hierarchies work in a slightly different way (they aggregate the volumes of the objects in the tree rather than sub-dividing spaces), and are a simple way of trimming unnecessary things from being iterated over. But because BVH doesn't put any restrictions on how two sibling nodes are related, it's not such a good scheme for figuring out rendering order, or for arbitrary collision queries.

BSP systems are good when you're subdividing the world based on individual polygons, but for larger objects a volume based approach makes more sense.

Above all though, it's worth noting that none of these systems are perfect for determining render order for transparency, even the BSP approach. It will always be possible to construct geometry which breaks your algorithm, unless you are able to subdivide polygons on the fly. What you're most likely looking for is a 'best effort' solution, where geometry can be ordered correctly in the majority of the cases; and the art team can subdivide models for any of the cases which don't work (because the model/polygons are abnormally large, long, or self-intersecting). Smaller models/nodes are always much easier to sort 'correctly', but you pay for it in terms of iteration overhead.

Kd-trees and Oct/quad-trees are both good general purpose solutions, for which a platform friendly implementation can be written, but in the end you are going to have to balance the depth/complexity of your spatial partitioning tree against the cost of iterating it, and the overhead per model (i.e. draw call cost). If you're targetting XNA, I'd recommend you keep it simple and high level, and if there is sorting problems with some of the content, then strongly consider changing the content before trying to improve your engine until it can cope with it; the returns diminish very quickly after the most basic render sorting is implemented.

# Answer
> 3 votes
McCranky covered amazingly all the data structures you mentioned, however I see that you havent considered R-Trees. The body of knowledge on those structures is huge, and they are very suitable for spatial range queries (most of the work have been done by database theorists and practitioners) in the last 30 years. Recently Sebastian Sylvain from Rare has given a course on the GDC on why they work for games too (specially on consoles with in-order processors). You can learn more from its pdf: http://www.gdcvault.com/play/1012452/R-Trees-Adapting-out-of

A naive and simple implementation is pretty easy, and the basic structure gives you lots of room for improvement (better management of splitting heuristics, prefetching oportunities, parallel searching, etc).

# Answer
> 2 votes
The answer highly depends on the amount of models that you are planning to use. I haven't really worked with these kind of things for XNA, but if you use AABB's for the tests and don't have too many models you might be good enough with a brute force test. Perhaps even throw it out on a thread. I'm not sure how/if there are any SSE/VMX optimizations that can be used for C# but if you manage to get the AABB's linearly in memory (so that you get no cache-misses for the CPU), you should be able to push through a high amount of tests in quite little time.

---
Tags: performance, graphics-programming
---


# Question
Title: trouble in box2d flash with invoking a setLinearVelocity() from inside an eventHandler
The set linear velocity doesnt affect a sprite when written inside an event handler.. but if i call setlinear velocity inside the main constructor..ie if the setlinearvelocity is called at the beginning of game code ..it moves..but not when i call it within a event handler..either keypress or mouse,it doesnt work?

Please ..any help would be greatly appreciated

# Answer
> 1 votes
Could it be that the event handler gets called at the wrong time in Box2D's pipeline? Or are you not unintentionally overwriting it somewhere else (like in an update loop)? Could you set a variable to the desired velocity in the event handler and set that velocity in an update that gets called more regularly?
Pure speculation - I never used flash's event system the way it's supposed to be used (I prefer update loops) and I never used Box2D so take it for what it's worth.

---
Tags: flash
---