title: Time granularity for games

text:
# Question
Title: Time granularity for games
So far I've always used a time granularity of 1 msec (that's it, 1 millisecond is the atomic time unit).

I'm wondering if this is **always** fine, or if for some cases (some specific games, game components or platforms) it would be suggested to have a more accurate time unit (on the order of microseconds or, I don't know, hundreds of microseconds).

# Answer
> 9 votes
There's really two different questions here.

First is, *how accurately can I measure the time?* and the answer is incredibly accurately.

All modern CPUs (like, ~2000 onwards) come with high-resolution timers. On Windows, QueryPerformanceCounter is used to read these; on Linux and other POSIX systems, clock\_gettime; on Mac OS X you can use mach\_absolute\_time or this wrapper that provides a basic POSIX-like clock\_gettime wrapper around mach\_absolute time.

These timers provide counters measured in nanoseconds, and the practical resolution is usually measured in microseconds. These clocks are also *monotonic*, meaning they should not go backwards, even if the user adjusts their clock or you're on a multicore CPU system, although there have been buggy BIOSs that caused this for some chips.

The second question is *how quickly can I respond to events?* and the answer here is much more depressing.

PC operating systems use preemptive multitasking, which means how much time your program gets is completely under the purview of the OS. When you `sleep(10ms)`, that's a suggestion to the OS. It's rarely perfect, but usually it'll do its best, and you'll wake up sometime within the next 9.9 to 10.1 milliseconds. Sometimes though, it might be 15. Sometimes, if the system is under heavy load, it might be 10000. If an interrupt or signal occurs, it might be 1ms. This is why we have to jump through hoops to get truly stable timesteps in games.

Just *knowing* the time within 1ms precision? No problem. But relying on game logic that requires more precision than 1ms? That's a tricky business, and probably not appropriate for anything today.

# Answer
> -1 votes
It depends.

As far as I'm concerned a game has a time unit of 16.66667ms (1/60 seconds).

Other than synchronizing framerate with the display, I don't need a concept of real-time except how much to idle at the end of a frame before rendering the next one.

I use a high performance counter there though (*and microseconds!*), because if there only is 1.45 ms left in the frame before the next one should be rendered, I don't want it to wait 2ms!

---
Tags: timing
---


# Question
Title: Why is this .obj loader not drawing anything but the included .obj?
I've been adapting a tutorial on .obj file loading on the windows system to glut.

The thing's not drawing a thing except the "Foot.obj" file that the tutorial included and I'm going kinda nuts trying to figure out where's the fault. I'd appreciate a look into the code.

To try loading a different .obj just change the line

```
#define FILE_NAME_1 "Foot.obj"

```

in `Main.cpp`. I included the .obj files I've been trying to load into the VS project.

edit: codepad link to Main.cpp

# Answer
> 2 votes
I'd start by looking at the file you are trying to load. My experience with different exporters of .obj files is that they can play a little loose with the formats structure/order. Make sure the data looks the same between the two.

If you are loading the non-foot files, but just failing to render then another thing to check is if the foot model is entirely triangulated, and if the other models you are loading have faces defined by more than 3 verts.

---
Tags: opengl, models
---


# Question
Title: How to handle pathfinding on a non-grid/non-node terrain map
I'm not sure if this is even path-finding. All I have is a 3D map that has hills, etc. I'd like the enemy to flock an object, but also walk around other objects. These blocking objects may be added after the path is calculated, which would cause a re-calculation of the path.

What algorithm am I looking at here?

# Answer
You can use a variation on A\* pathfinding using an "influence map" technique to vary node-node weights based on whether they go near to bad things or good things (but be careful because A\* breaks if your heuristic ever over-estimates). So your heuristic needs to be based on "best case" i.e. the cheapest it can possibly be. In practice it works ok if your heuristic is stupid and you don't have negative-weight edges between adjacent nodes, or any edges between non-adjacent nodes (think teleporters etc).

So for example, if you want your AI characters to avoid climbing hills (because it is more expensive), you make edges which climb hills more expensive.

Or if you have some undesirable entity on the map (say an enemy watch tower or something) then you can make paths which go close to that proportionately more expensive, and have the algorithm automatically find routes which go around it.

Then the only problem is, what happens if conditions change while you're going there. Clearly you could take the "lazy" approach, and just have entities periodically recalculate their paths (although you can get into a loop where Bob tries path A for a while, then it looks a bit bad, and then changes to B, then that looks bad, so he goes back for path A).

Or you could have some threshold, where if the perceived "cost" of a path exceeds estimates by more than a certain amount, you recalculate. Or simply, if your entity hits an unexpected obstacle, he recalcs the path.

But in any case, what you really want to avoid is getting into a situation where large numbers of entities recalculate their paths every tick, which typically leads to a performance disaster.

So perhaps you need to put a minimum time limit on re-calculating a path, so that your entities won't keep repathing all the time.

Anyway, it's a tricky problem, good luck with it, I hope this helps.

---

EDIT: I am now going to try to answer your question.

Your map has no "grid" - but it doesn't matter, you can simply overlay an imaginary one on top of it. Provided you can query the height of a particular spot on the map, and its passability, if your grid has a high enough resolution, you can get a useful path out of it.

You need to be careful about "passability". If you make the grid too low resolution, then you can have a choke point which falls badly on the grid, and an entity of radius R won't notice that he can get through a gap of \> 2R , because the way the grid falls on it, it looks like a completely blocked path.
> 3 votes

---
Tags: path-finding
---


title: Robust Architecture for Flash Games?

text:
# Question
Title: Robust Architecture for Flash Games?
What's a good architecture for Flash games? I've read that MVC is great, with symbols just used purely for views (set states, use the class to manage which state/frame to show).

I would presumably then stick all my code in one or more .AS files, use object-oriented programming, try to unit test whatever I can, and make my art and symbols purely view-state stuff with no code.

Has anyone tried this? On anything other than a small game? How do these big flash RPGs and MMORPGs architect their games?

# Answer
Although MVC is a pattern that is widely used, I think it's not really appropriate for games. When developing games you'll also deal with sound, physics, networking etc. where do they belong to? Model, View or Controller?

You'll find that model and controller (sometimes even the view) are most often better combined in one class and/or that there are other patterns that are better suited for game development than MVC, for example the component pattern.

As a flash developer, I encourage you to separate your code from your assets though. If you're using an IDE like Flash Builder, there's no way around that anyways.

Also try to separate things that represent different layers of "information/logic", like *sound*, *rendering*, *ai* etc. to make these components reusable. You can leverage the flash event-system or use a signal-slot implementation to loosely couple these objects. Eg. The player class (or maybe even the *collision-handler*) dispatches a signal whenever the player collects a coin. By connecting the "collect-coin-signal" to the *sound-class*, the appropriate sound can be played without explicitly calling any sound-related code inside the player class. Of course this signal/event could also be connected to the *keep-track-of-score-class* etc. This architecture allows you to easily attach more components later on and/or swap them with different ones without rewriting huge portions of your existing code.

I think that most of the patterns commonly used for game development also apply when developing games in ActionScript. So just go ahead and look for some good game-development patterns and make use of them in your next Flash project.

Btw. I have never used Unit-Tests for a game, but maybe that's just me :)
> 6 votes

# Answer
Look at the source code for Flixel and FlashPunk. They work similarly to XNA in that they have a main Game class which contains the setup code and maintains a state machine which will run the Update(); Render(); loop on a GameState object.

Your different "screens" (ie: Menu, Gameplay, post-gameplay high score screen, etc.) will inherit from GameState, and each has their own Update, Render loop, as well as containers of game entities such as sprites and sounds.

Flixel's method for changing states is really just a method called ChangeState() which takes the state class and creates an instance of it to use.

Here's a good XNA article that can provide a good overview of state management.
> 2 votes

---
Tags: architecture, flash
---


# Question
Title: Counting point for a recursive domino-like game: Carcassone
I have to build a 2D version of this game:

http://en.wikipedia.org/wiki/Carcassonne\_(board\_game)

