# Question
Title: XNA Adding Craters (via GPU) with a "Burn" Effect
I am currently working on a 2D "Worms" clone in XNA, and one of the features is "deformable" terrain (e.g. when a rocket hits the terrain, there is an explosion and a chunk of the terrain disappears).

How I am currently doing this is by using a texture that has a progressively higher Red value as it approaches the center. I cycle through every pixel of that "Deform" texture, and if the current pixel overlaps a terrain pixel and has a high enough red value, I modify the color array representing the terrain to transparent. If the current pixel does NOT have a high enough Red value, I blacken the terrain color (it gets blacker the closer the Red value is to the threshold). At the end of this operation I use SetData to update my terrain texture.

I realize this is not a good way to do it, not only because I have read about pipeline stalls and such, but also because it can become quite laggy if lots of craters are being added at the same time. I want to remake my Crater Generation on the GPU instead using Render Targets "ping-ponging" between being the target and the texture to modify. That isn't the problem, I know how to do that. the problem is I don't know how to keep my burn effect using this method.

Here's how the burn effect looks right now:

Does anybody have an idea how I would create a similar burn effect (darkening the edges around the formed crater)? I am completely unfamiliar with Shaders but if it requires it I would be really thankful if someone walked me through on how to do it. If there are any other ways that'd be great too.

# Answer
> 7 votes
One way you could do it is similar to what you have been doing. Have a "Damage" texture and the actual background texture, but instead of copying the data over each time, just keep the two as two separate textures.

When a blast is made, draw a circle on the Damage texture that has a slightly transparent edge. This will be the "burn" area.

Whenever you draw the terrain, give the GPU both textures, and have your shader multiply the color (.rgb) of the background pixels by 1 - the alpha value of the damage texture. Get rid of the fully black pixels (alpha them to 0, or you can multiply this to alpha as well (.rgba instead of .rgb) depending if you want translucent scorched areas) and voila!

I doubt this is the *best* solution, but it is fairly similar to what you've done before which may make transferring easier. You could probably also get away with passing in an array of Vector3's (x,y,radius) and doing some math in the shader based on those explosion points but I am unsure as to the efficiency of such.

Hope this helps!

---
Tags: xna, textures, effects
---


# Question
Title: Algorithm for making sets in a Rummikub game
I'm developing an Okey game (a Turkish version of Rummikub/Rummy). In it, each players has a bunch of tiles. Tiles have a colour and a number, like playing cards. Now, the player needs to make sets of these tiles, with three options:

* Groups: Same number, different colours (Red 1, Blue 1, Black 1)
* Straights: Same colour, sequence of numbers (Red 1, Red 2, Red 3)
* Doubles: Two identical tiles

I'm now trying to create a simple AI for the game. I want it to be able to find and create sets in/from its own tiles.

I already have a TileSet class. Feed it a list of tiles and it will say whether it's a valid set and of what type.

Using this, what kind of algorithm can I use to find the sets in an unordered heap of tiles?

# Answer
Since you have 52 distinct cards, you can represent them as bits and fit in a 64-bit int. E.g. taking `suit` as an int in `0-3` and `card` as an int in `0-12` one way of packing them would be

```
int64 ToBit(int suit, int card) { return ((int64)card) << (16 * suit); }

```

Then you can easily detect doubles and get a bitmask representing the cards present in a list:

```
List<int64> cardsAsBits = ...
int64 cardsAsBitset = 0, doubles = 0;
foreach (int64 card in cardsAsBits) {
    doubles |= (cardsAsBitset & card);
    cardsAsBitset |= card;
}

```

To check for doubles now you just have to look at the set bits in `doubles`. To check for straights and groups it's just a case of making a suitable mask and &ing.

```
for (int i = 0; i < 11; i++) {
    for (int suit = 0; suit < 4; suit++) {
        int64 straight = 7L << (i + 16 * suit);
        if ((cardsAsBitset & straight) == straight) handleSet(straight);
    }
}

for (int i = 0; i < 13; i++) {
    int64 group1 = 0x0000000100010001L << i;
    int64 group2 = 0x0001000000010001L << i;
    int64 group3 = 0x0001000100000001L << i;
    int64 group4 = 0x0001000100010000L << i;

    if ((cardsAsBitset & group1) == group1) handleSet(group1);
    if ((cardsAsBitset & group2) == group2) handleSet(group2);
    if ((cardsAsBitset & group3) == group3) handleSet(group3);
    if ((cardsAsBitset & group4) == group4) handleSet(group4);
}

```
> 1 votes

# Answer
use a nested loop.

outside loop is the tile sets on the board and the inside loop is the ai tile.

one at a time pass the tile set class a tile from the ai and a set on the board to see if it is a viable move.

if you want the ai to make mistakes the have a random generator in the loop so it dosn't check all of its tile for every set on the board or jumble the order it searches the tiles on the board and take the first move available so it doesn't always take the best move.

hope this helps
> 0 votes

