# Question
Title: Effective methods to continuously update movement in a tower defense game?
We are four guys making a Tower Defense game as a project in first grade on a university. The game is going to be really simple!

* Three different towers
* Three different monsters
* One map (maybe add some more if we have time)

The game has to be object oriented.

The class structure is as following

* **Game** \- Drawing of graphic, etc.
* **Level** \- Every level is an object of this class. Each level has a finite number of wave-objects (in a list)
* **Wave** \- Contains a list of monster-objects.
* **Monster** \- This is a superclass. We make subclasses for the different type of monsters
* **Tower** \- Superclass to the towers. There are subclasses for each type of tower.

We are thinking about how to solve the problem that many objects have to do stuff, at the same time, e.g. move one pixel in one direction.

What we came up with is the idea of implementing av class Timer, to control when objects do things. I am not sure this is the best way to do it. Could someone give some good ideas about how to solve the continious update case?

# Answer
Game Coding Complete describes an Update loop well. It's simply a while loop running in your main class that does the following (more or less):

```
while( game.isRunning )
{
  GetInput();
  Update( dt );
  Render();
}

```

You pass in a dt (delta time) depending on whether you want your game running at a fixed or variable frame rate. For a fixed frame rate, this isn't necessary.

Now to do what you want to do quite easily is use the notion of 2D vectors, where one vector represents the position of the monster (x,y) and a velocity vector that represents the direction the monster is travelling in (in units/sec).

So to create monsters with different speeds, all you need to do is change the velocity vector to whatever you want and let the monster.update() function handle it for you.

For example:

```
Monster monster = new Monster();
monster.position = new Vector2( 0, 0 );
monster.velocity = new Vector2( 1, 0 );   // Every frame I want the monster
                                          // to move 1 unit to the right

```

And your update method would look like this (for a fixed frame rate of 60 frames per second):

```
monster.position += monster.velocity * ( 1.0f / 60.0f ); // The ( 1.0f / 60.0f ) would
                                                         // be dt if it was passed into the Update() method

```

This is known as the Euler update method and it's a very easy and straightforward method of implementing the equations of motion.

Hope this helps.
> 12 votes

# Answer
Basically, I use an **update loop** and not an event based system.

To update monsters, you could iterate a list of monsters and update them in the update loop with, let´s say, `monster.update()`

If a monster has to walk it has to update its position. So, in the update method I calculate the new position on base of the elapsed time, which is stored in a seperate 'timer' class.

That should be all the 'walking' stuff ;)
> 3 votes

# Answer
I suppose it will fill it's purpose well for a uni project, but in a real game i would have a concrete monster class, and instead of subclassing for types, have the different types of monsters described in data files. Speed, health points, resistances to different types of damage and sprites can be perfectly described in files, it will make it easier for you to add new types of monsters to your game, and you won't have to compile each time you'd want to do so.

Anyway, about the movement. Give all your "movable" objects different a speed variable. Each frame in your game logic you loop through all those movable objects and do something like

```
object.x += Math.cos(object.angle) * object.speed * timeSinceLastIteration;
object.y += Math.sin(object.angle) * object.speed * timeSinceLastIteration;

```

This applies to monsters, missiles from towers, etc...
> 2 votes

---
Tags: software-engineering, java, timer, tower-defense
---


title: Xcode on Hackintosh (under VM)

text:
# Question
Title: Xcode on Hackintosh (under VM)
Should I be pessimistic about the iOS game development under VM? A virtualized environment will run on AMD (4-core 2.8 ghz Phenom II)/ATI/Linux/VMware host.

Not talking about any 3D engines, may Xcode's emulator bring at least 15-20 FPS for a simple 2D game like, errr, `Airport Mania`?

# Answer
> 1 votes
I ran some cocos2d examples on a weaker PC than the one in the question, running snow leopard through VMWare with sufficient FPS, but that's all i can say. I also remember running some stuff that was more GPU intensive than this on a Mac Mini, and than running it on the device. It actually ran faster on an iPhone 3GS, i assume it's because the emulator doesn't utilize the GPU, but i might be wrong about that one.

Hope that was any help to you :)

Other stuff to consider:

In anyway, you're really going to want to test your game on a device frequently no matter what, and not just because of performance related issues, but compatibility as well. When working with OpenGL ES (and not only!) often stuff that runs on the simulator won't run on the device and the other way around.

And another thing to keep in mind might be the most important one, assuming you're talking about *some* kind of an "action" game - getting your gameplay to feel right and intuitive depends alot on it being tested with real input, as opposed to simulating clicks with the mouse.

# Answer
> 3 votes
Check out here and here for some related questions ans their corresponding answers.

The biggest pain I'm told is setting up the virtual environment for leopard / snow leopard to run and facilitate. Honestly, I'd recommend just getting a Mac mini or the full MBP and devving on that. You'll save yourself a lot of pain and headache setting up the VM environment.

But it's entirely possible, baring that you can get a 10.5 / 10.6 OS install. XCode won't really run on anything else. And I definitely wouldn't use the machine to build a distribution version for submission.

Also, there's nothing to be pessimistic about! Learning a new language on a new environment is exciting (about as exciting as learnin' Zerg if you're a 'Toss player on SC2 as I tell one of my dev's). I'm simply recommending the best tool for the job ("best" being qualified as the one that'll get you started the quickest without any headache and fit in your monetary expenditures - time vs money that is.)

# Answer
> 1 votes
You can find an already installed 10.6.2 VMware image. Upgrade it to 10.6.7 (the latest version) using the Mac OS X updater, **install the VMware Tools** (otherwise is slow as hell) and after XCode 4.

I've done this, it runs a little sluggish (Win 7 x64, **Intel** quad core, 8 GB RAM, 3 GB for VM) but it's usable. Don't know if it will work on AMD.

OpenGL ES 2.0 also works, but very slowly. Yes, shaders work. From my understanding it's software emulated. Some Mac OS X native OpenGL applications I've tested cause a kernel panic.

If you tell me how I can install Airport Mania in the emulator (I'm new to this) I can test the FPS for you, assuming it's displayed somewhere (please tell where).

---
Tags: 2d, ios, ipad, virtual-machines
---


# Question
Title: Looking for a GUI library for OpenGL, or tips for my own (MetroUI)
I am making an OpenGL graphics accelerated FPS, and I need to find a library to handle GUI correctly. My current GUI handler just wont do!

Yes, as in the title says, the UI of the game is Metro (ZuneHD, WP7, etc).

So the UI contains little to NO images, just fonts.

# Answer
> 3 votes
One of the best GUI libraries that renders in OpenGL is CEGUI: http://www.cegui.org.uk/wiki/index.php/Main\_Page

It isn't specifically designed to emulate WP7 but I would imagine you can accomplish that with customized graphics within CEGUI.

---
Tags: opengl, gui
---


title: texture distortion at a distance

text:
# Question
Title: texture distortion at a distance
I produce a strip of quads with texture coordinates to represent a path.

My texture is tiled along these quads.

When the quad is drawn very small (on my integrated Intel chip) it draws distorted.

How can I avoid this?

# Answer
Try anisotropic filtering. In opengl it should be enabled like this:

```
GLfloat largest_supported_anisotropy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, largest_supported_anisotropy);

```
> 5 votes

# Answer
As notabene said, anisotropic filtering will help, especially if you combine it with mip-mapping.

Why this works is explained perfectly in this wikipedia article: http://en.wikipedia.org/wiki/Anisotropic\_filtering

"In layman's terms, anisotropic filtering retains the "sharpness" of a texture normally lost by MIP map texture's attempts to avoid aliasing. Anisotropic filtering can therefore be said to maintain crisp texture detail at all viewing orientations while providing fast anti-aliased texture filtering."

On how todo mipmapping in OpenGL see: http://www.swiftless.com/tutorials/opengl/mipmap\_generation.html
> 5 votes

---
Tags: opengl, textures
---


# Question
Title: From camera coordinates to world coordinates
I want to calculate world coordinates from camera coordinates. However, I seem to have problems with my understandings of how matrices in HLSL work.

From world to camera is clear:

```
cameraPosition = mul(mul(worldPosition, view), projection);

```

Logic would now say that for the reverse, I could just use something like

```
worldPosition = mul(mul(cameraPosition, invProjection), invView);

```

However, when I check if it is correct with

```
cameraPosition = mul(mul(mul(mul(cameraPosition, invProjection),
                                   invView), view), projection);

```

I don't get the same point back anymore.

The inverses should be fine as `view` * `invView` produces the identity matrix etc.

What is my misunderstanding here? Even the simpler case does not work:

```
void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = inPosition;
}

```

produces the triangle I want. However, using

```
void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = mul(mul(inPosition, view), invView);
}

```

already produces no visible triangle. Same with

```
void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = mul(inPosition, mul(view, invView));
}

```

Pixel shader is just a shader which returns a constant color.

**UPDATE**

I have 3D camera-space coordinates WITH z-buffer value, like (0, 0, zNear) for the point directly in the center of the screen. I want to know what world coordinates correspond to this by doing the whole view-transform backwards.

# Answer
Okay, stupid me. I accidently forwarded a wrong inverse matrix to the shader :-)
> 1 votes

# Answer
I think that the problem is that you don't normalize screen space point after worldViewProj multiplication. This should do the job:

```
cameraPositionScreenSpace = mul(mul(worldPosition, view), projection);
cameraPositionScreenSpace /= cameraPositionScreenSpace .w;

```
> 1 votes

# Answer
Since you mentioned the projection matrix in your code, I'm going to assume that you mean screen coordinates rather than camera coordinates.

While it's true that mathematically `matrix * invMatrix` results in an identity matrix, if one of these operations discards information (eg, turning 3D world coordinates into 2D screen coordinates), then you can't get that information back. You can *cast rays* out from the camera at a particular vector to try and hit something, but you can't reproduce the original coordinate.

Need proof?

```
(X * 0) / 0 == ? // Solve as an algorithm, not as algebra :)

```
> 0 votes

# Answer
I'm not entirely sure what you're trying to do but I'll give it my best shot =). First of all you are on the right track - to undo a transformation you must multiply the result by its inverse. So in a vertex shader you are taking an object/local space point and transforming it into homogeneous clip space for the pixel shader:

```
float4 outPos = mul(float4(inPos.xyz, 1), matWorldViewProj);

```

This can also be represented as:

```
float4 outPos = mul(mul(mul(float4(inPos.xyz, 1), matWorld), matView), matProj);

```

Thus to get the world space position of a point after a transformation into homogeneous clip space you must multiply the point by the inverse of the view and projection matrices:

```
float4 worldPos = mul(outPos, matInvViewProj);

```

Which can also be represented as:

```
float4 worldPos = mul(mul(outPos, matInvProj), matInvView);

```

So if you already have a vertex that's in view/eye (camera?) space, which means the origin of the coordinate system for that point is the current location of the view/eye:

```
float4 outPos = mul(float4(inPos.xyz, 1), matWorldView);

```

To get back the world position of that point you multiply it by the inverse of the view matrix:

```
float4 worldPos = mul(outPos, matInvView);

```
> 0 votes

---
Tags: xna, shaders, camera, hlsl, matrix
---


# Question
Title: Overview/showcase of shader techniques/uses for games
I am looking for resources that can provide me with a better understanding of what kind of things shaders are used for in games, what they can do, and maybe even more importantly, what they cannot. I understand how the graphics pipeline works and all that, and I have made some very basic shaders in GLSL (mostly just to replace the fixed-function pipeline functionality), but I don't yet fully understand which things are only possible with custom shaders, which things can be done more efficiently, etc. I have been able to find some examples of certain techniques, most notably lighting, but I am looking for a more higher-level overview of their usage.

Links to and explanations of certain interesting techniques, as opposed to an overview, are also appreciated (but less than an overview ;) ), preferrably in GLSL or pseudocode.

