# Question
Title: UI: Main Menu options for mobile games. What options should be listed? What do users want to see?
When a user arrives at your main menu on your mobile touch phone game. What do you want them to see? What do they need to see?

*Start*, *About*, *Load*, *Leaderboards*, and *Settings* are just a few of the options that I "could" put on the *Main Menu*. The question really is what "should" be there and why?

My game is about surviving waves of enemies to get to the next level, with a twist of course.

What options could/should be shown on my *Main Menu* and why?

**EDIT UPDATE:**

* Easy recognizable PLAY button.
* Possible buttons include, but are not limited to *Options*, *Stats/Achievements*, *Leaderboards*, *Level Solutions*, and *Promote Game*.
* Choose appropriate options for your type of game. (ie. *Level Solutions* good for puzzle games but not FPS)
* Less is more, don't clutter the *Main Menu* to prevent users from getting confused. Weigh the benefits of an additional button against the risks of confusing users.
* Symbols can be used to convey the meaning of a button, be sure to reach the largest audience possible.
* Have as few clicks as possible to get into the game.

# Answer
As mentioned, users want to quickly get to the gameplay, after all, that's why they bought/downloaded your game. The most prominent option (or options) should take the user to the game. But, there's a few other things that might be worth including. Let's use some examples from popular (casual) games.

The Peggle Title Screen. There's 4 prominent buttons here, each of them taking you to a different game mode. These buttons are a bright blue, and stand out against the red/orange/green background. Even if you didn't know any English, you would probably be drawn to these buttons, and likely to click on them. There's also 3 smaller buttons, labeled with text explaining what each button does. They also stand out, though not as obvious, and it'd be confusing to know what to click on if you didn't know English. But the screens they take you to are generally important (options mostly, you want to allow users to disable or enable sounds, or possibly change control schemes, or something else)

The Angry Birds title. In some ways, it's a bit more confusing that you can click on the "**Play**" in the middle (if you don't understand English), but at the same time, the word "**Play**" is in the centre of the screen in bright, bold letters. It's hard to miss, and the actual selectable area includes more than just the letters. There's also four buttons at the bottom, using symbols (which is great if you don't read English, but can be confusing to work out exactly *what* they do until you click on them). The left and right are the **Options** menu and a "**promote the game**" menu (this is true of the Chrome Angry Birds, I don't have the iPhone version to double check). Again, having an options menu is useful if you don't want to have sound going off while playing on the toilet or riding the subway. There's also **Leaderboards** and **Stats/Achievements** (again, these are best guesses in this case...), useful if you want to show off to people how much better you did at a certain level of the game.

So, what can we take away from all this? The key feature of a title screen is an easy, recognizable **Play** button, possibly a separate one for each game mode if your game has that. Other things to consider are **Options**, **Stats/Achievements**, **Leaderboards**, **Level Solutions**, and/or **Promote the Game**. Some of these are more important than others, and some of them might not even apply to certain games (Level Solutions is a good idea for a puzzle game, but useless for an FPS). It *is* important to not clutter your main menu, lest users get confused, but if you design it well, you can include all of these options and still make it obvious which one takes you to the game itself.
> 7 votes

# Answer
Your user is as interested in as few options as possible. Show them what they should care about and nothing more.

Ideally there would be as few clicks as possible to get into the game. So arguably, if you're supporting the ability to load a game, you might want to put "new game" and "load game" as separate buttons on the main screen instead of a generic "play" button that takes you to a sub menu as there's less input to get where you need to go at the cost of more buttons.
> 1 votes

---
Tags: game-design, interface
---


# Question
Title: How to properly handle errors in a D3D11 framework?
I'm writing a D3D11 framework and I'm trying to clean it up a little, and I'm unsure how to handle errors and return codes in my classes/code.

What is the "best" and cleanest way to implement error handling ?

Should I just use the HRESULT and other D3D types as return values for errors and such, or should I create my own types, or should I go with native c/c++ types ?

# Answer
## Misunderstood the question, see the comments.

---

You basically have three choices:

* Throw an exception
* Return an error code and use an **out** parameter to return the actual value
* Call an error callback

