# Question
Title: What score/level function is often used?
In many games you raise a level when you reach a certain score, and later levels are harder to reach than in the beginning.

I am suspecting that it is some sort of exponential function that is used in e.g. WoW.

Does anyone know of a good exponential function for this purpose?

# Answer
There's no standard, nor is there actually any reason for there to be. People seem to like the exponential growth as it makes them feel like they're getting more powerful and being faced with proportionately more challenge each time, but in fact that is only true if the way you collect points doesn't also change proportionately as well. If the experience-per-victory rises as the same rate as the experience-per-level, then there's little point either rising - they could both just stay constant.

Further, the implication is that you can't just pick a function for how you want your experience curve to go without knowing how you want your experience accrual to go. And that is a game design decision based on the type of experience you want, and not one we can provide for you.

Still, to answer your question: the type of function you've seen elsewhere is just something like this, a trivial polynomial with a scale factor:

threshold\_for\_next\_level = x * current\_levely

Typical values might be x=1000, y=1.5. eg:

```
level 1 = 1000
level 2 = 2828
level 3 = 5196
...
level 10 = 31623
etc.

```

If you want the slope to be steeper, you increase y. If you want the numbers larger, you increase x.

You might want to have rounder numbers, in which case just round the end result up to 2 or 3 significant digits, or the nearest thousand, whatever you like.

Just remember that these values are meaningless in isolation. If it requires 15000 experience to go from level 15 to level 16, then you must make sure that your game design makes it practical for a level 15 character to accrue 15000 experience points during normal play. There's no point just tweaking the curve after testing because that is generally too time-consuming - you must start out with a curve that matches the awards your game gives out in a way that fits your intended design.
> 11 votes

# Answer
Moria/Angband (and all their spinoffs including -- debatably -- Diablo) base their systems on matching monster level to player level, to see what you earn, with rising XP-per-level requirements beyond that.

In **Diablo**, there are optimal levels of monster you can kill, within 5 levels of you in positive and negative. That looks something like this (apologies if this isn't accurate, Diablo fans):

```
XP Gain = monsterBaseXP * (5-|(characterLevel-monsterLevel)|) / 5
(where result cannot drop below 0)

```

Examples for characterLevel 16: Monster A's level: 16. Gain 100% of monster base XP. Monster B's level: 13. Gain 40% of monster base XP. Monster C's level: 20. Gain 20% of monster base XP. Monster D's level: 23. Gain 0% of monster base XP.

In **Angband** (the model I prefer), it's something like this:

```
XP Gain = monsterBaseXP * monsterLevel / characterLevel.

```

So if you killed a level 50 monster when you were level 5, you would gain 10x the XP that a level 50 character who killed that same monster would gain. I like this, it is high-risk, high-reward. I have lost thousands upon thousands of characters in Angband to this. But the one's who make it, well they are the legendary ones. I think I once hit level 29 instantly from level 1 ;) Likewise, a level 50 character killing a level 5 monster would gain 1/10th of the XP a level one character would gain for killing that monster. Further, because the base XPs also go up, this means killing low level monster can still net you some reward, but go too far down and becomes utterly pointless.

In both games, they additonally use multipliers on XP needed (on a rising scale), however, and the ratio between this and the optimal level monster XP given does get gradually steeper.

The simplest form of this idea is to do the following. Decide how many monsters of equal level to you, you must kill each level to grade (ignoring quest rewards etc.). Let's say 100 -- irrespective of your level. Say that if the player kills a monster of equal level to herself, she gains 1XP.

Using an Angband-like formula to reward increase & reduction according to monster level, your levelling table is linear:

```
1: 100xp
2: 200xp
3: 300xp

```

...And so on. I find this to be the easiest jumping off point -- tweak as appropriate, include monster base XPs, level cutoffs, etc. to your heart's content.
> 4 votes

---
Tags: mathematics, software-engineering, levels, leaderboards
---


# Question
Title: Why would I support multiple rendering engines simultaneously?
I've seen some games from the early 2000s that had a launcher where you could select the rendering engine you wanted to use: DirectX or OpenGL.

Maybe I haven't looked hard enough, but I haven't seen anything like this lately so I have two questions:

1. Why did they do this before?
2. Why aren't they still doing it?

# Answer
> Why did the do this before?

It's complicated.

In the pre-shader days, there were significant differences between OpenGL and D3D. There were also other APIs, like GLIDE. These have since fallen by the wayside.

If the drivers for some particular hardware didn't support OpenGL very well, it might support D3D, so you needed a D3D path. But you could do more stuff with OpenGL via extensions. So having a GL rendering pipeline was important for features.

> Why aren't they still doing it?

Because there's no point anymore.

OpenGL and D3D are cosmetically different, but for the most part functionally equivalent. Outside of certain proprietary extensions, you can't really do more with either API.

And the sad fact is that D3D drivers are more likely to be stable on Windows than OpenGL drivers are. Intel's OpenGL drivers are somewhere between terrible and Godawful, while their D3D drivers are somewhere between crap and not entirely incompetent.

You are either writing a Windows-only application, or you aren't. If you are Windows-only, then the reasons for writing a GL rendering pipeline are... rather dubious. You will gain very little by it without using proprietary extensions, and even that won't buy you a lot these days.

And if you're writing a cross-platform or just non-Windows app, then OpenGL is the way to go. Of course, if you want to be cross-platform on Windows, then it wouldn't be a terrible idea to have a D3D rendering path. But at the same time, it isn't that bad to just rely on OpenGL, depending on how wide a net you want to cast for your application.
> 9 votes

---
Tags: opengl, directx, scalability
---


# Question
Title: How many moves to think ahead for chess minimax AI?
I am thinking of making a chess game, and I read up on minimax trees. How many moves should the AI think ahead so that the player doesn't have to wait a long time?

If there are 25 possible moves (probably an underestimation):

2 moves = 625 boards 3 moves = 15625 boards (huge jump)

I'll be making the game in flash / actionscript 3 (not really a fast language), and I want to keep the turn times acceptable.

Thanks

# Answer
> 6 votes
The real answer is: enough to give your player a smart opponent, and as many as you can get away with whilst giving your player a high quality experience.

But that's probably not going to help yet since you can't really calculate moves in any decent amount of time.

### What it's going to take to make a smart AI

You can't afford to evaluate every possible result of every possible move. Only seeing two moves ahead makes for a slightly unintelligent AI in a game where it's often said the player who can see the farthest ahead will win. Former world chess champion Garry Kasparov is quoted here:

> Asked how many moves ahead he can think, Kasparov replied that it depended on the positions of the pieces. "Normally, I would calculate three to five moves," he said. "You don't need more.... But I can go much deeper if it is required." For example, in a position involving forced moves, it's possible to look ahead as many as 12 or 14 moves, he noted.

So 3 ahead is the minimum, and it's clear you can barely calculate farther than that before you reach insane wait times between turns, thanks to the exponential nature of the calculations.

### You need to optimise.

Alpha-beta pruning works to reduce the amount of possible paths you evaluate in a min-max tree. It cuts out paths that lose in the long term and identifies paths where wins are possible so you don't waste time on fruitless searches.

Even with AB pruning your AI will never be able to evaluate all possible games in a timely manner for any significant number of moves. You need to set it a time limit - say 5-10 seconds, maybe more in situations where the computer is really having trouble finding a good move. Once the time limit is up (if not sooner) your computer *must* stop and make the most appropriate choice based on what it worked out.

Note that the most appropriate choice isn't necessarily the best one (for its winning), since sometimes you might want your AI to stuff up a bit. Note also that in its limited available time, your computer may not actually find an optimum move, or even necessarily a very good one.

---
Tags: algorithm, ai, actionscript-3, performance
---


# Question
Title: Image splitting / tiling software for Mac
I have been programming for a bit and for 2D games and other applications I frequently make large images for the levels / the maps. Before I place these into the games I split the large images down into smaller equally sized squares, but I do this manually in 'the Gimp' and it takes ages sometimes! Is there some software which can do this much quicker for me, where I can select how I want the image split down etc? And for Mac as well?

Thanks

# Answer
> 3 votes
One possibility is ImageMagick, a set of command-line tools for doing things with images. You can write a script in your language of choice that calls the command-line tools to do whatever you need.

Another possibility is Python paired with PIL (Python Imaging Library), which lets you load image files as Python objects, programmatically perform operations on them and save them out again.

# Answer
> 0 votes
An image editing program I use all the time is PixelMator (app store link). It's not free, but it's very good and takes advantage of OS X. I don't think it has a tool for specifying a size and getting images dice automatically, but it does have a tool expressly for dicing up images manually. It's designed for dealing with web site graphics which are often broken up.

---
Tags: tiles, maps, image
---


# Question
Title: Is it safe to use Sleep() in game loop (on Windows)?
Is it safe to use Sleep() function on Windows in game loop (C++)? I want to have fixed frame rate.

# Answer
No, it's not. Sleep only guarantees a *minimum* time to sleep for, but it may actually sleep for any arbitrary amount of time over that. Your timer resolution (set via timeBeginPeriod) is also important for it, and even if you're using something else (like QueryPerformanceCounter) for your timer, you still need timeBeginPeriod to control Sleep.

So in summary:

* Time to sleep for is only a guaranteed minimum and actual sleep time may be higher.
* Sensitive to value set (or not set) via timeBeginPeriod.

The only reasonable case for using Sleep would be if you wanted to reduce CPU usage for e.g. mobile devices. Even then you'd be using Sleep (1); using it to control framerates is not the way to go.

Forcing vsync on is probably one common way to get a fixed framerate, but even then, different hardware will run at different refresh rates and you won't be able to have a consistent fixed framerate across different machines (this depends on what kind of hardware you're targetting of course).