# Answer
> 5 votes
You can find something here and also here. And if you want, you can find a lot of information in GPU Gems 1, 2, 3 and Shaders for Game Programming and Artists (I think, it's not about GLSL, but about HSL and shaders and games generally).

---
Tags: graphics, shaders, glsl, effects
---


# Question
Title: What is Java missing that might make it difficult to develop fully-featured 2D games?
Without using any external libraries, does Java, including all officially supported APIs give you enough to develop fully-featured 2D games? The reason I ask is that I hear a lot of "bad-mouthing" about Java and game development, but I'm wondering if that is only in regard to intensive 3D games. Also reading up on some Java games there often appears to be external graphics or sound libraries involved that simply have a Java port. This makes me think it isn't possible.

# Answer
> 8 votes
In 2011 any language with bindings to OpenGL is more than capable of a "2D game" in the style of Nintendo from the 1990s or so, when running on a desktop PC made in this millennium.

For TV game consoles, the only language available for development across all platforms is C++, so that's what people use for the most complex 3D games and the simplest 2D games. Java would work for simpler games, but C++ is the compromise we live with to avoid the cost of supporting more than one language.

For handheld devices (and to a lesser extent TV game consoles) performance is critical often enough that the overhead imposed by Java et al. can't be tolerated for games with medium or high complexity.

Android phones do run games in Java, but there is a clear trend recently toward "native" C++ games on Android, not primarily for performance, but because ironically Java isn't as "platform-independent" as C++. All non-Android platforms use some kind of C/OpenGL, and porting a game among them is fairly cheap. Porting from any of them to Android/Java is relatively expensive.

# Answer
> 5 votes
In theory, nothing.

In practice, mainly the fact that not a lot of people have done it already. If you're looking for code samples or documentation you'll more likely find code written in C or C++ instead of Java.

# Answer
> 4 votes
There's nothing missing from Java that is required to make a fully featured 2d game. There are definitely games written in Java that don't use external libraries, or, use them sparingly. Most of the complaints people tend to make about Java are either the slowness of games vs C or C++ (valid, but computer speed is fast enough to make the point moot), or personal frustrations with Java (almost everyone has a language they like to hate...). Java also has a reputation for being a 'business' programming language.

The only issues that might come up from using Java is hardware acceleration. If Java's native graphics rendering is not hardware accelerated, then you'd be risking performance problems. External libraries can often solve this problem.

# Answer
> 1 votes
Of course you can. But some boring stuff you have to do at your own.

I read a book, 'killer game programming in java', and there was no external library, just Java2D. I also developed an arcade game with it...

Java can be an engine IMO, but you should really prefer another engine, which is built on top of this stuff and OpenGL.

I am currently using libGDX for my android game and I am happy so far. With it you can develop simultaneously for android and PC ;)

# Answer
> 0 votes
For modern high quality 2D graphics you'd often use 3D rendering, meaning you'd need a 3rd part 3D library for most languages anyway.

I think mostly for game development Java just doesn't do a lot that C++ or C# doesn't do, and it might be a little slower than C#.

A lot of people seem to have very strong opinions on what is good for what and what isn't, it's often a sign that they simply don't know what they are talking about.

---
Tags: architecture, java
---


# Question
Title: Why do pixel shaders not let us read directly from the framebuffer or the depth buffer?
Letting me sample the framebuffer or the depthbuffer in the pixel shader would be an extremely useful feature. Even just being able to know the depth or the color of whatever is behind the current pixel would be useful.

Why does both OpenGL and DirectX not let me do this? I was expecting there to be some kind of hardware limitation, but alpha blending uses the color in the framebuffer for blending calculations, and the Z-test samples the depth buffer at the current location. Why not just expose these values to us directly? Can I hope to see this in the future?

# Answer
> 21 votes
It *is* a hardware limitation. The fragment shader is part of the programmable pipeline, but the final color blend with the target buffer(s) isn't programmable in widely-available/commodity hardware at this point (it's configurable via blend states, but you can't write arbitrary code that replaces the GPUs built-in blend operations).

The reason the hardware isn't built for this probably has to do with the fact that GPU are massively parallel; they process many fragments at a time. Some of those fragments may ultimately interact with each other within the destination buffers, but due to the asynchronous nature of fragment processing it isn't possible to know how until after the fragment has been processed and final color has been emitted... which won't always happen deterministically.

Just because pixel A will be behind pixel B in the final frame does not mean that pixel A will always complete fragment processing and be written to the destination before B, especially across multiple frames of rendering. So the value read from the destination buffer during pixel B's processing will not always be pixel A's -- sometimes it will be the clear values.

So I suspect that disallowing direct destination buffer reads during the fragment stage has far more to do with stopping the shader programmer from shooting himself in the foot by getting potentially nondeterministic results from that read than from any actual technical limitation in making the blend stage fully-programmable. By keeping the read operations tightly controlled (the depth test, for example), the GPU ensures that the operations done with the read value make some kind of sense.

That said, there may also be a cost/benefit thing going on. Making that aspect of the GPU pipeline programmable would complicate the chip design somewhat, and the need/demand for destination buffer reads has been relatively low in comparison to other features.

# Answer
> 5 votes
The pixel shader can't read from the color and depth buffers because:

Pixels A and B may be shaded at exactly the same moment in hardware, though B ultimately renders on top of ("after") pixel A.

If you made it so the hardware is guaranteed to shade A before B, then parts of the hardware would sit around doing nothing while A is shaded, and then parts of the hardware would sit around doing nothing while B is shaded.

In the worst case imaginable, all the pixels you shade render on top of each other, and the thousands upon thousands of GPU threads - all except one - sit idle. This one thread patiently shades pixel A, then B, then C...

# Answer
> 4 votes
While annoying, it allows hardware manufacturers the flexibility to optimise the rendering process in numerous and transparent ways.

For example, the PowerVR hardware (certainly used to back in the day, not used one for a long time) wait until the entire scene to be rendered was submitted, then perform automatic depth sorting using the painters algorithm and not actually need to generate a depth buffer. It would divide the screen up into tiles and render each one in turn.

---
Tags: opengl, 3d, directx, shaders
---


# Question
Title: Creating a database with special items, like in Diablo
I am in the middle of creating a browser game. I need to add 'special items' like in *Diablo*, but simpler. Item names are fixed (e.g. 'ring of power'), so only their attributes change.

In my game there are different towns. Each town may trade a different set of items with randomized characteristics. For instance, in Town A a 'ring of power' will have better attributes than the same item in Town B (and, thus, it will cost more).

My question is how to construct the database to handle this.

After constructing the database I will create a small script that will assign a different subset of items in each town. Each item with random attributes and a price that reflects its value.

I can make the script; what I need help on is creating the database.

# Answer
> 1 votes
You can think about items as a pair of names with description and attributes (including the price)
You can do a table 'items': ID, descid, attrid

You can make the two others like this:
'item\_descriptions': ID, name, desc
'item\_attributes':

ID, strength, intellect, agility, price

This would split up the description part and the, let's say, value part of the item.

Edit:
I would, as said in a comment, now recommend the following structure:

'items': ID, descid, strength, intellect, agility, price
'item\_descriptions': ID, name, desc

The item is in a table with the attributes, because every attribute set should be unique.

The description is in another table, because you wanted to have the same description for different attributes.

And one thing in addition:
I strongly recommend to use memcached! With it you don't have to query the database all the time. Memory is much faster.

# Answer
> 2 votes
The problem here is you are trying to key the item on the name "Ring of Power" and thus running into a conflict. Instead, use a hidden key for the item, multiple items display as "Ring of Power".

# Answer
> 0 votes
If it's multi player it's going to have to run on the server, you can only export the interface to the browser without allowing people to cheat.

If your generation script is fast enough and made as an ID-\>item formula you may simply generate the item whenever needed. You could also store the entire list as a literal in a code file. I'd suggest using one of these methods for the client code.