counting scores for Towns and Roads seems easy enough (but I'm not sure), but for Lands I feel I don't have a clue.

I'm guessing I can define 3 "plugs" for each side, 12 for each tile, and then using pairs to create links between them inside a tile...

I remembered seeing that there is some book about graphes with boost, but I'm sure I don't need that...

# Answer
Lands are only being counted at the end of the game, so you'll only have to do this once per game-session.

Since you'll know all completed cities beforehand (to calculate points for the cities), I'll probably do the following:

* Remove one "follower" from the list of followers (**list A**) that were placed on "land". Add the follower to **list B**.
* Start a flood-fill at the followers position.
* If your fill hits a city (which wasn't added before), add it to a list of adjacent cities.
* If your fill hits another follower, remove it from **list A** and add it to **list B**
* Separating road-pieces, rivers or missing pieces will obviously stop the flood fill.

After your flood-fill completes, count the number of followers from **list B** for each player. Depending on what ruleset (second edition, third edition) you'll have to implement, you can now split up points for all players that placed their followers in the land in question.

Now repeat this procedure, as long as **list A** still contains any followers.

I might be mistaken, but I guess one *plug* (or node) per corner should be sufficient to model the different possible connections.
> 1 votes

---
Tags: tiles, game-mechanics
---


# Question
Title: Does XNA 4.0 for Windows Phone 7 require Visual Studio 2010?
I have a copy of Visual Studio 2008 Pro. The Windows Phone Developments tools which include XNA 4 continuously fail to install on my machine. I am wondering if it was due to having 2008 vs 2010. Any ideas?

# Answer
Yes you need VS2010. If you don't have the full VS2010 the installer will download VS2010 Express Edition. Obviously that's a bummer if you've got stuff in VS2008 Pro that you like, but hey, that's Microsoft for you.
> 3 votes

# Answer
Yes, you need the application from this website to be able to develop for Windows Phone 7

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/windows-phone-developer-tools
> 0 votes

---
Tags: xna, windows-phone-7
---


# Question
Title: Easiest way to compute closest point between two triangular meshes
What is the easiest (not most efficient or fastest) algorithm to find the closest points between two triangular meshes? What are the easiest early out algorithms in the broad phase? What kind of broad phase algorithm would you recommend if I only have 2 (large and complex) objects? Lastly, what is the again easiest way to compute the closest point between two triangles?

# Answer
> 7 votes
In the absence of further clarification on what the restrictions are, I'm going to assume two meshes that are basically polygon soup (a set of triangles, possibly unconnected).

You're basically doing n\*m triangle to triangle collisions (where n is the number of triangles in object A, m the number in object B). The easiest way is to simply do a brute force closest-point-between-two-triangles for every pairing of triangles. So check triangle 0 in object A against triangle 0 in B, then 1 in B, 2, etc.

Triangle to triangle checks are pretty straightforward, if you have the RTC book mentioned you probably have a better algorithm already. But basically you only have three cases

1. the two triangles are parallel (in which case any point on the triangle is equally close to the other triangle)
2. an edge on one triangle is parallel to a line which crosses the triangle. So you can find two lines of equal length, one contained in the first triangle, one in the second. As those lines are parallel to each other, every point along those lines is equally close to the equivalent point on the other triangle.
3. a single vertex of one triangle is closest to some point on the plane inside the other triangle.

The 3rd case is just a closest-point-on-triangle-to-point, for which you project the point onto the plane of the triangle (i.e. find the closest point to your target on the plane which contains the triangle), and then constrain it to be within the triangle. If the projected point is within the triangle, then you have your closest point, otherwise you now have 3 closest-point-on-line-to-point problems, which you can solve with dot products (and pick the smallest of the three solutions).

Again you can brute force the triangle-triangle check, by iterating every vertex in triangle X and doing a closest-point-to-triangle check against triangle Y; then iterating every vertex in Y and doing a closest-point-to-triangle check against X. Now for each vertex you have a distance to the other triangle. If you have one vertex which is strictly closer than all the others, you're in case 3, and you're done. If you have two vertices *on the same triangle* equally close to the other triangle, you're in case two. If all three verts of one triangle are equally close to the other, you're in case 1.

In terms of optimisations / early outs, you need to find a cheaper way of testing two triangles for rough closeness, so that you can discard all but the few potential options. I think you could probably get a lot from AABB checking. E.g.:

* for each triangle calculate the AABB
* for each triangle pairing (n * m), calculate the distance between the two closest parts of the AABB, and the two furthest parts (separating axis makes this fairly cheap).
* Now you know that for those two triangles, the closest point is somewhere in between those two distances.
* Find the pairing with the smallest maximum distance (\[min\], \[max\]). From that pairing you know that you have a closest point which is at most \[max\] distance away, and so you can eliminate all other pairings which have a minimum distance further away than \[max\], because even at its best, the pairing is worse than the one you already have.

# Answer
> 1 votes
This is a really broad topic, and I suppose the answer would be 'it depends'. I can recommend the book 'real time collision detection'. There are a lot of options, and they all have tradeoffs.

My guess for easiest early out would be using a grid, then again, it's not very effective if you only have two large objects, in which case bounding volumes are a good choice.

Only having two objects is kind of weird though, could you give us a scenario? (as it is, it smells a bit like a homework question)

# Answer
> 1 votes
The following answer assume a fairly good grasp of geometry.

The shortest distance between two triangles fall into one of four cases:

It is between two corners, calculate all the corner to corner distances.

It is between a corner and an edge, calculate all the corner to line distances, remember to assert that the point on the line you find is actually part of the edge, if not then the number must be discarded.

It is between two edges, calculate line to line to distances, again assert that the points on the lines are on the edges.

It is between a corner and a centre area, calculate the corner to plane distances, assert that the point on the plane found is within the area of the triangle.

---
Tags: collision-detection
---


title: C# XNA Normals Question

text:
# Question
Title: C# XNA Normals Question
I have been working on some simple XNA proof of concept for a game idea I have as well as just to further my learning in XNA. However, i seem to be stuck on these dreaded normals, and using the BasicEffect with default lighting i can't seem to tell if my normals are being calculated correctly, hence the question.

I'm mainly drawing cubes at the moment, I'm using a triangle list and a VertexBuffer to get the job done. The north face of my cube has two polygons and 6 vectors:

```

Vector3 startPosition = new Vector3(0,0,0);
corners[0] = startPosition; // This is the start position. Block size is 5.
            corners[1] = new Vector3(startPosition.X, startPosition.Y + BLOCK_SIZE, startPosition.Z);
            corners[2] = new Vector3(startPosition.X + BLOCK_SIZE, startPosition.Y, startPosition.Z);
            corners[3] = new Vector3(startPosition.X + BLOCK_SIZE, startPosition.Y + BLOCK_SIZE, startPosition.Z);

            verts[0] = new VertexPositionNormalTexture(corners[0], normals[0], textCoordBR);
            verts[1] = new VertexPositionNormalTexture(corners[1], normals[0], textCoordTR);
            verts[2] = new VertexPositionNormalTexture(corners[2], normals[0], textCoordBL);
            verts[3] = new VertexPositionNormalTexture(corners[3], normals[0], textCoordTL);
            verts[4] = new VertexPositionNormalTexture(corners[2], normals[0], textCoordBL);
            verts[5] = new VertexPositionNormalTexture(corners[1], normals[0], textCoordTR);

```

Using those coordinates I want to generate the normal for the north face, I have no clue how to get the average of all those vectors and create a normal for the two polygons that it makes.

Here is what i tried:

```

            normals[0] = Vector3.Cross(corners[1], corners[2]);
            normals[0].Normalize();

```

It seems like its correct, but then using the same thing for other sides of the cube the lighting effect seems weird, and not cohesive with where i *think* the light source is coming from, not really sure with the BasicEffect.

Am I doing this right? Can anyone explain in lay mans terms how normals are calculated. Any help is much appreciated.

Note: I tried going through Riemers and such to figure it out with no luck, it seems no one really goes over the math well enough. Thanks!

# Answer
> 3 votes
Normals for flat faces (like the side of a cube) are at right angles to the triangles themselves. To work out what these should be you can either calculate them using the cross product like you are (though you will want to take the cross product of (vert\[1\] - vert\[0\]) X (vert\[2\] - vert\[0\]) - so you're using vectors on the plane not vertices in the plane). Moving to this vert\[a\] - vert\[b\] form should fix the weirdness you're experiencing.

However to make things a bit simpler in this case you can just set the normals manually. For this face of the cube the vertices all lie in the plane where Z = 0 (since startPosition.Z = 0 and all faces use startPosition.Z for their Z coordinate), so the normal = (0,0,1).

# Answer
> 2 votes
> ```
>         normals[0] = Vector3.Cross(corners[1], corners[2]);
>         normals[0].Normalize();
>
> ```

There is a subtle problem here, the two corner vectors that you are crossing are vectors that go from the origin to the corners. What you want to cross are two edges of the face (vectors that go from one corner to another corner). try:

```
Vector3 edge1 = corners[1] - corners[0];
Vector3 edge2 = corners[2] - corners[0];
normals[0] = Vector3.Cross(edge1, edge2);
normals[0].Normalize();

```

I assumed that corners 0, 1, 2 are all associated with the same face.

This may produce a normal that points in the wrong direction depending on how the corners wind. If you think the normal is pointing inward to the cube instead of outward, simply switch places of the edges in the cross function.

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


title: Node-Based pathfinding vs A* and others

text:
# Question
Title: Node-Based pathfinding vs A* and others
Whats the difference between node-based pathfinding algorithm and the A\* among others?

A friend just told me about node-based, but I cannot find much tutorial or information on it.

# Answer
> 10 votes
My AI is rusty, but it sounds like your friend is describing a common approach to defining the environment for the pathfinding: explicitly or algorithmically define a set of discrete nodes that agents can travel between in a network. Once you've got that node graph, you can run any algorithm you want on it, including A\*.

A\* can be run on a grid (which is really just a very regularly-spaced set of nodes) or a terrain mesh, too. Making a node graph is just a way to simplify a complex pathfinding situation by defining possible paths through an area.

Of course, there may be a definition of "node-based pathfinding" with which I am unfamiliar.

# Answer
> 6 votes
A\* *is* node-based. In fact, the only difference between A\* and depth-first, breadth-first, uniform cost and every other graph search algorithm is how they determine the next node to visit. Using a stack, queue, priority queue based on cost from start, and a priority queue based on cost from start plus estimated cost to goal yields DFS, BFS, uniform cost and A\* respectively.

Graph search algorithms, especially A\*, sound all mysterious until you grok what I said above - then they all become obvious. I plan to write a set of articles for my blog exploring this topic in depth.

# Answer
> 1 votes
Dijkstra's algorithm gives the correct answer on any grid of nodes, and exaustively finds the best route. If you have a small number of pre-populated nodes on your map (e.g. you placed them in your editor) then there are probably sufficiently few that it works fine.

On the other hand A\* uses a "distance function" (typically manhattan distance or something) to optimise Dijkstra's algorithm for the special case where you have a very large number of evenly spaced nodes, e.g. a grid - which is the normal case.

The A\* algorithm can find the best route in a grid with some caveats regarding weights. For example, if you place a few teleporters on an otherwise grid-like map, A\* can no longer work, as its "Distance funcion" doesn't give the right result, taking into account the teleporters.

But Dijkstra isn't efficient\** on a big open grid either, because the number of nodes you have to consider gets big quickly. Dijkstra's algorithm is like a flood-fill - it always touches all reachable nodes. A\* does not.

I'm not sure if this answers your question but I hope it helps.

\** For a given defintions of "efficient" and "big".

---
Tags: path-finding
---


# Question
Title: Is quake3/ioquake's OOP good to do a large game?
Everybody heard about the release of the Quake3 source code.

But since it's plain C but uses OOP a little, isn't it too complex to decipher or to use for large projects such as a 3rd person shooter/hack&slash with smooth camera movements ?

Would it be a good idea to use it instead of Ogre, I want to be sure it's really harder to use since it's only an engine dedicated to FPS.

Ogre seems to be a standard OSS, especially when thinking about OOP, but since I'm not looking for complex effects and since the rendering quality of quake3 seems to be good enough to me, I wanted to ask what did the release of the quake3 engine changed for open source developpers (except the infamous invsqrt method).

I heard Carmack released it for students or people alike, but C++ is here: is quake3's code obsolete compared to Ogre's when it comes to learning ?

# Answer
> 2 votes
If you want OO follow Ogre. Quake is more built for itself, messy, and seems like that had a tight deadline and didn't care about structure.

---
Tags: c++, c, quake3
---


# Question
Title: Tiled game: how to correct load background image?
i'm a newbie. I'm trying to develop a 2d game (top-down view). I would like to load a standard background, a textured ground... My "world" is big, for example 3000px X 3000px. I think it is not a good idea to load a 3000px x 3000px image and move it... So, how is the best practice ? To load a single small image (64x64) and repeat it for N times ? If yes, ok, but how i can manage the "background" movement ? Thanks Bye!

# Answer
> 2 votes
Use a Tiling Algorithm. Unless each pixel of your 36MB map is unique, you can break your map up into tiles. See the RPGMaker to get a feel for how it's done.

Then, you'll just need several small images, and a grid describing the map in 32x32 chunks. During a frameDraw, just draw the portion of the grid relating to what the screen around the character shows. It keeps memory down, and performance up.

# Answer
> 1 votes
It depends on your target display size.

On one end of the scale there's the "have everything on a single 3000x3000 framebuffer" approach. This is probably the fastest method (one single render call) but a framebuffer that big can cause problems.

On the other end of the scale there's the "draw every single tile individually" approach. This is memory-conservative, but requires a lot of render calls.

To me, the sweet spot is bundling the tiles on chunks that take rougthly half the size of the screen. The number of render calls is at worse 9, and the hardware should cope well with a texture size that is half the screen.

This way, for a PC screen with 1024x768 pixels, you will probably be ok with 512x512 textures, while for a mobile device with a 300x256 pixels, 256x128 should be ok.

# Answer
> 0 votes
I'd try to render images at the same size as the source image, so if that is truely the max size (and also the size of your .png or whatever) I'd render it as-is and be done with it (unless I saw noticable framerate drop by doing that).

If you do see performance problems, or you anticipate much larger imagery, you'd need to come up with a tiling scheme, which will determine which tiles of your map need to be on the screen and render them. One way to do it (maybe not the best) is to use a Tile class, then have an `array[x,y]` of tiles. Each Tile knows its realitive position on the screen and can react to user-input in order to move on the correct axis.

---
Tags: game-design, tiles
---


title: New to Game Development, need advice

text:
# Question
Title: New to Game Development, need advice
> **Possible Duplicate:**
> What are some good resources for getting a beginner started in developing games?

I'm a CS student, having plenty enough knowledge in programming, and general algorithms. What is your suggestion in game developing? How to start?

Thanks a lot!

# Answer
> 5 votes
Well, (if you don't already know one) the first step is probably learning a graphics API like SDL (C/C++), Pygame which is basically the Python binding of SDL (Python), or XNA (C#/.NET).

Probably the most important point is **start simple**. Don't try making a huge 3D MMORPG, like a lot of beginners do.

Here's a nice list of small, simple games to start with. The general idea is to get a feel of how to develop games specifically, rather than programming generally.

Here's a good list of resources which are worth checking on.

After that, work your way up from 2D to 3D. You'll need to learn OpenGL or DirectX, or one of the many engines and wrappers for different languages.

After that, run wild. As long as you know what you're doing, and it doesn't feel like you're diving in the deep end, you should be fine.

Good luck! :)

'Make Games Not Engines'. this ScientificNinja article is probably one of the most important things to read. (I frequent GD.Net) The amount of people I see, very often hardly being able to program, talking about having to make 'a general engine to do everything' is huge. They rarely get anywhere.

Another thing to mention, though is probably one of the most important things: **Take your game through to the end, that is finish it**. I for one have many half done game projects lying about, and as such you sort of forget about it and have little to say 'I achieved this' to other people and to motivate yourself.

# Answer
> 2 votes
Okay, you asked: learn everything you can about:

* 3D/4D matrices: rotation matrices, projection matrices, matrix inversion, matrix product...
* trigonometry and geometry: trigonometric circle, arc-functions, common properties of a circle, a square, a triangle etc.
* "Advanced OOP" in C++: virtual function and pure virtual function behaviors, and the classic STL containers: list, vector, but especially map.
* Design patterns: you can begin with the composite pattern, the factory pattern, observer pattern, prototype pattern, and of course the singleton pattern (which is more a language feature than a true DP).
* Optimization matters: how why when use references/pointers, the reason multiple inheritance can slow down, and other complicated stuff like where and how you should declare and use variables and your data.

Finally, do some little game on your won, you might have to do a classic game like tetris or pacman, but eitherway it will be hard to find a better idea of game.

# Answer
> 0 votes
I'd suggest starting with something small, probably 2d.

Also, I'd recommend using an already made engine or framework. Starting from scratch with OpenGL or DirectX is possible, but it will be daunting.

Also, make sure the engine you choose has a nice community behind it, so you can ask questions.

In summary, try LÖVE.

---
Tags: software-engineering
---


# Question
Title: Windows Class Library vs XNA Class Library
I'm going to start a library in C# for Navigational Meshes. I would like to use it in both WPF/Winforms and in XNA. Can I create a windows class library and still use it in XNA?

# Answer
> 2 votes
In short, yes. They're both just class libraries, the different templates just helps adding some default references.

Also see this Stackoverflow question and follow the advice in creating both types and running the resulting project files through your favorite diff tool for the details ^^

---
Tags: xna, windows
---


title: Where can I find a list of gameplays?

text:
# Question
Title: Where can I find a list of gameplays?
Long ago I found a website with a huge list of different gameplays; around 250 or so. I wanted to go back but right now I cannot find it (I've already spent some time on Google, believe me).

The site had a little picture with a brief explanation, that's all I remember.

I'd appreciate if anyone who rememebers the web site publish the link.

Thanks in advance.

# Answer
URL is: http://www.squidi.net/three/
> 4 votes

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


# Question
Title: How can I find out what URL my game is executing from in Flash?
I want to upload my game to Kongregate and other sites, but on Kongregate I want to invoke one function and other sites I want run another function. How to check in AS3 where (I want to get host like: www.kongregate.com or www.games.com etc) my game is? Or maybe you know other, better way to make this?

# Answer
> 4 votes
I found a post on how to site-lock flash movies/games here. It is the fourth post down. You can modify it slightly to make it do something or set any variables you need changed.

Here is the code from the post.

```
//Assuming you have a movieclip or sprite named myMovieClip (you can use any movieclip or sprite)
var URLofSWF:String = myMovieClip.loaderInfo.loaderURL;

//You will do some string methods to get domain name etc etc, it's up to you
var domain_parts:Array = _url.split("://");
var domain_parts_2:Array = domain_parts[1].split("/");
var domainOfURL:String = real_domain[0];

 //Then you compare the URL to any URL you wish to allow or disallow
if(URLofSWF == "http://www.google.com/mySwf.swf"){ // strict swf url checking
proceed();
}else{
stopEverything(); // Or inject some funny code to the stealer :P
}
// or
if(domainOfURL == "www.mysite.com"){ // domain checking only
    proceed();
}else{
    stopEverything(); // Or inject some funny code to the stealer :P
}

```

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


# Question
Title: Making sense of the Game State manager tutorial?
I have come across the Game State Managemnet tutorial at http://create.msdn.com/en-US/education/catalog/sample/game\_state\_management because I thought this would be a good place to start a game off.

I have added a new screen, but I am still a bit lost on how everything works. When I make my game, do I only need one more additional screen? just for gameplay? or should I have a different screen for each level?

# Answer
Just in case you missed it, there is a document (think its a html page) that outlines what it all does. Though you probably have already read this, and just need a brief overview.
> 4 votes

# Answer
Since it is most likely that the logic of your game will not change from level to level, rather it is the content that changes - map, characters, enemies - it doesn't make sense to create a new screen for each and every level.

Each new level screen will be almost identical to the previous ones except for maybe a few properties, fields, and the Initialization and LoadContent methods. Most of the fields, properties, and methods - such as Draw and Update - will not change.

Thus, it makes more sense to have one GameplayScreen and create something like Level and LevelManager classes to handle the switching from one level to another. If you want something even simpler, you can just have a method on the GameplayScreen that switches levels and handles the transition while switching.

My recommendation would be to go through the rest of the tutorials on the App Hub site or at least go through some of the labs or kits that actually document the creation of a full games using the Game State Manager. Labs are tutorials that take you through the creation process while kits are full games with lots of comments in the source that you can use as a building block for your own games.

The Role-Playing Game Starter Kit uses the Game State Manager and shows one possible level management solution. They create a master Session class that handles the game play and the switching of levels - or in their case switching Maps. Also, this kit uses a number of screens like ChestScreen, DialogueScreen, etc., which will give you a better understanding of what Screens are used for.

Also the Platformer Starter Kit is another game that shows how to work with levels, but doesn't use the Game State Manager. But, it wouldn't be hard to integrate their mechanism into a game that uses the Game State Manager.
> 4 votes

---
Tags: xna, c#, screen
---


# Question
Title: Sample Projects/Source for Navigational Meshes
Anyone aware of any sample source code that contain Navigational Meshes?

I'm aware of recast navigation (which is a little bit too complicated). - Written in C++.

Preferably C# but C++ is ok.

# Answer
> 2 votes
I haven't really used Navigation Meshes extensively yet, but from your reply, since you're only looking at how to generate the nodes and traverse it, I would do it the following way.

Firstly, to generate the nodes in the navigation graph, I'd iterate through all the quads in the mesh and add them to a graph appropriately.

E.g.

```
foreach quad in mesh
{
   add quad to graph
   if quad has neighbouring quads
      add neighbouring quads to the neighbour list of the added quad
}

```

That's a fairly simple brute-force method, but there's probably better methods out there.

To traverse the created graph simply make use of A\* (A\* Algorithm). This will give you a higher level path (a path from quad-to-quad).

Then to pathfind within each quad you can use a simple steering behaviours towards the next quad or even A\* again to find the shortest-path (if you've got obstacles in the way).

Not sure if that's been explained very well, but it's a very high level look at it.

Hope it helps.

Ray

---
Tags: path-finding
---


# Question
Title: Is there an open source sports manager project?
For a long time I've tried to search for an open source manager game, but without any luck. I'm looking for a suitable project for a reference to my own pet project. Features like well designed data model, tournament and fixture generation and understandable match simulation algorithm would be a great bonuses.

I'm especially interested in game projects like Hattrick and SI Games' Football Manager, although it is irrelevant what the particular sport is. The project should be preferably web-based as Hattrick is.

I've crawled through GitHub and SourceForge, but I found only a few sports simulation projects. Projects, which I have found, were either dead or not fulfilling my wishes.

Do you know any open source manager game / fantasy sports game project, which would be available as open source, OR at least any material, which would be useful when building a such project?

# Answer
Score OS came up on the google search. It's open source (Google code).
> 5 votes

# Answer
Bygfoot is a soccer management game

http://bygfoot.sourceforge.net/new/about/

(does not seem to be very actively developped, though ..)
> 2 votes

---
Tags: web, open-source
---


# Question
Title: Time based movement Vs Frame rate based movement?
I'm new to Game programmming and SDL, and I have been following Lazyfoo's SDL tutorials. My question is related to time based motion and frame rate based motion, basically which is *better* or *appropriate* depending on situations?. Could you give me an example where each of these methods are used?.

Another question I have is that, in lazyfoo's two Motion tutorials (FPS based and time based) The time based method showed a much smoother animation while the Frame rate based one was a little hiccupy, meaning you could clearly see the gap between the previous location of the dot and its current position when you compare the two programs.

As beginner which method should I stick to?(all I want is smooth animations).

# Answer
> 17 votes
What's being shown as "FPS based" there is . . . well, basically, it's awful. It's pinning the game's speed to the performance of one particular computer. If you upgrade to a nice fast computer, your game will suddenly run in turbo speed, if you downgrade to a slower computer you'll be grinding around in slo-mo.

The real choice is fixed time step vs. variable time step, and at that point I will defer to this excellent post which goes into great depth.

---
Tags: game-design, c++, motion-control, sdl
---


# Question
Title: How can I render fonts in a game with correct hinting?
I've used angel code's bitmap font generator quite a bit; though it's very good, I wonder if there would be a way to use the hinting information to provide a better and more readable result, by using hinting to provide differing thickness based on size/pixel coverage.

I imagine any solution would have to use the distance field tech presented in the valve paper on smoothing fonts while maintaining or reducing asset size. I haven't found any demos of it being used with hinting information turned on, or included in the field gradients in any way.

Another way of looking at this is whether there are any font bitmap generators that will output mipmaps that still maintain their readability in the face of pixel size. I think the lower mip levels would try to guarantee fill and space where it is necessary to maintain readability/topology over maintaining style/form; the point of hinting.

---

***Is there a reason you can't just render the size you want?***

The problem lies in the fact that font rasterisers currently don't render in 3D, and hinting information would be important in different amounts, due to the pixel density being different along different axes; even differing in importance along the length of a string, due to the size reducing over distance. For example, I only want horizontal hinting in a texture that is viewed from the side, and only really want vertical hinting in a font that is viewed from below or above. This isn't meant to be a renderer that tries to render a perfect outline as accurately as possible, as hinting distorts the reality of the font; instead, this is meant to be a rendering solution for static scenes, where the scenes use 3D transformed and warped text layout. In this case, the legibility is important; more important than the accuracy of representation of the polygon shape.

# Answer
> 2 votes
My only *good* suggestion is to try making the thresholds in the distance field technique a function of the desired character size or (somewhat equivalently) the ratio between the rendered size and the desired size. (I think this is mathematically equivalent to applying a non-linear filter when scaling.) That would drastically increase the cost of the fragment shader (though maybe not significantly in a real program), and you'd end up duplicating non-trivial code if you also wanted a fixed-function path.

Another possibility would be to average the distance field across many font sizes while generating it, which would get you the hinting information "in" the texture. However, usually the distance fields store between 32px and 64px per character. The cases where manual hinting truly benefits is at small (8-16px) font sizes. I don't know how much meaningful information there is to get from averaging something intended for ~8px with something intended for ~256px and storing it in ~32px.

Any other techniques I can think of require more memory, at which point you're really better off just rendering the fonts in the size you want, and using them as-is.

# Answer
> 1 votes
IANAL, but the hinting patents have recently expired. A TrueType implementation, such as FreeType should be usable with hinting enabled.

My group has built our own TrueType rasterizer, although I know several teams that are satisfied with the degraded quality found in the distance field technique (largely because they're using simple sans-serif fonts in simple situations such as subtitles and decals).

All that said, most fonts have crummy auto-generated hints in them. Stick to the major type houses or you'll just be looking at the output of FontLab.

Although we knew the hinting patents were expiring, we did not implement a bytecode interpreter because we felt that the small sizes where hints are most designed to help shouldn't be used on game consoles, which is what we target.

---
Tags: rendering, fonts
---


# Question
Title: Homebrew development for 7th gen home consoles
I'm looking to do some homebrew development for either the Wii, Xbox360 or PS3. I'll be developing from a Linux system. The programming language doesn't matter.

* Wii - devkitPPC and libogc look fairly easy and complete
* Xbox360 - Mono.XNA looks interesting but not very feature complete
* PS3 - psl1ght seems interesting but I haven't been able to find out much

How homebrew friendly are each of these consoles? Is someone able to give a comparison of each of these scenes?

# Answer
> 3 votes
Mono XNA will not run on the xbox, Its designed to allow windows XNA applications to run under mono/open gl rather than the .net runtime/direct x. Also,

Good luck running homebrew code that doesnt involve paying microsoft for an xna creators club membership on the xbox, Ive no idea about the other platforms as ive never looked into it.

# Answer
> 2 votes
I can only address the PS3.

The ps3chain and ps3toolchain distros referenced by ps3l1ght are unsuitable for use with Game OS; they do not implement the correct ABI and you will eventually crash as a result.

AFAIK, there are no working compilers available for PS3 that aren't simply stolen copies of the official SDK.

---
Tags: xbox360, playstation3, homebrew, wii
---


title: Calculating the force of an impact?

text:
# Question
Title: Calculating the force of an impact?
I'm trying to figure out a way to determine the force two objects collide in.

I have two vectors defining their linear velocity at the time of impact, their mass and their angular velocity. Keep in mind this is all for a 2D physics engine.

I don't think it's as simple as adding up these values and figuring out if it's large enogh it makes a large impact since that doesn't take into account if the two objects are travelling in the same direction (as an example).

Any ideas?

# Answer
> 4 votes
High school physics should do the trick here, preserve total energy (unless you want energy to dissipate into friction, heat and deformation) and preserve total momentum, which will give you the result of the impact. Adding rotation to the equation makes it a bit more tricky (although not so much in 2D), preserving angular momentum as well, do you want to go there?

Actually getting the force which is applied, you need to look at the characteristics of the impact, the most simple assumption is that the force is constant during the impact, in which case, the force is the change in momentum (known as the impulse) divided by the duration of the impact.

Do you really want to know the applied force (useful for damage models, but rarely for simple physics), or are you just looking to determine final velocities?

---
Tags: physics
---


title: Slick 2D first trial error

text:
# Question
Title: Slick 2D first trial error
I followed some advices to learn Slick2D and when I started doing the "SimpleGame" I got my first error. Does anyone have any idea of what is it and how to fix?

```
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:Slick Build #274
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:LWJGL Version: 2.0b1
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:OriginalDisplayMode: 1024 x 768 x 16 @60Hz
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:TargetDisplayMode: 800 x 600 x 0 @0Hz
Sun Dec 26 23:09:12 GMT-03:00 2010 ERROR:Could not find a valid pixel format
org.lwjgl.LWJGLException: Could not find a valid pixel format
 at org.lwjgl.opengl.WindowsPeerInfo.nChoosePixelFormat(Native Method)
 at org.lwjgl.opengl.WindowsPeerInfo.choosePixelFormat(WindowsPeerInfo.java:52)
 at org.lwjgl.opengl.WindowsDisplayPeerInfo.initDC(WindowsDisplayPeerInfo.java:54)
 at org.lwjgl.opengl.WindowsDisplay.createWindow(WindowsDisplay.java:158)
 at org.lwjgl.opengl.Display.createWindow(Display.java:299)
 at org.lwjgl.opengl.Display.create(Display.java:848)
 at org.lwjgl.opengl.Display.create(Display.java:800)
 at org.newdawn.slick.AppGameContainer.tryCreateDisplay(AppGameContainer.java:299)
 at org.newdawn.slick.AppGameContainer.access$000(AppGameContainer.java:34)
 at org.newdawn.slick.AppGameContainer$2.run(AppGameContainer.java:364)
 at java.security.AccessController.doPrivileged(Native Method)
 at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:345)
 at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
 at SimpleGame.main(SimpleGame.java:38)
Exception in thread "main" org.newdawn.slick.SlickException: Failed to initialise the LWJGL display
 at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:375)
 at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
 at SimpleGame.main(SimpleGame.java:38)

```

# Answer
> 2 votes
Did a quick Bing search and got the following forum post and another one. Note that the problem is `Failed to initialise the LWJGL display` and according to both forums this could be fixed by adding the following line:

```
-Dorg.lwjgl.opengl.Display.allowSoftwareOpenGL=true

```

to the `VM Arguments` of your IDE. I am not a Java developer, so I am not sure if this is the best way to do this.

# Answer
> 0 votes
I am totally unfamiliar with Slick2D, but it looks like you're requesting a 800x600 fullscreen resolution when your monitor / video card only supports 1024x768.

---
Tags: java, slick
---


# Question
Title: Civilization 4: time in own scenario runs up too quickly
In Civilization 4 (Beyond the Sword) I started making a scenario that focuses on the colonization of North America. For added realism, I set the `StartYear=1780`.
Everytime I run the scenario, the time runs up far too quickly–probably because I set `Era=ERA_ANCIENT` and `GameTurn=0`–so that after just twenty turns the clock nears present day.

I'm not really sure how to go fix this, other than by playing an actual marathon game from the start up to the year 1780 and copy over the values.

Is there any way to calculate/know the right values for my scenario?

# Answer
> 2 votes
You will want to open your worldbuilder save file, which by default is in

```
YourInstallDirectory\Sid Meiers Civilization IV\PublicMaps\

```

Open it with notepad or a similar program. You will probably want to set it to

```
Era=ERA_RENAISSANCE

For Calendar=: "The Calendar setting is used to determine the length in time of
each turn in the scenario.  By default the calendar is set to default which
means the scenario will use the same turn length time as the normal game.
Valid options include CALENDAR_YEARS (each turn is one year),
CALENDAR_SEASONS (each turn is one season: Winter, Spring,
Summer, Autumn), CALENDAR_MONTHS (each turn is one month)
and CALENDAR_WEEKS (each turn is one week, with four weeks to the
month)."

```

Read more about the world builder.

---
Tags: modding
---


title: Algorithm to make groups of units

text:
# Question
Title: Algorithm to make groups of units
In Age of Mythology and some other strategy games, when you select multiple units and order them to move to some place, they make a "group" when they reach the desired location:

I have a Vector with several sprites, which are the selected units, the variables `tarX` and `tarY` are the target x and y. I just want an example, so you can just set the x and y position and I can adapt it to my code. Also, I would like to ask that the algorithm calls "isWalkable" for the x and y position, to determine if it's a valid position for each unit.

# Answer
What you're looking for is basically coordinated movement. The units pathfind to their destination and when they reach it, they form a "formation".

This is a topic decently covered in the AI Game Programming Wisdom (Book 1, Book 2, Book 3 and Book 4) books. But, I'll refer you to the following articles:

Coordinated Movement \- A link explaining the fundamental principles of coordinated unit movement in RTS games

and

Implementing Coordinated Movement \- An article continuing from the first, that talks about how to implement this type of movement in a game.

It's written in C++ but it shouldn't be too difficult to port to any other language, as the underlying principles remain the same.

Hope that helps.

Ray
> 5 votes

---
Tags: algorithm, actionscript-3, strategy
---


title: Smooth terrain rendering

text:
# Question
Title: Smooth terrain rendering
I'm trying to render a smooth terrain with Direct3D. I've got a 50\*50 grid with all y values = 0, and a set of 3D points that indicate the location on the grid and depth or height of the "valley" or "hill". I need to make the y values of the grid vertices higher or lower depending on how close they are to each 3D point. Thus, in the end I should have a smooth terrain renderer.

I'm not sure at all what way I can do this. I've tried changing the height of the vertices based on the distance to each point just using this basic formula:

```
dist = sqrt(a² + b² + c²)

```

where a, b and c are the x, y, and z distance from a vertex to a 3D point. The result I get with this is not smooth at all.

I'm thinking there is probably a better way.

Here is a screenshot of what I've got for the moment: https://dl.dropbox.com/u/2562049/terrain.jpg

# Answer
> 4 votes
Is there something special about these 3D points because it sounds like you are just trying to render a heightmap. Doing a bunch of distance calculations to an arbitrary number of 3D points is not the best way of doing that.

Here is a simple DX9 tutorial on rendering a heightmap.

The basic concept is that you have a 2D image that represents displacement. So the pixel (X,Y) location corresponds to a vertex (X,Z) and the color of the pixel represents a height value (Y) for the vertex.

The nice part about using an image is that it's very intuitive for the developer to visually create and or modify the terrain.

EDIT: Looked at the screenshot. It seems to be working to me, I assume you aren't happy with the falloff of the effect? Smooth at the ground level and then a spike at your 3D point.

If you took any of your mountains/valleys and imagined them in 2D and cut them in half you'd see a curve that looks like the one on the left and I'm guessing you want one that looks like the curve on the right.

Instead of looking for the 3D distance to your 3D point I suggest look at the 2D distance ignoring the height. Then for every vertex within some predetermined falloff, apply the height to your vertices based on a ease in/out curve.

# Answer
> 2 votes
If you're looking to create smooth rolling hills you can use the box-filtering method. Be warned though, if you want sharp cliff edges, the method will just smooth those out.

Here's the link to it on GameDev.net: Box Filtering for Smooth Rolling Hills

The code assumes you're using a heightmap, but from your solution an easy change to make is just to iterate through the list of 3D points (mapping those 3D points to the appropriate vertex, as you are doing now).

---
Tags: c++, directx, terrain-rendering
---


# Question
Title: Who know how to implement the 2D bone animation showed in the game?
I wonder how do they implement the bone animation in the flash game http://www.foddy.net/athletics.swf Do you know any study materials which I can start to learn 2D bone system from? I just implemented a avatar system by compose multiple bitmaps in each frame(similar with maple story), but some guys tell me that, a bone system can save more art resources, so I want to learn some thing about that.

# Answer
> 7 votes
I'm pretty sure the bones/joints in QWOP (the game you're referring to) are modeled using the Flash Port of Box2D. By pressing the buttons you apply forces to these joints and make the character move *eventually*.

On the Box2D page you'll also find ragdoll examples that might serve as a starting-point for your characters. You should be aware that creating animations using such a setup (eg. using a physics-engine and apply forces to joints) can be *very* complicated and might not yield the desired results.

If you just need a "skinnable" avatar, it would probably be simpler to use pre-animated characters. You can use the bones-system of Flash for this and replace the different MovieClips (eg. upper leg, lower leg etc.) at runtime to get some sort of skinning.

**Update:** I created a very basic example how you could easily change the appearance of an animated character (click to change skin, sorry for crappy art). Source file is here. Different skins are on different frames. You could most likely extend this concept to dynamically load new skins though.

---
Tags: physics, skeletal-animation
---


# Question
Title: ATI driver bug and rendering to a texture 2d array in OpenGL
I am trying to render to a `texture2Darray` in OpenGL, with a similar setup as descriped in this post. My question is, if anyone has gotten this to work on ATI hardware? Or is there still a bug in the driver, preventing multi layered rendering? The bug is also mentioned in the forum post.

# Answer
> 1 votes
Curious. The extension in question seems to be gl\_ext\_texture\_array.

According to the OpenGL extensions viewer 3.34 database, that should be supported by a wide variety of ATI hardware, and even one S3 chip too. The only discussion about it that I could find was http://forums.amd.com/devforum/messageview.cfm?catid=392&threadid=120024&enterthread=y where nobody answered the question, but there seem to be some issues. Judging from that thread, the issue seems to be related to clamping; you may want to try with the wrap mode instead.

---
Tags: opengl, graphics-programming
---


title: Tools for game script / storyboard

text:
# Question
Title: Tools for game script / storyboard
I am searching for a tool that will help in writing a game script. By "script" I mean the text core of a storyboard - without the drawing drafts, which may or may not be there (yet).

What I'm thinking of will let write a piece of text of the script, define a simplified workflow from that step, and then define the text of next steps, and so on.

Searching online, I found Inform http://inform7.com/ ("A Design System for Interactive Fiction Based on Natural Language") which in theory is exactly what I am searching for, but trying to use it it has this model of a space (a dungeon, a library) where you are picking up objects and exploring them. In my case I am designing more a Sims like game, the flow is entirely different.

Considering non specific software, mind mapping tools miss the linearity of the process. What I am writing is a directed graph - simply a work-flow, but the way I want to design it is more text based than work-flow based.

SO what I'm doing now is using a text editor, which I'll transform directly in code.

Any suggestions?

# Answer
Sorry for the late and self-answer, but I found a tool that fits perfectly the original description (in particular: "What I'm thinking of will let write a piece of text of the script, define a simplified workflow from that step, and then define the text of next steps, and so on." and being not just focused on exploration) as it is centered mainly on dialogue between characters (also allows exploration): its called Chat Mapper.

Unfortunately it runs only on windows systems, but is not too hard to use and quite complete:

http://www.chat-mapper.com/

The installer is a bit bugged, if after installation it doesn't start, check out the forum, you may need to update a DLL.
> 1 votes

# Answer
I googled 'directed graph software', but most of them seemed to work from C++ or Java, and not exactly what you wanted, which I'm taking is a script/storyboard tool for a non-programmer.

Graphiz seems like it would work well with what you want:

> The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)

You could still write your scripts into text files (use the nicest processor you can find, Notepad++ maybe?) and then export them into a format you and any future co-workers would be able to digest and scan easily.
> 4 votes

# Answer
It looks like Celtx might be lean more towards what you are looking for. Free media preproduction suite that focuses on script writing, storyboarding, etc... I used it for one of my game script writing classes a while back and was pretty happy with the workflow and results.
> 3 votes

---
Tags: tools, storyboard
---


title: car crash android game

text:
# Question
Title: car crash android game
I'd like to make a simple 2d car crashing game, where the player would drive his car into moving traffic and try to cause as much damage as possible in each level (some Burnout games had a mode like this).

The physics part of the game is the most important, I can worry about graphics later. Would engine like emini or box2d work for this kind of game? Would Android devices have enough power to handle this? For example if there were about 20 cars colliding, along with some buildings, it would be nice if I could get 20 fps.

# Answer
> 2 votes
I assume this is a top down game.

I've not tried Emini, but Box2D (or Chipmunk) isn't really suited to this as they are generally geared to side on views. There is an article on GameDev that might be of some use.

I have seen some examples of faking it with box2D but the hacks they used meant things like skidding where out the question.

I think Android devices should be able to handle it, it all depends on your implementation and graphics, sounds etc. however Android is becoming fragmented a little and it could be a problem on some devices.

**EDIT:** As pointed out by bummzack, b2FrictionJoint exists for top down, I did a quick search and couldn't find anything else about Box2D and top down.

---
Tags: physics, android
---


title: How to achieve a Neon-Light effect?

text:
# Question
Title: How to achieve a Neon-Light effect?
I'm wondering how to achieve a neon-light type effect. For example, in Pac-Man Chamipnship Edition:

Or in Geometry Wars:

Is that a Bloom Effect? Or what techniques would I have to look for?

# Answer
> 13 votes
Here you go :)

GPU Gems - Glow Effect

With that many entities with a glowing effect on the screen (especially in Geometry Wars), it's more often than not a shader effect that's similar to the shader described in that paper.

# Answer
> 6 votes
You may not even need a full-screen bloom/glow effect (remember that this sort of effect is quite GPU-intensive, particularly if you're making a 2D game and want to avoid high system requirements)

First, try just rendering your sprites with additive blending - with a blending equation such as:

(SRC\_COLOUR * SRC\_ALPHA) + (DST\_COLOUR * ONE)

Then bake the glows into your sprites (or render them as additional additive sprites - to create a 'glow sprite', just blur your original sprite using a gaussian blur filter in whatever paint package you use)

Of course, this approach has some limitations - the adding-up of overlapping sprites may be undesirable, and would be avoided by using a full-screen bloom/glow effect

# Answer
> 2 votes
There are two ways of achieving this;

The top one (at a guess) just uses semi-transparent images.

The bottom one more complicated (again a guess) plays with buffers to create the glow (bloom) effect.

---
Tags: 3d, graphic-effects, special-effects, bloom
---


title: algorithm to "explode" mesh

text:
# Question
Title: algorithm to "explode" mesh
i have a simple triangle mesh which i want to explode. so i am looking for an algorithm that makes every triangle to move outwards from the centerpoint. is there already something premade like this?

thanks!

# Answer
> 1 votes
You may want to check this out:

http://www.cgafaq.info/wiki/Half\_edge\_general

http://en.nicoptere.net/?p=960

# Answer
> 4 votes
Look into particle physics. Each vertex would be set up as one particle per triangle it is a part of and each would be pushed away from the explosion point using whatever force you want. To keep the triangles from warping as the particles move, add stick constraints for each edge (they're described in the article linked above). When the constraints are resolved, it will modify the particle movement and cause the triangles to move independently, flipping and rotating as they go.

---
Tags: 3d, 3d-meshes
---


title: Which game portals support Unity games?

text:
# Question
Title: Which game portals support Unity games?
I'm considering development of some simple Unity games but am worried about distribution. Which well known game portals currently support unity?

# Answer
Large community wiki list of that answer here: http://answers.unity3d.com/questions/7558/which-game-portal-websites-accept-unity-webplayers.html
> 5 votes

# Answer
we accept unity games and host them for free on www.tinyutopia.com. You can find submission information on our main page.
> -1 votes

---
Tags: unity, support
---


# Question
Title: what is the most popular mmorpg game that has an out-of-game api?
World of Warcraft is off the table, because of the "WOW Glider Lawsuit" of 2008. Also see: Where is Blizzards official World of Warcraft API? Eve Online has an API

But, what is the MOST popular (in terms of usership) MMO Game that does allow programmers to develop out-of-game things (like an Android app).

# Answer
WoW does have an external API with the Armory. It is read only through. Unless you access the pages with a bad browsers, it returns a clear xml structure. According to various blue forums posts, automatic querying of those pages is okay, unless too many requests are sent.

The Glider Lawsuit was about a bot that linked to the original game client in memory. It is pretty obvious that bots are bad for business because a) players spent less time paying while leveling up and b) other players get frustrated and may leave.
> 6 votes

# Answer
Everquest had an instant messaging protocol that allowed communication with in-game players from outside the game. I am unsure if the protocol was well documented or supported by any third party clients.
> 3 votes

# Answer
EVE Online's Web API is read-only. It's only to monitor character skils/inventory assets/assets and states of various in-game structures,etc There are ways to get actual control of EVE(control your ship,actually manage said in-game structures,etc) but they are against EULA and basically works like WoW Glider
> 2 votes

---
Tags: mmo
---


title: 2D graphics with Direct3D

text:
# Question
Title: 2D graphics with Direct3D
I'm trying to work with 2D graphics using Direct3D 9, but am not sure where to start. Right now I'm using a texture as the "draw buffer", and drawing that texture to screen. For the simplest things, it works. But I can't see a way to e.g. draw lines, arcs, and the like onto the texture. How should I go about doing this?

# Answer
**The GDI approach:**

* Create a bitmap and a device context
* Render your 3d graphics into the bitmap using GDI
* StretchBlit the bitmap onto the texture

**The Pixel approach:**

* Lock the texture and fill the pixels using e.g. Bresenham's algorithm.

**The Render approach:**

* Use DrawPrimitiveUP with D3DPT\_LINELIST or D3DPT\_LINESTRIP for drawing lines.
* Arcs, circles and other curved shapes can be composited from lines.
* For filled shapes generate meshes using D3DXCreateShpere/Box/Torus etc. and render those using orthographic projection. You'd use a sphere mesh to render filled circles, a box mesh for filled rectangles and a torus would allow for curved shape outlines.
> 6 votes

# Answer
Use Sprites in Direct3D 9. Very simple way of creating 2D objects in a 3D space.

There's a tutorial here: Sprite Tutorial

I've used sprites to create a 2D HUD in my 3D games and they turn out pretty well.

To draw lines, just use the D3DPT\_LINELIST or D3DPT\_LINESTRIP primitives with DrawPrimitive().

Drawing Arcs might be a little bit more difficult. You could look into drawing Bezier curves for that: Bezier Curves
> 3 votes

---
Tags: 2d, directx, directx9
---


# Question
Title: Sending changes to a terrain heightmap over UDP
This is a more conceptual, thinking-out-loud question than a technical one. I have a 3D heightmapped terrain as part of a multiplayer RTS that I would like to terraform over a network. The terraforming will be done by units within the gameworld; the player will paint a "target heightmap" that they'd like the current terrain to resemble and units will deform towards that on their own (a la Perimeter).

Given my terrain is 257x257 vertices, the naive approach of sending heights when they change will flood the bandwidth very quickly - updating a quarter of the terrain every second will hit ~66kB/s. This is clearly way too much.

My next thought was to move to a brush-based system, where you send e.g. the centre of a circle, its radius, and some function defining the influence of the brush from the centre going outwards. But even with reliable UDP the "start" and "stop" messages could still be delayed. I guess I could compare timestamps and compensate for this, although it'd likely mean that clients would deform verts too much on their local simulations and then have to smooth them back to the correct heights. I could also send absolute vert heights in the "start" and "stop" messages to guarantee correct data on the clients.

Alternatively I could treat brushes in a similar way to units, and do the standard position + velocity + client-side prediction jazz on them, with the added stipulation that they deform terrain within a certain radius around them. The server could then intermittently do a pass and send (a subset of) recently updated verts to clients as and when there's bandwidth to spare.

Any other suggestions, or indications that I'm on the right (or wrong!) track with any of these ideas would be greatly appreciated.

# Answer
> 3 votes
I don't know why you think you should use UDP. A RTS or similar can benefit from running the simulation consistently on all nodes, which means that the ordering of messages is vital to avoid going out of sync. This means that you need to essentially do everything that TCP does anyway, so using UDP is not necessary.

So you'd typically have the stream being a sequence of commands. Or rather, a stream of "tick" messages each containing a command-list. The command-list would be executed, in sequence, by each node playing the game (and the server). Provided the simulation is deterministic, nobody would be out of sync.

You can certainly extend that to a height map modification. So for example, you have a type of unit which has a command called "do some terraforming", in which they modify the map in a specific way, over the subsequent ticks. No data need be transferred *at all* except for the initial command, as the consistent simulations on each node will take care of terraforming their own height maps in a completely consistent way.

Note that to do this kind of approach, the player's actions (clicking widgets in the UI which have some effect, or commanding individual units / groups of units) need to be sent to the server, NOT EXECUTED LOCALLY. The server will then receive them at some point, and insert them into the tick-stream at an appropriate point, at which point they then take effect.

But as RTS are basically not very time critical, this won't matter in the slightest. The player will hardly notice any lag.

---

This is possibly not the only strategy for running a simulation game, but it is one which has been used by several games and works pretty well (if your code is bug-free).

In summary:

* Each client starts with a consistent world view, which they download from the server as a bulk download when they connect or at the start of the game
* Simulation happens in a series of ticks, which are fixed-timestep and completely deterministic ("random" events need to be pseudorandom seeded in a consistent way on all clients)
* The client only ever sends commands which change behaviour or carry out actions to the server; it does not execute them locally.
* The server sends a sequence of commands per tick to each client, in the order it expects to execute them, and also executes them locally.

You can use TCP for this, because it's extremely dependent on the reliable, in-order delivery of messages, which is what TCP works well at.

This system sends very little data over the network, because the amount of data generated by a player is essentially limited by how much they can click the mouse (or whatever), NOT how many tanks, troops etc, they have.

No messages change hands to indicate that a unit who was already doing something, is continuing. Or indeed, anything which happens autonomously. Entire battles can take place without a single message (except "tick" timestamps) changing hands (assuming all the players are happy to sit back and watch).

# Answer
> -1 votes
Regarding the data you are sending, you could "pack" data together since all you need to send is the new height and the index of the vertex in the buffer, you could pack both of these in an int or a long depending on the max/min values of the vertex positions. Still, that won't solve the problem, since, even if you are sending less data, you are still sending data that may not get to the client side, so would need a way to reliably send the data over but without killing the bandwidth. IMHO using client side prediction with you "brush-based system, is a good idea, that way you can send less data, less often.

---
Tags: networking
---


title: RTS on a 3D map e.g. a globe

text:
# Question
Title: RTS on a 3D map e.g. a globe
How can you 'tile' a 3D globe if your existing artwork and maps are simple 2D grids?

Are there approaches that can re-use much of the artwork and such?

# Answer
> 6 votes
I've built something like what you're looking for. I used this site mostly as a reference for the map build process. BUGS Geodesic Map

The basic steps:

* Create an icosahedron. Each 'cell' will be one of the vertices on the mesh. Subdivide to desired resolution.
* Treat each icosahedron vertex as the cell center - the geogrid's cell vertices are the midpoints of each icosahedron triangle face.
* Using the indices of the icosahedron mesh, you can lookup cell neighbors and built up their correct order - this will let you build the cell faces correctly.
* You will have 12 pentagons and the rest will be hexagons - there's no way around this.
* Some people I've seen like to try and convert down to a 2d grid (examples of the process on the BUGS site), and it's possible. I never did this because it's hard and can be worked around.

In mine, the whole grid is one giant mesh, not repeated cell models (http://blog.chronoclast.com/search/label/OTD). For lower mesh resolutions this runs okay. If you're looking at tens of thousands of cells, you'll want to explore more dynamic mesh building - mine is all pre-built. Cells are textured off a page-map (2/9/16... textures per image) and can blend uv's (that was hard, took forever, still kind of meh).

# Answer
> 2 votes
Here are a couple of articles from Spore

Creating Spherical Worlds

# Answer
> 1 votes
Our game "Save Us!" used that. It is pretty fun to have rts on planet and control it. Save us gameplay (but the game is not fun at all :-))

Save Us! Uses regular 2D heightmap which is transformed to a sphere. It is easy to do, but has problem on sphere's poles. We just have there ocean. Not really nice solution, but works. Problem of non rectangular tiles is not big. It looks quite ok. For determining which tile is clicked we use color picking.

This is old project and the solution is not the best, but it is very very easy and quite good looking.

Much better solution should be usage of **icosphere**.

---
Tags: 3d, maps
---


title: 3D Ray Casting / Picking

text:
# Question
Title: 3D Ray Casting / Picking
I am not sure if I should post this link, but I feel this falls into game development just as much as it does math. I have a ray cast's far and near values and I am trying to calculate the end point of the ray so that I can either draw a line to show the ray, or render an object at the end of 3d mouse position.

Here is my post on the stack overflow math site, if there is a problem with me doing this just close the thread. Thank you. https://math.stackexchange.com/questions/15918/help-with-matrix-mathematica

# Answer
I think that you don't know 3D position of the clicked point, because otherwise it would be easy :).

So if you know 3D position of the clicked point in origin basis then you can calculate far and near points like this:

```
nearPoint3D = cameraposition3D
farPoint3D = cameraposition3D + (normalize(clickedPoint3D - cameraposition3D) * zFar)

```

The problematic part is `clickedPoint3D`. You can compute it nicely with help of view and projection matrices. As you are using opengl i suppose that you have them. view * projection matrix converts 3D points to the 2D screen space. You can use inverted viewprojection matrix and get matrix which converts 2D screen points to the 3D space.

```
pseudo code and some openGl:

//define matrices
Matrix4x4 g_CameraViewMatrix;
Matrix4x4 g_CameraProjectionMatrix;

//read projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(...); //your perspective function
glGetFloatv(GL_PROJECTION_MATRIX, &g_CameraProjectionMatrix.m[0]); //returns matrix as float array

//read view matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLookAt(...); //you lookat function or whatever - NO translation,rotations or anything else for getting camera matrix!
glGetFloatv(GL_MODELVIEW_MATRIX, &g_CameraViewMatrix.m[0]);

//compute 3D position of clicked point
Matrix4x4 viewProjInv = (g_LightViewMatrix * g_CameraViewMatrix).getInverse();
vector4D clickedPointOnSreen = (x_screen,y_screen,1.0f,1.0f); // Z have to be between 0 - 1 and W have to be 1
vector4D clickedPointIn3DOrigin = viewProjInv * clickedPointOnSreen;
vector3D clickedPoint3D = clickedPointIn3DOrigin.xyz;

```

Note that you can use this to compute 3D points of zNear and zFar really easily:

```
vector4D clickedPointOnSreen = (x_screen,y_screen,1.0f,1.0f); // will produce 3D position of zFar
vector4D clickedPointOnSreen = (x_screen,y_screen,0.0f,1.0f); // will produce 3D position of zNear.

```

**Isn't that algebra wonderful? :)**

To learn something about projection matrix you can read this what-is-the-purpose-of-the-canonical-view-volume
> 12 votes

---
Tags: 3d, camera, raycasting
---


title: Looking for a good actionscript 3 book

text:
# Question
Title: Looking for a good actionscript 3 book
I've been looking for a book on actionscript3 development, but while there's tons of books out there, nobody seems to want to recommend any specific one.

One book I've been pointed towards is the cookbook by o'reilly, but it, like most books out there, seems to be based on the assumption that I'm using flexbuilder or flash. Instead, I'm "just" using flashdevelop, or the free SDK directly.

I've also been told to just go with the api reference and live with it. I could do that, I suppose, but I'd rather have a book that gives me the big picture. Kind of like with cocoa, there's the hillegrass' book, or the red book of OpenGL.

So, what would be **the** actionscript3 book out there?

# Answer
> 2 votes
**Foundation ActionScript 3.0 Animation: Making Things Move!** is an excellent book covering ActionScript 3.0 from a programmer's perspective focusing on game or animation programming. Lots of practical examples in topics like velocity, acceleration, friction, easing, collision detection, rotation, basic physics, particles, and forward/inverse kinematics. I'd highly recommend it.

ActionScript 3.0 Animation on Amazon

# Answer
> 2 votes
A good book to read if you want to get up to speed with AS3.0 is Essential ActionScript 3.0 by Colin Moock. However it's not game related, it covers the "entire" AS3.0 language.

For topics that are more gamedev related, as Bob Somers points out, Foundation ActionScript 3.0 Animation: Making Things Move is pretty neat!

http://www.friendsofed.com/book.html?isbn=1590597915

There is also the follow up to that book, AdvancED ActionScript 3.0 Animation, it covers a little more in depth topics, and is a great read too.

<sub>(source: friendsofed.com)</sub>

http://www.friendsofed.com/book.html?isbn=1430216085

---
Tags: actionscript-3, books, flashdevelop
---


title: Soft body, where to start learning?

text:
# Question
Title: Soft body, where to start learning?
I want to ask you about some resources to learn simulating soft bodies, do you know some good knowledge sources?

I asking because I want to make car crash simulator, I've made something but it didn't work well. :/

# Answer
> 8 votes
These might help:

http://cg.skeelogy.com/?download=SoftBodyPhysicsTutorial

http://en.wikipedia.org/wiki/Soft\_body\_dynamics

I also used some verlet integration once to do some pretty simple soft body physics. I know verlet I used more for rigid body physics, but by making the constraints a little more slack, It seems It can be used for some soft body stuff.

http://www.google.com/#hl=en&q=soft+body+verlet&fp=9bef8cda26d1a6ec

Hope it helps.

---
Tags: physics, simulations
---


# Question
Title: Development platform for 2D web and mobile games
Is there a game development platform -- similar to Torque, or Unity -- which can be used to deploy 2D games on the following platforms:

* Web
* iOs
* Android
* Xbox Live Arcade (Preferred but not required)

And which has an integrated or mature physics engine? Perhaps, even a built in editor?

I've looked at the following possibilities but I've found something missing in each one. Of course in each case I may be guilty of misconception.

* Corona SDK (No web deployment, no windows support)
* Torque 2D (No web deployment)
* Flash + Flash Punk or Flixel (No native android deployment, and I'm not sure if it is stable on mobile platforms)
* Unity + SpriteManager2 (Not really optimised for 2D games, and I haven't seen enough advanced 2D examples -- like say platformers -- to really have any confidence in using it for something like this)

Has anyone had any luck with this?

# Answer
> 2 votes
Just use Unity. At worst you could write your own sprite management solution and you'll get the platform deployment you want. The only other real solution is writing your own, but that's hardly a solution.

# Answer
> 1 votes
Cocos2d may be an option. There are some recent projects for it that have ported the API to most of the platforms you've specified aside from XBLA. It won't be a write-once, run anywhere sort of thing though. You'll need to convert it to the language for each platform, unless you use the C++ port but that won't get you on the web.

I've only used the iOS version, but it has Box2D packaged with it for physics. I'm not sure about its integration on other platforms.

---
Tags: 2d, physics, mobile, web
---


# Question
Title: Follow point of interest by applying torque
Given a `body` with an orientation angle and a point of interest or `targetAngle`, is there an elegant solution for keeping the `body` oriented towards the point of interest by applying torque or impulses?

I have a naive solution working below, but the effect is pretty 'wobbly', it'll overshoot each time, slowly getting closer to the target angle - an undesirable effect in my case. I'd like to find a solution that is more intelligent - one that can accelerate to near the target angle then decelerate and stop right at the target angle (or within a small range).

If it helps, I'm using box2d and the `body` is a rectangle.

```
def gameloop(dt):
    targetAngle = get_target_angle()
    bodyAngle = get_body_angle()
    deltaAngle = targetAngle - bodyAngle
    if deltaAngle > PI:
        deltaAngle = targetAngle - (bodyAngle + 2.0 * PI)
    if deltaAngle < -PI:
        deltaAngle = targetAngle - (bodyAngle - 2.0 * PI)
    # multiply by 2, for stronger reaction
    deltaAngle = deltaAngle * 2.0;
    body.apply_torque(deltaAngle);

```

One other thing, when body has no linear velocity, the above solution works ok. But when the body has some linear velocity, the solution above causes really wonky movement. Not sure why, but would appreciate any hints as to why that might be.

# Answer
From what I've understood from your post, this is essentially an Arrive behaviour. Arrival is a fairly simple behaviour to implement, and you don't have to use angles to get an angle back either.

```
Vector toTargetVector = targetPosition - bodyPosition;
double distanceToTarget = toTargetVector.Length();

// It's very simple to get the angle from here, just use atan2 (or the equivalent function in whatever language you're using)
float angleToTarget = atan2( toTargetVector.y, toTargetVector.x );

if( distanceToTarget > 0.0 )
{
    double rateOfDeceleration = 0.2;    // This can be tweaked to whatever value you like
    double speed = distanceToTarget / rateOfDeceleration;

    Vector desiredVelocity = ( toTargetVector * speed ) / distanceToTarget;

    return ( desiredVelocity - body.velocity );
}

```

This behaviour (among the rest of them) is very clearly detailed in Mat Buckland's book "Programming Game AI by Example".

If you want a very, very simple behaviour just to get your target angle correct then use Seek.

```
Vector toTargetVector = targetPosition - bodyPosition;

double distanceToTarget = toTargetVector.Length();

float angleToTarget = atan2( toTargetVector.y, toTargetVector.x );

```

And that's basically it, you can then do all your physics stuff after this basic vector stuff.

Hope that helps.
> 2 votes

---
Tags: mathematics, physics, orientation
---