# Answer
You could try something like this (using C# syntax, not verified for correctness). Note also that I'm not instantiating the inner-collections, for brevity.

```
Dictionary<int, HashSet<Color>> groupTest = new Dictionary<int, HashSet<Color>>();
Dictionary<Color, bool[]> straightTest = new Dictionary<Color, bool[]>();
HashSet<Tile> doubleTest = new HashSet<Tile>();
foreach (Tile tile in AllTiles)
{
  if (doubleTest.Contains(tile)) { /* Found a double */ }
  groupTest[tile.Number].Add(tile.Color);
  straightTest[tile.Color][tile.Number] = true;
  doubleTest.Add(tile);
}
foreach (int number in groupTest.Keys)
{
  HashSet<Tile> group = groupTest[number];
  if (group.Count >= 3) { /* Found a group */ }
}
foreach (Color color in straightTest.Keys)
{
  HashSet<int> straight = straightTest[color];
  int consecutive = 0;
  for (int i = 1; i < HIGHEST_NUMBER; ++i)
  {
    if (straight[i-1] && straight[i])
      consecutive++;
    else
      consecutive = 0;

    if (consecutive >= 3) { /* Found a straight. */ }
  }
}

```
> 0 votes

---
Tags: algorithm, ai, card-game
---


# Question
Title: What is the difference between a library and an engine?
I am working on a library to help 2D game development with Scala. So far, it is a collection of helpful classes, file loading, collision detection, images, sprites, etc.

So when does it stop being a class library and start being an engine? Where exactly lies the difference between useful framework and a game engine?

# Answer
> 21 votes
I think the confusion people get into here is that one is generally made up of the other, so what people really want to know is when you have enough of one to be considered the other.

> So when does it stop being a class library and start being an engine?

Never.

> Where exactly lies the difference in a useful framework and a game engine?

There is none.

Now let me explain the answers. A game engine is made up of class libraries. They do not stop being class libraries simply because they are within a game engine. A library is a useful framework to tackle a specific need within a game engine. A framework that entails the needs for a complete game is a game engine.

Here are some examples of game engines:

* Unreal Engine
* Reality Engine
* Source Engine
* Quake Engine
* Unity Engine

And some examples of libraries

* Novodex (Physics)
* FMOD (Audio)
* Havok (Physics)
* Ogre3D (Rendering)
* BINK (Video Library)
* Direct3D (Graphics)
* OpenGL (Graphics)
* DirectSound (Audio)
* XInput (Input)

Hope this helps

# Answer
> 15 votes
There really is no concrete definition for either term (or for the related term "framework," for that matter). There are hundreds of different ways of interpreting the varied subtle distinctions in software packages and assigning them classifications.

I personally view a "library" as a thing that provides a relatively small and directed set of functionality, whereas a "framework" provides more or broader functionality, and an "engine" provides the same (or more) and typically has a set of associated tools that come with it.

I have seen enough of other people's personal interpretations of the same terms to feel safe suggesting that an "engine" provides more, or higher level, functionality than a "library" typically does... but where you draw that line for your own software is up to you.

# Answer
> 2 votes
This is a tricky question, since the line between library and engine can sometimes be a very thin, blurry one. I'd have to say that the point where a library turns into an engine is when it becomes geared towards a specific game, or a specific type of game.

For example: the Unreal engine (or Source, or Quake) is designed to be used for FPS games (it could feasibly be used for other games, but you'd spend some time working against the engine). Ogre3d (or even Directx, SDL, or other common libraries) can be used to make any type of game, without having to rip out major parts of the code, or work around them.

---
Tags: terminology
---


# Question
Title: How to properly repeat a texture on a quad in OpenGL?
I'm drawing a quad and binding a texture to this quad like this:

```
#define TERRAIN_WIDTH         2000
#define TERRAIN_LENGTH        2000
#define TERRAIN_WIDTH_2       (TERRAIN_WIDTH / 2)
#define TERRAIN_LENGTH_2      (TERRAIN_LENGTH / 2)

glBindTexture(GL_TEXTURE_2D, gameTextures.terrain);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-TERRAIN_WIDTH_2, 0.0f,  TERRAIN_LENGTH_2);
    glTexCoord2f(X, 0); glVertex3f( TERRAIN_WIDTH_2, 0.0f,  TERRAIN_LENGTH_2);
    glTexCoord2f(X, X); glVertex3f( TERRAIN_WIDTH_2, 0.0f, -TERRAIN_LENGTH_2);
    glTexCoord2f(0, X); glVertex3f(-TERRAIN_WIDTH_2, 0.0f, -TERRAIN_LENGTH_2);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);

```

Normally, `X` would be equal to `1` but this will stretch the texture because the quad is very large. The idea is to increase that value so the texture is repeated (the texture was generated with `GL_REPEAT` of course).

But how should I find the best value for `X`? I have a few 512x512 textures which look nice if I replace `X=512`. Then I have another 1024x1024 texture which looks good to with `X=512` but doesn't start to look so good with a higher/lower value. Another texture is 2048x2048 and now I need to go down to `X=256`, otherwise it won't look so good.

What's confusing me even more is the fact that both 512x512 and 1024x1024 textures look good with `X=512`. The way I see it, the lower the texture resolution, the more times I need to repeat it.

How should I calculate the value of X then?

# Answer
> 2 votes
If `2048×2048` textures look good with `X = 256`, and `1024×1024` ones look good with `X = 512`, then it is probably that each time the texture size shrinks by a factor of `2`, `X` should grow by a factor of `2`, leading to the following formula:

```
X = 256 * 2048 / TextureSize

```

---
Tags: opengl, textures
---


title: Plot and Story design basics

text:
# Question
Title: Plot and Story design basics
I have made several games but they have all been space invaders or mario style.

Following my last question (thank you for all the great answers) I am trying to write out a plot line and a plan for the events that will take place.

The problem I am having is that my story's tend to resemble things that already exist like films or other games I have played.

The events to feel like a mix of various other games I have played.

So apart form become a more creative person does anyone have any advice. Has anyone written a fairly lengthy story for a game and have pointers or does anyone know any good books on the subject.

Any thoughts would be welcome, story of event ideas to.

FYI the game has a final fantasy style battle system and a pokemon catch/raise system.

# Answer
> 12 votes
As someone who's written a great number of novels, I can tell you one closely-held secret of writing: **It involves reusing elements (characters, plots) from other sources (games, movies).**

Most of my novels start out with a macro-level plot (eg. boy saves world by defeating sword-wielding maniac), from which I brush out details -- characters, elements, etc. One of the best ways to build a story is to borrow elements from other stories/games/movies, then tweak them and tweak the world they're in.

For example, in one story (eight volume fantasy genre), I had elements borrowed from Chrono Trigger, Berserk (the anime), Wheel of Time, and bits and pieces from everywhere. But mixed in all together, with everything tweaked to fit the world, it turned out pretty unique.

So I would say the process that worked for me was:

* Start with an overall plot
* Pick some characters/villans you want to see
* Pick some elements you want (eg. pokemon)
* Start detailing the plot with events
* Keep subdividing to add story details until you're happy with it

Just tweak it until you're happy with it. A lot of your story will be backstory; it's harder to figure out how to make it appear in-game.

# Answer
> 2 votes
I think Stephen King's *On Writing* is a good resource for any aspiring writer in any medium and genre.

I have not read *Chris Crawford on Interactive Storytelling* but I have seen several recommendations for it. Crawford is a vaguely divisive - or at least confounding - figure in game development, but regardless of which side you take it's probably worth reading what he has to say.

*The IF Theory Reader* (free PDF download) is a recent book. It covers primarily writing for *interactive fiction*, which is a small subset of games. Some of the topics won't be relevant for FF-style games, but I think at least half of the *Craft* section essays probably have useful information, and the entire thing has a depth of analysis rarely found in game development book.

(Disclaimer: Despite years of on-and-off attempts I am still a horrible writer.)

# Answer
> 1 votes
As long as you're not copying any one story or game outright then I shouldn't be too much of a problem. It practically impossible to write wholly original stories anyway. For example "Romeo and Juliet" and "West Side Story" are essentially the ancient Greek myth of "Pyramus and Thisbe".

It's all about adapting, combining, and reworking elements from different works to make a new story which embodies the ideas you want to convey.

---
Tags: game-design, rpg
---


# Question
Title: Improving Processes in One-Man GameDev Shops
As a hobby programmer, **how can I incorporate a continuous-improvement-like process like Agile's retrospectives in my processes?**

I've tried bullet items of three good/bad things at the end of each project, but I feel it's not enough. And I feel that a sprint retrospective is overkill. Where's the balance? How can and should I open the door for continuous process improvement?

Or maybe this question should go on the beta Project Management Stack Exchange site?

# Answer
> 6 votes
As this is a personal project, you have to be very careful not to get bogged down in process. While continuous improvement is very desirable, consider choosing elements from Lean and Agile that are philosophically in-line with the simplicity of a one-man-show.

In Scrum and many other systems, sprint retrospectives are beneficial, as they provide time for a team to identify improvements. In Lean, there's frequently a focus on solving a problem as it arises, and I think this is where you could greatly benefit.

When you identify a nasty bit of code or an issue, flag it and take a moment to do the following:

1. Look at where the problem resides
2. Look at the interacting elements and systems
3. Find a quick solution (something that works, what we typically do and stop at)
4. Identify the root cause (ask the 5 why's)
5. Generate a more fulfilling (possibly even standardized) solution or plan for a solution (possibly something to be implemented after this project or sprint)

So, this is taken from the five golden rules of Gemba management and fiddled with to match your scenario. To some degree, it's still not super applicable. Your mileage will vary and you'll have to adapt; but, there's good news: that's all part of Lean!

You need to adapt whatever processes you can find to be "right fit." This is going to be something you'll have to continually improve upon, in and of itself.

I hope that makes sense. I can provide more specific references and comments if you'd like.

EDIT (in response to question in comments):

To get started, I'd suggest visiting LeanBlog.org. You might want to read this article first. It's short and full of pithy quotes. Most of it is about healthcare; but, you'll really rapidly see how it also applies to games.

Not to toot my own horn, but, I wrote an article on gamasutra about standardized work and it has some great resources in the comments section as well as ideas. You can find it here.

I would highly suggest checking out Menlo Innovation's blog. Most of what they talk about is applicable for larger companies; but, you should be able to adapt it.

I'd be interested in finding out your results after a few months :)

I hope those links help!

# Answer
> 0 votes
Although at work we use JIRA for this type of stuff, I adapted a version of it for my own use in gamedev at home. It may or may not be a system that works for you, but I'll add it anyway:

1. Get some index cards and somewhere to keep them - a few piles on the desk works just fine. Mark these piles "Not Started", "In Progress", "Blocked", "Needs improvement", and "Complete".
2. If I think of a task that needs to get done, I immediately write it down on an index card and give it an estimate of difficulty/complexity
3. If a task I'm currently working on is blocked, I write the reason why on the back
4. Unless the task is a blocker, don't do it until you have to (or until you're out of unblocked/in progress tasks)
5. If all of your tasks are in the Needs Improvement or Complete stage, start working on those that need improvement.
6. ????
7. Profit!

---
Tags: process
---


# Question
Title: What shall I choose between CoronaSDK or AirPlay?
1st Question is I want to write a board game for iOS and Android so I'm coming up with CoronaSDK and AirPlay. Since I have a mac, development platform is not an issue but the problem is which one should I choose. I'm fluent with PHP and web languages and familiar with C but it's a new language for Lua. I know a lot of people prefer Corona but why not Airplay? It even provides more devices and able to write in C/C++.

2nd Question is I want a SDK with shortest development time and easier coding. I don't need complex 3D or animation engine since the game is a board game like chess or monopoly. What would you recommend?

Really appreciate anyone trying to answer my questions here :)

# Answer
Lua is a far more productive language than C++. I spent 6 months writing a game using C++ (not Airplay admittedly, I was using a different framework) and got about halfway through before I came to grips with how excessively long it was taking. Then I started using Corona three months ago and am about to release my game.

Also, Lua is pretty similar to PHP so you shouldn't have any trouble picking it up in a weekend. Simpler actually

Basically, the answer to both your questions boils down to it is much faster and easier to develop using Lua in Corona. Although they have differences in features (eg. Airplay deploys to more platforms but apparently lacks a web view) those pros and cons mostly cancel each other out, so the choice mostly comes down to the programming language.
> 3 votes

# Answer
Without any experience in using either Corona or Airplay, on the surface level I'd say Corona might be easier because it uses a high-level language, Lua, but then if you're already familiar with C, but have never used Lua, maybe that advantage is lost. The advantage of Airplay on the other hand is that it supports a lot of platforms. If you only need iOS and Android though, maybe that doesn't really matter either.

I think if you feel like C++ would be easier for you, there's not much reason to go with Corona. Both even have similar pricing models, but Corona costs more unless you're making over $100,000 a year, but if you do, you probably don't care either way.
> 2 votes

---
Tags: c++, c, lua, turn-based
---


title: OpenGL ES indices optimization

text:
# Question
Title: OpenGL ES indices optimization
I am using OpenGL ES 1.x/2.x

I have 2 attributes to be passed to the GPU(one is colors, one is vertices, one color per vertex).

I use indices. Both attributes will use the same indices array

This is not a big issue but I was wondering if there is a way to tell the GPU that both attributes use the same indices array so that it is not transfered to the gpu twice, or maybe it does not matter because the GPU uses the RAM?

# Answer
> 1 votes
If you are using indices then all of those attributes are already using the same index array. Each entry in your index array is an index into the vertex buffer that is currently being used for drawing. If you are using an interleaved vertex buffer then each vertex is represented by a single block of memory (in code usually defined by a struct) that contains all of the associated vertex attributes. The other method is to use multiple vertex arrays where each array contains a different attribute. Regardless of the method used for storing vertex data the current index pulled from your array of indices will point to the same data.

To summarize, if I understand your question correctly, it sounds like you're already doing the right thing.

---
Tags: opengl, 3d, iphone, android, shaders
---


title: When is low-poly not low-poly?

text:
# Question
Title: When is low-poly not low-poly?
When is it considered high-poly?

# Answer
> 5 votes
It's *entirely* relative: if you're building an RTS, then low poly is probably about 1500 polys for a unit (I can't recall but I believe the zergling from SC2 is around that much). However, if you're building an FPS you're probably looking at 10-15k per player.

There's no one true definition of it: the phrase "low poly" depends on a few different things, all of which are important:

* When the mesh was made
* What system the mesh is designed for
* the shape that the mesh is being used to represent
* *other meshes that are in the scene*
* etc

These days main characters have upwards of 15k-20k polys which was unheard of back in the days of say, N64. Random objects usually stick around 6k-9k these days.

# Answer
> 6 votes
One of the common definitions these days is that low-poly is the model as in the game. High poly is the source model that's used to bake down normal maps.

---
Tags: 3d, models, low-poly
---


title: Linux OgreXML model viewer

text:
# Question
Title: Linux OgreXML model viewer
Is there an OgreXML model viewer for Linux? I know about OgreMax but apparently that's Windows only.

# Answer
You can use OgreMeshy, but first the OgreXML file must be converted to .mesh file with the command line tool OgreXmlConverter, included in the source code.
> 3 votes

# Answer
Seconding OgreMeshy as I don't have enough rep to comment, though it does require 1.8.0 (so you'd have to build from source).
> 2 votes

---
Tags: 3d, models, ogre, linux, jmonkeyengine
---


# Question
Title: Simple Game Feasibility: Unity + Turbo Squid + $0 =?
I've been coding 2D games exclusively for a while, partly because I have very limited graphics skills, partly because it takes less effort to make something look great, and partly because I have very limited time in which to code.

I have an idea for a very simple 3d kids game that I'd like to build; it would be based around a player roaming a randomly-generated city and looking for a particular building (eg. dollar store, grocery store, bank, etc.)

My question is: **Would it be feasible to build this in Unity, using only free models and animation (presumably from Turbo Squid), in a decent time-frame?**

In terms of features, this would range in extremes from "generate some random buildings, paths, and select one as the winning building to locate" to adding people to talk to, objects to interact with (water, ladders, keys and locks, ropes, etc.)

I haven't touched 3D modelling for years (I used 3D Studio Max 3.x back in high school), and I don't have 3-4 hours to spend creating, rigging, and animating models. That's really the crux of my doubt. I also don't have cash that I can spend on models/animation.

So to summarize, my main two questions are:

1. Is it feasible to create a decent-quality game using free stuff from Turbo Squid?
2. Are many/most/all of the models from TS compatible with Unity?

# Answer
As the adage goes, you get what you pay for.

Sure, you can find free assets to probably technically fill most of your needs (and with the embedded Unity Asset Store it's even easier, but without the breadth of content that TurboSquid provides).

But you're not going to have a consistent look. Quality is going to be all over the place. And you might not find a particular kind of building you're looking for. And depending on what kind of assets you find it might be pretty hard to get a set of things that fit together in some kind of city generation scheme. You'd be much better off just having a single static level you throw together manually.
> 5 votes

# Answer
Building wise you'll have more luck with sketchup and Google warehouse library

And if you don't have a never version I doubt you can animate any of them(since those models generally have no animation)

You will have better luck using Blender and scouring the web for free stuff,but you will have allot of import problems, if you have some basic topology skills and texture as well as animation you might manage with free stuff,but then you have the trouble of license

I don't see it as feasible,you will probably have more luck with paid packs but not by much
> 1 votes

# Answer
I have made some projects with Unity and am also not willing to pay big amounts of cash for good 3D models. So yes it is possible but for an exampe: At turbosquid if you search for the tag buildings you will find about 100 models. from wich 2 are good looking but Medieval themed. the rest is like a cube with a roof and 2 textures. My advice, what i did, get a little knowlege of a program like Maya or 3dsMax and im sure you'll be verry capable of making some decent models in a small timeframe.

as for free models, it is possible. But quality wont be to high im afraid.

Good luck on your project, it sounds like a verry fun game for the young ones =)
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: Loading PNG textures for use in Android OpenGL ES1
I'm very new to Android and OpenGL coding (I have previously used ogre3d). I am trying to find an efficient way to load PNG textures. It is currently taking around 8 secs to load 3 512x512 textures on a fairly fast phone (Motorola Defy)

There seems to be a problem with the texture being upside-down (I used a Matrix to flip it below). Secondly, the order of the colour channels are incompatible, therefore each pixel needs changed. This (I believe) is the cause of the slowness, is there a way to make the BitmapFactory load it in a channel order that is compatible with opengl? Is there a better approach here?

Here is the code: -

```
// Will load a texture out of a drawable resource file, and return an OpenGL texture ID:
private int loadTexture(GL10 gl, Context context, int resource, boolean loadMipMaps) {
    // We need to flip the textures vertically:
    Matrix flip = new Matrix();
    flip.postScale(1f, -1f);

    // This will tell the BitmapFactory to not scale based on the device's pixel density:
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inScaled = false;

    // Load up, and flip the texture:
    Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
    Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
    temp.recycle();

    int id = loadTextureFromBmp(gl,bmp, true);

    bmp.recycle();

    return id;
}

protected static int loadTextureFromBmp(GL10 gl, Bitmap bmp, boolean reverseRGB) {
    ByteBuffer bb = ByteBuffer.allocateDirect(bmp.getHeight()*bmp.getWidth()*4);
    bb.order(ByteOrder.nativeOrder());
    IntBuffer ib = bb.asIntBuffer();

    for (int y=bmp.getHeight()-1;y>-1;y--)
            for (int x=0;x<bmp.getWidth();x++) {
                    if (reverseRGB) {
                            int px = bmp.getPixel(x,y);
                            int alpha = (px & 0xFF000000) >> 24;
                            int red = (px & 0xFF0000)>>16;
                            int green = (px & 0xFF00)>>8;
                            int blue = (px & 0xFF);
                            ib.put((alpha << 24) | (blue << 16) | (green<<8) | (red));
                            //ib.put(Integer.reverseBytes(bmp.getPixel(x, y)));
                    }
                    else {
                            ib.put(bmp.getPixel(x,y));
                    }
            }
    ib.position(0);
    bb.position(0);

    int[] tmp_tex = new int[1];

    gl.glGenTextures(1, tmp_tex, 0);
    int tex = tmp_tex[0];
    gl.glBindTexture(GL10.GL_TEXTURE_2D, tex);
    gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, bmp.getWidth(), bmp.getHeight(), 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    return tex;

```

}