For the server code, if you are using a stateless language like PHP a literal list may be a lot of strain on the server as it will have to be loaded once for each request, so in that case you would have to use on-the-fly generation, or if that is not practical either a database.

Your typical relational database is very slow, that is why I'd as far as conveniently possible would try to avoid using it.

# Answer
> 0 votes
Items is the most high loaded part of game database. So you should create the most effective design to handle it. In your case it will be table like this one

```
   create table item (
    id long primary key
    item_name string
    ....
    item_state_type int
    item_state_data varbinary
)
id - it is the key for unique item entity.
item_name - "ring of power"
item_state_type - type of your item. Ordinary or random generated.
item_state_data - serialized custom data. In your case it is an array of custom attributes.

```

The pair of tables item and item\_attributes with keys-and-values isn't a good idea. Operation with one row (in my design) will be converted in operation with ~10 rows in different tables (in key-value design)

For example

```
id, item_name,      item_state_type, item_state_data, owner_town, owner_id
1, "ring of power" , 0, null,    1,    null - vendor ordinary item
2, "ring of power" , 1, binary1, 1,    null - vendor customized item
3, "ring of power" , 1, binary2, 2,    null - vendor customized item in another town
4, "ring of power" , 1, binary1, null, 10 - user1 item
4, "ring of power" , 1, binary2, null, 10 - user2 item

```

Actually I prefer to store item templates in XML files, but this approach is OK too for simple data model.

item\_state\_data - serialized custom data. In your case it is an array of custom attributes. The main idea - you should somehow translate your custom data into one byte array. Or into string.

Example in java + pseudocode.

```
public void saveItem(ItemDataSet item) {
       ...
      PreparedStatement stmt = getConnection().prepareStatement("insert into item ... ");
      ItemSerializer serializer = SerializerFactory.createItemSerializer();
      byte[] item_state_data = serializer.serialize(item);
      stmt.setBytes(1, avatarInfo);
      ...
}

public ItemSerializer {
  public byte[] serialize(ItemDataSet item) {
    DataOutput out = new DataOutputStream(...);
    out.writeInt(item.customParams().length);
    for (long value : item.customParams()) {
      out.writeLong(value);
    }
    ...
    return out.toByteArray();
  }

  public ItemDataSet item deserialize(byte[] bytes) {
    DataInputStream in = new DataInputStream(bytes);
    ItemDataSet item = new ItemDataSet();
        int arrayLength = in.readInt();
    for(int i=0;i<arrayLength; i++ ) {
      item.addParam( in.readLong);
    }
    ...
    return item;
  }
}

```

---
Tags: architecture, databases
---


# Question
Title: What exactly causes a surface to overlap another?
I cannot really figure out what causes one surface to overlap another. In a 3D engine I'm creating, my technique is failing in edge cases.

My method is sorting the surfaces to be painted from the furthest to the closest. To determine the closeness, I'm comparing the average z values. Sometimes, however, an overlapping surface has a **higher** average z value than the one it is overlapping. Thus, the surface further away is painted over the closer one - resulting in bizarre rendering like this:

What one is meant to see is the purple front surface of the cube only, whilst the red side surface is painted over the purple one. The average z value of the purple surface is higher, and therefore 'further away'. So I'm having some doubt as to whether this technique is correct.

What I also tried is getting the distance from the camera (i.e. origin) to the surface, but then I needed a point. I chose the middle of each surface but also this doesn't always seem to work because not all surfaces are as large as each other.

Therefore, what is a reliable way to determine the order of closeness of surfaces towards the origin?

# Answer
You seem to be trying to implement the Painters Algorithm. I'm guessing you're trying to write a rasteriser from scratch as a learning exercise, as most modern 3D hardware uses what Bart has mentioned (the Z/Depth buffer). For the painters algorithm to work in all cases, you'd need to be prepared to subdivide the surfaces as they're rendered to solve possible scenarios (such as the overlapping polygon problem shown on the Wikipedia page).

By rendering from furthest to closest you're also spending time rendering pixels which will possibly later be occluded by other polygons, which when you start putting textures and complex shaders on the polygons wastes precious cycles. This is the reason modern hardware would prefer you to render from front to back, using the depth buffer to determine if the pixel to be rendered is further away than the one on the screen (and can therefore be discarded).

Even with most modern acceleration hardware you'll still need to sort and render from back to front any semi-transparent polygons, rendering this only once all the opaque polygons have been rendered.
> 11 votes

# Answer
What you have is a visibility problem. One solution is using a z-buffer.
> 3 votes

# Answer
Sorting the faces according to their average z-value doesn't work, because the average z-value provides no information on the actual z-value of the vertices or even surface pixels.

Example (warning, ASCII art ahead):

```
          /
         /
cam     /
-->    /
      /
     /--       <--B
    /
    ^--A

```

There are two faces A and B. From the camera's perspective A is in front of B. Yet the average z-value of B is smaller. Let's look at the other z-values:

* the minimum z-value of A is 4
* the maximum z-value of A is 11
* therefore the average z-value of A is 7.5
* the minimum z-value of B is 6
* the maximum z-value of B is 8
* therefore the average z-value of B is 7

You could try to sort them by their minimal z-values but there cases where that won't work too. There is just no way to sort arbitrary faces correctly using just one z-value.

In Newell's algorithm http://en.wikipedia.org/wiki/Newell's\_algorithm what you do is sort the min/max-ranges of the z-values. If the ranges of two faces do not overlap you can know for sure which one is in front. If they do, sometimes you absolutely have to split the faces. Sometimes it will suffice to raytrace every vertex for occlusion or some other technique.
> 2 votes

# Answer
It's good that you are learning about rendering by doing. Kudos. In this instance, there is no "painters algorithm" solution, instead of trying to fix it by sorting, on the PS1 we used to just try to keep polygons around the same size when they were next to each other (which you are doing as far as I can tell), and **backface cull** (which you're not doing)

**Backface culling** is checking the surface normal in screen space for it's direction (just get the sign of the depth element from the screen space transformed normal (in our case it was the z of the normal), or the cross product of two vectors of the triangle i.e. cross( v1-v0, v2-v0 ))

If you implement backface culling, you also reduce the amount of rasterising you're doing.. double win.
> 1 votes

---
Tags: 3d, rendering
---


# Question
Title: Which protocol should I use for a networked Pong clone?
I have to design a Pong game for Android. There are multiple mobiles and a game server. Application is installed in mobile. Mobile 1 (M1) can see the movement of bat and ball of mobile 2 (M2) an vice-versa.

Suppose if M1 hits the ball, all the movements of the ball and bat of M1 can be seen on M2's screen and vice-versa. Now I want to know which protocol I should use and why?

Edited: how can a server take the initiative to send a message? What are the different methods to do this: i.e. "push", other,...

# Answer
I'd recommend the User Datagram Protocol -- have each client send user inputs to your server, have your server calculate the results of all inputs and respond that result to each client.

```
**Pseudo Code for UDP Client/Server**
// public
int sendSequenceID= 0;
int receiveSequenceID = 0;

// send data
var data = new { id = sendSequenceID, DeltaX = changeInXCoord, DeltaY = changeinYCoord };
udpSocket.Send(data);
sendSequenceID++;

//receive data
var receivedData = null;
udpSocket.Receive(receivedData);
if(receivedData.id > receivedSequenceID) // ignore packets out of order
{
    receivedSequenceID = receivedData.id;
    // process received data
}

```
> 5 votes

# Answer
TCP and UDP would be the two choices for this and you will want to go with UDP.

As for the Why part of your question, TCP is a 'guaranteed delivery' system, but its slow. For video games and where up to date information is a priority over ensuring the data gets there, UDP fits the bill. You will generally want to have an incremented Packet ID so you can ignore outdated packets to take care of them showing up in the wrong order, but this will suit your needs.

EDIT: A bit more information on the incremented packet IDs. With TCP, you are not only guaranteed that the data is sent, but that it is sent in the right order. It will not try to send a new piece of data along the same TCP connection until the current one has been confirmed to be sent.

UDP does not guarantee delivery order. So if you have an incrementing ID in the packet data and you keep track of that value, you will know that incoming data with an ID lower than what you have already processed is old data. In that way you can safely ignore that packet and just wait for the next one.

Hope this helps.
> 4 votes

---
Tags: networking, server, mobile
---


# Question
Title: Should we go for our Vector2Int/Vector3Int implementation or just use built-in float based vectors?
So in one of our projects we're using Vector2/Vector3's a lot but we do only use integer/byte values mostly. So up to the point we've implemented our Vector2Int, Vector3Int, Vector2Byte and so structures;

```
public struct Vector2Int
    {
        public int X;
        public int Z;

        public Vector2Int(int x, int z)
        {
            this.X = x;
            this.Z = z;
        }

        public override bool Equals(object obj)
        {
            if (obj is Vector2Int) return this.Equals((Vector2Int)obj);
            else return false;
        }

        public bool Equals(Vector2Int other)
        {
            return ((this.X == other.X) && (this.Z == other.Z));
        }

        public static bool operator ==(Vector2Int value1, Vector2Int value2)
        {
            return ((value1.X == value2.X) && (value1.Z == value2.Z));
        }

        public static bool operator !=(Vector2Int value1, Vector2Int value2)
        {
            if (value1.X == value2.X) return value1.Z != value2.Z;
            return true;
        }

        public override int GetHashCode()
        {
            return (this.X.GetHashCode() + this.Z.GetHashCode());
        }

        public override string ToString()
        {
            return string.Format("{{X:{0} Z:{1}}}", this.X, this.Z);
        }
    }

```

But i don't know if we're on right track? Should we just better use XNA's float based vectors because of performance-wise concerns?

On the other hand a Vector2Byte or Vector3Bytes consumes less space which is also quite important when you use so much vectors.