**Exceptions**: Very simple to implement, however they **might** incure a huge performance and/or memory impact, even during normal execution, depending on the compiler. You should run a performance analysis on your target compiler and platform, both in normal execution (i.e. don't actually throw an exception, use only a try/catch), and in exceptional execution. If your program slows down by a large amount after using exceptions, don't use them. However, Joel doesn't like exceptions because they create invisible return paths. Thanks to C++ RIAA (shared\_ptr) I don't think that's an issue anymore, your mileage may vary.

**Error codes**: The upside of error codes are that you can see all code paths in your source code. There are however two problems with them:

1. You need to check the error code of every call that can fail.
2. They steal your return code, so you are forced to use an **out** parameter for your actual return value.

Another upside of this approach is that it is not memory intensive like some exception handling implementations. Also, you still need some CPU time to check the return code of your function calls, however this cost is usually only a fraction of the cost that exception handling incurs. Again, check with your compiler.

**Callback**: When something goes wrong, you call a callback. This only works if the callback is actually able to fix the problem (i.e. if the game can't allocate any more memory, defragment the heap).

Another approach are **assertions**, which are useful for testing for "impossible situations". They are usually only enabled if the game is running in a debug environment and are stripped out in a release environment. The assert implementation in **assert.h** does this automatically, it makes the assert macro do nothing if **NDEBUG** is defined.

I've taken much information for this answer from the book *Game Engine Architecture* by Jason Gregory, specifically Chapter 3.3.
> 8 votes

# Answer
The HRESULT type is extensible for user application (i.e. is not limited to system applications). Here's the MSDN documentation for it's layout. As long as you set the *Customer* bit you can use the other 31 bits for whatever you want. So I see no reason to not use HRESULTs. Of course you'll need a function to convert the HRESULT into a string.

That's how most C APIs work, too. Except they use `int`s instead of `HRESULT`s. Also, the standard library stores the error code in a global variable `errno`. This works as long as there is an "invalid" return value for every function, for example a null pointer for functions returning pointers.

You shouldn't invent your own types unless you have to. If you use `HRESULT`s you can't store things like filenames in the value. For example, if loading a resource file fails, you can't store the filename inside. The solution to this problem is to log the error as soon as you find it, directly in the caller of the resource loading function, and not any further up the call stack.

---

That's about as clean as it gets.
> 2 votes

---
Tags: architecture, directx11
---


# Question
Title: Faking isometric graphics in a 2D space game
First off, I know exactly *what* my drawing problem is, and I have various ideas on how to approach solving it. I am here to figure out how to adjust which frame is drawn so that the isometric "illusion" is maintained.

I am writing a 2D, birds-eye view game that takes place in space. I am trying to use isometric graphics in a world where Up is North, no rotating of the game world like in traditional isometric games (remember, the game takes place in space, no terrain). Here is an example sprite I am trying to use: http://cell.stat-life.com/images/stories/AsteroidOutpost/Spaceship64.png Rotated 64 times about it's own vertical axis with a viewing angle of 35 degrees (aka, iso). The image was generated, so this **can** be changed.

For the sake of clarity, I have dictated that North (Up) is 0 degrees, and East (Right) is 90.

My problem is that my sprite doesn't always *look* like it's facing where the game thinks it is due to a difference in the 3D planes used. Not sure if I'm using the terminology correctly, but my spaceship was rotated on one plane, and the view plane is expecting things to be rotated on its own plane. Here's a depiction of the problem:

http://cell.stat-life.com/images/stories/AsteroidOutpost/ProjectionIssue.png On the left, I have side views, on the right I have top-down views. On the top, I have the space ship/sprite sheet view of the world. On the bottom, I have what the sprite *looks* like when it is drawn to the screen.

In the top right is a simplified version of how my spaceship was rotated (even degree separations between each frame). In the bottom right is the angle that the sprite *looks* like it's facing when a particular angle is drawn on the screen. The problem is most evident at around 45 degrees. Here is an image that is overlaid with a "screen plane" line that is pointed in the direction that the ship is supposed to be facing: http://cell.stat-life.com/images/stories/AsteroidOutpost/Spaceship64RedLine.png The red line should **always** be pointed in the exact same direction as the ship, but as you can see, the projection issue is causing a problem. I hope I am describing the issue well enough.

**EDIT:** The red line is rotated on the screen plane, while the space ship is rotated on the "ship plane", hence the large difference between the ship angle and the screen angle when it is drawn. **END EDIT**

It looks rather odd when this ship is shooting a laser beam at a target that is off to one side, when it should be shooting straight ahead.

So... the solutions that I have come up with are:

1. Stop trying to fake an isometric view, go big or go home. Rotate my world already. (PS: this will fix my problem, right?)
2. Alter my sprite sheet (somehow) to have frames that represent the "screen angle" that the model will be viewed at. So when I ask for a 45 degree image, it will actually look like it's facing 45 degrees on the screen.
3. Alter my sprite rendering system to grab a different frame from the sprite sheet (somehow), knowing that grabbing the "normal" frame will look funny. So instead of grabbing the 45 degree frame, it will grab the ... 33 degree frame (just guessing) so that it *looks* correct to the user.
4. Just use 3D! It's so much easier man

**For one:** Which solution would you recommend? I'm leaning toward 2, even though I know it's wrong. Remember that I have full access to the sprite generation tool. Method 3 would be my second choice. Both of these methods simply require that I apply some math to the angle(s) to get my desired result. Btw, I added #4 in there as a joke, I don't want to move to 3D.

**For two:** Using methods 2 or 3, how would I adjust the input or output angles? I'm not all that good with 3D projections, and 3D matrices (let alone 2D matrices), and whatever other math might be used to achieve me desired result.

Thinking out loud here: if I take a unit vector facing in the direction that I want the ship to look (on the screen plane), then project that onto the ship plane, then figure out what the angle between that projected line and the plane's north is, I should have the angle of the ship graphic that I want to display. Right? (solution for #3?) Man... I can't work that out.

**EDIT:**

I know the problem is hard to visualize with static images, so I have complied my Sprite Library Visual Tester to display the issue: http://cell.stat-life.com/downloads/SpriteLibVisualTest.zip It requires XNA 4.0 This application is simply rotating the sprite, and drawing a line from its centre point outward at the angle the game thinks the ship should be facing.

**EDIT Sept 8**

Continuing from my "thinking out loud" paragraph: Instead of using a projection (because it looks hard) I'm thinking I could take a north facing unit vector (0x,1y,0z), use a matrix to rotate it to the angle the sprite is actually facing, then rotate it again from the "viewing plane" outward to the "sprite plane" around the X axis, then... flatten? the vector (essentially project it) back onto the viewing plane by only using the X and Y (ignoring Z). Then using that new flattened vector, I could determine its angle and use that to... something something. I'll think more later.

**EDIT Sept 8 (2)**

I tried following my idea from above with some success, yay! So... to get a red line to *look* like it is coming straight out of my spaceship (testing purposes only), I did the following:

```
Vector3 vect = new Vector3(0, 1, 0);
vect = Vector3.Transform(vect, Matrix.CreateRotationZ(rotation));
vect = Vector3.Transform(vect, Matrix.CreateRotationY((float)((Math.PI / 2) - MathHelper.ToRadians(AngleFromHorizon))));
Vector2 flattenedVect = new Vector2(vect.X, vect.Y);

float adjustedRotation = (float)(getAngle(flattenedVect.X, flattenedVect.Y));

```

Where `rotation` is the screen angle and `adjustedRotation` is now that screen angle looks on the sprite plane. I don't know why I needed to rotate Y instead of X, but it's probably something to do with 3D that I don't know about.

So, now I have an additional piece of information, but how do I use this to pick a more appropriate frame? Maybe instead of rotating from the view plane into the sprite plane, then projecting back, I should try to do it the other way around. Here's my sprite with an adjusted red line, but what I really want to do is to adjust the model, not the line: http://cell.stat-life.com/images/stories/AsteroidOutpost/Spaceship64RedLineCorrected.png

**EDIT Sept 9**

HORAY! It's fixed! I will describe what I did to fix it:

I followed eBusiness's advice and "squished" by world coordinate system (or stretched...?). This is essentially solution #1, although I was under the impression that I would have to rotate my world coordinate system in relation to the screen coord system. Not true! Up is still +y, and Right is still +x. I modified my WorldToScreen and ScreenToWorld methods to properly convert between the world and screen coordinates. These methods may not be optimal, but here are the only two methods in my codebase that had to change.

```
public Vector2 ScreenToWorld(float x, float y)
{
    float deltaX = x - (size.Width / 2f);
    float deltaY = y - (size.Height / 2f);

    deltaX = deltaX * scaleFactor / (float)Math.Sqrt(3);
    deltaY = deltaY * scaleFactor;

    return new Vector2(focusWorldPoint.X + deltaX, focusWorldPoint.Y + deltaY);
}

public Vector2 WorldToScreen(float x, float y)
{
    float deltaX = x - focusWorldPoint.X;
    float deltaY = y - focusWorldPoint.Y;

    deltaX = deltaX / scaleFactor * (float)Math.Sqrt(3);
    deltaY = deltaY / scaleFactor;

    return new Vector2(size.Width / 2f + deltaX, size.Height / 2f + deltaY);
}

```

That was it! Changing those two methods affected everything else: what I was looking at, where the objects where drawn, where I was clicking, everything. My spaceship now looks directly at the target it is shooting, and everything is falling into place. I will be experimenting with the orthographic projection, see if it makes everything seem more 'real'.

# Answer
When you have chosen isometric perspective you need to correct the scale between the X and the Y-axis. If a given distance projects to 1 on the screens Y-axis then the same distance will project to sqrt(3) on the screens X-axis. So if you draw stuff flat on the screen you'd do something like:

```
draw(object.image, object.x*sqrt(3), object.y)

```

Non-answer notes:

* Why would you mess with sprite sheets and stuff? You can get a 3D renderer to do isometric if you want.
* Since you are using sprite sheets, why ain't they anti-aliased?
* Isometric in space, I don't think I have ever seen a game use that, I'm not sure how well it will work given the lack of a clearly isometric ground for visual reference.
> 4 votes

# Answer
How is the rotated sprite generated? Are these screenshots of a rotating 3D model? The facing angle could be off due to the camera perspective of the 3D modeling tool. Isometric perspective is not an accurate representation of the 3D space. Stuff far away from the 'camera' does not get smaller.

If you just want a quick fix. Solution 2 might be difficult to get right. Solution 3 seems easy just swap the frames not matching the angle with one that fits the angle better.

The lasers will still be off sometimes. As you are not doing a smooth rotation but showing different frames for certain degree ranges.

**EDIT:**

Your problem is that the generated screenshots are not isometric perspective, but a normal 3D camera view.

Isometric view simulates 3D space but is not an accurate representation. Things get smaller with increasing distance from the camera. This is not done for isometric perspective as this would cause ugly scaling artifacts in the sprite.

Your space ship screenshots are made with 3D camera perspective. Thats why the laser shooting is off. Compare the red line in the 'isometric' and the 'perspective'.

Your sprite generator should use **Matrix.CreateOrthographic()** instead of **Matrix.CreatePerspective()** for the projection matrix.
> 5 votes

# Answer
I think what you've got here is simply how isometric looks. You're right in that, visually speaking, there appears to be a larger difference between 0deg and 10deg than between 90deg and 100deg . . . but that's because isometric intrinsically compresses one axis. If you don't want that look, you don't want isometric.

That said, I think the visual issues you're having are thanks to not having a visual reference point. Your brain is assuming you're looking at it top-down - hey, it's space, why wouldn't you be - and so is interpreting it as a standard top-down view. For the sake of testing, try adding some floating holographic reference points. A 45-degree angled grid, for example, or a set of range circles around your spacecraft. Make sure they're appropriately distorted as if they were on the same isometric plane your spaceship is rendered on. I'd wager that your brain will figure out the perspective and it will suddenly look right.

Now, figuring out how to get that across to your users . . . that's another matter altogether.
> 1 votes

---
Tags: mathematics, xna-4.0, isometric, spritesheet, projection
---


# Question
Title: Going from using XMLSerializer to using the XNA Content Pipeline
A well known limitation of using the XNA Content Pipeline is that it is not included in the XNA redistributable. So, if you want to create an editor for your game, the designer must download the whole deal: your editor, your engine, XNA Game Studio and Visual Studio Express. Even then, I'm not sure you can compile your XML data into xnb outside of Visual Studio.

So I decided to simply use XMLSerializer, which works fine. However, I'm thinking that, once all the content of my game is done, prior to release, it would be great if I could convert the whole system into using the XNA Content Pipeline. In my mind, I think that the compiled xnb files would load faster than deserializing XML into objects.

Is the conversion possible? More importantly, **is it worth it**?

Note: my intention is to release the game as an XBOX Live Indie Game.

# Answer
> 2 votes
I'm afraid the conversion in the first place was probably a bad call. Depending on Visual Studio (Express) and XNA Game Studio isn't so bad, because they're free downloads. And I believe the WinForms 2 sample is a good starting point for getting the content pipeline working outside XNA. And loading from XNB should be faster than de-serializing XML.

As for the conversion back - it's probably not worth it.

Possibly a better option would be to write a custom content processor that (rather than using XNA's built-in XML importer) loads your XML files and deserializes them into objects as normal. And then outputs those objects using the content pipeline's automatic XNB writing support. Then you can use `Content.Load` to load those objects back from the output XNB.

That way you get to keep all the benefits of your XML format (including that it's already written), as well as all the benefits of using XNB in your game.

---
Tags: xna, xml, content-generation, xna-content-pipeline
---


# Question
Title: Is a multiplayer game in JavaScript a bad idea?
What are the possible downsides to using (client side) JavaScript when creating a multiplayer game?

Game description: It's an MMORPG/RTS. That means players actively contribute to structures in the world and create much of the content themselves.

# Answer
It's fine if:

1. The server doesn't send any information about players behind local player's field of view (must be calculated serverside) to the local player (to prevent wallhacking).
2. All actions are checked for availability on server when a player presses action button.
3. You only render on client - all actions are done on server and only predicted on client.
4. All timed actions are serverside.
> 9 votes

# Answer
Whether or not your game is a good fit for JavaScript development depends on the game. You didn't describe your game, so there's no way for us to answer the question in the title.

However I *can* say that your hacking concern is not a problem here. Not because JavaScript can't be hacked (it can, and easily) but *so can every other client-side technology.* One of the basic tenets of multiplayer game development is "never trust the client". Design your game in such a way that anything you need to protect from hacking is running on the server, because the client will be hacked. This means only send UI commands from the client (eg. "the player clicked the Bomb button") and calculate the results of player actions on the server. Then the server sends back to the client the results of those actions.

Since no matter what technology you relied on you should design your game with the assumption that the client-side component will be hacked, the hackability of JavaScript isn't a consideration when deciding whether or not to use JavaScript.
> 10 votes

# Answer
People can change the client code in order to cheat, that is a problem for any multiplayer game. If reaction speed or speedy solving of mathematical tasks is a part of the game you can't completely prevent cheating.

For any other game element you must ensure that the client won't and can't obtain information that is supposed to be hidden to the player. And of course the server must validate that every action taken by a player is legal.

The greatest problem I see in JavaScript games is that a lot of browsers have a tendency to stutter, especially Firefox was pretty bad last time I checked. For this reason JavaScript is not a good choice for timing-sensitive gameplay. But for turn-based or at least slow-paced games JavaScript can work quite well.
> 2 votes

# Answer
Changing Javascript variables is pretty easy to do with tools like Firebug (for firefox) or the build in dev tools of Safari/Chrome. You can simply type in javascript in the console and it'll get executed. As a simple rule, do not rely on the client side for security. Apart from that, with the introduction of the HTML5 canvas element, javascript offers you some real possibilities for simple games (There is a full javascript/html5 version of Angry Birds for instance).
> 2 votes

---
Tags: 2d, multiplayer, javascript
---


title: Where to start with game development?

text:
# Question
Title: Where to start with game development?
I asked this earlier in this thread at stackoverflow.com. One of the early comments redirected me here to gamedev.stackexchange.com, so I'm reposting here.

Searching for related questions I found a number of very specific questions, but I'm afraid the specifics have proved fruitless for me and after 4 hours on Google I'm no closer than I started, so I felt reaching out to a community might be in order.

First, my goal: I've never made a game before, although I've muddled over the possibility several times. I decided to finally sit down and start learning how to code games, use game engines, etc. All so that one day (hopefully soon) I'll be able to make functional (albeit simple) games. I can start adding complexity later, for now I'd be glad to have a keyboard-controlled camera moving in a 3D world with no interaction beyond that.

My background: I've worked in SEVERAL programming languages ranging from PHP to C++ to Java to ASM. I'm not afraid of any challenges that come with learning the new syntax or limitations inherent in a new language. All of my past programming experience, however, has been strictly non-graphical and usually with little or extremely simple interaction during execution. I've created extensive and brilliant algorithms for solving logical and mathematical problems as well as graphing problems. However in every case input was either defined in a file, passed form an HTML form, or typed into the console. Real-time interaction with the user is something with which I have no experience.

My question: Where should I start in trying to make games? Better yet- where should I start in trying to create a keyboard-navigable 3D environment? In searching online I've found several resources linking to game engines, graphics engines, and physics engines. Here's a brief summary of my experiences with a few engines I tried:

Unreal SDK: The tutorial videos assume that you already have in-depth knowledge of 3D modeling, graphics engines, animations, etc. The "Getting Started" page offers no formal explanation of game development but jumps into how Unreal can streamline processes it assumes you're already familiar with. After downloading the SDK and launching it to see if the tools were as intuitive as they claimed, I was greeted with about 60 buttons and a blank void for my 3D modeling. Clicking on "add volume" (to attempt to add a basic cube) I was met with a menu of 30 options. Panicking, I closed the editor.

Crystal Space: The website seemed rather informative, explaining that Crystal Space was just for graphics and the companion software, CEL, provided entity logic for making games. A demo game was provided, which was built using "CELStart", their simple tool for people with no knowledge of game programming. I launched the game to see what I might look forward to creating. It froze several times, the menus were buggy, there were thousands of graphical glitches, enemies didn't respond to damage, and when I closed the game it locked up. Gave up on that engine.

IrrLicht: The tutorial assumes I have Visual Studio 6.0 (I have Visual Studio 2010). Following their instructions I was unable to properly import the library into Visual Studio and unable to call any of the functions that they kept using. Manually copying header files, class files, and DLLs into my project's folder - the project failed to properly compile.

Clearly I'm not off to a good start and I'm going in circles. Can someone point me in the right direction? Should I start by downloading a program like Blender and learning 3D modeling, or should I be learning how to use a graphics engine? Should I look for an all-inclusive game engine, or is it better to try and code my own game logic? If anyone has actually made their own games, I would prefer to hear how they got their start.

Also- taking classes at my school is not an option. Nothing is offered.

# Answer
> 39 votes
I have asked such a question when I joined GD. Here are some links that might be of interest to you which I hope will guide you toward your objective.

In short, I would go with `XNA Game Studio` to get a grip on game development. Then, moving forward to what you wish to achieve as knowledge/technology. `XNA` taught me about working with sprites, and allowed me to apply some of my knowledge right from the beginning of my learning curve so that I have been able to get a grasp fast enough to understand how I should design my game to use classes while working with dependency injection and so forth. So, I'm keeping you waiting no more.

1. Where to start writing games, any tutorials or the like?
2. What are the fundamentals of game development? (Interesting question, IMHO)
3. Separating physics and game logic from UI code
4. Moving my sprite in XNA using classes

Why XNA will you ask? Simply because of your Java background. XNA uses C# which is similar to Java on some multiple ways, and is also a simple framework to use which abstracts away the Game Loop and stuff so that you may concentrate on what is important.

I really do hope this will get you starting. =)

# Answer
> 8 votes
You might try Unity 3D, because

* it can be programmed in JavaScript, C# or Boo
* it has a good tutorial over here
* its learning curve is not as steep
* there is Unity Answers, where you find even more resources.

(Disclaimer: I'm in no way related to the makers of Unity, I just use it myself and found it a great tool to learn the basics).

But yeah – you set yourself up to quite some task. I'm now in my 6th semester studying game design, and I still don't feel like I scratched more than the surface. It's no wonder the industry has specialists for pretty much every facet of the process of creating a game.

**Edit:** There has been a comment about Unity being seen as not a "proper" game engine, that could be misunderstood as me saying that – therefore spawning the comments below. It was not my intention to suggest that Unity could not be used to do proper game design, on the contrary. I use it myself, and I like it. ;)

# Answer
> 2 votes
Well if you had problems with irrlicht, you should also try Ogre3D; it's not easier, but it may work better if you put some time into it. The important thing you have to understand are what is a framelistener, how to get the time since the last frame was displayed, and that's pretty much the only thing you have to understand if you want to make this application you are talking about.

I've also had some difficulties with irrlicht, the tutorials are not very up to date, but you should have tried the samples !

I also ran a lot in circles at the begining, toying with panda3d and other stuff like pygame etc. Try to focus on some game idea and implement one thing at a time.

And try to remember some matric math, it will have some use in 3D !

# Answer
> 2 votes
I've recently started the same pursuit as you. I ran into a pure java engine called jMonkeyEngine which has led me through a fantastic set of tutorials. I don't know if it really explains game design to a massive extent but it does get you started on the graphical front.

It suggests/links to tools you might use for modeling and has copy and paste-able, well-described examples to step you through putting a box on the screen to setting up the physics engine.

Definitely worth a read - I had a good idea of what I was doing after only several hours.

# Answer
> 2 votes
You should really try Flixel http://flixel.org/ I Made my first "demo" game using flixel. Nice community, nice tutorials.

It's not 3D but it does have many nice features that make your first steps into the game programming environment easy.

Such that: Display thousands of moving objects
Basic collisions between objects
Group objects together for simplicity
Easily generate and emit particles
Create game levels using tilemaps
Text display, save games, scrolling
Mouse & keyboard input
Math & color utilities

And it's free for commercial use, which is awesome.

# Answer
> 1 votes
If you haven't worked with graphics at all.before just learning open gl or direct x is a start. I programmed my first game that way. Our company engines are in house and most systems support open gl in some form. I learned while on the job looking through the code written before I started working. You might want to take a look at some open source projects to see how a game structure is set up and start modifying those until you feel comfortable about starting your own thing. I also suggest "Game coding complete" as a great reference to all the little bits of game programming you don't realize are there, like proper file structure and resource management.

# Answer
> 1 votes
Try Source Engine. It is easy to develop games on it and you can get distribution platform (Steam) and sell your game for free if you sign an agreement with Valve Corportaion.

# Answer
> 1 votes
I would recommend starting with flash games, since you really have everything you need in one package to make simple games. There are tons of blogs with walkthroughs, Emanuele Feronato's for example. He even has a book out with 10 complete games or so.

I've been using FlashDevelop, which is sufficient for development.

Chris Moeller's "Creating a Asteroids Flash Game" is an excellent case in point, with a complete step by step approach using flash develop.

For Tile-based games, there's an excellent tutorial at Ironcoding.

Armed with all that, my recommendation is to find some place where there is a video game challenge, with a community of people building games. Build one video game a month, focusing on something small you can finish, polish and present before going onto your next project. I'm participating in a monthly video game challenge here.

**Keep it small so you can finish it and release it.**

---
Tags: 3d, graphics, career, planning
---


# Question
Title: Should Different "Types" of Animations be in the Same Class?
For example, say you want a character animation and a health bar animation. Since these require different algorithms, should they be in the same class?

They both re-use some of the same code but having them both in one class for me requires MANY parameters to be sent in upon instance creation.

This could just be a lack of Object-Orientation understanding on my part.

I'm no sure what you would call these different "types", possibly static and moving animations. I am sure there are plenty more. I just would like to know best practices when it comes to this type of thing.

Thanks!

# Answer
> 8 votes
Fundamentally, animation is the changing of a set of properties over time.

Animating a health bar rectangle is just changing the width of the rectangle (or maybe the height) over time, whereas animating an on-screen 2D character is basically changing the image used for its sprite as well as its position over time.

It's certainly possible to generalize an animation class as a container of transformations of properties (sometimes called keyframes) that are applied at some time offset. Complete generalization -- the ability to animate any property on any kind of target object -- may be overkill for your needs. WPF has an animation component, and CoreAnimation is also something you may be interested in looking at -- although they are both *so* generalized that they can be cumbersome, so be wary.

I would encourage you to arrive at a design that does *not* have one class per overall animation type, if possible. At least trend towards having as few as possible and sharing code. The best thing for you to do is probably figure out which kinds of animations you want to support in your code, and what actually has to change on your objects to make those animations happen, and then build a system that can cleanly change those types of properties over time. That will serve as a decent baseline.

---
Tags: animation, objects
---


title: Designing a ResourceManager class

text:
# Question
Title: Designing a ResourceManager class
I've decided I want to write a central ResourceManager/ResourceCache class for my hobby game engine, but am having trouble designing a caching scheme.

The idea is that the ResourceManager has a soft target for the total memory used by all the game's resources combined. Other classes will create resource objects, which will be in an unloaded state, and pass them to the ResourceManager. The ResourceManager then decides when to load / unload the given resources, keeping the soft limit in mind.

When a resource is needed by another class a request is sent to the ResourceManager for it, (either using a string id or a unique identifier). If the resource is loaded, then a read-only reference to the resource is passed to the calling function, (wrapped in a referenced counted weak\_ptr). If the resource isn't loaded, then the manager will mark the object to be loaded at the next opportunity, (usually at the end of drawing the frame).

Note that, although my system does do some reference counting, it only counts when the resource is being read, (so the reference count may be 0, but an entity might still be keeping track of it's uid).

It is also possible to mark resources for loading well in advance of first use. Here is a bit a sketch of the classes I am using:

```
typedef unsigned int ResourceId;

// Resource is an abstract data type.
class Resource
{
   Resource();
   virtual ~Resource();

   virtual bool load() = 0;
   virtual bool unload() = 0;
   virtual size_t getSize() = 0; // Used in determining how much memory is
                                 // being used.
   bool isLoaded();
   bool isMarkedForUnloading();
   bool isMarkedForReload();
   void reference();
   void dereference();
};

// This template class works as a weak_ptr, takes as a parameter a sub-class
// of Resource. Note it only hands give a const reference to the Resource, as
// it is read only.
template <class T>
class ResourceGuard
{
   public:
     ResourceGuard(T *_resource): resource(_resource)
     {
        resource->reference();
     }

     virtual ~ResourceGuard() { resource->dereference();}
     const T* operator*() const { return (resource); }
   };

class ResourceManager
{
   // Assume constructor / destructor stuff
   public:
      // Returns true if resource loaded successfully, or was already loaded.
      bool loadResource(ResourceId uid);

      // Returns true if the resource could be reloaded,(if it is being read
      // it can't be reloaded until later).
      bool reloadResource(ResourceId uid)

      // Returns true if the resource could be unloaded,(if it is being read
      // it can't be unloaded until later)
      bool unloadResource(ResourceId uid);

      // Add a resource, with it's named identifier.
      ResourceId addResource(const char * name,Resource *resource);

      // Get the uid of a resource. Returns 0 if it doesn't exist.
      ResourceId getResourceId(const char * name);

      // This is the call most likely to be used when a level is running,
      // load/reload/unload might get called during level transitions.
      template <class T>
      ResourceGuard<T> &getResource(ResourceId resourceId)
      {
         // Calls a private method, pretend it exits
         T *temp = dynamic_cast<T*> (_getResource(resourceId));
         assert(temp != NULL);
         return (ResourceGuard<T>(temp));
      }

      // Generally, this will automatically load/unload data, and is called
      // once per frame. It's also where the caching scheme comes into play.
      void update();

};

```

The trouble is, to keep the total data usage hovering around / under the soft limit, the manager will have to have a smart way of determining which objects to unload.

I'm thinking of using some kind of priority system, (eg. Temporary Priority, Frequently Used Priority, Permanent Priority), combined with the time of the last dereference, and the size of the resource, to determine when to remove it. But I can't think of a decent scheme to use, or the right data-structures required to quickly manage them.

Could someone who has implemented a system like this give an overview of how their's worked. Is there an obvious design pattern I am missing out on? Have I made this too complicated? Ideally I need an efficient, and hard to abuse system. Any ideas?

# Answer
I'm not sure if this pertains to your question 100% but a few advice tips are the following:

1. Wrap your resources in a handle. Your resources should be split into two: their description (usually in XML) and actual data. The engine should load ALL resource descriptions at the start of the game and create all handles for them. When a component requests a resource the handle is returned. That way functions can proceed as normal (they can still request the size etc..). Now what if you haven't loaded the resource yet? Make a 'null resource' that is used to replace any resource that is attempted to be drawn but hasn't been loaded yet.

There's a bunch more. I recently read this book "Game Engine Design and Implementation" and a has very nice section where it goes and designs a resource manager class.

Without the ResourceHandle and Memory Budget functionality here is what the book recommends:

```
typedef enum
{
    RESOURCE_NULL = 0,
    RESOURCE_GRAPHIC = 1,
    RESOURCE_MOVIE = 2,
    RESOURCE_AUDIO = 3,
    RESOURCE_TEXT =4,
}RESOURCE_TYPE;

class Resource : public EngineObject
{
public:
    Resource() : _resourceID(0), _scope(0), _type(RESOURCE_NULL) {}
    virtual ~Resource() {}
    virtual void Load() = 0;
    virtual void Unload()= 0;

    void SetResourceID(UINT ID) { _resourceID = ID; }
    UINT GetResourceID() const { return _resourceID; }

    void SetFilename(std::string filename) { _filename = filename; }
    std::string GetFilename() const { return _filename; }

    void SetResourceType(RESOURCE_TYPE type) { _type = type; }
    RESOURCE_TYPE GetResourceType() const { return _type; }

    void SetResourceScope(UINT scope) { _scope = scope; }
    UINT GetResourceScope() const { return _scope; }

    bool IsLoaded() const { return _loaded; }
    void SetLoaded(bool value) { _loaded = value; }

protected:
    UINT _resourceID;
    UINT _scope;
    std::string _filename;
    RESOURCE_TYPE _type;
    bool _loaded;
private:
};

class ResourceManager : public Singleton<ResourceManager>, public EngineObject
{
public:
    ResourceManager() : _currentScope(0), _resourceCount(0) {};
    virtual ~ResourceManager();
    static ResourceManager& GetInstance() { return *_instance; }

    Resource * FindResourceByID(UINT ID);
    void Clear();
    bool LoadFromXMLFile(std::string filename);
    void SetCurrentScope(UINT scope);
    const UINT GetResourceCount() const { return _resourceCount; }
protected:
    UINT _currentScope;
    UINT _resourceCount; //Total number of resources unloaded and loaded
    std::map<UINT, std::list<Resource*> > _resources; //Map of form <scope, resource list>

private:
};

```

Notice that the SetScope functionality refers to a Scene-Layered Engine Design where the ScopeLevel refers to the Scene#. Once a scene has been entered/exited, all resources according to that scope are loaded and any not in the global scope are unloaded.
> 9 votes

---
Tags: c++, design-patterns, resource-management
---


title: iOS Game Development - Where to start?

text:
# Question
Title: iOS Game Development - Where to start?
I'm a web developer with a keen interest in game development for the iOS platform. I develop mostly with Ruby for the day job but I have dabbled quite a bit with Java in the past, random world generators, platform games, space invaders etc, never anything serious though and only using Java2D.

It seems to be an extremely steep learning curve to get into iOS game development, so my question is where do I start?

I'm not particularly interested in 3D initially, top down / isometric would probably suit the first game I have in mind.

Can anyone recommend a good skills path to learn through, or any videos/tutorials or books to get? I realise this will take a while but I'm happy as long as I know I'm on the right track.

Thanks, Matt

# Answer
If you are interested in iOS game dev the best possible way to become familiar with it is to just code. Code up some small projects first to get the hang of things. I would check out 10 iOS game projects to get you started . This is exactly the type of thing I am talking about.

From there, come back with any technical questions you have from those experiences and you will be on your way to making a sweet game!

If you're not interested in doing that then do some simple searches related to this question and you will find plenty of resources and cool books.

Here is a book for @matthewrk engine reference. Learning Cocos2D: A Hands-On Guide to Building iOS Games with Cocos2D, Box2D, and Chipmunk*book update*
> 2 votes

# Answer
I really enjoyed Learning iOS game programming. It's an amazing book for beginners that holds your hand through the development process to ultimatly end up with a complete game (which the author released on the App Store as a free game). I'm pretty sure everything is included with the book (assets and such) and it doesn't really make any assumption about prior knowledge of OpenGL, OpenAL, etc (although minimal knowledge of Obj-C/C is a plus).

What I also really enjoyed is that it doesn't use any game frameworks (Cocos2D, Box2D, etc) and that's important for me because I prefer learning about the underlying technologies (OpenGL/OpenAL in this case). I think it makes my learning experience harder yet more complete and satisfying. If that's not your thing, then this book might not be for you obviously :).
> 0 votes

# Answer
Also if you do not want to learn Objective-C you could also try either GameSalad Creator, which is mostly graphical with some scripting or Corona SDK, which allows you to program lua on the iPhone. The advantage of these two approaches that they save time and allow for fast prototyping. Most 2D Games should be possible with those two development tools. The disadvantage if you want to distribute your games you need to pay some fee and there might be things that are not possible.
> 0 votes

---
Tags: ios
---


# Question
Title: Most efficient way to capture OpenGL ES content of iPhone screen
I'd like to efficiently capture a "screenshot" of my OpenGL ES iPhone game. I put screenshot in quotes because I really want to move the screen contents into a pixel buffer that I can eventually use to create a mov file using AVFoundation.

Currently I'm taking the screenshot with this method from Apple. The resulting image is great... however capturing the image causes a small stutter in my game. Looks like the call to `glReadPixels` causes the stutter.

**How can I capture the screen's contents more efficiently?** Perhaps I can improve the efficiency of the call to `glReadPixels`? Or perhaps I can populate a CMSampleBuffer or CVPixelBuffer without calling glReadPixels?

Perhaps the OpenGL ES data could be accessed directly somehow w/o having to copy the data into a buffer via `glReadPixels`.

**Edit #1**: Perhaps a "Frame Buffer Object" could be useful? Or "rendering directly to a texture"?

# Answer
Frame Buffer Object allows to create a texture where you can draw. That is Render To Texture. It is very fast (no use of CPU) and useful for mirror effects or post 2D effects. But it is a gpu object so you can access to its content with CPU; you need glReadPixels if you want to use it on CPU. the main advantage is you can set your size. So you can create a small FBO for a good framerate.
> 3 votes

# Answer
FBO is a lot faster than glReadPixels.
> -1 votes

---
Tags: opengl-es, ios, efficiency
---


title: Collision Managers and bitmaps

text:
# Question
Title: Collision Managers and bitmaps
I am rewriting a game I made to use a (custom) collision manager that uses the minimum displacement method. As of now, my simple manager can only recognize and act on a couple of shapes - Circles and AABB's. Those were pretty simple to implement, but I've run into a problem: My game also needs to be able to have bitmaps that the player (represented by an AABB) can interact with, such as the one below:

I have a couple of questions:

1) Does it make sense to have a shape BitmapShape, which does collision detection at the pixel level and searches outward in the bitmap for a place to move intersecting objects to? In the image above, it would make sense to check the players bottom-center coordinates against the bitmap of the hill, but you can imagine that this would provide odd results for an intersection from the top of the player.

2) How could any system like this allow for a rectangle to move up a hill? Wouldn't an minimum-displacement based method always move the rectangle backwards down a hill?

Thanks

# Answer
> 1 votes
1: That is a very processor consuming scenario, ditch the bitmap to bitmap collision.

2: Correct, minimum displacement would have the player sliding down the hill. What you need is axis-aligned displacement.

Suggestion:
Fill your collision shapes completely, that looks nicer. Make the player collision figure a vertical line, that is so much easier to check against, if you want him to behave like a box you can extend the collision shape to make up for the figures thinness.

In order to perform the actual collision check split you line into 3 sections, perform the check for each of them.

If the figure does not collide with the ground. Or if only the bottom linepart collides with the ground and the figure can be moved upwards vertically so that only a small part of the bottom linepart collide with the ground, without the top linepart intersecting with the ground. Or if it is the opposite case where only the top linepart intersect with the ground. Then it is a legal position.

If the figure does not occupy a legal position, move it backwards towards the position it came from in small steps until it does.

If the figure was moved backwards set it's horizontal movement to 0.

If the figure is in a legal position where only the top or bottom linepart intersect the ground you must move it as described in the collision check.

If the bottom linepart is intersecting and the figure is moving downward you must set it's vertical movement to 0. Likewise if the top linepart is intersecting and the figure is moving upward you must set it's vertical movement to 0.

Note:
The bottom linepart acts as a ground check, if it collides with the terrain the figure is standing on the ground and should therefore be able to jump etc.

---
Tags: collision-detection, collision-resolution
---


# Question
Title: Which one is better for a beginner to start with game development - unity3d or cryengine 3?
I am beginner in game development and want to work with either unity or cryengine because they have thier own player and we can play on web also with the player installed. I am confused with which to start. please answer this in terms of flexibity, visibility and speed, which one would be better?

# Answer
> 1 votes
If you just start in game development personally don't recommend to begin with a game engine like Unity or Cryengine because they are really complex, with a lot of functionality that may help you or not and like you're starting this will be too much.

Personally for a beginner I recommend to start with the basis so you will understand how a videogame works under the hood like Tetris, then Pacman, and later a scroller where you have to check collisions, physics, projectiles...etc...and after I recommend move on to a 3D engine...

I know that could be a little tedious but it's the best way to start in this industry and it's a path little bit hard but believe me all those little games will help you on the future..

# Answer
> 4 votes
Unity3d is the way to go, between Unity3d or CryEngine3, if you want web based product. CryEngine don't support that.

There is also other options with web support, NeoAxis Engine & Shiva 3d.

Google for more.

**Edit:** The term game development is a huge one. It includes a lot of thing. So, `wanna be a game developer, want suggestion` wont give us any clear idea about what you want to do. It's better if you tell us who/what you already are/can, and what you want to be. *Give us a bigger picture so we can suggest you to fix the details.*

---
Tags: unity
---


# Question
Title: How to make a tile vanish after player steps on it, in a tilebased game?
So I'm adding the basic mechanic of making frail/breaking tiles, those that break apart and disappear after the player has walked ontop of them. Now I thought this would be as easy as...:

```
//Breaking tiles represents the 2d array number, that describes the breaking tiletype.

if( TileWeAreStandingOn == breakingTile){

        //frameCount is a variable that counts the frames, after 30 frames (1 second) the tile disappears.

            frameCount++;
            if(frameCount > 30){

        //So, when 30 frames has passed, the tile is removed

            TileWeAreStandingOn = noTile;
            frameCount = 0;

        }
}

```

Now this works, but it only works WHILE you are standing on the breaking tile, once you jump, the countdown stops since the initial if-statement is not valid anymore. So I am trying to find ways around this where the player could jump onto a frail/breakable tile, and then jump onwards, and the tile would still break after 1 second. Also, if he walks past several breakable tiles in a row, they should all break timely, that is, they should all break after a second of the player has moved off of that tile. (which would result in a domino like timing, where one breaks shortly after another)

I need to make the tiles work independently, so that each tile reacts and starts to disappear/break whenever the player touches it. But my system is build around how the player interacts with the 2d array map and the tiles aren't independent entities, only the player is.

So I'm asking for suggestions how I can make the tiles react independently based on Players interactions with them? Especially in this case, where a tile should disappear a second after the players has touched it.

Thanks in advance guys!

# Answer
> 7 votes
Isn't it as simple as having a collection of tile locations and frame counters that get updated?

So where you have that code now (in rough pseudocode),

```
if( thisTile == breakable && !breakingTiles.Contains( thisTile ) )
{
    breakingTiles.Add( thisTile );
}

```

And somewhere else you do something like

```
foreach( tile in breakingTiles )
{
  ++tile.timeUntilBroken;
  if( tile.timeUntilBroken > 30 )
  {
     tile.Break(); // or whatever
  }
}

```

# Answer
> 1 votes
Use `flash.utils.Timer` to fire a destruction event for each tile.

In the simplest case, this would look something like this (no guarantee for syntax correctness, I don't have the SDK installed here).

```
if( TileWeAreStandingOn == breakingTile)
{
    var destructionTimer:Timer = new Timer(1000 /* milliseconds */, 1);
    /**
      * This assumes TileWeAreStandingOn is a local variable in this method's scope,
      * so it can be bound with its current value into the event-handling closure.
      * It would need a small rewrite if it's an instance or class variable.
      */
    destructionTimer.addEventListener(TimerEvent.TIMER_COMPLETE,
        function {) { TileWeAreStandingOn = noTile; });
    destructionTimer.start();
}

```

# Answer
> 0 votes
The way around it is to have/create a memory where You store information WHAT should happen and WHEN it should happen. Then memory should be checked whether time has elapsed (in WHEN) and if it did, then do that WHAT should happen.

You can acomplish this in several ways:

* have few variables, this would work for one event (one WHEN, WHAT)
* have array of variables ... see Tetrad
* have callback ... see Martin

Each has its own pros/cons.

You seem to me to be quite new/unexperienced to programming. I would recommend You to do some more excercises in general programming. Data structures and algorithms. Quite nice book about programming is C Programming Language, the language it is for -C- is similar to Flash. You should also try searching stackexchange for recomendations on beginners book/tutorials on programming.

---
Tags: 2d, flash, platformer
---


title: How does hardware tessellation work?

text:
# Question
Title: How does hardware tessellation work?
I would just like someone to explain in relativly clear terms how hardware tessellation works considering it is the new buzzword with DX11.

Thanks.

# Answer
I'll give you the "simple" version and let someone else fill you in on the details if you're interested :).

There are basically two ways to model 3D objects. The first is one you don't see a lot of in games, and it involves using precise, mathematically defined curves to define the shape of an object. Using this method, the level of detail is (practically speaking) "infinite". Take a cylinder for example. A cylinder can be defined in very simple mathematical terms: all you really need to know is the radius at the ends and the length of the cylinder. In terms of the geometry, this information is all we need in order to render the cylinder in a 3D scene. Moreover, we can easily scale the cylinder to make it larger or smaller; all we need to do is maintain the ratio of the length to the radius. We can use the same formulas to represent the geometry, but with different parameters. We can represent a torus ("donut" shape) easily as well: we simply need to know the inner radius and outer radius. From that, we can compute the diameter (and therefore the radius) of the donut's body (the "cake") by subtracting the inner radius from the outer radius. The circular body wraps along the arc defined by the inner radius. This type of 3D definition is nice because it is relatively simple (resulting in a small model file), and there is no significant limit to the level of detail. The downside is that today's video hardware isn't designed to process these types of models efficiently (if at all).

The other way is to combine simple geometry to approximate the shape we want to represent. We do this with a process called *tessellation*. We could *tessellate* a cylinder by breaking it down into more primitive shapes: two circles and a series of long rectangles, which wrap around the outer edge. The circles can be further broken down into many tiny triangles, as can the rectangles along the edge. The end result is a model comprised *only* of triangles:

Or, for the torus:

The good news is that video hardware is optimized to handle this sort of geometry. Today's GPUs have no trouble churning out tons and tons of triangles every second. However, there's an obvious problem: we are trying to represent curved surfaces using shapes that have flat edges. In order for our cylinder to *look* like a cylinder (as opposed to a cube), we want to break it down into a *lot* of little triangles. Well, how many do we want? It depends. What kind of hardware will be used to render the scene? Faster hardware can render triangles faster than slower hardware, producing faster frame rates. There are other factors to consider, like how many other objects will be present in the scene, and how complex will they be? In games, there are typically a lot of objects in a given scene. Moreover, objects may travel through different scenes, each with different levels of visual complexity. It's hard to figure out the *level of detail* to use when we tessellate our models.

Another problem is that of geometric complexity: whereas a curve-based definition of a cylinder is very simple (radius and length), a tessellated definition likely combines hundreds of triangles, each of which needs to be defined independently. Consequently, our tessellated model file will be much, much larger. Let's say we have a mathematically defined model of something complex, like a person. Our model file may be a mere 24kb in size. Well, once that model is tessellated, the resulting file could be 24mb (24,000kb). That's quite a difference.

Hardware tessellation takes advantage of *geometry shaders* to perform hardware-assisted tessellation *in real time* (or in nearly real time). Essentially, it provides a mechanism to take a mathematically defined 3D model and transform it into a tessellated format that the video card can render efficiently. Traditionally, game developers have performed tessellation at the studio and shipped the tessellated models with the game. Hardware tessellation allows us to defer this process until the game is *actually running* on the player's computer. This has some serious benefits:

1. The size of the game's 3D content decreases dramatically (fewer discs or smaller downloads, and less hard disk space required).
2. We can control the level of detail *in real time*. Are we running on a cutting-edge beast of a gaming machine? If so, we can tessellate using a very high level of detail. Are we running on an old laptop with integrated graphics? No problem; we can simply reduce the level of detail to boost performance.

So that's the gist of it. It's probably not 100% accurate, as I am not a 3D programmer, but that should give you a better idea of what all the fuss is about :).

Cheers,
Mike
> 42 votes

# Answer
Too bad that is not the way most developers are making use of tessellation now or in the near future. All they use tess for right now is to displace mostly flat surfaces acording to its heightmap. That also results in good looks, but I still think it's a poor use of much more capable technology.
> 0 votes

---
Tags: hardware, tessellation, directx11
---


# Question
Title: How to wisely update body trajectories in a 3D space simulation game?
Suppose I have a Spacecraft object in 3D space, controllable by the player. I want it to update its own trajectory, so I give it a function for that (actually it might be inside a controller component associated with it). No problem until this point.

For this function I want to use a scientifically tested, accurate N-body simulation algorithm (like this). It's my field so I already know how to do that.

The challenge is how to make the game activate the function efficiently. This is what I've thought of so far:

1. The algorithm can calculate a *lot* of time steps in a short time, so I could activate it in one loop, save the trajectory data, and go on for several game loops using that data. During this time the spacecraft's position is updated every loop, but the algorithm is sleeping.
2. When the predefined number of loops has passed, or when the user gives a movement command, the algorithm is activated again, producing the new portion of the trajectory to use next.
3. This might require double-buffering.

The question is: **who should be responsible for activating the spacecraft's algorithm?** Should I do that directly in the game loop, or perhaps create a "timer object" that keeps track of the number of loops and user input and calls the function when appropriate? Something else?

Note that the same thing would happen for all the other bodies orbiting in space. However the other bodies would simply have to follow predefined trajectories, no need for an algorithm. The timer object could take care of updating all the trajectories at the right times.

Also, if you think there is a totally different and better way to do this, please let me know.

Additional info: the game is in C++, and the graphics engine is Ogre3D.

EDIT: changed the part about the trajectories of the non-interactive bodies, because comments here made me realize that it was plain stupid.

# Answer
> 2 votes
This is a interesting software engineering problem.

First of all you need to identify what entities are involved (entities broadly speaking) and assign them responsibilities (-bility is better) and knowledge about the other entities (less is better).

Here I can see: your trajectory algorithm, the generic position updater, the user interface or user control subsystem.

Your algorithm does not need to know anything about user control subsystem or frame related updating stuff so it should be highly decoupled about the rest: it should keep the environment status and output the trajectory information and time validity by its own. You should implement it so you can run it without any game related component. This make your life easier in debugging and unit-testing phases.

Your algorithm needs a bridge to let its outputs be used for your ludic purposes. This kind of bridge should be implemented in a way so a different algorithm may be used with easy.

The interface side of the bridge (the side that will be used by the game) should give to its consumers a way observe the relevant environmental status (this prescinds the particular trajectory algorithm) and the user input while providing a query interface that can return a positional status, given a particular time coordinate.

The implementation side of the bridge should be aware of the trajectory algorithm: this encapsulates how you transform a positional query to a positional computation or a projection of your trajectory).