At this point in time it's necessary to mention this article: Gaffer On Games - Fix Your Timestep!. That describes the steps you need to get a consistent timestep in your simulation.
> 33 votes

# Answer
Short answer: no, it is not.

To have a fixed frame rate you have to call a certain callback function that forces a specific frame rate. Obviously, if you don't now how long a single iteration in a loop will take you cannot set a fix sleep time.

GLUT provides **glutTimerFunc()**, which is, if you are programming in OpenGL, the right function you need. Take a look at **this example**, or **this** one.
> 16 votes

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


# Question
Title: How can I assign entity IDs in a robust way in a network game?
I'm working on an entity system for a networked game and I'm assigning each entity a unique 32-bit integer id that I can use to serialize references to entities and the entities themselves.

Currently I'm just incrementing a counter every time an entity is created. I guess the ids will eventually run out but I don't really expect to have 4 billion entities. Also this avoids the problem if entity #5 is destroyed and we get an id of 5. Is it meant to refer to the new #5 or the old deleted #5?

The problem is that I'm not sure how to handle/avoid collisions. Currently if a client receives an update for an entity with an id higher than it's current "free id" it just bumps it's free id up to past that. But that doesn't seem very robust.

I thought about maybe assigning ranges to each client so they can allocate entities without conflicting (say the top n bits are the player number) but I'm worried about what happens if ranges began to overlap over time.

Is there a better way of handling this? Should I even care about ids overflowing or going past the end of the allowed range? I could add code to detect these cases but what would it do if they happen other than crash.

Another option is to use something with a higher chance of being unique like a 128-bit GUID but that seems really heavyweight for a game that's trying to minimize network traffic. Also, realistically I would never need more entities at one time then would fit into a 32-bit or even 24 bit integer.

Thanks!

# Answer
> 13 votes
What I have done is make the server do *everything*. The client(s) can merely ask the server to do something but can't do anything themselves. In this case, the server will always be the one assigning IDs and problem solved.

I have not dealt with client-side prediction while waiting for the server to approve actions like: "Shoot a rocket" or "Make a solar station here". These actions will want to create entities, and entities have IDs. So far, I'm just sitting on my thumb waiting for the server, but I believe what needs to be done is create a temporary entity while you wait for server approval. When you receive server approval, the server will assign an ID and you can either update or overwrite the temporary object.

I also have not dealt with an ID overflow, but if the server is in full control and it detects an overflow, it could do whatever handling you deem necessary (restart at 0, pick from a free stack, crash, etc) and all of the clients won't even know or care. The clients will just accept the IDs handed out by the server.

# Answer
> 7 votes
When I did this for a commercial multiplayer game, I did exactly what you propose: use a 32-bit GUID integer, where the top eight bits are the player number, and the bottom twenty-four bits contain a locally unique number.

If/when the local number overflows (in my case, it would almost never happen; under normal usage, it would have taken four to five days of continuous playtime in a single network session to cause it to happen), the owner would send a "Resetting all my objects" message, and renumber all still-existing objects starting from zero ago. The message told all peers to discard objects they had received and to query for them again.

A more fancy approach would be a "Object with GUID 'n' is now Object with GUID 'm'" message for every existing object. But in my case, it was unlikely to ever actually happen, and I didn't think people would really mind remote objects vanishing from the world for half a second, after five days nonstop play in a single network session. ;)

# Answer
> 4 votes
If your clients can spawn their own entities, I'm guessing you have a peer-to-peer multiplayer game.

If that's the case, you probably don't have too many clients. Certainly not more than 256. And your entity id is guaranteed to fit into 24 bits (16000000+ entities is enough for everyone!). So, just make the highest byte of your id equal to client's id:

```
entityId = clientId<<24 + (maxEntityIn++)

```

or something.

And if I'm wrong and you have an authoritative server, just *never* create new entities on clients.

# Answer
> 1 votes
I'm using the 'most naive' method (just increment an integer for each new ID) in my persistent multiplayer game and it works fine because I don't let the client create new ID:s.

If you let the client decide (by using a sort of GUID technique explained), the client can also introduce various bugs by assigning an Old ID to a new item (that is just what I thought up on top of my head thinking like 5 seconds, there might be loads of other loopholes).

As usual, **to prevent cheating**, the server should do **ALL creation and validating**.

---
Tags: networking, entity-system
---


title: Farseer - Apply Impulse