# Answer
> 3 votes
Here's my code to load from a bitmap, which doesn't suffer from the same problems you describe, and looks like it will accomplish the same thing:

```
/**
 * Helper method to load a GL texture from a bitmap
 *
 * Note that the caller should "recycle" the bitmap
 *
 * @return the ID of the texture returned from glGenTextures()
 */
public static int loadGLTextureFromBitmap( Bitmap bitmap, GL10 gl ) {

    // Generate one texture pointer
    int[] textureIds = new int[1];
    gl.glGenTextures( 1, textureIds, 0 );

    // bind this texture
    gl.glBindTexture( GL10.GL_TEXTURE_2D, textureIds[0] );

    // Create Nearest Filtered Texture
    gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR );
    gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR );

    gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT );
    gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT );

    // Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
    GLUtils.texImage2D( GL10.GL_TEXTURE_2D, 0, bitmap, 0 );

    return textureIds[0];
}

```

and to load from a resource, I call it via this method (i have another similar method that will create a bitmap from a file):

```
/**
 * Create a texture from a given resource
 *
 * @param resourceID the ID of the resource to be loaded
 * @param scaleToPO2 determines whether the image should be scaled up to the next highest power
 * of two, or whether it should be "inset" into such an image. Having textures that are
 * dimensions of some power-of-two is critical for performance in opengl.
 *
 * @return the ID of the texture returned from glGenTextures()
 */
public static int loadGLTextureFromResource( int resourceID, Context context, boolean scaleToPO2 ) {

    // pull in the resource
    Bitmap bitmap = null;
    Resources resources = context.getResources();

    Drawable image = resources.getDrawable( resourceID );
    float density = resources.getDisplayMetrics().density;

    int originalWidth = (int)(image.getIntrinsicWidth() / density);
    int originalHeight = (int)(image.getIntrinsicHeight() / density);

    int powWidth = getNextHighestPO2( originalWidth );
    int powHeight = getNextHighestPO2( originalHeight );

    if ( scaleToPO2 ) {
        image.setBounds( 0, 0, powWidth, powHeight );
    } else {
        image.setBounds( 0, 0, originalWidth, originalHeight );
    }

    // Create an empty, mutable bitmap
    bitmap = Bitmap.createBitmap( powWidth, powHeight, Bitmap.Config.ARGB_4444 );
    // get a canvas to paint over the bitmap
    Canvas canvas = new Canvas( bitmap );
    bitmap.eraseColor(0);

    image.draw( canvas ); // draw the image onto our bitmap

    int textureId = loadGLTextureFromBitmap( bitmap );

    bitmap.recycle();

    return textureId;
}

```

and lastly, here's a utility to get the next-highest-power-of-two:

```
/**
 * Calculates the next highest power of two for a given integer.
 *
 * @param n the number
 * @return a power of two equal to or higher than n
 */
public static int getNextHighestPO2( int n ) {
    n -= 1;
    n = n | (n >> 1);
    n = n | (n >> 2);
    n = n | (n >> 4);
    n = n | (n >> 8);
    n = n | (n >> 16);
    n = n | (n >> 32);
    return n + 1;
}

```

---
Tags: opengl, java, android
---


# Question
Title: D3DX11SaveTextureToFile with shared resources
I'm using shared resources to send textures from one D3D11 device to another, so that I can copy the back buffer over the second device and use the second device context to save that texture to a file. This seems to be working, but when I save the texture, it saves an empty PNG. I tried saving the texture with the primary device context and it works, except if I use the D3D11\_RESOURCE\_MISC\_SHARED\_KEYEDMUTEX MiscFlag, which I need in order to share the resources. Is there any reason D3D11\_RESOURCE\_MISC\_SHARED\_KEYEDMUTEX prevents a texture from being saved ? Or am I maybe missing something out in order for it to work ?

Here is the code I'm using:

```
D3D11_TEXTURE2D_DESC td;
backBuffer->GetDesc(&td);
td.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
this->_device->CreateTexture2D(&td, 0, &g_tex);
this->_context->CopyResource(g_tex, backBuffer);

// saves a blank image if using D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX
D3DX11SaveTextureToFile(this->_context, g_tex, D3DX11_IFF_JPG, "test.jpg");

g_tex->QueryInterface(__uuidof(IDXGIResource), reinterpret_cast<void **>(&g_dxgiResource));
g_dxgiResource->GetSharedHandle(&g_shaderHandle);
g_dxgiResource->Release();
g_tex->QueryInterface(__uuidof(IDXGIKeyedMutex), reinterpret_cast<void **>(&g_dxgiMutex));

```

And this is the code used to save the shared textue in the second device

```
ID3D11Texture2D *texture = 0;
IDXGIKeyedMutex *keyedMutex = 0;
device2->OpenSharedResource(g_shaderHandle, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&texture));
texture->QueryInterface(__uuidof(IDXGIKeyedMutex), reinterpret_cast<void **>(&keyedMutex));
UINT acqKey = 0;
UINT relKey = 1;
DWORD timeout = 16;
DWORD res = keyedMutex->AcquireSync(acqKey, timeout);
if (res == WAIT_OBJECT_0 && texture)
{
    // saves a blank image too
    D3DX10SaveTextureToFile(texture, D3DX10_IFF_JPG, "test2.jpg");
}
keyedMutex->ReleaseSync(relKey);

```

Edit: Also, the code that is supposed to save the shared texture to the filesystem is running in it's own thread.