A possible implementation of the query functionality can be that the bridge uses the time coordinate along with the current computed trajectory to compute the position. If the trajectory is invalid than a new one is computed: a stored trajectory becomes invalid if used outside its time range of validity or if the environmental update methods detect an action by the user.

About the way the non-interactive objects trajectory are computed, keep in mind that probably everything is better than read through a file. Here we are talking about to trade-off disk usage, memory occupation and CPU allocation.

The answer to this trade-off is simple "compress": compressing basically means to store a fraction of the whole data and use CPU and RAM to transform compressed data into real and useful data.

In your case, the knowledge of the data is the key: you can start by identify the minimum data that is required to compute your trajectory; how you can translate it into a real(raster) path?

If the CPU usage for this is acceptable you are done, if not (as it should be reading your question) you need to look for where CPU intensive temporary data are computed.

This kind of data can be stored along with the basic trajectory parameters to speed up the trajectory reconstruction (memoization-like). You may preload these data if the ratio memory\_usage/usage\_frequency is good or avoid it and discard used data(hence re-read if re-needed).

In a nutshell: your custom specialized compression algorithm has to be tuned to achieve the better CPU/RAM/DISK trade-off.

---
Tags: c++, game-loop, simulations
---


# Question
Title: Proper way to handle destruction of game entities
Imagine a game world where loads and loads of entities are dynamicly loaded all the time, I would represent that as a list of entities perhaps, but what about removing them?