text:
# Question
Title: Farseer - Apply Impulse
I'm new to Farseer and have a simple question. The demos I went through didn't seem to demonstrate what I want. I would like to apply an impulse (not force) to an object at a specific position on that object. How would I go about doing this in code? (I've created the objects already). I'll be using XNA and SL, but I guess the code for this method would be the same. thanks

# Answer
> 5 votes
I haven't used it, but a quick google search turned up this thread.

Here is a summary:

> When you apply a impulse or force using `ApplyLinearImpulse` or `ApplyForce` respectively, you can specify a point indicating where to apply the impulse or force on the target.
>
> To apply angular velocity, use `ApplyAngularImpulse`.
>
> The **moment of inertia** can be considered as an object's resistance to changes in its rotation; the greater the moment of inertia is, the harder it is to make it rotate.
>
> **Torque** is like a force that rotate an object on an axis, it can be thought of as a twist.
>
> Consider a game of pool / billiards using:
>
> `ApplyLinearImpulse(new Vector2(0f, 100f), new Vector2(0,0));`
>
> The first parameter is the direction and magnitude of the impulse. Since the shape is a circle, the second parameter will apply torque. Specifically, it is the local coordinates on the circle where you apply the impulse. Thus, the first parameter should contain the angle the cue has to the center of the circle. The second parameter should be the point of impact on the ball.The first parameter is both

It makes sense since all physics engines, in my experience, give you the ability to apply impulses and/or forces. So look for the ApplyLinearImpulse/ApplyAngularImpulse functions. They enable you to specify points where you apply the impulse.

# Answer
> 0 votes
You want to use the Body.ApplyLinearImpulse, or you can directly set the Body.LinearVelocity.

---
Tags: xna, c#, physics, silverlight, farseer-physics-engine
---


# Question
Title: Has Silverlight got a future in the online Game world?
We have spent several months planning, testing and developing a new game. We have been trialing a host of Platforms (Java Applet, Desktop Via XNA, Flash etc) and Silverlight was pretty much our prefered choice.

However, the more we get into the game the more problems we face, mainly down to the communication with a server. HTTP Polling is slow and in-efficent yet the socket functionality that is now available in SL4 is only really useful for a Intranet enviroment - Unless we are missing something.

Anyone have any opinions or experiance with this and the future of SL for Online Browser based games.

# Answer
> 5 votes
Future of online browser games is HTML5 in my opinion. It offers most what is needed for simple browser games. Low latency is needed in big standalone games, so that is not our case. Of course if you need it, you can always make with flash or silverlight plugin only for communication.

# Answer
> 1 votes
Distribution is always a roadblock with games and having a no-click, it just works experience is a big win. That makes it excellent for casual social games that are all the rage these days.

Flash is doing very well for games, but it lacks the real programming platform that silverlight has. And HTML5 with it's Javascript is just a nightmare for developing serious programs in, not to mention all the performance and compatibility problems.

According to http://riastats.com Silverlight is approaching 80% availability and growing and that's not going to go away easily.

---
Tags: architecture, silverlight
---


title: Pathfinder not acting correctly

text:
# Question
Title: Pathfinder not acting correctly
I've taken the A\* Algorithm from this example XNA Pathfinder Example so that it will be able to plot a path for a moving goal.

The issue I'm having is that it will go in the right general direction but it will keep going back and forth in a line. I've changed the method so that it calculates a new path every half a second, clear out the previous points from the list and adds the new points to and from what I have debugged I can't find any issue with the points being added to the queue, to be honest I don't have the foggiest idea what is going wrong :/

This is the field where the waypoints are being held for the character

```
private Queue<Vector2> waypoints = new Queue<Vector2>();

```

This section is in the update loop and deals with the plotting a new path and laying out the new one onto the list mentioned above.

```
            timer += gameTime.ElapsedGameTime;

            if (timer.Seconds >= 0.5)
            {
                timer = TimeSpan.Zero;
                pathFinder.NewPath(position);
            }

            if (pathFinder.SearchStatus == SearchStatus.PathFound)
            {
                waypoints.Clear();
                foreach (Point point in pathFinder.FinalPath())
                {
                    Waypoints.Enqueue(level.MapToWorld(point, true));
                }
                moving = true;
            }

```

This section is where the waypoints are either taken off or used to set the new position of the character.

```
                if (moving)
                {
                    // If we have any waypoints, the first one on the list is where
                    // we want to go
                    if (waypoints.Count >= 1)
                    {
                        destination = waypoints.Peek();
                    }

                    // If we’re at the destination and there is at least one waypoint in
                    // the list, get rid of the first one since we’re there now
                    if (AtDestination && waypoints.Count >= 1)
                    {
                        waypoints.Dequeue();
                    }
                    if (!AtDestination)
                    {
                        direction = -(position - destination);
                        //This scales the vector to 1, we'll use move Speed and elapsed Time
                        //to find the how far the tank moves
                        direction.Normalize();
                        position = position + (direction * MoveSpeed * elapsedTime);
                    }
                 }

```

# Answer
> 1 votes
*Note:* I happened upon this because "Community" bumped it and I see that my comment was helpful so I figured I'd post it as an answer.

---

Is it possible that when it recalculates the next best position, it thinks going "forth" is a good idea so it goes that way. Then, when it checks a half second later, it thinks "back" is a good idea and goes back that way since you're erasing the old path?

As John McDonald described in the comments, to fix this you could weight the points already on the path so that it's more likely to follow the previous path but isn't necessarily stuck to it.

# Answer
> 0 votes
Your character should check for a new destination only when it has reached the current destination. At this point if your target has changed you should recalc the path.

I'm afraid with the AtDestination calcs. I'd like to see how you determine it.

---
Tags: c#, ai
---


# Question
Title: OpenGL textures loaded with SDL_Image display with no alpha
I am making a game using OpenGL, with SDL\_Image employed to load the textures. When drawn on screen, there's no alpha -- in an exact square around the opaque contents of the texture, black is drawn; outside that space, white is drawn. Here is my OpenGL init code...

```
SDL_SetVideoMode(windowWidth, windowHeight, 16, SDL_HWSURFACE|SDL_GL_DOUBLEBUFFER|SDL_OPENGL);
glClearColor(0, 0, 0, 0);
glClearDepth(1.0f);
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, windowWidth, windowHeight, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();

```

...here is my image loading function...

```
SDL_Surface *loadImage (const char *filename, bool alpha = true) {
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* zoomedImage = NULL;
    SDL_Surface* optimizedImage = NULL;

    loadedImage = IMG_Load(filename);

    if (loadedImage != NULL) {
        zoomedImage = zoomSurface(loadedImage,windowScaleH/4,windowScaleH/4,SMOOTHING_ON);
        SDL_FreeSurface(loadedImage);

        if (alpha) optimizedImage = SDL_DisplayFormatAlpha(zoomedImage);
        else optimizedImage = SDL_DisplayFormat(zoomedImage);
        SDL_FreeSurface(zoomedImage);
    }

    return optimizedImage;
}

```

...here is the code I actually use to create the GL texture...

```
GLuint thisIsMyTexture;
glGenTextures(1, &thisIsMyTexture);
temporarySurface = loadImage("theimagetomytexture.png");
glBindTexture(GL_TEXTURE_2D,thisIsMyTexture);
glTexImage2D(GL_TEXTURE_2D, 0, 4, temporarySurface->w, temporarySurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, temporarySurface->pixels);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

```

...and the drawing code itself.

```
glBindTexture(GL_TEXTURE_2D,thisIsMyTexture);
glBegin( GL_QUADS );
    glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex3f(32.0f, 0.0f, 1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex3f(32.0f, 32.0f, 1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, 32.0f, 1.0f);
glEnd();

```

That's all the relevant information I can think of. Help would be appreciated! :D

# Answer
> 5 votes
You set the blend func, but you didn't enable blending. You'll need to call

```
glEnable(GL_BLEND);

```

to turn it on, then use glDisable to turn it off when you want to go back to regular opaque drawing.

---
Tags: c++, opengl, sdl
---


# Question
Title: Free Moddable 2d game with good community and tools
**Disclaimer:** I'm okay with making this a community wiki, as I see a lot of benefit in having a place to ask this question and get good answers from people who have experience.

I would like to mod a 2D game. Having never modded a 2D game before (unless you count Starcraft custom maps back in 199x), I am looking for a game/system that has:

* **A good community:** this means I can ask questions if I get stuck and expect a (decent) answer in roughly a day.
* **Solid tools:** I would ideally prefer clicking and creating content over diving into optimized C++ to make changes. The better the tools, the faster you move.
* **Scripting language:** Ideally, access to some scripting language *above and beyond the main tools* is an ideal middle-ground between high-level puritan tools (SC level editor) and low-level coding.
* **Free:** I'm looking for something I can try out free, or very cheap.

It also goes without mention that I want something current; I'm sure I can mod Super Mario Brothers, Link to the Past, etc. (SNES-era games) but that's pretty worthless to me.

And please don't say "Starcraft (1)" :)

# Answer
> 3 votes
The Battle for Wesnoth.

* Open source under GPL
* Scripting language which allows you to customize large aspects of the game
* Built-in map editor
* Dedicated server for hosting user created content
* Active community with people glad to help out
* No obscure file formats

# Answer
> 2 votes
Civilization 3 isn't free, but you can get it very cheap (Complete edition is under $5 online) and it still has a smallish but very active modding community, especially at CivFanatics. In fact we're right now celebrating the 10th anniversary of the game's release with various modding awards.

It's a 2D game with a very solid editor and lots of community made-tools for modding. No programming is required, but we're always digging into the file formats looking for ways to cheat the system and occasionally go off on a crusade to develop our own Civ clone. So there is coding to be done if you're interested. In general making a mod involves plugging information into the editor, some basic text configuration, and dropping files into place, plus whatever graphics creation you're interested in.

Best of all, we're a tight-knit and welcoming community with some of the most helpful and enthusiastic people you could ask for. There are hundreds of full mods, scenarios, graphics packs, and more covering everything from obscure historical settings to sci-fi to steampunk, and always something new. This is probably starting to come off like a commercial, but we always welcome newcomers. Just pop in and say WildWeazel sent you. :)

---
Tags: modding
---


title: Ogre3D: customize water demo

text:
# Question
Title: Ogre3D: customize water demo
On the water demo supplied with Ogre3D's SDK, controls are set to actually control the camera and environment, but not actually the ogre head that generates the disturbances. I tried digging into the SDK code but couldn't find the actual pieces of code that allow customization of the controls (keyboard input). Maybe that's coming from the SampleBrowser application?

I intend to use that demo to generate the same Pygame/OpenGL water ripple effect I seek here: Pygame water ripple effect with the added benefit of the 3D engine. This is also targetted at a multitouch library that tries to stay away from Flash in support of harder reverse-engineering of the output binaries.

Bottom line, my question is, where are the keyboard controls bound to the scene on Ogre's SDK Water Demo? I am just starting in C/C++.

# Answer
I think you need to override the keyPressed virtual method inherited by the Sample\_Water class (in Water.h) from SdkSample class.

Adding something like the following code in **Sample\_Water** class (Water.h) should help you

```
bool keyPressed( const OIS::KeyEvent &arg )
{
    //-- Don't process any more keys if dialog is up
    if (mTrayMgr->isDialogVisible()) return true;

    //-- keyPressed actions
    switch (arg.key)
    {
        case OIS::KC_UP:
        case OIS::KC_W:
            // up action
            break;

        case OIS::KC_DOWN:
        case OIS::KC_S:
            // down action
            break;

        case OIS::KC_LEFT:
        case OIS::KC_A:
            // left action
            break;

        case OIS::KC_RIGHT:
        case OIS::KC_D:
            // right action
            break;

        default:
            break;
    }

    // Call the keyPressed method of the inherited class SdkSample for others keys...
    return SdkSample::keyPressed( arg );
}

```

It will probably not be enough by itself, so if it doesn't works try to edit the SdkSample.h (Samples/Common folder) in order to remove/deactivate the following lines:

* `mCameraMan->injectKeyDown(evt);` at the end of the **keyPressed** method.
* `mCameraMan->injectKeyUp(arg);` at the end of the **keyReleased** method.

Those two lines propagate the key actions to the camera controller **mCameraMan**.

I didn't tried it, but it should be ok, or at least not that far from what you are looking for.
> 1 votes

# Answer
In my previous company (Touchscape), I did exactly this. The code for the water demo is part of the multitouch sdk sample. we used Ogre3D for graphics. but what specifically will help you is to understand multi-touch interaction with water and how water is simulated (plus the rendering if you are interested). You can download it for free from http://touchscape.org/v2/products/.
> 1 votes

---
Tags: c++, input, c, ogre, water
---


# Question
Title: What is a good algorithm for fractal-based procedural city layout?
**Background**

I run a minecraft server where I'm going to design a starter city of fairly large scale. I have a series of things, like rule signs and mob cages, I would like to put in buildings there. The city itself will be extremely large and spread out, preferably up to 1000 by 1000 blocks in size.

The buildings themselves will be have cube or rectangular footprints that are based on a certain base cube, like all multiples of 3 blocks. The streets and distance between the buildings will be preferably 5-11 blocks wide, depending on the importance of the street.

When I begin the plan for the city, I will know exactly how big I want the buildings to be and how many there will be.

**The Problem**

The problem is designing the layout for the city. Obviously with something of such a scale, and me coming from a programming background rather than an urban planner background, it's quite challenging to even begin to wrap my head around the problem.

The problem specifically is that I want the city to look as natural as possible. Of course this would be fairly easy to build on a simple grid pattern, but I want to avoid a grid, or anything that looks like a grid, as much as possible.

**The Question**

What algorithms might I be able to pursue to be able to help me design it using code? I was thinking that it would look most natural if I used fractals in some way, as minecraft uses fractals already in its terrain generation, and a city seems to grow in a fractal pattern naturally.

I think it's similar in some ways to a tetris playing algorithm, so if anybody has solutions that exist down that direction then it would help also. I'm picturing something where I'll be able to define the shapes that I want to use, and the software then iterates until it finds the most "optimal" solution for even distribution of buildings. **Does something already exist to help me solve this problem using python, preferably in a visual way using pygame?**

Naturally this also has interesting implications for city generation in general in game design, so I'm very excited to see what the best solution is.

*edit* To be clear, I'm just looking for the layout at this point as the buildings will be designed and built in game.

# Answer
> 20 votes
I've recently implemented an algorithm for a procedural city layout. It's still very much a work in progress, but seems promising to me. Take a look:

The algorithm used to create this layout is loosely based on L-Systems. I have a base `Element` class, that has a rectangle marking its place on map and a method `Grow`, which creates other `Elements` inside the rectangle, and/or spawns some objects on map. Then there are actual elements, inherited from this base class: `City`, `Street`, `Building` etc.

The generation starts with a number of "seed" objects (in my case, just a single `City` element randomly placed on the map). Then the system iterates over all elements, calling `Grow`, until all elements become inactive (`Grow` returns `false`), or some large number of iteration passes.

The city in the picture is built using only a few simple rules:

* `City` becomes a `Street` element splitting the area someplace.
* All `Street`s grow 0-3 side streets, further splitting the area.
* Also, `Street`s continuously try to fit a random-sized `Building` at the side.

The result is not terribly interesting, but not bad either. The system can be extended easily, and is simple enough to understand what's going on (-8

# Answer
> 8 votes
There's this GDC talk on procedural building generation from a couple of years ago. It's for creating individual buildings based on a set of templates, but not for creating whole cities (laying out streets and so forth). There isn't any free code to go with it, unfortunately. The system described in the talk is implemented in Unreal although I'm not clear whether it's in the free version of UDK or not. In any case, you could use some of the same ideas to build your own system.

Googling "procedural buildings" or "procedural city" will also give you quite a few other papers and articles on the topic.

# Answer
> 1 votes
I ran across a very good/detailed tutorial for creating procedural cities a while back. There is a video @ http://www.youtube.com/watch?v=-d2-PtK4F6Y The tutorial is on the author's blog: http://www.shamusyoung.com/twentysidedtale/?p=2940 Hope this helps amb

---
Tags: python, terrain-rendering, pygame, minecraft-modding, fractal
---


# Question
Title: How to make a background fill the screen on different-resolution phones?
I am developing my first Android OpenGL game. It's a 2D game and I would like the background to always fill the screen. I've managed to achieve this by stretching the texture to fit the size of the screen based on the aspect ratio, but the texture becomes quite pixelated when stretched.

What is the correct way to achieve this?

# Answer
You could choose from those options:

* Make the texture big enough to avoid stretching - scale down and crop only
* Include differently size versions of the background and select depending on screen resolution
* Make up your background from several smaller textures which you can place next to each other to fill the screen

If the background is static you could probably come up with a background size which works well across most devices because the general form factor is similar - unless you also target pads in which case you probably need two versions anyway. The third option mentioned is suitable if the background can be constructed from repeatable tiles, like a brick wall.
> 4 votes

# Answer
You have multiple problems to solve here. Your background has the same type of constrain as most textures and 2d assets. Your textures (and other assets) have to adapt to hardware with:

* different resolutions
* different aspect ratios
* different pixel densities
* and different performances

In this case you will have to make sure that your game looks good on the best hardware and is not a pile of crap on the rest you have to make compromises. First, you will have to ensure that you have assets for the best hardware and the worst (think pixel densities).

So make your assets for high resolution screens. Make sure you support the highest resolution available.

Also make sure your background has room for different aspect ratios. Therefore make it so you have room on the sides to expand on larger or higher screens.

Ensure that you use the information about pixel density screen size and other indicators to avoid displaying the wrong assets. The resolution is not necessarily the best way to decide which asset to use. For example text must be readable on high density screens and it should be smaller on low density large screens (tablets) so if you have some details to show in your background you might want to dissociate the details the user must see from the background and ensure users can see them on all devices (density/size/form factor).

And finally to accommodate most of the form-factors and use the lowest footprint you might want to divide the largest resources into tiles or crop them at runtime. To reduce processing time at initialization you might also want to add assets for lower density and lower quality screens.
> 1 votes

---
Tags: android, opengl-es, libgdx
---


title: Cloning a game and releasing the source

text:
# Question
Title: Cloning a game and releasing the source
I'm not really aware of the legal issues surrounding game clones.

I'm around halfway done of making a clone, but it's not just the same gaming concepts, I'm literally using the original game's files (which I do not intend to distribute in any way) in my clone. My original intention was to add features to the game (Firefly studios's first Stronghold) while still using the same art.

Is it ok to distribute the source of my clone?

# Answer
**Short Answer:**

Yes, as long as the codebase differs from the cloned project in its implementations. (i.e. You don't directly use code from the original game)

**Long(er) Answer:**

This entirely depends upon the legal copyrights set forth by the original creator.

By default, U.S. copyright law automatically grants copyright ownership to the original creator of the content.

The artwork, sounds (music and effects), narratives, and other such assets can **not** typically be re-used unless explicitly specified in a license chosen by the original author. An example of non-restrictive licenses for creative assets would be the Creative Commons licenses.

Code for the original game is often licensed separately from the art assets, but has the same set of rules. However, as long as your code base differs significantly in its implementation, it is not generally considered a "copy", and therefore is not in violation of copyright. Much software out there provides similar *features* of other software, but they differ in specific *implementation*.

As far as gameplay goes, there are plenty of clones around already, so it's not quite as restricted. Although you may make some people pretty furious if they're protective of their ideas. :-)

Extra reading on copyright laws: http://copyright.gov/

**Amendment**

Answered quite a while ago, but some additions are necessary.

*I'm not a lawyer*

...and...

@Josh1Billion is correct regarding patents. They're an entirely different beast. Unlike copyright, which pertains to your specific implementation of code, these will get you for using the general architecture of a concept (and not necessarily with code). @Josh1Billion's comment provides a good example.
> 9 votes

# Answer
Disclaimer: I'm not a lawyer.

Game play can't be copyrighted so you're definitely safe on that aspect.

> Is it ok to distribute the source of my clone?

You certainly are. You are the owner of the code.

**However, you cannot distribute the game's graphics.** Using them in the game is allowable because they are separate works, so long as the user provides the graphics from the original game. Also be careful not to modify the graphics as that may be violating their copyright.
> 5 votes

# Answer
Plenty of answers on copyright law already (summary: if you're not distributing the game resources, you're probably OK with respect to actual copyright law), but nobody has brought up EULAs yet. Regardless of whether copyright law would allow this or not, you also need to examine the EULA of the original game to determine whether it allows the game's assets to be reused by other games. I strongly suspect that it does not, unless you're dealing with an indie game whose developer(s) either deliberately chose to allow reuse or lack the legal experience to realize that they need to restrict it. Any mass-market game most likely prohibits it.

Standard disclaimer: I am not a lawyer and, even if I were, I'm not *your* lawyer. Consult an appropriate legal professional licensed to practice in your jurisdiction before distributing anything that you think could potentially get you sued. Your laws may vary. Do not taunt Happy Fun Ball.
> 1 votes

# Answer
I'm aware of a situation where Valve C&D'ed a Counterstrike clone some 10 years ago. The scenario was almost identical - the engine code and game code were either original or based on existing open source material, but it used the actual Counterstrike content. I believe that the basis for the C&D was that it removed the requirement to own a copy of Half Life.

Unfortunately links and sources for this are long lost, but the lesson remains. Step carefully, and make sure that you're on watertight grounds before doing anything.
> 1 votes

# Answer
Serously can't you come up with something more creative and original? But of course, FreeCiv and OpenTTD are very popular open source games based on originals.

You better not use any trademarks, graphics, sounds or other assets from the original game, even if you only publish it as open source.
> -1 votes

---
Tags: legal, open-source
---


# Question
Title: In a scrolling 2D game, should the objects move or should the camera move?
I'm new to game design and don't really know how things are done. I'm thinking of building an iOS game where a ship has to fly as high up as possible (at variable speeds), collecting power ups, et cetera, on the way.

What is the way to go here? Should the background and items scroll down from the top or should the ship really fly up moving the view with it?

# Answer
It's all relative. Really, you're always transforming your view relative to your fixed player position.

So, forgetting the screen for now, let's say you have these 3 steps (representing positions as they update on each game loop):

1. `playerWorldPosition = 50, 100; objectWorldPosition = 60, 200;`
2. `playerWorldPosition = 55, 110; objectWorldPosition = 60, 160;`
3. `playerWorldPosition = 60, 120; objectWorldPosition = 60, 120;`

(as x,y in each case)

As you can see, the player is flying up or jumping up and moving slightly to the right, while the object (could be a powerup) is falling straight down. The player catches the powerup. Now how do you draw this onscreen?

First, let's assume you want your player in the centre of the screen at all times. So the view locks to the player -- this is the simplest approach to visualise. The position of your player will then always be `screenCentre` (i.e. `screenWidth/2, screenHeight/2`). How then do you get the onscreen position of other objects in the world?

```
objectScreenPosition = (objectWorldPosition - playerWorldPosition) + screenCentre;

```

You can see that this formula works even for the actual player, since `(playerWorldPosition- playerWorldPosition) + screenCentre` is equal to `screenCentre`. So you can apply the same formula to each entity in your game, running through a list. You can use this simple approach to build on for other things (like camera lag, cases where you are in the corner of a level, etc.)
> 6 votes

---
Tags: ios, camera
---


# Question
Title: How much extra power is required for a stereoscopic 3D game?
If we use Cryengine 3 for game development and make the game 3D compatible. Because 3D sends out two pictures, will this mean that you need a computer with twice the "power"? So if you get 30 fps when playing normal you will need 60 fps for playing with 3D?

# Answer
In short, yes you will need to be outputting 60fps to have the effect of 30fps.
> 1 votes

# Answer
**You do not lose half your performance when turning on stereo 3d.** The games logic, AI, physics, and anything the CPU does still is only run once. Only the rendering is done twice, and that is efficient, because the card has everything in memory for what each second frame is going to be, so it doesn't use any additional bandwidth.

The only situation where this will be true is if you had a static 3d scene that was really complicated with the GPU doing everything and the CPU sitting idle. And even then I doubt it will be a 50% drop in performance

I have tested a lot of games with nvidia 3d stereo, and no game ever dropped near 50% performance.
> 16 votes

# Answer
Especially with CryEngine 3 this is not true. Yes, it halves the framerate, but turning on 3D does not cost you half your frames (or you need doubled hardware power). They use a reprojection cache and the available depth buffer to get the second image, thus the performance drop is 5-10% when turning on 3D. They call this "Screen Space Re-Projection Stereo".
> 9 votes

# Answer
I would say not negligible at all. It's both a hardware resource problem and a development challenge.

Most of the time you cannot split the framerate between the two eyes; if your game usually runs at 60fps, **you need to run at 120fps** for the same visual comfort.

However, a lot of things can be done only once per stereo pair: frustum culling -- at the cost of a slightly larger frustum (see *Setting up the 3D Cameras* in Optimization for Making Stereoscopic 3D Games on PlayStation®), occlusion culling, vertex and index array uploads, scene captures and renders to texture...

Parts of the scene may be rendered only once: for instance, a complex sky with clouds, stars, etc. will usually be at infinity, so the pixel shader cost is only needed once, and the second rendering can be a mere texture lookup into the first render target. Actually some stereo games use a method called reprojection that builds on this approach to make it viable for the whole scene: see this thread at beyond3d for pointers to this technique.

To cope with the required extra processing power, you can reduce the resolution. From my personal experience, it is far more acceptable to do so than to reduce the framerate. Do not try to disable anti-aliasing, though: as Sony engineers say in the above paper, *rendering to lower resolution buffers with AA looks better than high resolution buffers with no AA*.

Note that there are other approaches to stereovision in games that don't need a 3D TV, such as Trioviz. I cannot go into the details here, though (NDA issues).
> 1 votes

---
Tags: 3d, requirements
---


# Question
Title: Why am I seeing this assertion error during Collada DOM loading?
```
D3DXMATRIX ColladaFileLoader::processMatrix(daeElement* node)
{
D3DXMATRIX matWorld;

daeTArray<daeElementRef> nodeChildren = node->getChildren();

for (int i = 0; i < nodeChildren.getCount(); i++)
{
    string type = nodeChildren[i]->getAttribute("sid");

    if (type == "rotationX")
    {
        string data = nodeChildren[i]->getCharData();
        stringstream stm(data);

        stm >> matWorld.m[0][0];
        stm >> matWorld.m[0][1];
        stm >> matWorld.m[0][2];
        stm >> matWorld.m[0][3];
    }

    if (type == "rotationY")
    {
        string data = nodeChildren[i]->getCharData();
        stringstream stm(data);

        stm >> matWorld.m[1][0];
        stm >> matWorld.m[1][1];
        stm >> matWorld.m[1][2];
        stm >> matWorld.m[1][3];
    }

    if (type == "rotationZ")
    {
        string data = nodeChildren[i]->getCharData();
        stringstream stm(data);

        stm >> matWorld.m[2][0];
        stm >> matWorld.m[2][1];
        stm >> matWorld.m[2][2];
        stm >> matWorld.m[2][3];
    }

    if (type == "location")
    {
        string data = nodeChildren[i]->getCharData();
        stringstream stm(data);

        stm >> matWorld.m[3][0];
        stm >> matWorld.m[3][1];
        stm >> matWorld.m[3][2];
        matWorld.m[3][3] = 1;
    }

}

return matWorld;
}

```

This function will run run debug assertion failed after it ends the first pass through the loop. The loop will run correctly, it will enter the last if statement and set all values correctly. However when the pass is done and before it starts the next pass it will debug assertion failed on me. I think it is trying to destroy the string type variable but something is breaking when it does tries to delete it. I don't know what the problem is. It seems to do this on other parts of my program that get strings from the file and place in std::string. I fixed those by just removing those entirely but this one cannot be removed it needs to exist.

Don't know if this has anything to do with it, but I'm using visual studio 11 dev preview, and using compiler vs100 (vs10's compiler) settings.

dbgheap.c Line:1322

Expression: \_CrtISValidHeapPointer(pUserData)

also when i use debugger none of my vars from this function show up after the error.

# Answer
> 0 votes
Ok found the problem after nearly a week of beating my head against the wall, for others who may have run into this issue in the future I'll post the solution.

The version of colladaDOM I used was compiled with /mDd library (multi-threaded debug dll) while my project was using /mtd (multi threaded debug static) settings. After changing my project to /MDd all my problems vanished.

Another possible solution would be to rebuild DOM with /mtd to match the project settings.

# Answer
> 3 votes
You can use assert(\_CrtCheckMemory()); to check the whole heap for corruption.

By adding lots of those tests you should be able to narrow down the line of code that causes the corruption.

# Answer
> 2 votes
Is `node` null (or otherwise invalid)?

Are you sure `getCharData` doesn't modify the object it's called on?

---
Tags: c++, directx, collada
---


# Question
Title: Is there any reason for doing back face culling in software?
I, a newbie, have been doing back face culling in javascript for my WebGL app because I didn't know gl.cullFace() existed. Is there any reason to use software-based culling instead of just passing all faces to GPU and let it do the culling?

# Answer
No. The GPU has dedicated hardware for the purpose, so it will be far faster, especially compared to Javascript. (I wouldn't do *anything* that iterates over individual verts / faces in JS!)
> 4 votes

# Answer
Sometimes, but it depends on your use case and data structures. You can still get a win if your data is set up so that you can cull *groups* of faces per test, and if doing so doesn't require you to break a batch. Otherwise just let the GPU do it (especially if you have VBOs available).
> 1 votes

---
Tags: javascript, webgl, culling
---


# Question
Title: Hemicube algorithm d3d9 or d3d11, float valued colors
The hemicube algorithm renders the scene to 5 sides of a half-cube, from the perspective of each polygon.

Assume you place the hemicube around **me** and render to the 5 sides. The idea is, we can see exactly **how much** of each other polygon in the scene **I** see, and so determine the amount of light I receive from those respective polygons.

The way I did this before was using DWORD colors, and assign a **different** (integer) color to each poly, called its id. This allows for 16M colors using DWORDS. It worked fine with the fixed function pipeline, because I was able to choose `D3DDECLTYPE_D3DCOLOR` in the vertex declaration, render to texture, and tally up the polygon coverage counts.

Now that I've switched over to shaders, I can't seem to make DWORD colors work anymore. All that works is 3x 32-bit `float`-type colors (I am using Cg, so `float4`'s.)

Is there a way to force D3D9 or D3D11 to use integer colors in a shader, and if not, how can I guarantee the colors I choose as "ids" for the respective polygons **will end up being distinct colors in the texture I render to**?

# Answer
You *can* simply take your integer vertex colors and divide by 255.0 them prior to sending them to the shader. I was wary of doing this when I posted the question, because I was afraid that floating point error would cause this to be inaccurate.

But as you can see from Photoshop / point sampling the circle below, the colors smoothly show transitions from `0->255`, without skipping a value.

Because the end result is *you have to* export a `float4` for color from your pixel shader anyway.

So again the 2 options are:

* Convert your RGB\_DWORD( 0-\>255,0-\>255,0-\>255 ) colors to rgb\_float( 0.0-\>1.0, 0.0-\>1.0, 0.0-\>1.0 ) colors prior to sending colors to the shader (**recommended**, since it eliminates a needless DWORD-\>float4 conversion in the vertex shader)
* Use `DXGI_FORMAT_R32_UINT` in your vertex layout for the color component (`DXGI_FORMAT_R8G8B8A8_UINT` doesn't work for some reason), send RGB\_DWORD( 0-\>255,0-\>255,0-\>255 ) colors, and bitshift/divide by 255.0 in the shader code (arguably less efficient than simply passing rgb\_float( 0.0-\>1.0, 0.0-\>1.0, 0.0-\>1.0 ) colors to the shader.
> 1 votes

---
Tags: directx9, directx11, color
---


# Question
Title: How should I represent a tile in OpenGL-es
Let me start with I am currently learning OpenGl-es using Android.

I have been having the hardest time trying to design a simple and logical way of making tiles (2d flat polygons). The tutorials tell me to just keep the polygon as a `float` array of veticies:

```
private float vertices[] = {
      -1.0f,  1.0f, 0.0f,  // 0, Top Left
      -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
       1.0f, -1.0f, 0.0f,  // 2, Bottom Right
       1.0f,  1.0f, 0.0f,  // 3, Top Right
};

```

That in and of itself is easy enough. I modified the code to suit my desired polygon and it drew fantastic. Now I wanted to draw more tiles and have a scrolling feature (look around the world). But I'm not sure what's the best way to do so.

Should I leave every tile with a `float` array of indices and when it comes time to move the tile, directly modify the`float` values?

Is it a good idea to create an `ArrayOfPoints` (`Point` just being a container for exactly 3 `float` values) class to hold all of the points and then have methods that cycle through the points and change their values in a more safe fashion?

Does anyone have any tutorials on simple tile based map building so I can look at how they do their maps?

(Note: these questions are based on what I have read on animating. That is to say that you change the coordinates of the object in relation to the origin and leave the camera at `0,0,0`. If it is more proper to just leave objects where they are, I guess my question loses value.)

# Answer
> 5 votes
I've tried lots of variations myself; the recipe I've found best is:

Put any tile textures into a texture atlas. In this way, you can draw your whole map in a single draw-op because they are all using the same texture.

Mipmap the texture atlas, natuarally. For a large number of tiles you may spill over one texture 'page' in the atlas and it turns into multiple pages. If you keep that in mind, it won't be a big deal to retrofit support for pages if you need it.

If your tiles are a nice fixed size then just use the smallest non-float data-type for the vertex components for the points that you can e.g. bytes if the map is less than 256x256. Texture coordinates also help not being float.

Now build your map VBO using interleaved texture coordinates and vertices for a `GL_TRIANGLE_STRIP` array. I imagine that each vertex data starting on a nice 4-byte boundary is a good idea, but I have no empirical data to support that. Its just a hunch. Avoid element index arrays.

It depends on the camera position and such, but I found the best performance is to regenerate the tile array to draw all visible tiles each time the camera moves! This has, in my code, won more framerate than approaches of keeping all vertices GPU-side in blocks or such and issuing multiple calls to draw all the bits that are visible.

So what I normally do is, if the camera moves, compute the visible tiles and make an array of them, that I draw. Then if the next frame the camera hasn't moved, at that point promote it to be the vbo for subsequent frames until the camera moves again.

You could use `gl_VertexID` in the vertex shader to avoid needing x and z components for your vertices at all. (I haven't tried that, I've had problems with `gl_VertexID` on integrated Intel drivers on the desktop, stopping my cross-platform efforts in that direction. But on Android (Imagination/NVidia/Mali) devices it likely works well and is well worth the effort.)

If your map has varying heights then you have to have three components (or, with `gl_VertexID`, one) for the vertices but otherwise you don't need that y and then you don't need to track the normals per vertex either.

I rather hope someone weighs in with sounder advice to try something I haven't thought of myself, so as to improve my engine too ;)

# Answer
> 1 votes
Check out the open source Replica Island source code for a 2d grid to get ya started.

Do not modify vertices at runtime, build the entire level into a VBO when loading and draw using offsets based on camera position,

---
Tags: tiles, opengl-es, maps
---


# Question
Title: How to properly handle collision in a component-based game?
Trying to wrap my head around the ways to properly handle collision in a game designed around components.

I see many examples have some sort of `PhysicsComponent` that gets added to the entity's list of components but the actual implementation is confusing me.

For this to work, the `PhysicsComponent` would need access to the world around it. This doesn't make intuitive sense to me. Shouldn't a component be unaware of not only its container (the entity), but its container's container (the world)?

To me, it sounds like the level or scene should maintain a list of these entities and every game update, loop through the entities to determine which collide.

My question is firstly, whether or not this is good design, and secondly, how to determine which entities can collide. I suppose solid entities could implement an empty IRigidBody interface so the level could determine which entities in the list support collision. But is this breaking the component design?

Instead, should they contain an empty RigidBody component? This may actually be better because it may not always be empty and this approach is more future-proof. The only problem with this is the complexity. The scene would have to loop through not only every entity, but also every entity's components to determine if it had this RigidBody component.

Thirdly, when they do collide both entities should be informed somehow and I am unsure on how to accomplish this either.

Let's say that both entities contained a HealthComponent and when they collided both their healths would be decreased by some arbitrary value, 5. I suppose it would be the scene's responsibility to handle this when it detects a collision between two entities?

But then is the scene responsible for too much? I could see this possibly getting out of hand and becoming unwieldy when the scene is responsible for many things entities should not (?) have access to.

**Edit:** Question updated with more details.

# Answer
Honestly, from a component design side of things, my components do not know about each other unless they have to (And that is very rare). Even then I usually prefer the components talk to some managing system of said components instead of the components directly. (The scripting interface looks like its object to object, but its not in the actual engine, hehe).

To that end I would side with what you first said and go with physics components that exist wherever objects need to be tested for their collision. Now clearly these objects may have to inform other components of themselves upon collision resolution but, as mentioned, this is where I prefer the event itself just to go out to the objects through another interface (either to a manager or through an event messaging system if you have one of those for instance).

I think you are on the right track and just need more of a 'Yes, that sounds right' So.. Yes, that sounds right.

Hope this helps!
> 5 votes

# Answer
Normally game engines use a 3rd party library to detect collisions between entities. In that scenario one creates or register those entities that have the PhysicsComponent into the "physics" world. And whenever it detects a collision between two entities (A and B), it would normally call a callback to entity A informing that it has collided against entity B and the same for entity B, informing that it has collided against entity A.

For 2D, a well known free physics library is Box2D. Also it's worth to take a look at Chipmunk. For 3D, Bullet is free (probably the best free one you can find). Havok and PhysX are famous for being used in lots of triple A Games.
> 3 votes

# Answer
The problem you're having is in seeing that collision detection (which is the only reason you would need one physics-component-bearing entity to reference another such) is done at a higher level, usually either by your game loop directly, or by a helper function/class that does this. My answer to someone a few weeks ago talks about entity removal on similar grounds, and bearing in mind that if a collision causes one of your entities to be destroyed, that same answer, in its given context, is going to be very relevant to you, since a "higher power" is still going to have to manage cleanup of the bodies... so to speak.

Doing any of this between entities alone, is not generally viable. There is nearly always a proxy for such things, in a solid architecture, whether that's via direct management as with collision detection, or event dispatches as in eg. a player messaging system where a client-side messaging manager listens for messages dispatched from players, and sends them off to the server to be rebroadcast to everyone.
> 2 votes

# Answer
I'm facing exactly the same problem as you in a project now. The way I decided to tackle it is by having a "ColliderComponent" which holds the body from the physics engine. The bodys are defined externally (shape definitions which are loaded at runtime) and then added to the physics-world *and* to the game-entities they belong to.

I'm using Box2D where you can attach a "collision-listener" that will get notified by the collision. Since I add a pointer to my "ColliderComponent" to the bodys user-data, I can get my two ColliderComponents that were part of the collision.

So the thing that happens when a collision occurs is the following: The ColliderComponents which were part of the collision will send a message out to their owner-object (the game-entity) which in turn will broadcast that message to all its components.

Every component can then react to that message, so your "health-component" could remove 5 points from health, etc.
> 2 votes

# Answer
Create a collision system that knows the collision "world". Then in your collision component tell the collision system to cast a ray from point A to B and respond if it collided or not.

Good luck. I find the collision system to be one of the more tedious parts of the game engine.
> 0 votes

---
Tags: xna, c#, game-design, architecture, component-based
---


# Question
Title: How do I move a 2D top-down racing camera smoothly and show what's ahead of the player?
I'm trying to make a camera that follows a race car. Right now, I'm smoothing the camera movement out by moving the camera's position a fixed percentage lerp'ed from the camera's position to the car's position.

However, this makes the car appear closer to the edge of the window when it's moving toward that edge. I want the camera to appear some distance ahead of the car. This makes more sense to me--The player wants to see what's ahead.

I tried using the velocity of the car, and putting it through a logistic growth function so that it would throw out an offset for the camera position. This made close-quarters collisions too jerky. This was especially true when the car obtains a boost that applies a greater force over some time.

Then, I tried applying the logistic function only when the speed was greater than a certain amount. This didn't work. When the car obtained a boost, the camera would offset itself. This made it jerky in close-quarters collisions. When the car was moving in open space without boosts, the camera wouldn't move toward the velocity.

---

How do I implement a camera that follows a race car so that the window shows more of what's in front of the car without introducing jerkiness? My game is viewed from the top-down.

# Answer
What I'd try would be:

1. Multiply the car's velocity by some constant *Δt* and add it to its location. (That is, calculate what the car's location would be *Δt* time steps in the future if its velocity remained constant.) Call this the *target point*.
2. Have the camera chase the target point in some natural manner. A simple way to do this would be to let the camera position be the exponentially weighted moving average of the target point position; this is essentially what you're doing by repeatedly interpolating between the current camera position and the target. You could also try adding some inertia to the camera movement, so that it takes a while to change direction.
> 4 votes

# Answer
What you're looking for is a chase camera, but you might have to do some tweaks to go from the usual 3D chase camera to the 2D chase camera.

I've got a small snippet here for you that I used a long time ago. It's in C# for XNA, but I think you will get the general idea.

It's a bit long, sorry for that.

```
    public class ChaseCamera
{
    #region Chased object properties (set externally each frame, or via Update)

    /// <summary>
    /// Position of object being chased.
    /// </summary>
    public Vector3 ChasePosition
    {
        get { return chasePosition; }
        set { chasePosition = value; }
    }
    private Vector3 chasePosition;

    /// <summary>
    /// Direction the chased object is facing.
    /// </summary>
    public Vector3 ChaseDirection
    {
        get { return chaseDirection; }
        set { chaseDirection = value; }
    }
    private Vector3 chaseDirection;

    /// <summary>
    /// Chased object's Up vector.
    /// </summary>
    public Vector3 Up
    {
        get { return up; }
        set { up = value; }
    }
    private Vector3 up = Vector3.Up;

    #endregion

    #region Desired camera positioning (set when creating camera or changing view)

    /// <summary>
    /// Desired camera position in the chased object's coordinate system.
    /// </summary>
    public Vector3 DesiredPositionOffset
    {
        get { return desiredPositionOffset; }
        set { desiredPositionOffset = value; }
    }
    private Vector3 desiredPositionOffset = new Vector3(0, 6.0f, 15.0f);

    /// <summary>
    /// Desired camera position in world space.
    /// </summary>
    public Vector3 DesiredPosition
    {
        get
        {
            // Ensure correct value even if update has not been called this frame
            UpdateWorldPositions();

            return desiredPosition;
        }
    }
    private Vector3 desiredPosition;

    /// <summary>
    /// Look at point in the chased object's coordinate system.
    /// </summary>
    public Vector3 LookAtOffset
    {
        get { return lookAtOffset; }
        set { lookAtOffset = value; }
    }
    private Vector3 lookAtOffset = new Vector3(0, 2.8f, 0);

    /// <summary>
    /// Look at point in world space.
    /// </summary>
    public Vector3 LookAt
    {
        get
        {
            // Ensure correct value even if update has not been called this frame
            UpdateWorldPositions();

            return lookAt;
        }
    }
    private Vector3 lookAt;

    #endregion

    #region Camera physics (typically set when creating camera)

    /// <summary>
    /// Physics coefficient which controls the influence of the camera's position
    /// over the spring force. The stiffer the spring, the closer it will stay to
    /// the chased object.
    /// </summary>
    public float Stiffness
    {
        get { return stiffness; }
        set { stiffness = value; }
    }
    private float stiffness;

    /// <summary>
    /// Physics coefficient which approximates internal friction of the spring.
    /// Sufficient damping will prevent the spring from oscillating infinitely.
    /// </summary>
    public float Damping
    {
        get { return damping; }
        set { damping = value; }
    }
    private float damping;

    /// <summary>
    /// Mass of the camera body. Heaver objects require stiffer springs with less
    /// damping to move at the same rate as lighter objects.
    /// </summary>
    public float Mass
    {
        get { return mass; }
        set { mass = value; }
    }
    private float mass;

    #endregion

    #region Current camera properties (updated by camera physics)

    /// <summary>
    /// Position of camera in world space.
    /// </summary>
    public Vector3 Position
    {
        get { return position; }
    }
    private Vector3 position;

    /// <summary>
    /// Velocity of camera.
    /// </summary>
    public Vector3 Velocity
    {
        get { return velocity; }
    }
    private Vector3 velocity;

    #endregion

    public ChaseCamera(float aspectRatio) : this(aspectRatio, 7500, 750, 50){}

    public ChaseCamera(float aspectRatio, float stiffness, float damping, float mass)
    {
        this.aspectRatio = aspectRatio;
        this.stiffness = stiffness;
        this.damping = damping;
        this.mass = mass;
    }

    #region Helper Methods

    /// <summary>
    /// Rebuilds object space values in world space. Invoke before publicly
    /// returning or privately accessing world space values.
    /// </summary>
    private void UpdateWorldPositions()
    {
        // Construct a matrix to transform from object space to worldspace
        Matrix transform = Matrix.Identity;
        transform.Forward = ChaseDirection;
        transform.Up = Up;
        transform.Right = Vector3.Cross(Up, ChaseDirection);

        // Calculate desired camera properties in world space
        desiredPosition = ChasePosition +
            Vector3.TransformNormal(DesiredPositionOffset, transform);
        lookAt = ChasePosition +
            Vector3.TransformNormal(LookAtOffset, transform);
    }

    /// <summary>
    /// Forces camera to be at desired position and to stop moving. The is useful
    /// when the chased object is first created or after it has been teleported.
    /// Failing to call this after a large change to the chased object's position
    /// will result in the camera quickly flying across the world.
    /// </summary>
    public void Reset()
    {
        UpdateWorldPositions();

        // Stop motion
        velocity = Vector3.Zero;

        // Force desired position
        position = desiredPosition;
    }
    #endregion

    /// <summary>
    /// Animates the camera from its current position towards the desired offset
    /// behind the chased object. The camera's animation is controlled by a simple
    /// physical spring attached to the camera and anchored to the desired position.
    /// </summary>
    public void Update(GameTime gameTime, Vector3 chasePosition, Vector3 chaseDirection, Vector3 chaseUp)
    {
        this.chasePosition = chasePosition;
        this.chaseDirection = chaseDirection;
        this.Up = up;

        UpdateWorldPositions();

        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        // Calculate spring force
        Vector3 stretch = position - desiredPosition;
        Vector3 force = -stiffness * stretch - damping * velocity;

        // Apply acceleration
        Vector3 acceleration = force / mass;
        velocity += acceleration * elapsed;

        // Apply velocity
        position += velocity * elapsed;
    }
}

```

Edit: oh btw, I didn't come up with this myself, I think the above code was a modified version of the chase camera on creators.xna.com, but I'm not 100% sure anymore.
> 0 votes

# Answer
Use the velocity and just multiply it with some value(you need to test witch one is good for you) and use that as an offset but then make sure that you don't position the screen to far off.

You could also use the function you had in the beginning but use the position+velocity\*x as the cameras goal where x should be some value you choose depending on what looks good.

And the third way I would try is again to use the velocity\*x as an offset and then have a camera offset that lerps towards the one the velocity offset.
> 0 votes

---
Tags: 2d, physics, camera, racing
---


# Question
Title: Need a reference to an [unusual?] RTS setting
Imagine an RTS game where so-called *basic* units play the main role throughout a whole game session.

In my game basic units are actually programmable by a player (like in Colobot/Ceebot), that's why it is so important to keep them significant from the first to the last second of each session.

**Problem**

I found out that end-game of a typical session is quite boring, no impression of... say, development of a game since middle-game. Don't know how to describe this feeling correctly.

I'm looking for reference to other games where such problem of end-game was resolved.

Thanks in advance.

**UPDATE**

Some more background:

The game is about splitting tasks which are best solved by chip and by brain. Player does not have to micromanage, he or she writes algorithms (in advance) instead. Players are to make strategic decisions and give high-level orders. I.e. if you have better combat algorithms for a group of bots == you're better at micromanagement. The same goes for engineering units in home front.

The typical border between middle-game and end-game is when all "free" resource sources are conquered by one of players, resources are being drilled, roads a constructed and factories produce bots at full speed (everything is automated by players in a way they want). Frontier line is more or less clear and stable.

From this point there is no choice of rush/produce/defend, you are to collect forces, invent tricky maneuvers and attack.

**At this moment** there is only one work for players brains: tricky tactics. It is something human brain excels at (in comparison to algorithms).

Balance is so that frontal attacks are very costly (good defense can destroy a great amount of units if an attack is frontal). Therefore attacking from multiple directions, "red herring" и fast relocation *along* the front line become very important (exactly like at wars in the middle of XXth century, e.g. WWII).

Again, this is where the human brain is much better than any program, so it makes no sense \[for players\] to write algorithms for such tasks.

**My concerns** is that in end-game it becomes just like a hexagon game with a very limited amount of units since all underlying tasks are "encapsulated" by algorithms.

Supreme Commander resolves such problem by introducing experimentals, Populous does it with spells (I remind, Populous: The Beginning has only five basic units).

Again, thanks in avance :-)

# Answer
The reason why it's boring is because at one point in the game, it will become a repetitive scenario where two armies clash, and then there's a race to rebuild the armies, clash again, repeat until one dies.

The way good RTS counter this is by introducing hard to get technology at the end of the game where if you have it, you have such a great advantage that your enemy will lose unless they see it coming. This can be units, upgrades, abilities, etc. which are powerful and ensure that the game ends fairly soon.

An example of this is the Zerg brood lords. It takes a long time to get, but once they are out, the game won't last long. They're so costly that if the Zerg loses them he's dead, and it's so powerful that if the enemy has no immediate counter, he's dead instead.

Not sure how to invent something for your basic units, but maybe some spells or awesome weapons can be researched for them?

The main points are:

1. Gradually increasing unit costs = more valuable army = increasingly important battles.
2. Gradually increasing unit damage = shorter battles relative to amount of units = spend money faster in the end game = game ends faster.
> 9 votes

# Answer
Adding upgrades to the units and buildings is one way to add a rich variety of dynamics to the game.

However, take a look at this game. It's different, yes, but it would fall in the same problem of build, clash, the end. But it doesn't fall, and it doesn't have any kind of upgrades. The strategy aspect here is in advancing your territory **during the game** with walls, traps, doors that open for your team only etc. You do have a few moments of just building, but from there you have to do all at the same time. All this building is playing pretty much the same role as upgrades in usual RTS.

My suggestion is to make changing the units' algorithms occasionally a key point in winning! For example, making workers stop gathering resources to fix a building or accompany an army to set a new outpost, closer to the battlefield, in order to advance on the enemy. If it's easier to just make more units than to reassign them, then make them more expensive.

Remember, even the smallest change in the game's parameters can change the game dynamics dramatically.
> 3 votes

---
Tags: game-design
---


# Question
Title: My isometric game looks flat; how can I improve this?
Being bored I decided to make my game isometric by applying a simple filter effect.

```
    g.scale(1f, 0.5f);
    g.rotate(400, c.getHeight() / 2, 45);

```

It works great, but now everything appears... flat.

# Answer
Your technique could work, to some limited extent, but you don't want to apply the same transformations for the objects that are supposed to be standing. For these, make a simple "skew", as illustrated here: The second rotation might not be the inverse of the first as it depends on the scale factor. The important thing is that the vertical lines are actually vertical, i.e, aligned with the y axis (look at the dashed lines). Also, you might want to scale back a little. This is more important for doors than characters.

But still, as the commenters said, if this project goes beyond boredom avoid this method and begin making isometric art with a regular grid :)
> 8 votes

# Answer
It looks fine. Since an isometric projection is essentially a rotation followed by an orthographic projection there should be no foreshortening - and hence a limited perception of depth etc.

So my take is, *keep going*.

* Put some taller buildings in. Obstruction should help create a sense of depth.
* Create shadows if you can (if you use actual 3d models to generate an isometric view out of them, you can use shadow volumes to get accurate shadows with little effort from artists (but a lot from programmers)
* Add moving characters (again characters going behind visual obstructions will help)
* **Reduce the view the person has / zoom in a bit**. This will help it look less *map like* (ala simcity 2000)

and more "overhead view" like (ala starcraft)

The more you zoom out, the more the brain starts to expect perspective / the player thinks he's looking at a map
> 6 votes

# Answer
You need differences in shadow heights, to make the isometry more believable. Higher objects cast longer shadows. Try it, you'll see an improvement right away.

All your edges which face upwards have very little definition. In real life, we recognize edges on a glance by a change in contrast between one surface and another. Your contrast (change in tone) is very slight between your top grey and bottom grey. Add to that the very fine brick detail -- I would emphasise that a lot. Also not that gaps between bricks aren't just a dark shade, more often than not you'll see highlighted edges contrasted directly adjacent to deep shadow. You have zero highlights -- of course things will look flat. Check this out as an example:

(from here) And yes, I know it's perspectival and not orthogonal. The point is the lighting.
> 2 votes

---
Tags: isometric
---


title: Triangulating a bunch of squares

text:
# Question
Title: Triangulating a bunch of squares
I have a set of squares (pixels coming in from an image) that I want to triangulate.

I narrowed my choices down to 2 possible routes:

* A, breaking the squares into lager rectangles, or
* B, generating a set of vertices and triangulating them.

B is better, as it generates fewer vertices.

I'm dumb, and couldn't find a way to implement route A. But oddly enough, I found it simpler go with route B and generate the vertices. I'm checking neighbor pixels and using a simple lookup table to determine where to place a vertex. That is done and easy.

But with that collection of vertices, I'm stuck. It might contain holes, or be composed of multiple islands of polygons. So from there, I don't know where to go. Any ideas?

Also, if it makes any difference, I'm using these triangulated images to build up a voxel mesh, marching through the voxel data in 6 directions and looking at it in cross sections. At the end, I'll piece them all back together. It's kind of similar to the "trixels" used in Fez.

# Answer
If you can generate a list of edges around the outside, counterclockwise, instead of a list of vertices (for holes, a list of edges clockwise around the hole), then you should be able to triangulate it using the answers from this question: https://stackoverflow.com/questions/406301/polygon-triangulation-with-holes
> 0 votes

---
Tags: 3d, voxels
---


# Question
Title: How do you simulate frictionless movement?
I am building a game in which I want to simulate smooth movement of an object upon pressing a key or any other event. Could someone advice me to get that feel of gliding of an object, sliding on a frictionless surface. How could I have that?

# Answer
> 4 votes
Well, simulating a frictionless object is really just like simulating an object with friction, except you leave out the friction.

Seriously, the only sensible interpretation I can make of your question is that you've either forgotten Newtonian mechanics since high school, or that you're still in school and haven't studied it yet. In either case, here's a quick refresher on motion under constant acceleration:

Let *x(t)* be the position and *v(t)* the velocity of the object at time *t*. Then the position and velocity of the object after a time step *Δt* under constant acceleration *a* are:

* *v(t + Δt) = v(t) + (a × Δt)*
* *x(t + Δt) = x(t) + (v(t) × Δt) + (a × Δt² / 2)*

You can express these quantities in any units you like, as long as they're consistent. For video games, a common choice is to measure time in update steps (which might typically occur, say, 20 to 60 times per second for smooth-looking motion), position in pixels, velocity in pixels per time step and acceleration in pixels per time step squared. This simplifies the formulas, since, in particular, *Δt = 1*.

Also, if the time step (and/or the acceleration per time step) is small enough, the *(a × Δt² / 2)* term will be so much smaller than *(v(t) × Δt)* that it can be left out of the second formula without anyone really noticing. A lot of games do that, since it makes the formulas even simpler.

And, before you ask, usually the positions, velocities and accelerations will indeed be two- or three-dimensional vectors. This is not a problem — you just apply the formulas to each component of the vectors separately. It's also perfectly okay for any or all of these quantities to be negative.

# Answer
> 10 votes
The idea is that friction is actually an *explicitly* added step, additional logic. So the answer is, "You don't". You just build for the basics -- forces, velocity, mass, collision response and then you will be able to play with frictionless bodies. The simulation is the theoretical "perfect" environment.

# Answer
> 4 votes
Fundamentally frictionless movement is just playing with inertia. In whatever your movement code is, don't stop the player immediately when they release their button/analog stick. Instead you want to *very* slowly reduce their velocity to zero. Or if you wanted to be truly frictionless you never reduce their velocity.

# Answer
> 1 votes
Your basic game code should be organized like this:

```
IntializeGameState
while (GameIsRunnnig)
begin
  handleInput
  updateGameState
  DrawNextframe
end

```

For the simualation of a moving object, you should store your objects current position, movement speed and direction.

When initialzing, set the movement speed to 0.

During handleInput, check if any inputs from the user have been made and if so, modify the movement speed and direction of the controlled object accordingly.

Then, during UpdateGamestate, add the current movement vector to the current postion.

Now, redraw your object at the new Position.

This are the basic steps to do. You will need some kind of timer to make your animation smooth by making each step of the animation take an equal amount of time.

# Answer
> 1 votes
Not sure if this is helpful, but this is the code I used in my asteroids game:

```
if (input.isKeyDown(Input.KEY_W))
    {

        dx += Math.sin(Math.toRadians(image.getRotation())) * delta * 0.01;
        dy += -Math.cos(Math.toRadians(image.getRotation())) * delta * 0.01;

    }

    x += dx;
    y += dy;

    dx *= 0.98;
    dy *= 0.98;

```

Increasing the values of the \*= on dx and dy decreases the "friction" the player receives. The clever part is that there isn't any top speed, the ship just slows it's accelration down until it's not noticeable. Of course, in a true frictionless environment you could accelerate infinitely, reaching ludicrous high speeds. In that case, you would simply remove this:

```
   dx *= 0.98;
   dy *= 0.98;

```

# Answer
> 0 votes
Store the current velocity of an object with each object. Each frame use that velocity along with the frame time to calculate how far to move it.

Acceleration (thrusters) and deceleration (brakes, or friction) simply modify the velocity to a new value.

---
Tags: movement
---


title: Evolutionary Procedural Generation

text:
# Question
Title: Evolutionary Procedural Generation
**Are there any examples of companies or papers using evolutionary algorithms (EA) or genetic programming (GP) in procedural generation of content for games? Does this exist in the industry?**

This is about the only place I have really found it:
http://pcg.wikidot.com/pcg-algorithm:automatic-game-design

I've checked these questions as well and I know my way around PCG:
What is "procedural generation" and how is it done?
Procedural Generation of Infinite Level
2d Procedural universe generation

# Answer
> 5 votes
In general, most games opt for the much easier and predictable method of scripting their AI, or use noise for terrain/content generation. Most games tend to avoid evolutionary/genetic programming because, frankly, it's often too expensive to implement, or too random for most players to understand.

Outside of a few mostly experimental and niche games like Darwin's Pond or the Creatures series, I really can't think of any games that use EA or GP. Black and White used the Belief-Desire-Intention model as the basis for it's Creature AI, but the game got a lot of negative response due to the Creature's behavior seeming to be random. It's likely that the second Black and White game used scripting for the creature AI.

# Answer
> 4 votes
thedaian's answer is a good one since it provides examples.

I think the main problem seen with these approaches is one of control. Once you start dealing with heuristics, which these ultimately rely on, it becomes very hard to evolve a system that does what you want it to do. Quite frankly, it's a matter of project cost and risk. If you have a game idea that you can implement without using these, or using some more direct procedural approach, the better for you.

The problem with even the most elementary AI approaches (take A\* pathfinding for example) is that they take some time to first understand, and considerably more time to master. I think this keeps us closer to simpler, more static approaches. It doesn't feed innovation, but a quick return on investment is a hard thing to ignore.

Having said that, I'm definitely on the side of "If Nobody Tries It We'll Never Know". A GP project has been brewing in my mind for some time.

(Another approach you might want to look into is neural networks, it's often grouped with these as being a machine process that mimics natural forms of improvement -- in this case learning -- through elimination.)

# Answer
> 1 votes
This type of programming is generally used, if available, to give AI Agents their 'personalities'. Using the different values that are avaialble you can try and breed the 'best' stats for an agent to survive and thrive within the world but it is not something actively done during game play for one very good reason. Its a game.

You can have the computer learn to constantly defeat the player, but who is going to play a game that you can only lose at? The point is to present a challenge, and using genetic algorithms you can try and find combinations of AI to play in certain ways to represent easy, medium and hard settings. Or, for example in RTS games, play styles like a the rusher or the turtler.

These algorithms are more applied to developers looking to tune their game as opposed to being actively used in the games after launch. If you read the Game Programming Gem books you can find articles in them that give examples of how these are used for RTS games to help balance AI out.

---
Tags: algorithm, procedural-generation
---