# Answer
Here is how I solved the problem. Turns out, using the D3D11\_RESOURCE\_MISC\_SHARED\_KEYEDMUTEX misc flag doesn't allow to save the texture to a file. So I used the D3D11\_RESOURCE\_MISC\_SHARED flag instead with a regular mutex, without using the DXGIKeyedMutex stuff.

Copy the back buffer to shared texture and create a shared handle:

```
D3D11_TEXTURE2D_DESC td;
backBuffer->GetDesc(&td);
td.MiscFlags = D3D11_RESOURCE_MISC_SHARED;

this->_device->CreateTexture2D(&td, 0, &g_tex);
this->_context->CopyResource(g_tex, backBuffer);
IDXGIResource *dxgiResource = 0;
g_tex->QueryInterface(__uuidof(IDXGIResource), reinterpret_cast<void **>(&dxgiResource));
dxgiResource->GetSharedHandle(&g_shaderHandle);
dxgiResource->Release();
backBuffer->Release();

```

Now that we have a shared copy of the back buffer and handle to it, we can save it to a file from another thread without hogging the device context:

```
// device_2 and context_2 are the "secondary" device and context
bool imgSaved = true;
ID3D11Texture2D *texture = 0;
HRESULT h = WaitForSingleObject(g_mutex, INFINITE);
if (h == WAIT_OBJECT_0)
{
    // check to see if there is an image to save
    if (wdata->hasFrame)
    {
        wdata->hasFrame = false;
        imgSaved = false
    }
}
ReleaseMutex(g_mutex);
if (!imgSaved)
{
    device_2->OpenSharedResource(g_shaderHandle, __uuidof(ID3D11Texture2D), (LPVOID*)&texture);
    if (texture)
    {
        h = D3DX11SaveTextureToFile(context_2, texture, D3DX11_IFF_PNG, "image.png");
        texture->Release();
    }
}

```

Basically this allows me to save HD screen captures without killing the frame rate because my device context is not stuck in the D3DX11SaveTextureToFile function, it's handled by the secondary context. On a side note, I've not tested it a whole lot, I just hack this together this morning, it might not work in some cases, but it solves the problem I had with the other flag, which caused empty images to be saved to file.
> 2 votes

# Answer
I have to say that you will not save any extra memory by using this. Textures are not stored in gpu's ram by the creation. They are sended after `SetResource(SRV)`. And cleared from gpu ram after the `SetResource(NULL)` call. That's the way how to save space. Always clear after your shader pass.
> 1 votes

# Answer
Have you tried using D2D interop ? This is just a stab in the dark, but you could maybe try sharing the surface with a D3D10 device instead, and then save it the texture as a bitmap with D2D.

The fact you can't save a shared texture may have something to do with how it is stored in memory, since it has to be shared between devices, but then again, I'm not sure so I might be wrong.
> 0 votes

---
Tags: c++, directx11
---


# Question
Title: What do colleges such as Rocky Mountain College of Art and Design look for in a portfolio?
I really want to get into Rocky Mountain College of Art and Design (RMCAD), but I don't know if my skills are up to par. A representative came down today and she told me the requirements for the Game Art degree. Turns out I don't need a portfolio, but I know it would definitely help me out with scholarships, acknowledgement of skill and so on. I want one for myself anyway.

I have a few 'good' sketches and some other 'eh' sketches I don't think are anywhere near my best. I have some life drawings I've been working on as well. To improve my skill I decided to start over and I'm currently learning the human anatomy to draw better skeletons for my characters and such.

I want to be a concept artist with characters and levels/buildings, but... I'm not the best at levels or buildings since I've never really drawn them before. My characters aren't the best, but I am improving. if anyone could help me, I'd greatly appreciate knowing what I should put in my portfolio, how to prepare for college, and etc.

Note: The college is an actual college which is a plus because I can learn my major (game art) plus a minor like business or something else. Maybe architecture...

# Answer
> 2 votes
While I'm not an artist, I think you've mostly answered your own questions:

1. While admissions to the Game Art program can be attained without a portfolio (you'll have to submit a personal statement instead, as noted in the application checklist), it may put you at a disadvantage. Applicants are "encouraged" to develop a portfolio prior to submitting an application.
2. Work on and practice what you believe you are weak at -- musculature, anatomy, and drawings of landscapes or buildings, apparently (based on your question).
3. Iterate on your work until you are proud of it. If you're not proud of it, why would you show it off?

It's hard to say exactly what the school (or any school, for that matter) will look for in a portfolio. Some places might want to see only the best work you have to offer, some might want to see a range of your work to show how you have grown and developed on your own. Some may not care if you demonstrate a very narrow focus in terms of media or subject matter, other may consider that a negative and prefer that you show off a broad range of styles, approaches, and subjects.

In the end, you have the most control over making *yourself* happy and satisfied with your portfolio. Focus on that more than what you think other people want to see in you; that alone will make you better, and should help open the doors you want as well.

---
Tags: art, education, portfolio
---


# Question
Title: What are the basics in game architecture? How do you create your game skeleton such that it doesn't stay in your way?
There must be some best practices on how you create your game architecture/skeleton. One of the best resources that I found is: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ My primely focus is for iOS games using cocos2d.

What is your know how on this topic?

# Answer
> 2 votes
In addition to MVC pattern as the other reader suggested, I would suggest you learn a little bit about discrete event simulation - because your game engine heart is basically that.

In brief, that means:

Your game is described by a model. A model is composed of game objects. In a real time strategy, this would be terrain, units, static objects (trees), buildings, players, etc. As time progresses, the model is repeatedly changed.

Model your game elements as simulation entities which are scheduled to do actions at a given point in time. When selected at some point in time, each game element produces an action based on the current state of the game (the model). An action changes the game state, produces an event and schedules the game object that produced the action again at some time in the future.

You can also have triggers - whenever a matching event (that an action created) is detected, a trigger is triggered (e.g. an action that moves a player character around produces a MoveEvent which can be detected by a CharacterEnteredRegion trigger, that then does something with the game state again - for instance, creates more monsters).

I found this approach quite extensible and adaptable. In fact, it can be used both for real-time and turn-based games.

# Answer
> 1 votes
First off, study MVC architecture. I've done a lot of UI design and this has really helped me to understand these roles well.

If you can, explain your code to someone -- even if they don't understand what you're talking about. I explain things to my wife all the time, and even though she's probably not even listening, it helps to clarify things for me simply by organizing my thoughts into words.

Lastly, don't be afraid to rip the guts out of your code. If you find that something doesn't seem to work right, come up with a better way to do it and re-implement it, even if you have to tear half of it out to do so. A good revision management system can help here.

---
Tags: architecture, ios
---


# Question
Title: Need help with rally point and spawning in StarCraft 2 map editor
I want to make a Tower Defense game using the *StarCraft 2* editor.

How can I make a rally point to control AI appear at one point and go to specific point? How do I make creep spawn properly at specific times?

# Answer
You need both Locations and periodic events for the functionality you've described. Using locations, you can create a trigger to order all enemy units in location A to move to location B.

Likewise, you can make another trigger to generate enemies in location A every x seconds (which can then be ordered by the first trigger to move towards the goal area).
> 1 votes

---
Tags: starcraft-2, tower-defense
---


title: Simulate 3D with 2D sprites

text:
# Question
Title: Simulate 3D with 2D sprites
I was thinking about 2D games (like Starcraft), where the sprites are in two dimensions, but the objects that are "higher" in the screen are behind the other objects (I think this is obvious when you think that "higher" in the screen means "far" when simulating a 3D environment).

But, how do you do this programmatically? It is a good idea to track every movement for every object, assigning object to different layers in order to simulate movement in that axis?

Is there a better way?

# Answer
> 7 votes
Just because your game operates and is drawn mostly in two dimensions doesn't mean you have to treat it in only two dimensions. You could add a height variable, but this really isn't any different than a third dimension (probably corresponding to a Z axis in your case).

I would simply treat everything in 3D space, and track its x, y, and z coordinates. The latter (z) probably won't mean a whole lot, and most of your calculations can continue to ignore it. As a unit climbs a ramp or falls down a cliff, etc. you adjust its z coordinate.

If you take this approach, you can solve your problem by letting OpenGL (or DirectX?) do the depth testing for you (though this would mean slightly more work for the GPU). Simply turn on the depth buffer / depth testing in your rendering engine and the GPU will take care to ensure that objects will not be drawn in front of objects that are "nearer" to the camera than them.

# Answer
> 1 votes
Here's how I did it for my "Starcraft" clone:

1. Collect all visible sprites locations into array
2. Sort the array by sprites lower edge. Lower edge should be taken in map-coords (so that units standing on a very tall hill still would be above units behind the hill).
3. Render terrain ground strips along with units standing on them from top to bottom

# Answer
> 0 votes
Maybe something like a height variable that gets updated each time the object moves.

Run a basic sort algorithm and then you could loop through and draw each level.

Unfortunately in game development I have found that everything is done the hard way. If you want to manipulate something you will have to track it, there is likely a trade off in starcraft (not everything tracked to save processing) and this can improve playability

In the end though that is what being a programmer is all about.

---
Tags: 3d, sprites
---


# Question
Title: How are profiling- and tracing -techniques used in Game Development?
I feel that in order to create realistic real-life games, game developers need some ways to monitor the system itself i.e. players' moves, other events and the state of the system itself. I know that creation of profiling/tracing -systems is not that easy, look how many people have tried to do better coverage -program in Python and fell far away from the original coverage.py.

1. I may be associating profiling/tracing wrongly to this game-development phase of dynamic monitoring but I am interested to know where/how profiling and tracing -techniques such as pythonic sys.settrace() are used in game development?
2. What is their purpose and what are the dynamic event monitoring systems really called? Game engines?
3. Are there some ready systems to advance/investigate profiling/tracing -areas in game development?

# Answer
> 4 votes
There are two kinds of data we can profile, at the high level:

1. We can profile the execution of the program itself -- what functions are called when and where, how long they take, and what impact they have on the environment (allocations, locks, threads spawned, et cetera).
2. We can profile what the user is actually doing with the program -- where they are in the game when they die, where they are when they earn the most experience, what they spend the most money on, which skills they use most often.

These aren't fundamentally different operations, really, although the type of data collected by each operation is pretty significant. The type of data collected by the first technique is generally reusable across many programs, whereas the second type of data tends to be more program/game specific (experience may not even exist in a particular game, for example).

You have the right terminology for this kind of technology -- "profiling," "tracing," "user monitoring" and such are all appropriate terms. The technology itself is fairly straightforward to implement as well. The most basic approach just involves instrumenting code by calling a function that collects the desired data. You can then write that data to a log file or (most usefully) send it to a database for later querying and report generation.

*Code coverage*, which you mention at one point, is a little more complex and difficult to get right (especially in more dynamic languages). It is more akin to the first technique, that is examining the state of your code rather than how users use your program.

---
Tags: profiling, profiler
---


# Question
Title: Is it ok to use NPOT textures with OpenGL in this situation?
I drew some icons to use on orthographic projection and instead of loading each icon file individually as a texture I thought of putting them all together in one single file. Now I have a file `72x36` which is not a **power of two**. This texture is divide in two icons, both with 36px wide.

I didn't remember about this restriction when designing the texture but I eventually noticed it when the texture didn't load because I have an if statement checking if the texture is a power of two, if it's not, than the texture is not loaded. I commented that code to see if the texture loaded anyway and it did. The texture was loaded and properly applied to the area I wanted.

To draw the first icon I do this:

```
glBindTexture(GL_TEXTURE_2D, gameTextures.hudKeys);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 36);
    glTexCoord2f(0.5, 0); glVertex2f(36, 36);
    glTexCoord2f(0.5, 1); glVertex2f(36, 0);
    glTexCoord2f(0, 1); glVertex2f(0, 0);
glEnd();

```

And for the second this:

```
glBindTexture(GL_TEXTURE_2D, gameTextures.hudKeys);
glBegin(GL_QUADS);
    glTexCoord2f(0.5, 0); glVertex2f(0, 36);
    glTexCoord2f(1, 0); glVertex2f(36, 36);
    glTexCoord2f(1, 1); glVertex2f(36, 0);
    glTexCoord2f(0.5, 1); glVertex2f(0, 0);
glEnd();

```

Which is easy to understand, I only use half of the texture depending on which icon I want.

I don't want my icons to be distorted or stretched, the icons were designed with 36x36 in mind. If I use a power of 2 texture, for instance 128x64 (that's the lowest possible to fit a 72x36 texture), how do I properly map the 36x36 texture area I want to the quad?