While when adding i could be pushing back the new entity, i could have the need to remove anywhere in the container. To avoid searching the element to find its position for removal, what choices do i have?

I tought that i could store the entity id as being its position in the container, creating a path for direct removal, but wouldnt that generate some kind of mutual dependency 'disorder' ?

I know the right way would be something like List.RemoveAt(whereToRemove); but what if only the entity knows when it should die?

Or am I just missing something and a list container would know when an object is destructed and reduce its own size?

# Answer
Here are your conditions:

* Other objects may still be dependant on your removed entity, after it is removed.
* You want only the entity to specify it's own removal.

You can't have both. Why? Because code at a higher level than your entity itself (see examples below) decides when that entity needs to be used. Consequently, only code at that same level can determine whether your entity is fit for removal or not.

*However*, what can happen is that the entity can *request* it's own removal, by firing off an event which the higher level code is listening for. That higher level then stores this request for removal in a list.

---

**Example 1: without events**

You are checking collisions between entities in your world. This is handled higher up, usually in your main game loop, which checks every entity against every other. In this example specifically, when an entity collides with another, only that entity's internal logic can determine how much damage it has taken, and whether or not it has "expired". So lets follow the logic flow for collisions where you have four entities in your world, A, B, C, and D. A is our entity we are concerned with.