I've searched for tests / information on XNA's built-in vector performance but couldn't find a bit even on it.

I'm happy to hear your experiences.

# Answer
This comes down to use the appropriate data structure for the task.

If you are using this for internal functionality key to your game and such then your own data types that hold the values in a format you are using them would make sense.

If however this is dealing with rendering and graphics hardware then you will want to use floats as that is what the hardware is generally built to use and accelerated for.

Hope this helps.
> 5 votes

# Answer
I would be more concerned that there are operations (divisions, square roots, et cetera) done on or to components of vectors that would cause integer-based representations to become inaccurate. Beyond that I'm not sure it's worth switching implementations mid-project.

There are minor potential performance nitpicks here and there, but none of them are likely to be serious. I would suggest using the XNA versions simply for uniformity and scalability, but probably only if you're about to start a new project. I don't see any compelling reasons to change everything up mid-stream.
> 2 votes

# Answer
I use integer vectors when my concern is in "which bucket" something occupies or "from which bucket onward" something occupies, and float vectors when my concern is "where in space" something "is."

Integers are much better than floats at bucketing things, and floats are much better at saying "where" something "is" in space.
> 0 votes

---
Tags: xna, vector
---


title: "Model Driven" Game Prototyping

text:
# Question
Title: "Model Driven" Game Prototyping
Are there any known libs / frameworks / systems allowing to prototype a game based on a defined "model" of the game mechanics?

Think all those match 3 games, i'm looking for "something" allowing to try out new rule sets in rapid prototypes where dealing with the grafix/updating the screen based on the state and input/output is only secondary and having something running and interactive is most important to validate an idea...

Do such tools exist? What would be your take on this when asked to skip as much coding as possible?

To clarify: nope I am NOT looking for any magic. What I am looking for are tools allowing to concentrate more on the "logic" of a game (atleast for simple games ala match 3) and not having to code all the screen/input/ui stuff, thus the "model driven" naming...

# Answer
Short answer is, I don't think that kind of thing exists.

Long answer is, you're on the right track thinking in terms of abstracting out the game rules from the game display. For some ideas, you should even be able to create a text based game, where instead of doing fancy graphics renders, the game simply uses text to describe what is going on. That kind of approach lets you concentrate on the game rules. Once you like the game rules, you can decide what to do about the display.
> 10 votes

# Answer
This is probably not the answer you're looking for, but I would recommend trying something like Paper Prototyping to test out these types of rules. For a match-3 it shouldn't be too difficult to craft the different game elements from paper and play things out by hand.
> 3 votes

# Answer
The closest thing you are going to find to something like that is going to be one of the off the shelf game engines. Game Salad is good for those I don't want to code it situations. There are low coding options like game maker. From there something like unity UDK or Panda3d are going to be your best bet, but they require a good bit of work to get to the point you are talking about.
> 1 votes

# Answer
Basically - You are asking question on how to decompose UI from game logic.

To do that - You must abstract things. Object-oriented programming helps with that. More specifically - MVC pattern is what You are looking for. Combined with rich domain model (Your game mechanics) which is able to interpret so called DSL You could achieve Your aim.
> 0 votes