Or maybe I can keep doing using this NPOT texture or should I still really create a power of 2 texture? How to fix the problem above then?

# Answer
Generally speaking you should use POT textures so you get the benefits of texture compression. For example, a PVR compressed texture at 128x64 @ 4bpp is going to be smaller in video memory than an uncompressed 72x36.

Calculating UVs is pretty simple. Just plug in pixel values over the size (in pixels) of the source image. So if you were to just expand the image you made to the next largest POT, the upper left bit of the second icon would be at ( 36/128, 0/64 ). And so on.
> 5 votes

# Answer
Combining images into a single texture is fine, but that texture really needs to be dimensions of P0T. You can avoid distortion by keeping up with the image size, its offset, and the texture size.

For example, say you have two small 12x12 images that you load and want to combine. You'd need 24x12 for both, but this isn't a power of two, so you'd find the next highest POT dimensions and get 32x16. Now keep up with the image sizes, and their offsets, and when rendering use these to find your texture coordinates.

I'll define some variables to walk through it:

```
tw, th = texture width (32) and texture height (16)
iw, ih = image width (12) and image height (12)
iox, ioy = image offset x (0 and 12) and y (0 and 0)

```

so to draw a given image, you'd calculate your top left as:

```
(tw / iox), (th / ioy)

```

and your bottom right as:

> (tw / (iox + iw)), (th / (ioy + ih))

It helps to draw this out. The POT is very important, though!
> 2 votes

---
Tags: opengl, graphics, textures
---


# Question
Title: What is the easiest genre of game to make?
Before you down vote let me give some restrictions.

I like RPG but they seem long and hard to make but after you make the framework the rest sort of falls into place where as platformers never get faster as each map starts from scratch.

So under these conditions what is the easiest genre of game to develop as a hobby project.

1. I am on my own.
2. The style of graphics must be available. Can be ripped (not publishing).
3. Not bothered about commercial quality.
4. Must be real size game, multiple levels and stuff.

Thanks

Edit:

I build games in C++ and Direct x 9.c

# Answer
I agree with Apreche, a side-scrolling shoot 'em up is by far the easiest genre to create a simple game in.

For the basic setup, all you need is three parts:

* Player: Moves to where mouse is
* Enemies: Move down- or left-ward, depending on if horizontal or vertical shooter
* Bullets: Move opposite to Enemy direction

Then you just need to add collision checks for Bullet-Enemy and Enemy-Player, and you've got a game.

From there on, you can then expand upon your design, adding enemies that shoot back, power-ups, asteroids, points, etc.

You can also easily try out adding all kinds of interesting "features" to your code-base before starting on a new project: AI finite state machines, spatial partitioning for collisions, particle systems, parallax scrolling, the list goes on and on.

In short: As your first game, you want something that is easy to make, and easy to expand upon, making a SHMUP an excellent choice.
> 9 votes

# Answer
The easiest kind of game to make, other than text adventure, is probably a Space Invaders style shmup. Many 2D game engines and libraries use this style of game for their tutorial.
> 10 votes

# Answer
For a simple hobby project it is good idea to make a game which doesn't require much content. For example even if a 2D platformer game would be easy to program, it requires lots of good levels. If you create an RTS game with automatically generated levels, you still need several unit and building types and need to balance them.

Try to start with game ideas where the engine makes the game. For example Asteroids style game can be simple to program and you can also get infinite amount of "levels" with very little effort. The faster you can make a playable and fun game the better. You can then improve it afterwards in many ways if you want to.
> 6 votes

# Answer
Rogue-likes. Part of the genre is the ease of development. The curses libraries make the interface the easy and straight forward, leaving the backend to be as complicated and awesome as you want to make it.

In 08 I participated in the 7 day roguelike challenge and went from stone-cold to a working game (albeit without much conflict other then falling damage). I had to pass on fencing and D&D that week, but I still put in 40 hours at work.

And the community is more or less friendly and helpful over on RGRD
> 6 votes

# Answer
The less content a game requires, the easier it will be to develop.

There are games in every genre with small content requirements but overall puzzle games require less content than other genres. Also almost all classic arcade games were made with little content (eg. Breakout was just the paddle, ball, and bricks.)

(By "content" I'm referring to how many graphics you need to create, how many levels you need to design, how many sounds you need to record... basically all the work in game development other than the programming.)
> 3 votes

---
Tags: game-design
---


# Question
Title: Calculating camera zoom value (top-down)
I need some help in 'camera maths'. I have a birds eye view of two characters. One character is static and the other can move. I would like the camera to always show both characters in full and, in order to simulate 'zooming out', I'm uniform-scaling the objects. The static character is always at the top of the screen and so the 'camera' can't move along the Y-axis (otherwise the static character would not be shown in whole). However, it can move along the X-axis as far as possible, until the screen reaches the side of the static character. How can I calculate the *minimum* distance the camera should zoom out in order to ensure that both objects are always on screen?

I hope that makes sense, but I'd be happy to try and clarify it if need be. Thanks.

# Answer
I'll take a stab here... I think what you want is:

```
tan( 1/2 * field_of_view ) * ( 1/2 * distance_between_objects)

```

Since you can't see my whiteboard, I'll try to describe the idea. Take your camera and your two objects, and draw a triangle between them. Now draw a line from your camera to the side of the triangle opposing it (and perpendicular to it). You now have two right triangles. You know the angle at your camera (1/2 * field\_of\_view) and the length of the line segment opposing it (1/2 * distance\_between\_objects). The tangent function, given the angle, will tell you the relationship between the length of your opposite side and your adjacent side, the first of which you know.

The result is the distance from the line between the two objects (probably your ground plane) and where your camera should be. You probably want to add some "padding" to this so your objects aren't on the very edge of your view.
> 1 votes

---
Tags: 2d, c#, mathematics, camera, vector
---


# Question
Title: What's a good Game development platform for a platformer game with these characteristics?
Yes, I know, the best way to make an indie game is to learn to code. I've got some scripting experience, but I want to do worldbuilding with already-existing tools (and communities surrounding those tools), and I've been really impressed with games like An Untitled Story that were made with pre-packaged toolsets at their core, like Game Maker. :)

So I'm planning to make my game using either Game Maker or something like it.

The basic parameters of my planned game:

* 2D platformer.
* Physics/speed akin to Sonic the Hedgehog.
* Large, non-linear world, flowing as seamlessly as possible -- think Super Metroid, but without the forced screen transitions.

The first two points have me leaning toward Game Maker -- Plenty of 2D platformers have been made with it, and there are serviceable, openly available Sonic-the-Hedgehog-style physics engines for it that could be adapted to my needs with minimal muss and fuss.

But the third makes me antsy -- from what limited information I hear, Game Maker has problems with large levels/boards/screens/whateveryoucallthem, thus necessitating transitions between screens.

I want to avoid that if at all possible -- it would, I believe, fundamentally alter the flow of the game. I understand that generally speaking, the more you have loaded into memory the more things are going to chug (especially for a one-size-fits-all game development platform that isn't a model of efficient coding), but I'm hoping there are systems that can un-load objects that are sufficiently far offscreen and thus better produce seamlessness.

Any thoughts, people? :) The sooner I can get a basic pre-fab physics engine and world-building program up and running, the sooner I can start prototyping areas and generally tooling around. Should I be looking at Game Maker, or elsewhere?

(My current plan is to more-or-less build the game prototype-style, then worry about art and sound at the very end once the damn thing is playable.)

**EDIT/RESPONSE**

To ultifinitus: I might pick up C# for a separate project.

I'm familiar with game dynamics and game design from past projects (Projects that used OOP scripting languages).

The amount of work I'm willing to put into my project is directly proportional to what I can do with what's already out there.

This is where a system like Game Maker appeals to me. :) I've then got the level editor, the physics, etc. all more-or-less taken care of, and the software has a giant enthusiast community that provides various modules, advice, etc.

If I can get most of my game done that way, then once I've got a functional prototype I can happily shell out the cash to pay artists to make the game actually look like something worth a damn.

This is why I'm looking for something like Game Maker. I'm just wondering if Game Maker (or another such system) is the most suitable for what I want to do.