We check A for collision with B. There is a collision. A takes damage 50%.

We check A for collision with C. There is a collision. A takes damage 50%. Because damage reaches 0, A determines that it has "died". It removes itself from the list.

We check A for collision with D. There would have been no collision, but you'll never get that far: you get a runtime exception because your entities list has been modified in the midst of a traveral operation.

**Example 2: with events**

Same setup as before.

We check A for collision with B. There is a collision. A takes damage 50%.

We check A for collision with C. There is a collision. A takes damage 50%. Because damage reaches 0, A determines that it has "died". It fires an event to the entity management code to say, "Remove me ASAP". The entity management code looks at the entity reference sent as part of the event, and stores that reference in a list of entities to be removed.

We check A for collision with D. There is no collision, and the check works just fine.

Now, at the *very end of the current game loop iteration*, run through the list of entities to be removed, and remove every one of these from your main entities list.

---

You can see how this avoids the problem altogether. You needn't use events, you can use signals or something else, but the principle is the same -- don't remove entities until you can safely do so. The flipside to this approach, to keep things clean and orderly, is doing the same with entities to add -- make sure you keep references to them, and only add them at the start of the next game loop iteration.

Lastly, don't forget to flush both your to-remove and your to-add lists, each time you use them to perform additions / removals on your main entity list.