# Answer
I would have a look at a framework like GeekGameBoard. Once you figure out how to write your code, you can quickly implement a new board game. The library abstracts a lot of the mechanics, allowing you to simply write the rules for which piece moves where, does it capture, etc. I was able to prototype a brand new board game from start to finish in about an hour (the game wasn't that much fun...).

For other types of games, you would need to do similar up-front work.
> 0 votes

# Answer
For no-code prototyping I recommend GameMaker on PC and GameSalad on Mac. Don't be fooled into thinking you're making the final result though; the only *released* game done with those tools that I enjoyed was Spelunky.
> 0 votes

---
Tags: prototyping
---


# Question
Title: Is there a fundamental technical reason for Flash being a more popular game platform than JavaScript?
Both Javascript and AS3 are implementations of ECMAScript.

Is there a fundamental technical reason for Flash being so much more prevalent as a game-publishing platform, when compared to Javascript?

# Answer
> 9 votes
As with everyone else, I'm going to assume you mean Flash vs what's collectively being called the HTML5 technologies.

I believe Flash is still more popular because:

* Momentum. Plenty of people who are interested in producing Flash type games are already well versed in Flash. People who are aspiring to create that sort of game are learning from them. Along with this comes a reluctance to switch for what seems like the sake of switching.
* Environment. The Flash designer is an integrated package that deals with asset management, authoring of data like animation curves, editing scripts, compilation, optimization and packaging, all with relatively low friction. There is no real competing HTML5 based environment to work in. With HTML5 you're still looking at reinventing a lot of the wheel just to get started.
* Robustness. HTML5, in its current state, is relatively new and still quite janky for game applications. The rules are constantly changing, which is exciting but not conducive to actually finishing a project. Flash, for better or worse, works as advertised. Its self contained graphics engine is several generations in, with support for all manner of advanced features, and should behave identically in all supported environments. HTML5 is a blank canvas still, and one that will behave differently depending on how it's viewed.
* Reference materials. This goes hand in hand with the environment and momentum reasons above: there's plenty of stuff to learn from if you're making a flash game; years of articles, discussions and postmortems. There really isn't that much stuff that talks about HTML5 yet.

# Answer
> 6 votes
Flash is a lot more than ECMAScript. Although there were attempts to introduce some features of ActionScript into ECMAScript version 4, those were abandoned.

JavaScript only got usable for most type of games very recently. JavaScript in HTML5 nowadays offers:

* performance gains dune to compilation into native code
* 2D and 3D canvas
* native Video And Audio support

But those things are provided by flash for a decade.

# Answer
> 5 votes
Flash:

> Originally developed by Macromedia, Flash was introduced in **1996**, and is currently developed and distributed by Adobe Systems,

"Javascript" really means HTML 5, when compared to Flash:

> The HTML5 specification was adopted as the starting point of the work of the new HTML working group of the World Wide Web Consortium (W3C) in 2007. This working group published the First Public Working Draft of the specification on **January 22, 2008**

(Emphasis added.)

# Answer
> 4 votes
Flash is a more established platform, and people are more used to using it to code games. In my experience, compiled AS3 running in the Flash Player runs much faster than Javascript running in-browser, and it offers easier access to things like sound and embedded files. Flash apps can also be encapsulated in a single .SWF file, while HTML5 apps written using Javascript tend to have a more complicated distribution method, since assets, scripts, and pages usually need to be separate files.

It's not entirely a fair comparison; Flash is compiled (to an extent), while Javascript is at best just-in-time-compiled for most web applications.

# Answer
> 3 votes
The semantic quibble Gregory made in his comment gets at the root of the issue here. Flash is a very established gaming platform because of the combination of ActionScript 3 and a host of powerful multimedia capabilities. While JavaScript was always just as good of a language, only recently has it been coupled with the powerful multimedia capabilities of HTML5.

As others are pointing out, you can compare ActionScript to JavaScript, and you can compare Flash to HTML 5, but comparing Flash to JavaScript is like saying "Which is better, Linux or C#?"

# Answer
> 2 votes
## I think this is a lot to do with tooling and marketing.

Most people back in the early AS2 and even AS1 days of Flash, were introduced via the Flash IDE. This was a great tool, were you could draw or import graphics, and add scripts very easily to get things happening very quickly. Macromedia (now Adobe) owes a lot of it popularity to this easy, graphics based entry point. There was not really much else out there that was even close (well, besides Director. Which I still love btw).

So Flash became a popular game creation tool before ActionScript was popular. ActionScript just provided a way to add the interactivity. The IDE is what really made it popular.

Things are different these days, at the platform has matured into many different part. It is now quite common to make Flash games without even touching the Flash IDE.

# Answer
> 1 votes
The biggest reason is because ActionScript contends only with the version of Flash you're using. You can reach a wide audience fairly quick with ActionScript in Flash because of the market penetration of some of the most recent versions of Flash (the adoption rate is quick). Now think about JavaScript; it is not a single implementation of ECMAScript, but several interpretations of the ECMAScript standard, which all depend not only on the browser, but browser version. Adoption rate for the updated browsers for a general audience (think IE) is very slow. It just makes more sense to choose Flash (or even Java) because it is more portable.

---
Tags: flash, javascript
---


# Question
Title: How could an XNA game close with no exception being thrown?
I've been messing with my game's network code recently (TCP/UDP sockets) and my game keeps shutting down with no exceptions being thrown at all.

It runs fine until the disconnection of a client, so I already know that it has to be related to the network.

My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?

# Answer
> 6 votes
I just found the answer to my problem:

The reason why the exception wouldn't show off is because it was actually thrown on a different thread. So removing my existing try/catch blocks in the main thread was of no help to show the exception. Adding a try/catch block to the Main method (to catch anything thrown in the entire application) wouldn't help either, since exceptions thrown on different threads don't fall in the catch blocks of the main thread.

My guess was correct: the problem came from the async TCP networking, which automatically generates and uses underlying threads. The exception was thrown whenever the client forcibly closed the TCP socket. Since the exception was on another thread, it silently forced the XNA runtime to stop.

This is the exception that was silently thrown and that stopped the runtime:

```
// Unable to read data from the transport connection: An existing connection was
// forcibly closed by the remote host.

// at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)

```

**Update:** Just to make it perfectly clear for anyone who might encounter this problem in the future, here's how to correct it.

This is the problematic code:

```
// runs on the main thread
private void ReadAsync()
{
    tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, readCallback, null);
}

// runs on an hidden underlying thread
// because of the asynchronous operation
private void OnRead(IAsyncResult result)
{
    // dangerous exception thrown here
    // which won't fall in the catch blocks of the main thread
    tcpClient.GetStream().EndRead(result);

    // process the received data
}

```

A simple try/catch block in the asynchronous thread will fix the problem:

```
private void OnRead(IAsyncResult result)
{
    try
    {
        // dangerous exception thrown here
        // which won't fall in the catch blocks of the main thread
        tcpClient.GetStream().EndRead(result);

        // process the received data
    }
    catch(Exception ex)
    {
        // handle the exception
    }
}

```

Naturally, this pitfall is not limited to TCP networking. You might encounter this problem for any type of .NET asynchronous operation and also in your own custom threads, so be sure to always put some try/catch blocks at these places!

# Answer
> 1 votes
With out knowing more I can not give you more detailed information but here are some things to look for:

Look for critical failures you may be handling in your code silently that could cause this.. and do not rule out that that is what is happening in the XNA code. This could be anything that you would assume would never happen but put in for good code theory.

Areas to look for are where you are access the data of the other user. Maybe a system is still tracking the remote user on a Mini map that is no longer there or the like. Pretty much any sort of data that you are guaranteed is there when not dealing with remote players but might disappear when dealing with remote players.

I will update if you get more specifics.

Hope this helps.

---
Tags: xna, networking, debugging
---


# Question
Title: Swapping axis labels between 2D and 3D coordinates
My game world is 3D.

The map is only 2D, however.

It is natural to think of the map as having an X and Y axis.

And it is natural to think of the world has having an X, Y and Z axis, where Y is upwards.

That is to say, X Y in 2D map coordinates is X Z in 3D coordinates.

What conventions and approaches do you have to keeping things straight at a code level to make mapping between them natural?

(Is Y usually upwards in 3D? Or do you have X and Z in map coordinates, or?)

# Answer
Y up and Z up (where the respective axis is considered the upright direction in 3D) are just conventions. Modelling packages often have toggles to switch between them.

You should arrange your game around whatever makes sense to you. You can always accept incoming data in any coordinate system and convert it internally to match what the engine is doing.

If your game is truly 2D in nature, as in you plan to do all your game logic in 2D but just draw a 3D representation of the action, then you might want to consider working entirely with a 2D coordinate data structure until you come to your drawing code, where you promote it to 3D to pass to the graphics engine. You'll save memory, gain performance, and get to work in your familiar XY space.

If your game is just "conceptually" 2D, but you're actually still performing calculations in 3D for whatever reason (say you had an undulating terrain and projectiles that actually travel in 3D even though your actors cant), then I suggest deciding on a drawing coordinate system (very likely the popular Y up), and just getting used to writing your "2D" logic on the appropriate matching plane (the XZ, assuming the aforementioned Y up).

Maintaining a code base with two different overlapping 3D coordinate systems will get unbearably messy and annoying with no recourse, while just learning to think of the floor as XZ will snap into focus within hours.
> 3 votes

# Answer
Y is usually upwards in 3D, but the designations of the axes are rather arbitrary. To keep it simple I'd either have:

```
X (width), Y (depth), Z (height)
or
X (width) Z (depth) Y (height)

```

Keep the naming of the axes consistent between 2D and 3D. Conversion between 2D and 3D can be done with a simple function.

If you're interfacing a lot with a library that has a different convention then either use the convention the library is using or make conversion functions. The conversion functions could look something like this:

```
vector3D switchAxes(vector3D in)
{
  return vector3D(in.y, in.z, in.x);
}

```
> 2 votes

---
Tags: vector, coordinates
---


title: Getting started with Box2D for iOS

text:
# Question
Title: Getting started with Box2D for iOS
I just want to run any Box2D "Hello World" or test apps. I've downloaded the source twice (zip file the first time and via svn the second time), followed the build instructions (do stuff w/ cmake, "make", "make install" etc) and don't know where to go from there. **How do I run the test apps or Hello World apps that come w/ Box2D on my iPhone (or simulator)?**

# Answer
It may not be exactly what you want, but it's worth mentioning that Cocos2D works very well with Box2D, and has an example that comes with it.
> 3 votes

# Answer
Ok finally got something to work (this was helpful: http://box2d.org/forum/viewtopic.php?f=18&t=6580&p=29800&hilit=cmake#p29800)

Anyways here's what I did:

1. get Box2D source like this: "svn checkout http://box2d.googlecode.com/svn/trunk/"
2. In the Terminal navigate to "Contributions/Platforms/iPhone"
3. In the Terminal do "cmake -G Xcode"
4. Double click on "iPhoneTestbed.xcodeproj" in the Finder

Now this Xcode project actually builds and will run in the simulator. There's some cool demos of Box2D physics. Hope this is helpful :-)
> 3 votes

---
Tags: iphone, box2d
---


# Question
Title: The need your game fills. Establishing your "hook."
I am a programmer and have worked on games although never attempted design myself. I am now attempting to design a game myself, working with a modest team of programmers and artists.

Game designers have been telling me it is important to establish the need your game fills, in order to develop a more complete vision of the product. I think in terms of mechanics and gameplay and am having trouble finding a "hook," even in existing games.

Any advice in identifying why a mechanic is fun, and what need a game fills, to help develop my own ideas is much appreciated.

# Answer
> 6 votes
I thought this article on prototyping games in under 7 days had some interesting ideas. The suggested focusing on a single theme and exploring it:

> “gravity”, “springs”, “evolution”, “sound”, “predator and prey”, “addictive games”, “drawing”, “exponential growth”, “vegetation”, “balance”.

I also appreciated the suggestion to focus on getting it working quickly so you can get a feel for the mechanics and if it's not right, fail quickly and move on to the next idea.

# Answer
> 5 votes
Find your OWN need that wants to be filled. My personal game idea is something that I've searched high and low for, but I've not been able to find a great game to fill that void.

Because I also have fairly typical interests, I get encouraged by the fact that my game will likely not fail. That it's something I really really want to play helps me keep motivated too.

Minecraft (seems to by my favorite example these days) was built because Notch noticed a void that needed to be filled. He filled it and is now a multimillionaire.

Find something missing and build that. It's the best reason for building a game ever. =)

# Answer
> 3 votes
On identifying why a game is fun, A Theory of Fun is a good book.

# Answer
> 1 votes
I get most of my motivation, inspiration, and design ideas from playing other games. In fact, most of my motivating "spark" comes straight from the super nintendo emulator these days.

# Answer
> 0 votes
You might pick a pick you like, and figure out how you could improve it. Or take a game that you thought had potential but didn't deliver, and figure out what could have saved it. In the process, you may come up with an idea that you like.

---
Tags: game-design
---


# Question
Title: Positive Evaluation Function - Territory AI Help
I am trying to implement some positive evaluation into my game. Let me explain.

I have a series (anywhere from 5 to 25 (might vary)) of circles (three sizes, big medium small). And each player starts with a main circle which gains 1 every turn (like risk the circles gain at different speeds, the big one gains the fastest and the small one gains the slowest). You can use these numbers to take over other circles, if the "enemy" is on this circle it does a risk thing (you fight to see who takes it over, who ever has more wins most of the time, I'm not getting into this logic as it is rather irreverent).

So this is a very basic overview of what occurs, now what I need some help with is how I can create an AI which will look at all available (and taken) circles and determine where it wants to move to. There would be circles closes to it, and circles in the enemies area and circles available and circles taken over. And it would need to determine where to move it's forces too next, and so on and so forth.

So after some research I read a lot about Positive Evaluation, which it takes all possible moves and determines the best one.

So I am wondering if anyone could help me out or give me some direction as to where to go from here. I think what I need to do is take all the circles with any forces on them, throw them into a table/array with the cords of each circle and determine which would be best, then I would need to determine how many forces I want to send and where from.

Help!

ADDITION:

Allow me to explain a bit, http://imm.io/4Xwy see that diagram lets assume the circles are sections of forces, and you gain a new force each "time interval" and lets say I want to take all my forces (I'm pink) the circle directly below me and capture it, well the AI would need look at all available circles and pick for example the big green on in the top right (since big would make more troops and its close to the "main"). I'm assuming what you said would still work? Weighted options?

# Answer
> 5 votes
I don't think I quite follow your explaination, but if I had to write an AI that evaluated multiple targets I'd do something like this:

* create a list of all possible targets
* pass each target to multiple behaviours, each which may return a score
    + for instance a "weak target" behaviour might return a high score if the target is not very well defended
    + a "supply chain" behaviour might reward a high score to targets that are vital links in the opponent's infrastructure
* add all the scores together
* attack the target with the highest score

This approach is modular and extendable. You may need to put some work into making it easy for you to tweak at run time the numerous constants you will invariably use in each behaviour.

For bonus brownie points, you could return multiple scores in multiple categories (eg seperate scores for how much of a defensive attack this might be, and how much of an aggressive one). Then you could define a personality of your AI as a series of multipliers to these scores (an aggressive AI might have personality \[0.5, 1.5\] for instance, to boost aggressive targets and relatively ignore defensive targets). You pick the target with the highest of any type of score.

---
Tags: ai
---


# Question
Title: How can I determine a budget for RAM used (LRU involving VRAM, in particular)
After some profiling, I've determined that one of my most expensive functions involves drawing text. As a solution, I'd like to implement a LRU type of cache that will "remember" the vertices, tex coords (etc) for a given string. This is particularly complicated because some of the resources involved reside in VRAM (most do, actually; I take a given string and convert it into a long sequence of vertices / tex coords / indices), while some reside in plain RAM.

If I knew what my limits were (in both respects) I could write a decent LRU cache system and probably buy myself a substantial performance gain. The primary target for this app is the Android platform, and as I understand it, most such devices share RAM with the GPU.

I'd appreciate any answers to this, whether they directly answer my question or not.

# Answer
> 6 votes
Having dealt with text rendering a lot, I have to say all the string LRU systems I've seen end up being, at best, a wash for performance, and at worse an enormous source of bugs and code complication. The only time it makes sense is if all your text is static, and that's rarely the case in any game these days.

Do you know what's actually taking the time? Is it...

* Binding the font textures? If so, make sure all your characters are on the same texture, and make sure you're sorting them correctly to avoid unnecessary binds.
* Looking up the character data? What kind of data structure are you using? If it's not a hash table, it really should be. If it is, take a look at the load factor to make sure you're getting decent hashing.
* Accessing the character data? Accessor methods are very slow on Android and discouraged for any performance-critical code. Use public members instead.
* Calculating the vertices and copying them into the buffer? This might be an appropriate time to break out the NDK so you can do float crunching without the overhead of Dalvik.

# Answer
> 2 votes
Instead of determining a memory budget by guessing, I'd suggest you make the size of the cache configurable and use profiling to determine the best size for you.

Also you shouldn't need more than one index buffer - you just need one which will handle the maximum length string. You should be able to use less than the whole index buffer for shorter strings by passing the appropriate parameters to your draw call.

---
Tags: opengl, android, resource-management
---


# Question
Title: Why has it become commonplace for NPCs to have one weapon per class instead of variants?
For instance, in Half-Life 2 you have Civil Protection, Combine Soldier and Combine Elite. Each class has a weapon. Is there a shift away from this at all, where the NPCs are matched with the player in the sense that the weapon they choose to use is based upon their advantage, while still maintaining some sense of competitiveness? Is there a reason this became the norm? Does it have to do with all the variables and complications that can arise from doing that?

# Answer
There are two reasons I can see immediately, both to do with simplicity: it's simpler to program the AI, and it's simpler for the player to understand. Now for certain games it may be an advantage if enemy characters can switch weapons for the situation (for starters, it's more realistic) but for most games it can be a significant problem if the player gets confused about what tactics to expect and counter. Players like being able to think "oh there's one of the grenade dudes, I better watch out for grenades."

As for complication in AI, there's just plain less thinking for the enemy to do if it doesn't have to consider which weapon to use. Consider your own thought process when deciding which weapon to use; now try to model that thought process as a set of instructions. You'll be considering damage per shot with how accurate the shots are, weighing effectiveness against different sorts of targets, and balancing all those factors against how much ammo you have. Pretty complicated huh?
> 16 votes

---
Tags: game-design, game-mechanics
---


title: File caching on the PC

text:
# Question
Title: File caching on the PC
Is it a good move to disable windows' file-caching capabilities (via I/O completion ports) for resource loading in a game environment? Most games will do their own resource management and caching anyways, so the OS will probably cache it a second time. Of course, you don't get the caching across the process' lifetime, but that's usually not a big downside. On the other hand, it probably makes file loading times more predictable - so you can actually give accurate load-time predictions.

# Answer
> 5 votes
> Premature optimization is the root of much evil.

If your goal is loading-time prediction, I would say **leave the OS file-caching in place.** It's probably general, but well-written, so I would say that you shouldn't disable it unless:

* You have a very good reason to do so, and
* You can measurably prove that disabling it is beneficial in your case.

Otherwise, it's probably not worth the work; and in the worst case (average case?), you may even *decrease* efficiency.

# Answer
> 3 votes
I'd say no. Windows will be using spare memory for this caching - it's basically free. Unless you've got a fancy system to somehow expand your process memory to cache more data when Windows is under low load, and then contract it again when Windows decides it wants more memory, just let the computer do what it's good at it.

I don't think increasing load time in order to give better load-time predictions is a good tradeoff :)

---
Tags: windows, loading
---


# Question
Title: Recommended 3D camera settings and model sizes for an FPS
I'm making a simple FPS and I can't decide on the size of my models and my camera settings. Could someone please recommend a good combination of:

* **camera field of view**
* **near and far planes**
* **model proportions** (such as 1 unit = 1 meter)

so that the game looks realistic enough and the numbers are easy to work with?

**EDIT:** I know I can use whatever dimensions I want, but I'd like to know what is most commonly found in games.

# Answer
* **camera FOV** \- near to human eye fov -\> 60 degrees, but you can play with that
* **near and far planes** \- near plane is usualy 0.1 distance, but far plane have to be as near as possible to gain the best depth buffer accurancy. Same for near plane, it should be as far as possible.
* **model proportions** \- use whatever you like. But meters are just fine.
> 4 votes

# Answer
For wide-screens you'd want a field of view around 1 (equal to 90 degrees of horizontal vision). Experiment a bit to find out what looks good for a default, but do give players the means to adjust it.

Near and far planes should ideally be as restricted as possible without clipping, but given a 24 bit Z-buffer it's not very important to restrict them tightly.

You can use what scale you like, it won't make any practical difference. 1 unit ~= 1 meter is probably the most common, but it's not like you are going to run into issues if a designer use a different scale than the game, it takes virtually no effort to rescale a model as needed.
> 2 votes

---
Tags: 3d, camera, first-person-shooter
---


# Question
Title: How to avoid flat appearance on sides that receive only ambient light?
How does one handle shading in a 3D game?

I have a directional light source that shades one side of a tree made of cubes. The remaining 3 sides all get ambient shading only. So the 3D effect is lost when looking at two ambient shaded sides.

Am I missing something? Should I be shading the side furthest from the light source even darker? I tried looking at Fallout 3 and it kind of looks like this is what they do, however Minecraft appears to shade a grass mound with two opposite sides light and the remaining two opposite sides dark, giving the effect that there are two directional lights for the two light shaded sides and ambient light for the dark shaded sides.

# Answer
> 10 votes
Many effects use a standard lighting rig which uses 3 lights similar to how a movie company would film a movie.

Here is a wiki link: http://en.wikipedia.org/wiki/Three-point\_lighting

here is an XNA specific blog about it (concepts can be applied to OpenGL too): Link

# Answer
> 5 votes
Your problem is that your ambient light is a constant color. In reality ambient light tends to be bright from the top and dark from the bottom, because light typically comes from above.

There is much you can do to fix this. At the very least, you should have a "top ambient color", "bottom ambient color", and "top ambient direction" vertex shader constants.

In your vertex shader, take the dot product of the "top ambient direction" and the vertex normal, and use the result to lerp between the "top ambient color" and "bottom ambient color:"

```
float value = dot( vertex_normal, top_ambient_direction ) * 0.5 + 0.5;
ambient_color = lerp( bottom_ambient_color, top_ambient_color, value );

```

That is one of the simpler ways to make ambient look better, and was used often in PS2 and XBOX1 games. Contemporary games go further by using an "ambient cubemap" or "ambient spherical harmonic coefficients."

# Answer
> 3 votes
This is a complex topic, and I'm barely qualified to talk about it, but I'll give it a shot. Many games use a pre-baked light map that takes into account light bouncing off of multiple surfaces, then combine that with dynamic lighting to produce a fast, realistic, and good-looking environment. There are probably modern games that do light bouncing in real-time.

Something to keep in mind is that light attenuates with distance; if your lamp is at an angle to a surface, the closer edge will be brighter than the farther edge. Things tend to look very fake if a lamp is shining on them straight-on rather than at an angle.

Minecraft's lighting is special, because it uses a weird system where light is treated almost like heat diffusing through the world: http://www.minecraftwiki.net/wiki/Light It's not easily extended to a general-purpose solution.

The most cool-looking effect I've seen used is called ambient occlusion. It's expensive, and is usually only used in a pre-baked solution, but it takes into account how corners of the room are darker because the walls occlude the ambient light; the middle of the wall has a hemisphere's worth of light hitting it, while the corner where three surfaces meet has only a hemidemisemisphere's (1/8 sphere's) worth of light. https://secure.wikimedia.org/wikipedia/en/wiki/Ambient\_occlusion

There's tons and tons of writing out there on lighting systems; searching around will probably serve you well.

# Answer
> 0 votes
Lighting/shading needs to be more advanced than just a binary decision. Blocks are not either lit or unlit completely by a light, they can be partially lit. Sometimes the face should be totally shiny, in which case it is being hit directly by the light. Sometimes you only want the ambient light, if it is completely untouched by the light. However, when it is partially obscured, you need to give it a light value between fully lit and fully unlit.

The standard basic lighting method shifts from zero light to maximum light based on the difference in angle between the incoming light ray and the surface normal of the face you are lighting.

If the normal of the surface is equal (or opposite, depending upon how you're looking at it) then you have maximum brightness. As the angle between the incoming light and the surface normal increases, you get less and less light on that face from that light.

This way, with two lights, each face should receive a brightness that is a combination of how much brightness each light puts on each face based on its angle.

This should be much more natural than trying to determine if a single face is lit or not. You'll have a natural gradient as surfaces get further away from the light, and you'll get balancing for surfaces effected by more than one light.

---
Tags: 3d, opengl, shaders, lighting
---


# Question
Title: Programmatically Modifying Images to Create Morning, Sunrise/Sunset and Night-Time Modes
I'm using RPG-Maker-XP-like sprites (any 2D adventure/RPG style sprites). I would like to tint them so that they look different at different times of day.

Times of the day are the set of:

* Daytime (normal)
* Early morning (bluish?)
* Sunrise and Sunset (orangish?)
* Night time (dark)

**What do I need to do to tint them, and make them look good, during different times of the day?** Are there any "known" formulas for any of these times, like "delete the green blue component and tint heavily red+green for a sunrise effect"?

Ideally, I have just the original sprites, with no additional information or images (like spot-highlights or shadows separated out).

Finally, I'm using Silverlight/FlatRedBall for this, so I do have access to per-pixel information, as well as RGB tinting (adding, subtracting, multiplying, etc.)

# Answer
I'd suggest playing around with Photoshop (if you've got it) with different color/layer overlays, and see if you can't get the visual effect you're looking for. If you can find it, duplicate it in code.

If the sky is visible, consider the idea of fading between two different background images (night sky, day sky). If you're using sprites, you could also consider animating a moon/sun in the sky.

Also, take a look at (as in play) World of Warcraft. Yes, it's 3D, and it has a dynamically lit day/night cycle, but at the same time shadows and lighting of things is totally baked on - the shadows don't move. It's more like what you see in TV shows where they don't actually film at night, but instead film during the day and apply a night time filter. In fact you might consider googling around for how this is done for film as it might give some hints.
> 2 votes

# Answer
Color temperature

But basicly it is orange at the morning and evening. White at the day. And blue is used for the night.

For creating shadows you may find useful program crazybump, which can create normal maps for 2D textures.
> 1 votes

# Answer
What you want is typically called 'color blending'. There's a blog post about how to do it in silverlight here: http://blogs.silverarcade.com/silverlight-games-101/15/silverlight-blitting-and-blending-with-silverlights-writeablebitmap/

As far as what colors to use at different times of the day, that's a much harder question to answer. The colors you included in your post might work, but you might have to play around a bit with the exact values to make everything look 'good'.

It might be worth pointing out that adding shadows to the sprites would likely go a long way to improving the effect of changing the time of day.
> 0 votes

---
Tags: 2d, graphic-effects
---


title: Rudimentary 3D graphics in C++ .NET

text:
# Question
Title: Rudimentary 3D graphics in C++ .NET
I am looking to implement an extremely rudimentary FPS game with extremely rudimentary 3D graphics using C++ .NET and DirectX.

I'm not interested in any third party libraries or anything special like that.

Having never done graphics based programming besides 2D stuff I don't really know where to get started or even how to find the right resources online.

I have a few weeks to build this game so im trying to keep it simple.

Can anyone give me a little guidance on how to get started?

# Answer
Download the DirectX SDK and fire up the sample code that puts a rainbow colored 3D shape on screen. Try making it draw more shapes. Try making it so that big shapes can shoot little shapes out of them. Try moving the shapes around. Try moving the camera around.

You can have a fully playable (but weird) game up and running in an evening that way. Later, you can worry about getting more sophisticated one step at a time. For example, keep the game playable while replacing the rainbow colored 3D shape with a mesh that looks like a person or a bullet or a tank.

The key point is to keep the thing playable at all times. That's where the fun is, and it will motivate you to go back again and again to fix "one more detail." It's like the folk story of Stone Soup.
> 1 votes

---
Tags: c++, 3d, directx
---


title: Blender modelling for a C++ game?

text:
# Question
Title: Blender modelling for a C++ game?
I want to know if it were possible to integrate models created with Blender into a game written in solely C++.

# Answer
> 5 votes
The programming language doesn't matter for this purpose. You just need to get your model data from Blender into your application, which is possible by using one of the various export formats that Blender offers.

Of course all models you create in Blender must be suitable for real-time rendering, i.e. their polygon count should be decent and their materials and other effects features must be supported by your game framework. Typically you'll need many iterations until a content pipeline becomes actually stable.

See this question for more information on suitable formats for use with Blender 3D.

# Answer
> 1 votes
For Blender you can use Python to write script for exporting models to your model data type.

---
Tags: blender
---


# Question
Title: Adding air drag to a golf ball trajectory equation
I'm developing a 2D golf game in VB.NET 2005, but I am stuck on how to implement air or wind drag that should affect the ball.

Already I have these equations for projectile:

* \\$v\_0\\$ for the initial velocity of a golfball when hit or fired
* Vertical and horizontal components the velocity of the golfball: $$ \begin{align} v\_x &= v\_0 cos(\theta) \\ v\_y &= v\_0 sin(\theta) - gt\* \end{align} $$
* Vertical and horizontal distance of golfball: $$ \begin{align} x &= v\_0cos(\theta)t \\ y &= v\_0sin(\theta) t - (0.5)gt^2 \end{align} $$

How do I add air drag to this equation to properly affect the velocity of the golf ball? I don't have any idea how to do it, has anyone worked with similar equations?

# Answer
I'm not sure if there even exists a closed form for drag or wind, but it is quite easy to simulate in a step-wise fashion (like all the physics libraries do):

1. set your initial condition:

$$ x, y, v\_x, v\_y \\; (\text{for }t=0) $$
2. update position:

$$ x = x + (v\_x \times dt) \\ y = x + (v\_y \times dt) $$

(where dt is the time elapsed since the last update, aka delta time)
3. calculate these velocity helpers:

$$ \begin{align} v^2 &= (v\_x)^2 + (v\_y)^2 \\ \lvert v \rvert &= \sqrt{v^2} \end{align} $$

(where \\$\lvert v \rvert\\$ represents the length of \\$v\\$)
4. calculate drag force:

$$ f\_{drag} = c \times v^2 $$

(where c is the coefficient of friction *small!*)
5. accumulate forces:

$$ \begin{align} f\_x &= \left(-f\_{drag} \times {v\_x \over \lvert v \rvert}\right) \\ f\_y &= \left(-f\_{drag} \times {v\_y \over \lvert v \rvert}\right) + (-g \times mass) \end{align} $$

(where \\$mass\\$ is the mass of your golf ball)
6. update velocity:

$$ v\_x = v\_x + f\_x \times \frac{dt}{mass} \\ v\_y = v\_y + f\_y \times \frac{dt}{mass} $$

That's basically Euler's Method for approximating those physics.

---

A bit more on how the simulation as requested in the comments:

* The initial condition \\$(t = 0)\\$ in your case is

$$ \begin{align} x &= 0 \\ y &= 0 \\ v\_x &= v\_0 \times cos(\theta) \\ v\_y &= v\_0 \times sin(\theta) \end{align} $$

It's basically the same as in your basic trajectory formula where every occurrence of t is replaced by 0.

* The kinetic energy \\$KE = 0.5m(V^2) \\$ is valid for every \\$t\\$. See \\$v^2\\$ as in (3) above.
* The potential energy \\$ PE = m \times g \times y \\$ is also always valid.
* If you want to get the current \\$(x,y)\\$ for a given \\$t\_1\\$, what you need to do is initialize the simulation for \\$t = 0\\$ and do small dt updates until \\$t = t\_1\\$
* If you already calculated \\$(x,y)\\$ for a \\$t\_1\\$ and you want to know their values for a \\$t\_2\\$ where \\$t\_1 \lt t\_2\\$, all you need to do is calculating those small dt update steps from \\$t\_1\\$ to \\$t\_2\\$

## Pseudo-Code:

```
simulate(v0, theta, t1)
  dt = 0.1
  x = 0
  y = 0
  vx = v0 * cos(theta)
  vy = v0 * sin(theta)
  for (t = 0; t < t1; t += dt)
    x += vx * dt
    y += vy * dt
    v_squared = vx * vx + vy * vy
    v_length = sqrt(v_squared)
    f_drag = c * v_squared
    f_grav = g * mass
    f_x = (-f_drag * vx / v_length)
    f_y = (-f_drag * vy / v_length) + (-f_grav)
    v_x += f_x * dt / mass
    v_y += f_y * dt / mass
  end for
  return x, y
end simulate

```
> 10 votes

---
Tags: c#, mathematics, physics, projectile-physics
---


# Question
Title: using odd number of sprites in multi-row spriteSheet?
Using XNA it's pretty easier to loop through a sprite sheet, I tell it how many rows and how many columns it has and I have a method that loops through the whole set.

I usually use this method in my sprite class, but I have a sprite sheet that has a odd number of sprites, and does not use the entire last line. Any ideas on how to do this?

for example: I have 3 rows of 6 columns, but on the last row I only have 3 sprites.

Thanks!

# Answer
> 5 votes
You're telling it how many rows and columns it has. Simply also tell it how many sprites it has on it. Therefore allowing you to skip over the final sprites as you loop.

(I assume you know how to index rows and columns with `/` and `%`? If not then this will tell you.)

So for something like this:

```
const int rowCount = 3;
const int columnCount = 6;
for(int i = 0; i < rowCount * columnCount; ++i)
{
    int row = i / columnCount;
    int column = i % columnCount;
}

```

Simply change it to something like this:

```
const int rowCount = 3;
const int columnCount = 6;
const int spriteCount = 15;
for(int i = 0; i < spriteCount; ++i)
{
    int row = i / columnCount;
    int column = i % columnCount;
}

```

(And then, obviously, you're generating rectangles like this)

```
int width = texture.Width / columnCount;
int height = texture.Height / rowCount;
Rectangle sourceRectangle = new Rectangle(column * width, row * height, width, height);

```

# Answer
> 2 votes
I haven't used XNA, but when I've used sprite sheets in the past, part of the meta data associated with that sprite sheet is the number of frames on it. Usually if that number is '0' I just compute it to be the width * height, but if it's non-zero I use that and assume that the last sprites are blank.

# Answer
> 0 votes
When you say you have a method that "loops through the whole set", do you mean it loops through the whole Spritesheet, or the whole current row? Normally when I make Spritesheets, I have every row being a single animation, and every column being a frame of that animation.

In my constructor, I set the maximum number of rows and columns my spritesheet can have (although that may not even be necessary). An animation won't necessarily have that many frames (e.g. rows per column) as the maximum, but it's good to keep track of.

Then, whenever you want to advance a frame of you're animation, simply have a method to do it where you pass the number of frames on the current row.

This is one way:

```
void AdvanceFrame()
{
    //currentNumFrames is the number of frames in the current animation -- see below
    frameIndex = (frameIndex + 1) % currentNumFrames;

    //animationIndex being your current row, frameIndex your current column.
    srcRect = new Rectangle(frameIndex * frameWidth, animationIndex * frameHeight, frameWidth, frameHeight);
}

```

Then, whenever you want to animate, you would call a function like this:

```
public void Animate(int animation, int framesInAnimation)
{
    //In your update you will animate when (!paused)
    paused = false;

    animationIndex = animation;
    frameIndex = 0;
    currentNumFrames = frameInAnimation;

    //Same as before, you can put it in a method.
    RealignSrcRectangle();
}

```

Another way is you could simply put the number of frames per row in an array. Then, you wouldn't need to send in `framesInAnimation` and store a `currentNumFrames`, in your advance you would do this instead:

```
    frameIndex = (frameIndex + 1) % framesPerAnimation[animationIndex];

```

# Answer
> 0 votes
I just implemented a animated sprite class that takes the total frames like others have said, and the frame size. I then calculate the rows and columns from those. Since we have large animations and didn't want to go over 2048x2048 sprite sheet size I also can span multiple sprite sheets.

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


# Question
Title: How to make shrunken textures look pretty
I am drawing lots of textures and panning and zooming in and out on them. When the camera zooms out they look really ugly.

What can I do?

# Answer
> 5 votes
Yup, looks like mipmaps. This looks like it might be a good resource on how to add them in. Once in though, you can manipulate the filtering - try enabling trilinear filtering or anisotropic filtering.

---
Tags: opengl, c++, 2d
---


# Question
Title: Trying to understand light on Opengl, how to simulate a realistic sun light?
I don't know if I'm doing something wrong or missing anything but I want to simulate sun light, like in a sunny day.

When the object is facing the directional light, it's well lit and there's no problems there. If I go around the object and look at it's back, it's dark. It's not too much dark because I'm using `GL_AMBIENT` but it's still too dark for a sunny day. If I increase the value, it will never look better because the side of the object facing the light will be too bright.

And there's another annoying issue with the ambient light, when looking at the back of the object, I can't see any shape, only a plain color. Hard to explain, here's some pictures:

Object Front: https://i.stack.imgur.com/YW53X.png
Object Back: https://i.stack.imgur.com/Qufha.png

As you can easily see, the front side looks nice, you can see the shape of that red thing. On the back side, it's plain, you can't see the same shape.

Now, I know that I'm looking at the back of an object and I'm looking in the direction of the light and it should be darker than the front side. But it shouldn't look so plain like this. That's not what we see when going against the sun light looking at some object, we see that the objects form some shape.

How can I have the same (or similar) effect on OpenGL?

My light is currently defined like this:

```
float posLight0[4] = {-1.0f, 1.0f, 1.0f, 0.0f};
float ambLight0[4] = {0.5f, 0.5f, 0.5f, 0.5f};

glLightfv(GL_LIGHT0, GL_POSITION, posLight0);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight0);

```

# Answer
With the ambient light your objects appear too bright because the diffuse light is added to the ambient light, and the diffuse light defaults to 1.0. This adds up to 1.5, and everything above 1.0 is clamped. Set the diffuse light to 0.5:

```
float difLight0[4] = {0.5f, 0.5f, 0.5f, 1.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, difLight0);

```

The second problem is harder to solve. You can try adding some fine details to the surface such as texture or bump map. In OpenGL the ambient light is constant, but in real world that is never the case. To simulate the real world, some form of global illumination solution is needed. Ambient occlusion helps a lot here, but is harder to implement than just setting OpenGL states. You could bake the ambient occlusion to the vertices of your model in your 3D modeling software or use SSAO, but I'm not going to the details.

What you can easily do is add another dimmer light source from some other direction (e.g. opposite direction). This will not be realistic, but at least it will give some shape for the back sides of your objects as well.

Also consider adding specular highlights to your application. It will make objects shiny.

```
float specLight0[4] = {0.5f, 0.5f, 0.5f, 1.0f};
glLightfv(GL_LIGHT0, GL_SPECULAR, specLight0);
glMaterialfv(GL_FRONT, GL_SHININESS, 10.0f); // Shininess between 0 and 128

```

You can also specify light and material colors separately, especially if the defaults are not suitable for you.
> 11 votes

# Answer
OpenGL's ambient light is a single color, but ambient light in the real world is usually brighter from above and darker from below. You can approximate this in OpenGL by setting the ambient light to very dark blue, and adding a dark blue directional light pointing downward. That, plus a bright white directional light coming from wherever the sun is, can approximate outdoors light pretty well.

What you really should do is write a shader that calculates light per pixel, but getting there from where you are is going to take a little time.
> 2 votes

# Answer
The answer you have got here is pretty good. Just one addition. Once you will want to have it nicer, try implement atmospheric scattering
> 1 votes

---
Tags: opengl, lighting
---


# Question
Title: How to simulate or actually make your code wait for user input in response to events in turn-based games
I'm controlling the main loop with Game States like in pseudo code below:

```
loop{
      if (Not Game.WaitingForUserInput){

          if (Game.Started){
              StartTurn();
          }

          if (Turn Started){
              DoSomething();
          }
}

```

This works fine, until the inner workings of a method like "StartTurn()" or "DoSomething()" requires waiting for user input.

Also, Assume that calling "DoSomething()" triggers an event that is listened to by more than one object. Each object that handles the event requires user input to finish handling the event. To illustrate:

DoSomething() ==\> fires an event that is handled by 2 objects with methods that follow this pattern:

```
HandlingMethod()
{
    // some logic

    // Here we need to get a variable X that is determined through user input
    // like clicking a UI element. So, we need to wait (or simulate wait) until X is
    // determined.
}

```

This means when the first object starts handling the event, the 2nd object must wait until the first object has finished handling the event.

I tried tight loops inside these methods like:

```
...
while (X is unknown){
   // just loop and check X until user has clicked something
}
... X here will be known

```

However, this leads to the UI to hang and user will not be able to interact with the application.

By the way, I'm using a windows application (windows forms) for the UI.

# Answer
> 0 votes
This is a design decision with countless possible answers. In the end it's related to how many states your state machine has and what the transitions are.

If `StartTurn()` needs to wait for user input, one possibility is to split it like you already split your method into `StartTurn()` and `DoSomething()`. This is akin to *adding a state* to your state machine:

```
loop{
  if (Game.WaitingForUserInput) {
    WaitForInput();
  }
  else {
    switch (Game.State) {
      case Game.State.GameStarted:
        PrepareTurn(); break; /* Will set WaitingForUserInput to TRUE */
      case Game.State.TurnPrepared:
        StartTurn(); break;
      case Game.State.TurnStarted:
        DoSomething(); break;
      /* More cases */
    }
  }
}

```

You could also make `StartTurn()` not change the game state until the second time it is called. This is akin to *adding a substate* to your state machine.

# Answer
> 2 votes
Coroutines are a beautiful thing. They are unfortunately not well supported in most languages.

A coroutine allows a function to yield its execution to its caller (silimar to return). The magic is that the function (coroutine) can be be restarted where it left off whereas a regular function must start from the top everytime. Coroutines are known for being able to transform complex IO (waiting for input) code into simple sequential steps.

In python coroutines are created by using the `yield` statement in a function. Python coroutines are limited in that the coroutine can only yield to its immediate caller.

Lua has great coroutine support. In lua you explicitly change a function into a coroutine. When the `coroutine.yield` method is called the function will return to the top most caller.

.NET has great coroutine support with its standard fiber library.

D has great coroutine support.

C/C++ have some implementations but they are arguably black magic.

So depending on the language you're using coroutines may be available. Personally, I love using lua for level scripting because of Lua's coroutine library.

# Answer
> 2 votes
Well, if you're writing WinForms, you could just turn your whole app event based and deal with input the way a normal windows app would: let your app idle waiting for updates, and just go through the motions of a turn until you're ready to idle again.

But I suspect, having a run loop and all, that what you're after is more of a traditional game loop for a turn based game like Civilization. In that case, you need to bear in mind that your logic is turn based, but your game actually isn't.

Here's an outline of what I would normally do:

```
main() {
  while( true ) {
    collectInput(); // deal with common code for filling in keyboard queues, determining mouse positions, etc.
    preBookKeeping(); // do any other work that needs constant ticks, like updating streaming/sound/physics/networking receives, etc.
    runLogic(); // see below
    postBookKeeping(); // again any stuff that needs ticking, but would want to take into account what happened in runLogic this frame, e.g. animation/particles/networking transmit, etc
    drawEverything(); // any actual rendering actions you need to take
  }
}

runLogic() {
    // this is where you actually have a statemachine
    switch ( state ) {
       case WaitingForInput:
         // look at the collected input and see if any of it is actionable
       case WaitingForOpponent:
         // look at the input and warn the player that they are doing stuff that isn't going to work right now e.g. a "It's not your turn!" notification.
         // otherwise, use input to do things that might be valid when it's not the player's turn, like pan around the map.
       case etc:
         // a real game would have a ton more actual states, including transition states, start/end/options screens, etc.
    }
}

```

The idea here is that runLogic() wouldn't actually block, it would just deal with input for the current time step.

Your transition from state to state would make the game appear to be turn based in that at the appropriate states it would appear to be waiting for the player to take action, but in reality your game loop ticks on carrying out animation and rendering duties.

You can hierarchically extend this to your objects: each object would get ticked to let it decide if it needs to take action based on the current state of the game. The trick is similarly to avoid blocking by having states that represent the object waiting for input. When you're in such a state, check the current input for the motivation you're looking for and just do nothing if it's not present, allowing the rest of the game to continue.

The same goes for messaging. Rather than delivering messages immediately between objects and blocking when you get to an object that cannot continue, what you want is to post all messages to a central postmaster, and then once a tick deliver them. Return results the same way, by posting a return message. In this manner, objects that expect a response will automatically be able to wait over any number of ticks where other objects are happily ticking away. You can decouple the frequency of this messaging from your display frame rate by just ticking the postmaster multiple times a frame.

A final note on optimization: it sounds like you'll have to do a lot of ticking and checking of every object just to do nothing, but once you have everything up and running, obvious optimizations should become self evident. For instance, rather than having one object list, split it into two: actively ticking objects that need to reconsider every tick, and dormant objects that won't need to do anything until a suitable message comes along to wake them up. You should find that very few things will really need to watch the world, and that the vast majority will just respond to messages to do their work.

---
Tags: turn-based
---