# Answer
> 2 votes
I think you might wanna try **Unity3D**. I haven't dive in it much, but I knew that Unity comes with level editor (and it's 3D, by the way). Game programming is done using javascript (CMIIW). Another good thing about unity is that it can be played in browser (provided you have the unity player), so your game can reach players easily. **Kongregate** hosts unity games, you may want to check them out.

Other platform that I'd like to suggest is Flash (using ActionScript 3.0, to be specific). I believe flash can make your game up and running quickly. It doesn't have native level editor (it's not even a game engine anyway), but there are ways like this to do just that. Physics are mainly done using third party library called **Box2D**, and there is also box2d game level editor available to use. There are also frameworks that builds on top of AS3, such as **flixel** and **flashpunk**, that helps a lot when developing 2D platformer game.

Hope that helps.

# Answer
> 1 votes
You might want to check out XNA. There is a lot of resources online showing how to create games in XNA, and there are a lot of people on here who know a good deal about XNA, C# and .NET.

You might have to step outside of your comfort zone of game maker, but if you really want large levels with good performance, you are going to want real language, and proper GPU acceleration.

XNA is much more suited to create 2D games than Unity, but XNA excels at 3D games as well. XNA is completely free and has no limitations, while Unity is free, but for some of the more desired features like color correction and other post processing, you would have to buy the full version which is not cheap.

# Answer
> 0 votes
You didn't specify the platform in your question, but since you are leaning toward Game Maker that clearly means you are developing a Windows game. There are of course many many tools you can use to make PC games, with lots of different pros and cons. Using XNA is an option I would strongly consider, but another great looking tool I recently learned of is:

http://love2d.org/

It uses Lua for doing the programming, and I have fallen in love with that language because I'm using Corona to develop an iPhone game.

---
Tags: 2d
---


title: glVertexAttribPointer normalization

text:
# Question
Title: glVertexAttribPointer normalization
glVertexAttribPointer(index, size, type, normalized, stride, pointer);

If I use type=GL\_UNSIGNED\_BYTE and normalized=GL\_TRUE

how is it normalized? would the data be divided by 256 for normalization? or? This would mean there is no way to have a normalized value of '1.0f'..

# Answer
From the manual,

> If set to GL\_TRUE, normalized indicates that values stored in an integer format are to be mapped to the range \[-1,1\] (for signed values) or \[0,1\] (for unsigned values) when they are accessed and converted to floating point.

I take that to mean that, with an unsigned 8 bit type, 0 would map to 0.0f and 255 would map to 1.0f.
> 15 votes

---
Tags: opengl, 3d
---


title: Unity3d or WebGL: Where should I go?

text:
# Question
Title: Unity3d or WebGL: Where should I go?
I am interested in making a simple 3D game this summer, and I'd prefer if it were playable in a browser. My choices I am considering are Unity and WebGL. Currently I have no experience in either. But I have taken an introduction course to OpenGL. As well I will later be taking a course that will use Unity. I have some C# experience, but no web background.

The factors I'm considering are ease to learn and the penetration each has. I know Unity games can be uploaded to Kongregate, which seems like a pretty big deal if I made a game that would be somewhat successful. But of course that may not be the case at all.

Which way should I lean? Personally I think learning WebGL would be the easiest transition, but I am not sure

# Answer
Unity is by far the easier option and thus the one I would recommend. Especially considering you have no previous experience developing a 3D game, you want to pick the simplest solution possible in order to complete your game in such a short time frame.

---

That said, there is one significant advantage to WebGL in your situation, so this advantage may be enough to sway your decision. Working with WebGL will teach you a lot more about how 3D graphics and 3D renderers work under the hood. If you are planning to be an engine programmer then you will need to learn that stuff.

Take a look at this link, because it is very useful for you to see in evaluating which technology you wish to use: http://learningwebgl.com/blog/?page\_id=1217

Notice that after 16 lessons it's still nowhere near a complete game.
> 6 votes

---
Tags: unity, webgl
---


# Question
Title: XNA 2D Collision Detection without GetData()
I'm currently working on a Worms game which involves terrain deformation. I used to do it with `.GetData()`, modifying the color array, then using `.SetData()`, but I looked into changing it to make the work done on the GPU instead (using RenderTargets).

All is going well with that, but I have come into another problem. My whole collision detection against the terrain was based on a Color array representing the terrain, but I do not have that color array anymore. I could use `.GetData()` every time I modify the terrain to update my Color array, but that would defeat the purpose of my initial changes.

What I would be okay with is using `.GetData()` once at the beginning, and then modifying that array based on the changes I make to the terrain later on by some other means. I do not know how I would do this though, can anyone help?

# Answer
I've done a bit of research, and I have yet to find a solution to getting rid of any GetData calls every time my terrain is modified, but I have found ways to "optimize" it, or at least reduce the GetData calls as much as possible.

* Crater drawing is batched, meaning that rather than draw each one as it’s created, I add them to a list and draw all of them every few frames. This reduces the number of GetData calls – one per batch of craters rather than one per crater.
* After drawing craters to the render target, I wait a few frames before calling GetData to make sure the GPU has processed all of the drawing commands. This minimizes pipeline stalls.
* If I have a pending GetData call to make and more craters come in, the craters will stay batched until the GetData call is complete. In other words, the drawing and getting are synchronized so that a GetData call always happens several frames after drawing a batch of craters, and any new crater draw requests wait until after a pending GetData.

If anyone else has any other suggestions I would still be glad to hear them.
> 3 votes

---
Tags: xna, collision-detection
---


# Question
Title: XNA Video Playback on XBOX "Invalid operation exception"
I am able to play a video in windows in my project, but the same code fails on the XBOX at the `_player.Play(_logo)` line. The error message is:

"An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.dll"

Relevant code:

```
    public LogoScreen()
    {
        TransitionOnTime = TimeSpan.Zero;
        TransitionOffTime = TimeSpan.Zero;

        _content = new ContentManager(Game3.Instance.Services, "Content");

        _player = new VideoPlayer();
        _player.IsLooped = false;

        _sb = new SpriteBatch(Game3.GDM.GraphicsDevice);
    }

    public override void LoadContent()
    {
        _logo = _content.Load<Video>("Video/intro_logo");
    }

    private bool _started = false;
    public override void Update(bool otherScreenHasFocus,
        bool coveredByOtherScreen, bool coveredByPopup)
    {
        if(_started == false)
        {
            _player.Play(_logo);
            _started = true;
        }

        if (_player.State == MediaState.Stopped)
        {
            Exit();
        }
    }

```

Here is the random test video that I'm using: http://olhovsky.com/xna/intro\_logo.wmv

Any ideas why this might be failing?

# Answer
The XBOX is very picky about which WMVs it will play. The fix is to encode a WMV with Windows Movie Maker -- encoding in After Effects creates WMVs that the XBOX 360 will not play.

Edit: I believe the problem more specifically, is that the bitrate must be 12000kbps or less, for XBOX 360 playback.
> 3 votes

---
Tags: xna, c#, xbox360, xna-4.0
---


# Question
Title: What programming languages would be used to make an Apple App like Angry Birds or Cut the Rope?
I'm currently working in the Multimedia industry and although I'm better at design then development. I have knowledge of HTML, CSS, very basic jQuery, Actionscript.

What programming Languages would you need to know?

What else would you need to know to develop an application?

I am assuming you would need to know xcode and Objective-C?

# Answer
Objective-C is the language of choice to develop for iOS. But you can also include plain C or C++ Code in there, so you could write large portions of your code in these languages. XCode and MacOS-X provide you with all tools needed to develop such Apps. There's (currently) no easy way to develop iOS Apps on Windows, except maybe a Virtual-Machine or trying to install OS-X on your PC.

Alternatively you can also create iOS Games/Apps using Unity3D, UDK or Flash.

As soon as you want to test your App on an actual device or sell it in the AppStore you'll also require an Apple Developer Membership.

**Update**: You asked about Angry Birds and there's actually a nice tutorial out there on how to create such a game using the excellent cocos2d framework.
> 13 votes

# Answer
Angry Birds is written in C/C++ and use its own 3d engine. For the physics part, rovio use Box2D. For the iphone version, they use ObjC to initialize the application and create the OpenGL ES context; otherwise it is C/C++.

If you want to develop your own game, it is easier to use Unity3d. If you need OpenSource library, use cocos2d.

Ps: You can find interesting symbols in .so of the android version.
> 2 votes

# Answer
You say application? I'm going to asume you mean just games rather than any old application.

For games in general (excluding iOS for the time being) C++ has been the staple for a long time in the games industry, and as such there are many many tools available for it, physics, graphics etc. C# is looking good atm, and the XNA platform is easy to use, You can also use C# with Unity3D if you are looking for a pre-built solution.

I'm not sure how many games on the iOS use Obj-C, I wouldn't be surprised if alot of them are C++, All the ones I know for certain are in C++ or Unity and I dont know anybody who's made a Obj-C game for the iOS (Which is more todo with the circles I'm in than anything else). The game I've been working on for iOS is all C++.

Obj-C and C++ talk to each other quite happily the xcode compiler is smart enough to know what is what.

In short:

Xcode is almost a must. The only exception I can think off at the top of my head is if you use Unity, or Corona (which you might want to look into, I've heard flash devs talk nicely about it)

Obj-C You will need to know a little at the very least (this can just be cut and pasting)

C++ Has a big following, however you will need a little Obj-C to get your game working even if you use C++.
> 1 votes

# Answer
Corona SDK is a great tool for developing 2D games like Angry Birds or Cut the Rope. cocos2D is a very awesome tool but programming in Lua is way more productive than programming in ObjC. It's a lot like using ActionScript.

They even did a sample specifically to demonstrate developing an Angry Birds clone in Corona: http://blog.anscamobile.com/2010/12/ghosts-vs-monsters-open-source-game-in-corona-sdk/
> 1 votes

---
Tags: ios, career
---


title: Maya .IFF plugins for Gimp

text:
# Question
Title: Maya .IFF plugins for Gimp
Maya's preferred format for saving off a UV Snapshot is its own .IFF format, so I was hoping to find a plugin allowing Gimp 2 (Windows) to read it. I've found plenty of plugins for different linux distros, but none are win-friendly (that I can discern - admittedly I'm no whiz with Gimp). Does anyone know of one?

Alternately, .tiff seems to work just fine, so if there's no good reason to bother fiddling with IFFs, I'd appreciate the input there, too.

(sorry if this isn't on-topic)

# Answer
> 1 votes
TIFFs work well, but the most widely used file format in 3D graphics is TGA. If you have existing .iff files that you need to work with then that's a problem, but for rendering out your own images use TGA.

---
Tags: windows, 3d-meshes, gimp, maya
---


# Question
Title: For games that time stamp a saved game (think Half-Life), is the entire game state really being saved every time?
It seems to me if that were the case that your directory of saved binaries or serialized objects could get massive real quick. Is there some sort of strategy being employed on top of the State pattern that is optimizing each time stamped saved game so that it isn't saving the entire game "context" all the time?

# Answer
> 11 votes
Remember that all you need to save is the dynamic data generated at runtime. For example, if you have a monster about to attack the player, you need to save its position, its monster type, and its aggressive state, but you don't need to save its textures, model, behavioural scripts, and so on, because they are part of the static state that can be inferred from the monster type.

As long as your system keeps a clear distinction between the dynamic properties of the game state and the static properties of the world, there is usually not all that much data to store.

# Answer
> 6 votes
I think you may be over estimating the size of that data and/or underestimating the size of what is saved. Taking a quick look, I see saves in my folder ranging from about 400kb to 3mb, with one outlier of 8.5mb

What can you fit in 400k? Well, to store the position and orientation of an object in 3d space you would probably use 24 bytes (32 bit floating point numbers for x, y, z, yaw, pitch, roll). That fits into 400k over 17,000 times. Obviously there is more to each object than that, but not much. Keep in mind that you are only storing dynamic objects for the level you are currently on, since you never move backwards to revisit old levels. If you think about it, there are probably no more than a couple hundred objects on each level, most of which are very simple, like physics objects or health/ammo pickups, which probably don't need anything more than the previously mentioned position/orientation and their type.

As example that I'm more intimately familiar with, a ~15mb file can hold all the data you need to recreate an hour of game play in Heroes of Newerth. The exact size/time varies depending on the particulars of the match, but what you have there is the initial state of the entire game, plus the changes between each frame and its previous frame. That is a complete game state (minus unchanged data) every 50 milliseconds!

# Answer
> 1 votes
One other aspect of game saving is that you really don't need to save anything that hasn't changed. Say you've got a room full of objects if the player enters the room but doesn't manipulate anything you don't need to bother saving the positions of those objects. So you when you're saving the game you could compare the object's default and current attributes and only save the delta. Obviously the comparisons would add complexity and overhead to the process but that's a typical CS trade off, storage or CPU.

---
Tags: game-design, state
---


title: Rendering collections of light sources

text:
# Question
Title: Rendering collections of light sources
I have a small test environment where small point lights are scattered. Players should able to collect them.

The collectible lights are rendered using a simple billboard technique where two triangles with a uniform color are rendered facing the camera and a gaussian is used as an alpha-map.

```
0/1     1/1
+---------+
¦        /¦
¦      /  ¦
¦    /    ¦ u/v texture coordinates for alpha map (gaussian)
¦  /      ¦ every vertex has same color rgb(1, 1, 1)
¦/        ¦
+---------+
0/0     1/0

```

When a player collects a light, the idea is that the collected light is merged with the lights he already has collected. The players are currently rendered with the same method as the collectible lights, the collected light has influence when the lighting is calculated =\> higher light intensity.

What I'm looking to do is to visualize the lights better. They look really boring the way they are rendered currently. Only good thing about them is that they do not influence the performance :-)

The process of the light merge could for example be visualized in a way where all collected lights circle around as small pulsating glowing particles - sticking together to some extent - maybe some nice lines which travel with them - you know, like such a thing *should* look like if it is a central part of a game.

The problem is that I don't really find many resources over advanced shader effects. Most information found is over the basics (diffuse / specular shader - maybe some blurring) or does not involve the HLSL language which I use in XNA 4.0.

I would appreciate any links to resources which could help me making more awesome light effects which could actually run on the xbox without running into performance issues. Basically, any techniques which involve rendering cool light orbs / beams etc. would be fine for the moment if the result i visually appealing.

# Answer
Neat idea for the game. The problem is that light really doesn't look like this. Light decay is NOT gausian :). That's for the begining. What i want to propose is adding simple (but relatively physicaly correct) fog or dust. Mean volumetric effect. You will have to implement volumetric raycasting on the gpu. Don't panic. It is not that hard as it might sound.

I have created this in our engine for you as a example how it might look like. It is realtime. And can be realtime for few lights with cube map shadow map. (low fps is caused by output)

What do you see here is fog (or dust) containing lights. Lights are represented only by their position, color and intensity. They have cubic decay, which looks natural and fits to the definition of the Radiance. Lights has different intensity, exactly what you wanted.

Volumetric raycasting casts ray for every pixel and samples through the volume. It is usualy used for smoke, dust or fire on offline rendering, but can be done on gpu in realtime. You dont have actual volume, but you have to sample for the shadows contained in the shadow maps. If you want only fog, it can be done with O(1) complexity (per pixel shader)

You sample on ray like this:

```
//pseudo ugly pixel shader code
samplePoint = zNear;  //position on zNear (in worldSpace)
color = 0;
until(z-buffur_value || zFar)
{
    lightDecay = getLightDecay(samplePoint,lightPosition);
    shadow = getShadow(samplePoint); //like regular shadow mapping, you have world space position and want to know if there is shadow or not.
    color.rgb += (1 - color.a) * (lightColor * lightIntensity * lightDecay * shadow);
    color.a += (1 - color.a) * (1 - opacity); //opacity is the same in your case. If rendering something like clouds it is loaded from the 3D texture. I suggest value like 0.01 or similar..
    samplePoint += direction * step;
}

```

It is not hard actually and can be done as a pixel shader (offscreen). You have to stop sampling rays at z-buffer value (so it has to be applied after the opaque scene render). And alpha blended with opaque scene render.

It is pretty solution to this. It also attenuates lights which are far from player, solves the intensity correctly and i think it looks cool.

For more info you maybe like read my paper about implementation of volumetric effects into game engine (well something similar to game engine :)).

There is also awesome book about volumetric rendering. I'm in love with it. Also this site contains pdf tutorials which are quite good introduction to the volume graphics.

Improvement: Adding colors to lights and perlin noise to the volume to look more natural (left without perlin|right with perlin)

(hmm those gifs are too low quality that there is no significant difference).

**edit (some performance notes):** it can be done as one pass per light, which is usefull if lights has lots of aditional textures (light color - projective texturing, intensity curves etc.). But this is frame rate killer, it can (and should) be done in one pass for all lights if you have enough texture units available (i think you have in your game). Than it can have about 45-60fps i hope.

Sampling doesn't have to be linear. You can make sampling logartmic (or similar function).

```
makeEveryStepALittleBigger = 1.05;
samplePoint += direction * step;
step *= makeEveryStepALittleBigger; //this should be actualy based on camera FOV

```

This however destroy physical correctness and "opacity correction" has to be done. Which is:

```
curentAlpha = 1 - pow((1 - opacity), delta);

```

where delta is difference between step1 and step2.

And if you dont mind little noise, you can add depth jittering which allows you to use much lower number of samples (that is pretty good and easier solution).

*That was fun...*
> 10 votes

# Answer
Motion and such will help, but what it sounds like might be an answer for what you're going for is a way to cause them to look more "glowy".

The key to making something look more lit in your scene is by darkening everything else. From there little things like over-saturation of color (leading to light colors washing out to white) and just plain being more lit than the ambient scene will do a lot to add to the effect.

One of the easiest and least intensive ways I can see to get this effect given what you have described would be to go with an additive blend with the scene. Make your individual motes of light have a 70-80% alpha center, before lowering the alpha rather quickly as you travel outward. Make sure if you do this to leave a rather wide (2-3x size of center) ring of very low alpha.

Now this area will be almost imperceptible when blended with the scene alone, but as you gather multiple together, the different slightly shaded areas will overlap causing a more general glow to the whole collection. On top of that, the field does not have to be uniform, and you can leave streaks of slightly more alpha areas in the texture to cause light beams to be hinted at. You'll probably want to rotate the texture over time so the lines don't look static, but overall the effect will cause the bits of light to look more like just that and less like little floating balls.

Hopefully this helps. It's not exactly advanced shader work, but I find sometimes the more simple effects can give a quite satisfactory look. Consider throwing in a soft particle effect as well to allow the lights to leave slight trails or other effects in the player's vision. Happy coding!
> 0 votes

---
Tags: xna, shaders, xbox360, lighting, hlsl
---


title: Simple puzzles in platform games

text:
# Question
Title: Simple puzzles in platform games
I'm working on simple platformer game. I've got already finished programming the main part of game, which is moving and collecting items.

I want a unique game puzzle in every level, but I can't think up enough. I've been thinking for hours but I've got only few puzzles which are not very good. I would be grateful for any ideas or help you can provide.

# Answer
Your puzzles will flow from the mechanics of your game, so you should start by defining those mechanics. For example, can the player run and jump? I would assume yes, since that's pretty much the definition of a platform game, but you should list that concretely.

What other stuff can the player do? For example, can the player collect keys to open doors? Can the player attack enemies somehow? If so, how exactly do they attack? etc etc

Once you've listed out all the different mechanics in your game (incidentally, you will probably come up with more later so don't worry about this being a complete list, just a place to start from) you can start planning ways for the player to accomplish specific tasks by using those mechanics.

If this is your first platformer then it's probably best to stick with mechanics that you've seen before and know work, but many innovative games have been built pretty much by starting with a couple new mechanics and everything else flowed out from there. Braid is a great example of a 2D platformer where all the puzzles started from the time-rewind mechanic and branched out from there.
> 3 votes

---
Tags: level-design, puzzle, platformer
---


# Question
Title: Good introduction to all things game dev?
I saw a lot of books which cover specific topics, but is there a book or a recommendation of a few books which covers the basic of everything involved in making a game? I know this would only cover the basics, but that would be a good starting point to later read more into specific topics.

# Answer
> 6 votes
If you're about C++ game development then..

Steve Rabin's Introduction to Game Development 2nd Edition.

Mike McShaffrey's Game Coding Complete 3rd Edition.

Gregory and Lander's Game Engine Architecture.

If you just want an overview of general game development (non C++ specific) then might be better to look elsewhere...

# Answer
> 6 votes
The Art of Game Design: A Book of Lenses \- as making games isn't only about programming.

# Answer
> 2 votes
start with flash, there are plenty of resourcces and some really good books:

http://www.emanueleferonato.com \- some good beginner code but the structure and efficency of the code is sometimes bad, but its a good and fast start

also this will probably have better code http://www.amazon.com/ActionScript-3-0-Game-Programming-University/dp/0789747324/ref=sr\_1\_1?ie=UTF8&qid=1302401359&sr=8-1

I skimmed it, it was fairly basic but an excellent start.

http://www.lynda.com/ActionScript-3-tutorials/projects-game-development/366-2.html a video guide into game development. It depends on your style of learning, if you like just looking at a source code and using that as a starting point, I would recommend the books, but if you're new to programming the video tutorial guide will be great help for you.

finally after getting all that done you'll have a good understanding of object oriented programming, after which you should read: http://www.amazon.ca/ActionScript-3-0-Design-Patterns-Programming/dp/0596528469

Design Patters will help you effectively create bigger games, and allow you to better transfer your skills to other languages. Don't need to read everything but make sure you read the chapters on inheritance, polymorphism, factory design patterns, and model view component.

However, you decide to learn make sure you actually program the code and not just read or watch it. Pick a sample game you want to learn every 2 weeks and really try to understand the code, where you don't have to reference the book too much - if you get stuck don't look at the ans in the book but try and googleing it, being a good googler and understanding how to read the documents for you language is really helpful. If you do those within maybe the next 5-10 months you should be able to make those games within 2 days (the logic at least) - but at that point you should move the the next plateau

I would then recommend moving onto C# creating games on XNA for xbox live and windows 7. Its a very good game development platform, and will be some good books on it in the next few months (xna just got updated so a lot of material online is still outdated), C# is a lot like as3 so don't spend too much time on it, just get comfortable with the language make a few games then move on.

I would say make a java game next for android, but if you think you're ready learn some C++. But before moving to C++ read: http://www.amazon.com/Data-Structures-Algorithms-Developers-Development/dp/1584504951/ref=sr\_1\_2?s=books&ie=UTF8&qid=1301897090&sr=1-2 get a good familiarity with algorithms and data structures.

P.S game programming and programming in general are frustrating so don't be demotivated every must go through that battlefield; if you find yourself really feeling comfortable and able to make games/app without much problem you need to move to harder material, because its a trap!

---
Tags: books
---


# Question
Title: Collision test solution for hack&slash game
I want to ask you what is the best way to deal with collisions in hack&slash game, I know that collisions must be very accurate. My first idea is to use sphere bounds ( I making hack&slash in 3d), but how to deal with hitting with sword some enemy, do you know some better solution for this type of game ?

# Answer
**First**

Simplicity is key.

**Second**

Expandability is necessary.

What I would do, if I were making a "hack n' slash" is create a simple bounding box technique. Define the height and width of the attack, then check collisions with the box. Keep in mind, that if your character can go inside of other characters you want to include your own collision dimensions in the attack box.

Simple, and expandable.
> 1 votes

# Answer
You could treat your sword as a line segment and continue treating your enemies as spheres. Line segment + sphere intersection would be very cheap and you'd probably gain sufficient accuracy for a hack and slash.

Determining the location and orientation of the line segment could be challenging, especially if it needs to correspond with animation.
> 1 votes

# Answer
I came up with a method for testing collision awhile back. I haven't used it so I don't know how useful it will be but the basic idea is this. if point x is inside triangle ABC (collision) then the area of triangle AxB + BxC + CxA will be approximately equal to the total area of triangle ABC. If point x was outside of triangle ABC then it won't be equal. This same idea could then be applied to 3 dimensional objects just using the formula for volume and testing all points within an object to another object. I'm not sure how CPU intensive it would be but I assume it would be too slow with testing lots of points every frame so I thought of only testing two objects if they were close to eachother. Hopefully you can use this information to come up with something.
> 1 votes

---
Tags: collision-detection
---


# Question
Title: XNA captures mouse clicks when the game doesn't have focus
If I alt-tab and do stuff outside of the game window, the game still captures mouse clicks (both left and right clicks).

The game doesn't "consume" the clicks, since they are also sent to the application that has the focus.

But it's rather annoying to hear a gunshot each time you click in your internet browser...

Also, the problem occurs even if the game is set to fullscreen.

# Answer
The best solution I have found to this is to stop responding to input (and probably pause your game as well) if it goes inactive.

**You can check `Game.IsActive` or hook the `Activated` and `Deactivated` events.**

There is one minor drawback - I would just about consider this a bug in the framework - the game always starts in the Active state, even if the game isn't actually active when it starts running. (For example: you click to another window between launching your game and your game actually starting.)

You could work around this by checking what the active window is when your game starts, probably using `GetForegroundWindow`. Or you could just not worry about it - it occasionally happens as a developer, but I suspect it doesn't really affect end-users.
> 16 votes

---
Tags: xna
---


title: Adaptive AI (Artifical Intelligence)

text:
# Question
Title: Adaptive AI (Artifical Intelligence)
I was thinking to make my arcade game match the players strength in the hard level mode. Like checking the score and if the human player's score is above computer's for certain number of units then the computer player would automatically increase the speed of its reactions, just like a human companion who gets more determined to fight back.

Does this sound a good idea to you? Are there other ways to approach this, so to make a game, like air hockey for a crude example, permanently challenging for anybody?

EDIT: I agree with the answers below. I believe that most people like to win about 70% time over the computer in order to be motivated. Hence an adaptive intelligence must not be become too superior to the player and depending on human player's concentration and some random elements in the game (good 'old' quantum RND), the outcome should be always uncertain.

A nice thing about this is that such a system could handle week and strong players and would adjust to the human's learing curve.

# Answer
> 2 votes
I believe it is a good idea, but to use wisely. Adaptive difficulty can be frustrating to players who wish to beat a game with a fixed set of rules and are suddenly faced with a different difficulty without asking for it. It will depend what your game exactly is about, though.

# Answer
> 6 votes
I think it's similar to the so called rubber-banding in race games which is fairly common, if done correctly it can make games more fun to play.

However when done incorrectly it can lead to the player feeling like he (or she) isn't getting better at the game or to the player getting frustrated that they aren't making any progress.

# Answer
> 1 votes
To be honest, I think most players like AI that can out smart them; the difficulty curve should be included in part of the level design, so that the player can still manage the challenge, but it is difficult. You want to keep the player constantly thinking, unsure of what the AI will do. Predictability and AI 'quirks' kill immersion and game play, so they should be the highest priorities.

Second to that, if they become too smart, lower their capabilities, for example in an FPS, you may hard code a bullet dispersion for AI to decrease their 'aim bot' abilities.

# Answer
> 1 votes
I believe not only is this a good idea but should be mandatory for most games.
Make your system not as simple as if the score is higher than some arbitrary number than send enemies with more health, that is the wrong kind of difficulty increase. Also, don't limit it to the hard difficulty, start easy and let the system adjust the difficulty according to what the player does.

For your example of air hockey I would divide the elements of gameplay into several parts through a brainstrom. Say, you start with the full game, that divides into offence and defence, and defence divides into keeping your goal safe and being quick enough to react. keep the player's score for each of those and then adjust it (according to a function, not some random number, I'm pretty sure there's some research for that) for each of the fields of the AI. Infinite adaptive mario is a great example of what you're trying to do, you should look at that.

# Answer
> 1 votes
I dislike that idea, because the change in difficulty is not obvious to the player, making him feel he has not improved, interfering with any achievement mechanism such as a high score table.

Instead, I prefer if the player gets to choose the difficulty level, but has an incentive to go as high with the difficulty level as possible, for instance because in-game rewards (score, powerups, whatever you have) increase with difficulty.

This doesn't have to break immersion or game flow; in an arcade top-scrolling shooter, the player could pick up a score multiplier (honey), thereby enraging the bee hive :D

---
Tags: ai
---


# Question
Title: Passing an OpenGL texture ID loaded in NDK back to java
Is it possible to load a texture using the NDK, but pass the result back to use in java.

I have used the code in the link above and it appears to load the png correctly and generates a texture ID without an error (the id is 0 before the loading function is called and non-zero afterwards).

Is it not allowed to mix opengl operations between C++ and java?

Thanks for your help All the best, Ash

# Answer
> 1 votes
I do quite a bit of the opposite -- I leverage the Android facilities for loading images from disk and into OpenGL, and then return the texture ID back over JNI.

So basically, I have native code, a JNI bridge, and then a series of utility functions in Java that do the actual work, and my call sequence looks something like:

\[native code\] -\> \[JNI code\] -\> \[Java Code\]

and of course the texture ID is passed back to native code. There's no reason this can't work the other way around, though I have to wonder what compels you to do so, since it's so easy to do in Java/Android as it is. What is the problem you're encountering?

Make sure you aren't attempting to make OpenGL calls simultaneously from multiple threads, and check to see if the OpenGL error flag is being set anywhere.

---
Tags: c++, java, android, ndk
---


title: Box2D stable range and position

text:
# Question
Title: Box2D stable range and position
Box2D marks stable range of object size is 0.1M ~ 10M. This specifies object size range. How about space size? If I make an 1M object at (1000.0f,1000.0f) position? Is it can be stable? Or should I assume spatial range is also limited same with object size?

PS. Maybe the resolution limit is defined because of limit of floating-point operations. I believe there's also some limitation on spatial range, but I couldn't figure out specific range myself.

# Answer
> 1 votes
The answer is yes and no. Calculations in local space won't be bothered by large positions, but calculations in world space will be.

Collisions, for example, happen in local space. If two 1x1, density 1, |v| = 1 objects collide, it doesn't matter where they are - no magnitude involved in the collision detection or correction is going to be much above 2. Likewise, a very large, dense, or fast object is not going to be stable no matter where it is.

But things like body position updates happen in world space. If the same object is at position 10000000 has a speed of 0.1/sec, it might as well have a speed of 0 - or worse, it might keep one component of velocity but not the other.

At 1000,1000 you're probably just fine, you've still got a bit of precision to spare. But the world is not unlimited in size.

---
Tags: physics, box2d
---