PS. Don't be afraid to seek through your main list to do individual removals. It's part and parcel of entity management, and even massive lists tend to be very fast to traverse -- after all, that's what they're engineered for.
> 10 votes

# Answer
You're definitely looking for a HashMap/HashTable. A hashtable is a map that matches a key to a specific value. The key can be anything (such as the Entity ID).
> 0 votes

# Answer
I Guess you could use smartpointer idea to handle deallocations for you, in that case there won't be a need to keep a list of all entities inside your code.

in some cases you need a list to iterate over all the objects in your game. this list could be simply a link list where inserting and removing objects from it will take exactly O(1) time.

even to increase your speed more you can use some static array (possibly a vector). in that case you'll need to keep track of 2 linked lists inside same vector, one will iterate over valid objects and one will iterate over free objects. whenever smartpointer marks some place to be deleted you simply remove that pointer and add it's space to free spaces list. and whenever you add some entity you only need to remove first freespace fill it with entity pointer and then add it to valid objects list.
> 0 votes

---
Tags: c++, data-structure
---


# Question
Title: How can I implement shader lookups for my material system?
I have been working on a material system and for the most part everything works just fine, however, I hard code the shader that will be used. Obviously this causes a problem when I want to have the materials be saved through the material editor.

What I ended up doing was having the material save "attributes". These attributes would know if the material is using a texture or diffuse color (that's it for now). I then have a VS/PS to render objects with a texture or a diffuse color. Then for each of those, I have shaders for either no lighting, or my lighting system. Right there that will leave eight different shaders, so you can see where the complexity comes in with which ones to pick. Also, that is only if all the objects all have the same vertex type (position, tex coord, normal). However, that is not always the case, as some times the geometry may be built differently.

My question is, how can a propery shader lookup system be written for a material system? There comes into two things I can think of

1. Shaders based upon different lighting models
2. Shaders based upon different vertex formats

# Answer
> 1 votes
One practice I've used is to write one big file of unified shader code with features wrapped in #defines that are turned on/off at compile time. The various parameters that feed into this shader source are used to create a hash value which is used to key the resulting shader binary for fast lookup.

There is an intermediary, a container for the binary shader output that acts like a little database using the hash value as the key to the shader itself.

You have two options for compiling these shader binaries. First option would be to precompile everything and ship out the binaries, this is sub-optimal on different hardware but very nice for the end user's first runtime experience. Second option would let the end user's computer compile the shaders when encountered or (better) when first run as a setup step. That option would be slightly faster but the end user gets an extended setup during their first runtime.

# Answer
> 0 votes
One common way to reduce the huge number of extra shader combinations that a standard lighting system will give you is to use deferred shading.

---
Tags: architecture, algorithm, rendering, lighting
---


title: Point line collision reaction

text:
# Question
Title: Point line collision reaction
I am trying to program point line segment collision detection and reaction. I am doing this for fun and to learn.

The point moves (it has a velocity, and can be controlled by the user), whilst the lines are strait and stationary. The lines are not axis aligned. Everything is in 2D.

It is quite straight forward to work out if a collision has occurred. For each frame, the point moves from A to B. AB is a line, and if it crosses the line segment, a collision has occurred (or will occur) and I am able to work out the point of intersection (poi).

The problem I am having is with the reaction. Ideally I would like the point to be prevented from moving across the line. In one frame, I can move the point back to the poi (or only alow it to move as far as the poi), and alter the velocity. The problem I am having with this approach (I think) is that, next frame the user may try to cross the line again.

Although the point is on the poi, the point may not be exactly on the line. Since it is not axis aligned, I think there is always some subtle rounding issue (A float representation of a point on a line might be rounded to a point that is slightly on one side or the other). Because of this, next frame the path might not intersect the line (because it can start on the other side and move away from it) and the point is effectively allowed to cross the line.

Firstly, does the analysis sound correct?

Having accepted (maybe) that I cannot always exactly position the point on the line, I tried to move the point away from the line slightly (either along the normal to the line, or along the path vector). I then get a problem at edges. Attempting to fix one collision by moving the point away from the line (even slightly) can cause it to cross another line (one shape I am dealing with is a star, with sharp corners). This can mean that the solution to one collision inadvertently creates another collision, which is ignored.

Again, does this sound correct?

Anyway, whatever I try, I am having difficulty with edges, and the point is occasionally able to penetrate the polygons and cross lines, which is undesirable. Whilst I can find a lot of information about collision detection on the web (and on this site) I can find precious little information on collision reaction.

Does any one know of any good point line collision reaction tutorials? Or is my approach too flawed/over complicated?

# Answer
Well first off I'm assuming you're doing a kind of "trace" like described here: http://www.realtimerendering.com/intersections.html

So for a given frame you have a certain amount of velocity you want to account for. For the sake of argument let's say you want to slide along surfaces instead of bouncing off of them.

So let's say the user is pushing their point (or circle, if you want to give yourself a little more wiggle room with penetration testing) along a surface. You might have a certain amount of movement until you hit the wall. So place the object at the earliest intersection point you detect (but slightly offset in the opposite direction to avoid the floating point errors you mentioned). Then in the same frame figure out the desired velocity (in our case we'd do a sliding effect by taking the remaining component of the velocity vector that's parallel to the hit surface). In the same frame you'd attempt to move the user's point along this updated velocity vector, doing collision detections along the way. Iterating the collisions, if you will. You'll probably have to set some maximum number of per-frame collisions so that you don't get into some kind of near-infinite-loop situation. This number is usually pretty small, like 5 or so.
> 1 votes

# Answer
The first part seems reasonable, and your solution also seems reasonable. The second part can be avoided by finding the closest line that intersects the path. You can't create a new collision if there is nothing closer that will collide.
> 1 votes

# Answer
I found this tutorial to be very revealing on the subject.

Metanet Collision Detection & Reaction

**Quote from one of the first lines of the tutorial:**

"*Before thinking about how to detect collisions, we should first think about what should happen to two objects which collide.*"
> 0 votes

---
Tags: 2d, collision-detection, geometry, computational-geometry
---


# Question
Title: (XNA) Checking coordinates, directly vs List<Vector2> vs Dictionary<X, List<Y>>
I'm currently working on a generator that generates rooms in biomes and i was wondering what is the fastest way of checking if a certain position is already occupied.

I've got 3 possible ways of doing this:

**1. Use nested foreach loops to directly loop through all rooms and check the position. (ugh)**

```
public bool IsOccupiedPosition(Vector2 position)
{
    foreach (Biome biome in this.Biomes)
    {
        foreach (Room room in biome.Rooms)
        {
            if (room.Position == position)
            {
                return true;
            }
        }
    }
    return false;
}

```

**2. Use a List, put everything in there, then check that using the Contains() method.**

```
public List<Vector2> RoomCoordinatesAsList { get; set; }

public void AddRoomCoordinates(Vector2 position)
{
    this.RoomCoordinatesAsList.Add(position);
}

public bool IsOccupiedPosition(Vector2 position)
{
    return this.RoomCoordinatesAsList.Contains(position);
}

```

**3. Use a Dictionary, where the first type is the X position and the second a list of Y positions. (my preference)**

```
public Dictionary<float, List<float>> RoomCoordinates { get; set; }

public void AddRoomCoordinates(Vector2 position)
{
    if (!this.RoomCoordinates.ContainsKey(position.X))
    {
        this.RoomCoordinates.Add(position.X, new List<float>());
    }
    this.RoomCoordinates[position.X].Add(position.Y);
}

public bool IsOccupiedPosition(Vector2 position)
{
    return (this.RoomCoordinates.ContainsKey(position.X) &&
        this.RoomCoordinates[position.X].Contains(position.Y));
}

```

# Answer
> 5 votes
```
 bool[,] Rooms = new Rooms[Width, Height];

 bool IsPositionAvalaible(int x, int y) { return !Rooms[x,y];}

 bool SetPositionValue(int x, int y, bool Avalaible) { Rooms[x,y] = !Avalaible; }

```

---
Tags: xna
---


# Question
Title: How do you handle iPhone graphics for both high and low DPI settings?
How do you guys create your game graphics for iPhone? Considering you need a retina version and a nomal one?

Do you create a big version of your image, save HD, then resize to smaller version, and save Normal?

Or do you create a vector image with say, fireworks, save HD, then resize, then save Normal?

# Answer
If you want your images to look good, do not simply scale up/down a raster image. Even with a vector based source, this doesn't always work so well, though the results are usually passable.

The best example of this I can give is this: say you wanted to resize this 48x48 icon into a 24x24 alternative. In 24 pixels, you likely would want to reduce the faux-writing lines from 4 down to 2 or 3. If you just scaled down the image and left it with 4, things would get messy and cramped.

Ultimately, it depends on what the images are being used for. Static images such as buttons and icons you'd want to manually resize, to make sure every pixel is perfect, and it communicates the same concept.
For animated images, the eye doesn't get enough time to fully scrutinize it, so flaws are more acceptable.
> 3 votes

# Answer
For targeting the iPhone, honestly I'd just try to make it look good on the iPhone 4 display. Make sure it is alright on the older devices (specifically fonts), but don't bother going out of your way for them.

At least at this point in time, pre-3GS devices only account for about 5% of the market. Soon I can imagine Apple sunsetting support for any non-retina devices. As long as it's "good enough", it's probably not worth it to put a lot of effort into making your graphics pixel perfect on the older devices.
> 1 votes

---
Tags: iphone, optimization, image
---


title: Algorithm to fit shapes to 2D grid?

text:
# Question
Title: Algorithm to fit shapes to 2D grid?
Let's say you have an n-by-m grid. Some squares are occupied, some are not.

You want to know where in the grid you can fit arbitrary shapes such as to not hit an occupied square. The shapes would variable, and could be x-by-y rectangles, trapezoidal-ish shapes, etc.

Are there algorithmic approaches to this?

# Answer
This is a form of the Packing Problem.

Here are your options:

* Brute force it as Gajet has mentioned. This can be aided by doing a pre-evaluation of existing space in your world grid, so as to find maximal axis-aligned bounding boxes. This article should give you some insight into how one developer applied solutions to the Packing Problem, in regards to packing arbitrarily-sized sprites into a spritesheet.
* Use a more physically-based approach to the Packing Problem; I call this "Place-and-Grow" for lack of having seen a better term elsewhere. Select a single pixel/cell of your bitmap/source grid to place -- I would start with the centremost pixel. Randomly pick a position in your bacgkround bitmap / destination grid, to place it on. Keep randomising till you find an open space (this process can be optimised in other ways). If it is now overlapping a solid pixel eg. on the left side, push it out in the opposite direction instead (same applies vice versa and for top/bottom). If you now find it in an empty space once more, you're good to go to the next step. "Grow" the pixel in in all 8 directions around itself, in terms of the source grid / bitmap. Then go back and repeat the shifting step to ensure it's not overlapping anything. Rinse, repeat. Eventually you will get to a point where either your image is completely drawn in to background space, or you cannot expand it anymore in any direction, and will have to try again. Basically this approach is described as "physical" because you are pushing away from any boundaries you meet -- until such time as the algorithm is done or it falls out because there is no space on any side to push out toward.

The second "continuous" approach is more organic, and it may in some ways be easier to handle than the large amounts of logic you might have to write for "discrete" Packing Problem solutions (as in the article above). BUT remember that for each subsequent AABB that you "grow" this way to it's maximal size, you will be doing a haphazard, randomised placement -- which may eventually end up being much slower than brute-forcing, as your grid fills up. It will depend on the sparseness of your grid, i.e. the average proportion of filled vs empty cells. If I wanted to do this efficiently, as you seem to, I think I would opt for the first approach. For procedural world generation algorithms, I would find the second approach to be more useful as it would produce more random / less ordered results.
> 7 votes

# Answer
You can optimize Brute force search:

For each point in plane compute how big disk (for example, can be arbitrary bounds) can be placed without colision.

```
set of (x, y, area of biggest shape to fit at the position)

```

Sort this by third parameter ("area of biggest shape to fit at the position").

```
sorted set of (x, y, area of biggest shape to fit at the position) by third value

```

Compute bounds of Your shape (one You want to place into grid) which are consistent with the sorted set. If You are lucky Your shape would be small enought to be enclosed by one in the sorted set. Finding which one it is is O(log N) for binary search.

Also note, that if You know what sort of shapes are going to be there You can precompute more.
> 1 votes

---
Tags: 2d, collision-detection, grid
---


# Question
Title: How forcefully should a single-player engine reject invalid data?
In a single-player game, when trying to build an entity out of components specified in external scripts, what do you think is more desirable to happen when one of the components is ill-formed:

* Should the engine skip over that component and let the entity live in the game world with only the components that were well written?
* Or should it not add the entity to the world at all if but one of the components is ill-formed?

Note, I'm not talking about logging the errors — that should come without saying — just about what should happen to the entity.

# Answer
> 11 votes
If you're talking about a moddable game, then you might want to follow one of your suggestions above. But if you are concerned about rolling over your own errors, I'd say don't do it. I have become an advocate of Fail-Fast. If this is an error that **you** have created and must resolve before releasing, you should make the error obvious. The article that is linked to at the bottom of the wiki page is a good read on the subject with why failing fast is good, and when it should and shouldn't be used.

# Answer
> 7 votes
The distinction between user and developer is not always clear in game development. Standard programming techniques like "fail fast" are not always advantageous, especially as team sizes grow.

For example, perhaps your technical artist has screwed up the shader for the targeting outline - broke the fallback, let's say, so it's only loading on SM4 systems, and he didn't notice because he's got a top of the line system. This results in some animations failing to load. Those animations are referenced by a particular spell your combat designer has written. Finally, your level designer is trying to get the spawns in place and those spawns all happen to be able to cast that spell - but now she can't place any of them in the world because their spells aren't valid because the effects aren't valid because the shaders won't load because the designers always have the worst computers.

So your demo isn't ready by 2PM and your investors wonder why you can't even get a single enemy in the game and your project gets shut down.

Or you choose the option where you log the failure but keep trying, and the game plays fine except some enemies spell effects don't appear - but the investors don't know what those are supposed to look like anyway, so they don't notice.

For that reason, I'll almost always advocate the first option - spawn as much of the entity as you can. There are cases for fail-fast - like if the data should never be edited except by people capable of doing builds (i.e. programmers and technical producers) and is always checked 100% at load, or if you're absolutely sure the person responsible for the problem is the person using the editor - but those are not the usual cases, and require a lot of technical infrastructure per se, which you might not be ready to invest in.

# Answer
> 1 votes
The user should be able to preview the entity he is going to import, and know in advance if there are errors.

You should somehow decide what errors should be fatal, preventing it to be added to the game, and which can be dismissed as *warnings*.

Of course if for any reason the imported entity might be somehow able to irreversibly alter the savegame data, you'd better require for it to be flawless.

# Answer
> 0 votes
I would suggest that in development, it should be noisy about invalid data. i.e. log everything somewhere it will be read. However, if your engine can ignore this and continue it should do so. You can have logic like

```
void setValue(int value) {
    if (value < MIN_VALUE) {
       log(value + " is too low, using " + MIN_VALUE);
       value = MIN_VALUE;
    }
    if (value > MAX_VALUE) {
       log(value + " is too high, using " + MAX_VALUE);
       value = MAX_VALUE;
    }
}

```

Even in a multi-player game this is acceptable unless you are assuming that one player is trying to cheat the system.

After releasing the software, you are likely to want to turn off this logging by default on the assumption the players are not going to read these logs.

---
Tags: component-based, validation
---


title: Graphic optimization for iPhone

text:
# Question
Title: Graphic optimization for iPhone
Basically, I am creating a large iPhone game (with an overwhelming amount of 2d graphics).

I am concerned about the game file size.

Since the iPhone game will accept Retina and Normal display, we need 2 versions of each image (one HD and on normal). Therefore, it is necessary to resize our image files (it is not a good idea to resize the images in-game, an iPhone 3GS would have memory usage problems).

So my team is thinking about using Adobe Fireworks for the image creation, since it has that nice vector-resizing behavior without losing image quality (not-blurry on resize).

And it works alright.

But then I created an image that is pretty much the same in Adobe Photoshop, and it happened to be about 3x smaller in memory.

So naturally, there's something wrong with our Fireworks' files. How can I save my .png Firework file with the smallest memory size possible?

Note: the images require transparency.

# Answer
> 5 votes
How are you saving these PNG files from Fireworks? Fireworks uses PNG as its native file format, but adds meta-data to it (such as information about layers, effects etc.). This could be the reason why the Fireworks PNG files are larger than a PNG saved using Photoshop.

Since your iPhone app won't need any of the meta-information Fireworks stores, you should always use `File > Export` in Fireworks to export your assets. Similarly, use `File > Save for Web & Devices` in Photoshop.

While this should already result in considerably smaller PNG files, you could even further optimize them. Here's an excellent article about PNG optimization. Here's a ready to use tool for Mac and one for Windows (disclaimer: I never used the windows tool, but the Mac one can yield very good results).

---
Tags: optimization, image
---


# Question
Title: Which files should I be looking at to do a total conversion mod using the Source Engine?
I just installed Source SDK. Made a multiplayer mod from a template using Source Engine 2007. I'm currently using VS2008.

I was wondering which folder I should work in. For example weapons, which files I should change?

Is it "\src\game\server\hl2\weapon\_crowbar.cpp" or "\src\game\shared\hl2mp\weapon\_crowbar.cpp" or "\src\game\shared\sdk\weapon\_crowbar.cpp"

Also, I've seen the various help on the wiki, if I want to change bullets for example, saying I should change the scripts in the mod folder in Steam. Is that necessary? Shouldn't I make changes from the source mod folder to things like that and recompile?

I'm aiming for a total conversion mod rather than just a mini-mod in case that matters.

# Answer
> 2 votes
This depends on the project you're using.

* Game\_Episodic\_2005.sln: use /hl2/ crowbar (from HL2/Episodes).
* Game\_HL2MP\_2005.sln: use /hl2mp/ crowbar (from HL2: Deathmatch, probably optimized for multiplayer).
* Game\_Scratch\_2005.sln: use /sdk/ crowbar (I think it's an example weapon here).

For total conversions, use Game\_Scratch\_2005, but it has several errors when compiling, Game\_Episodic\_2005 compiles without any errors on Release configuration, but contains HL2 content. It is HIGHLY NOT recommended to compile without HL2\_DLL (HL2\_CLIENT\_DLL) parameter while using Game\_Episodic\_2005 as errors may occur.

---
Tags: modding
---


# Question
Title: Ergonomics studies on choosing keys on a keyboard?
I have the following problem:

My game supports multiple powers, that you can use when you want, or even mix them, I currently assigned them to the numbers on the top of the keyboard.

After so much time playtesting, I ended developing high skills in playing my own game, and several of my new tactics involve mixing powers, but I found that I keep pressing incorrect buttons, or that I need to pause, look at the keyboard, and unpause, or I plainly press the wrong button (like, I try to press 5, but press 6 instead).

I already expected this when I made the keybindings, but I don't found how to solve...

How I fix that?

EDIT: The game is a fast-paced action game, or arcade game... (you know, not necessarily on a genre, except it is action, and you aim for high-scores), so I cannot use random keys, I really need to allow the players to press the keys REALLY fast, ANY key that they need to press.

# Answer
I've never been quite sure why people are so obsessed with numbers and the very edges of the keyboard.

Tell the players to put their left hand on ESDF. Now map commands to the rectangle bounded by 1, 5, Z, B. That's space for twenty commands, over half of which of which are very easily accessible, most of the remainder being only moderately more difficult.

Be careful with internationalization - on German keyboards, for example, Z and Y are swapped compared to most Roman-language keyboards.
> 8 votes

# Answer
You didn't say what kind of game. I'd say the easiest usability solution is, find a similar game that has similar mechanics, something your players might be familiar with, and use the same keys.

So, if your game is an action-RPG like Diablo, making the default keybindings work an awful lot like Diablo is not a horrible way to start.

See: http://www.joelonsoftware.com/uibook/chapters/fog0000000061.html
> 4 votes

# Answer
You may want to look into the keyboard layout called Dvorak for inspiration here. The Dvorak keyboard layout is designed such that the home row houses the most frequently pressed keys. The upper row (the one below the numbers) has the second most frequently used keys, and the bottom row has the keys with the lowest usage. For the Dvorak layout, I believe this is determined by the frequency of the characters within the English language.

In general, this design in based on the concept that it is easier to extend the fingers than contract them.

To apply this design to your game, you would need to know which abilities are the most commonly used to create an optimum layout.
> 3 votes

# Answer
Allow players to map their own keybindings would be the simplest solution in my mind.
> 1 votes

# Answer
Try adding quick-slots for the most used powers like in Diablo 2, Torchlight ,Titan Quest, World of Warcraft etc..

Let the player assign whatever skills he wants to these hotkeys without having to go into your options menu.

This adds to the excitement for the user, since he can try to create as effective hotkey combos as possible.

EDIT:

If it wasn't clear I meant for you to keep the number key mapping like you already have, but add the possibility to map which skill is where.

You could also have be able to map Q and E to your bindings.

Conan did this quite well with their combo combat. In conan you could hit 1,2,3,Q and E for directional attacks. These buttons are close enough for the player to hit them.
> 0 votes

# Answer
You could try selecting keys that are easy for the user to feel their way around. Something with a unique formation like the arrow keys. These are easy to locate and also from these it's easy to find Ctrl, Shift, Enter, Delete, End, Page Down and numeric 0. Until someone tries to play your game on a notebook of course.

Another possibility is the F and J keys on a QWERTY keyboard which usually have raised bumps on them.

Also if there's an alternative (buttons that can be selected with the mouse) then it's not necessarily a disaster if the keyboard controls are tricky to get the hang of. Look at Desktop Tower Defense for example. You can play it with just the mouse, but advanced players can use all 10 digit keys, S, F, N and U. It takes some getting used to but if the game is addictive and there is a simpler (if slower) alternative they can use early on then they probably won't mind.
> 0 votes

# Answer
I've always found games using 1-8 work well. As long as you give some kind of display menu, something like a wheel of the hot keys showing each power and the ability to correct a mistake, it should be fine.

If you are worried, then allowing players to change them works too; if they can't get key mapping X to work, they could try and find something that works for them.
> 0 votes

---
Tags: keyboard, interface, ui-design
---