# Question
Title: How can I implement voxel-based lighting with occlusion in a Minecraft-style game?
I am using C# and XNA. My current algorithm for lighting is a recursive method. However, it is *expensive*, to the point where one 8x128x8 chunk calculated every 5 seconds.

* Are there other lighting methods that will make variable-darkness shadows?
* Or is the recursive method good, and maybe I am just doing it wrong?

It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls.

My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re-adding sunlight and torchlight.

`world.get___at` is a function that can get blocks outside of this chunk (this is inside the chunk class). `Location` is my own structure that is like a `Vector3`, but uses integers instead of floating point values. `light[,,]` is the lightmap for the chunk.

```
    private void recursiveLight(int x, int y, int z, byte lightLevel)
    {
        Location loc = new Location(x + chunkx * 8, y, z + chunky * 8);
        if (world.getBlockAt(loc).BlockData.isSolid)
            return;
        lightLevel--;
        if (world.getLightAt(loc) >= lightLevel || lightLevel <= 0)
            return;
        if (y < 0 || y > 127 || x < -8 || x > 16 || z < -8 || z > 16)
            return;
        if (x >= 0 && x < 8 && z >= 0 && z < 8)
            light[x, y, z] = lightLevel;

        recursiveLight(x + 1, y, z, lightLevel);
        recursiveLight(x - 1, y, z, lightLevel);
        recursiveLight(x, y + 1, z, lightLevel);
        recursiveLight(x, y - 1, z, lightLevel);
        recursiveLight(x, y, z + 1, lightLevel);
        recursiveLight(x, y, z - 1, lightLevel);
    }

```

# Answer
> 3 votes
Someone said to answer your own question if you figured it out, so yeah. Figured out a method.

What I am doing is this: First, create a 3d boolean array of "already changed blocks" overlayed over the chunk. Then, fill in sunlight, torchlight, etc (just lighting up the block that its on, no flood filling yet). If you changed something, hit the "changed blocks" in that location to true. Also go though and change every solid block (and therefore no need to calculate lighting for) to "already changed".

Now for the heavy stuff: Go though the entire chunk with 16 passes (for each light level), and if its 'already changed' just continue. Then get the light level for the blocks around itself. Get the highest light level of them. If that light level equals the current passes' light level, set the block you are on to the current level, and set "already changed" for that location to true. Continue.

I know its kind of complicated, I tried to explain my best. But the important fact is, it works and is fast.

# Answer
> 6 votes
1. Every light has a precise (floating point) position, and bounding sphere defined by a scalar light radius value, `LR`.
2. Every voxel has a precise (floating point) position at it's centre, which you can easily calculate from its position in the grid.
3. Run through every one of 8192 voxels once only, and for each, see if it falls within each of N lights' spherical bounding volumes by checking `|VP - LP| < LR`, where VP is the voxel's position vector relative to origin and `LP` is the light's position vector relative to origin. For each light whose radius the current voxel is found to be in, increment it's light factor by the distance from the light centre, `|VP - LP|`. If you normalise that vector and then get its magnitude, this will be in range 0.0-\>1.0. The maximum light level a voxel can reach is 1.0.

The runtime is `O(s^3 * n)`, where `s` is the side length (128) of your voxel region and `n` is number of light sources. If your light sources are static, this is no problem. If your light sources move in real time, you can work solely on deltas rather than recalculating the whole shebang every update.

You could even store the voxels which each light affects, as references within that light. This way, when the light moves or is destroyed, you can go through just that list, adjusting light values accordingly, rather than having to traverse the entire cubic grid again.

# Answer
> 4 votes
Minecraft itself doesn't do the sunlight this way.

You simply fill the sunlight from the top to the bottom, every layer is gathering light from neighbor voxels in the previous layer with attenuation. Very fast - single pass, no lists, no data structures, no recursion.

You have to add torches and other non-flooding lights in a later pass.

There are so many other ways to do this, including fancy directional light propagation etc. , but they are obviously slower and you have to figure out if you want to invest in the additional realism given those penalties.

# Answer
> 2 votes
I'd suggest an algorithm that sort of combines your multi-pass solution with the original recursive method, and is most likely quite a bit faster than either of them.

You'll need 16 lists (or any kind of collections) of blocks, one for each light level. (Actually, there are ways to optimize this algorithm to use fewer lists, but this way is easiest to describe.)

First, clear the lists and set the light level of all blocks to zero, and then initialize light sources as you do in your current solution. After (or during) that, add any blocks with a non-zero light level to the corresponding list.

Now, go through the list of blocks with light level 16. If any of the blocks adjacent to them have light level less than 15, set their light level to 15 and add them to the appropriate list. (If they were already on another list, you can remove them from it, but it doesn't do any harm even if you don't.)

Then repeat the same for all the other lists, in decreasing order of brightness. If you find that a block on the list already has a higher light level than it should for being on that list, you can assume it was already processed and not even bother checking its neighbors. (Then again, it might be faster to just check the neighbors — it depends on how often that happens. You should probably try it both ways and see which way is faster.)

You may note that I haven't specified how the lists should be stored; really pretty much any reasonable implementation ought to do it, as long as inserting a given block and extracting an arbitrary block are both fast operations. A linked list should work, but so would any halfway decent implementation of variable-length arrays too. Just use whatever works best for you.

---

**Addendum:** If most of your lights don't move very often (and neither do the walls), it might be even faster to store, for each lit block, a pointer to the light source that determines its light level (or to one of them, if several are tied). That way, you can avoid global lighting updates almost entirely: if a new light source is added (or an existing one brightened), you only need to do a single recursive lighting pass for the blocks around it, while if one is removed (or dimmed), you only need to update those blocks that point to it.

You can even handle wall changes this way: when a wall is removed, just start a new recursive lighting pass at that block; when one is added, do a lighting recalc for all blocks that point to the same light source as the newly walled block.

(If several lighting changes happen at once — e.g. if a light is moved, which counts as a removal and an addition — you should combine the updates into a single one, using the algorithm above. Basically, you zero out the light level of all blocks pointing to removed light sources, add any lit blocks surrounding them as well as any new light sources (or existing light sources in the zeroed out areas) to the appropriate lists, and run the updates as above.)

---
Tags: xna, lighting, minecraft-modding, voxels, recursion
---


# Question
Title: HTML Javascript Hidden Object or Photo Hunt Game
Is anyone aware of any example photo hunt/hidden object games either in HTML and Javascript or flash if necessary? I am having trouble finding one, I may be using the wrong words to search.

Photo hunt being like the wheres wally/waldo books where you look for wally in a complex image until you find him. So if it were played on screen you would press the location of wally and it would either be correct or wrong, possibly timed. I am hoping to find one where you can just load in your own photos and specify some co-ordinates that match where the hidden object is.

A spot the difference example may be useful as a starting point but I haven't found an example of either that is web based yet.

# Answer
Here we have two in Python: https://github.com/siberianluck/PhotoHunt https://github.com/paulcwatts/1hph

For a javascript one, you can use a library for the drag and drop, and rotate stuff to place your hidden objects and then you only need to define a decent format for exporting but I'd say something like this:

```
{ name: "The backyard",
  file_name: "backyard.png",
  items: [
    {name: "water hose", x: 120, y: 30, rotation: 20, file_name: 'water hose.png'},
    {...}
  ]
}

```

\`\`\`

If you put the code up the github, please let me know, a seven-year-old I sometimes babysit loves this kind of games but it's hard to find german ones :)

**UPDATE** Actually it's much easier: You have one background image and plenty other (png) images of the same size but with a lot of transparency. Then you just overlay them and whenever a mousedown event comes you check that position with the images by using canvas' `getImageData`
> 2 votes

---
Tags: javascript, html5, browser-based-games
---


# Question
Title: What is the most common art creation process?
I am a developer and when I think about the creation of art assets I am a little lost. My idea is to create concept art first to get my thoughts into real images and after that start creating the backgrounds, sprites, menus, etc.

It sounds simple written like this and I expect lots of inner work, but is there a more formal way to do it? or at least something like a standard procedure?

# Answer
> 8 votes
I agree with DampeS8N. I always start with stand-in graphics. Just squares and circles, until I get the game working. Then I will just start filling in those squares and circles with actual images, just working one at a time. Usually in order of importance (what the user will see more often)

Art creation process is pretty personal and will be quite different for each person. I think sketching out scenes, characters first is a good idea (at least for me), to get a good idea of the environment.

# Answer
> 3 votes
David Hellman has written some great articles on The Art of Braid, which is the most artistic games I've ever seen. While art is an extremely personal, subjective process, it's definitely interesting to see other people's processes. The articles talk about how the art began as extremely abstract and moody and got more form as it was reconciled with game mechanics.

# Answer
> 2 votes
It's difficult to formalise an artistic procedure!

Nevertheless, this micro-documentary from Discovery Channel about *Prince of Persia: The Sands of Time* (the game, not the film!) might give you some pointers. It shows a standard art asset creation process in a major game studio.

Like you seem to have noticed, the key idea is **step-wise refinement**: Everything is a sketch to start with and becomes polished in time. This usually happens in parallel with the rest of development.

---
Tags: art, process
---


# Question
Title: Can Bullet Physics (or another 3d physics engine) use callbacks in my engine to check static geometry?
I'm wondering if it's possible to use or hack Bullet 3d Physics (or another free 3D physics engine) so that I don't need to "import" my static geometry into Bullet - instead I want to do it the other way, so Bullet uses some sort of callback system to check geometry properties of my mesh/polygons.

Sort of like that Bullet would expect a method in my static geometry classes "checkRayIntersection" or similar, and I take care of the details and optimizations myself. The meshes are immovable, so the only thing that I expect Bullet to care about is intersections and their normals, but I might be missing something..

**EDIT**: as an example, consider a 10 million polygon terrain mesh which is changing all the time. You probably don't want to keep parallel data structures in the render-engine and in the physics engine for this. You don't want to use an approximation for the physics either.

Bullet uses something called MotionStates to solve this problem for its output - I was hoping there was a similar design pattern for passing geometry input.

# Answer
Posting this here in case someone else has the same problem.

It seems like both Bullet and ODE can be manipulated into doing custom collision-handling. It's described here in the ODE wiki and on p.21 in the Bullet User's Manual. I should have read the manuals more closely before posting :)

In essence you provide a function which checks the collision and fills in a contact point structure with the position, normal and penetration depth (just like I wanted).
> 3 votes

---
Tags: collision-detection, geometry, bullet-physics
---


# Question
Title: What does an engine like Frostbite look like in the early early stages?
I have been having great fun playing Battlefield, and am blown away by how it all looks and sounds. I was just wondering what a game engine starts life as. At what point of writing code does it finally do something, and what did it do before it started rendering all the textures, light and particles, perfectly?

Are there any good articles, online, or examples anyone's seen?

# Answer
> 25 votes
If you're talking about from the *very* beginning, and note that very few major game engines are coded from scratch anymore, and note that this is an example and not necessarily how it always works . . .

Rendering:

Start by rendering a flat-shaded cube. Add basic lighting effects to it. Add a way to move the camera around. Now you can fly around a boring cube, suspended in an infinite black void. Yay.

Next, you probably want to import a model. At the very least, your artist can whip up a demo model (a teapot is surprisingly traditional), but they may have an actual game model they can hand you. Again, we're sticking with flat shading for now, so it'll show up looking like it's made out of . . . well, no realistic substance, but sort of a cross between matte plastic and porcelain. This, but without good lighting. And we're still at the point where it's completely unmoving.

The next three major steps can be done in any order.

* First, you'll want terrain. Most modern games divide rendering into "static geometry" and "actors", where static geometry include things that don't change (walls, ground, lampposts) and actors include things that do change (players, vehicles, destructible lampposts.) While the basic rendering concept is the same for both, there are optimizations you can do for static geometry that you can't do for actors. You'll *need* terrain for the gameplay engineers to really get going, so if they're waiting on you, it's time to rig up at least basic terrain rendering.
* Second, you'll want texturing. This is a *huge* subject and chances are you'll be getting to a milestone, going to do something else more critical, then coming back to it, repeatedly. Your first pass may simply add textures to the model. Your second pass may add improved lighting and surface behavior. Your third pass may add shadows (I could fill an entire response talking about shadows). Depending on what kind of a game you're doing, this can get arbitrarily complicated. Somewhere in here you may also switch your entire game engine to deferred rendering.
* Third, you'll want animation. Your animators (assuming you're not living in 1995) will have set up animation rigs for their models, consisting of bones running through the model and information about how the bones move during certain animations. You'll probably start with the ability to play animations on demand, then add the ability to mix animations together.

Once all of that is done, it's time to work on compatibility. If you're working on a AAA game then you have some way to test your code on many different kinds of hardware - maybe it's inhouse, maybe you contract out to a testing firm, whatever. A lot of your code will break on specific graphics cards or specific driver versions, and you get to fix as many as you can.

It's also time to consider optimization. Rendering is a big, big speed issue, so now you have to figure out how to exploit the hardware at the deepest level in order to run as fast as possible. If you think this may conflict with "compatibility", you're right! It totally does! The best optimizations, you'll find, will just flat-out not work on some cards. You get to balance all these factors.

Around this point, your artists will be demanding new texturing tools or new animation features, and your level designers will want new terrain rendering techniques. Go back to "the next three major steps can be done in any order" and repeat until the game is done.

Gameplay:

I'm going to skip the parts that aren't terribly visually noticable. First, you sorta have to wait until terrain rendering is in, although there's a lot of backend stuff you can do until then.

Once you've got that, you'll set up some basic collisions. This will likely take the form of flying to a location in-game then pushing a button that drops a cube. The cube falls and hits the ground. Once the cube lands on the ground consistently, you can start setting up player movement, so you can run around the world in the same way as a player does.

Once you've got basic movement physics working, you're in one of those "these can be done simultaneously" segments again:

* Combat needs to be implemented. You need things that can shoot things at things, and all those things need to behave appropriately.
* Physics needs to be implemented. You've got collisions working, but collisions are just a small segment of physics. When someone ramps a jeep off a tank, everything needs to behave roughly as intended.
* Game mechanics need to be implemented. How do you know when you've won or lost? How often do things spawn, and what controls that? If the Communists conquer a spawn point, why does it keep spawning Anarchist vehicles? That sort of thing.

All of these can take, again, arbitrary time, based on how much stuff your designers want you to do. You'll also be spending a ton of time tracking down bugs ("hey, look what happens when I drive a tank onto this jet fighter's wing"). Note that a good deal of this will happen with an untextured world, or with models running around in the character rig position, or with tanks that are just large boxes with the word "TANK" clumsily spraypainted on.

UI:

UI can actually start before the main rendering code goes in, since UI and game-world rendering tend to use totally different codepaths. Instead of starting with a cube, you'll start with a box, then add textures to the box, then add text to the box.

At this point, your life is spent trying to get enough time to write general-purpose widgets, while still putting in enough UI time that the designers and game mechanics developers can test the game in a vague semblance of realism. At some point your UI artists will come up with a consistent feel for the UI, and then you'll start work on the finalized UI elements, while testing those UI elements on actual players to ensure that they're understandable and usable.

I can talk more about these as needed, but it'll turn into a megaresponse if I do, so for now, I won't :)

---
Tags: game-design
---


# Question
Title: How to draw a line of a given length towards a given object?
I wanna draw a line between two moving objects

I can't use:

```
cDrawLine(startPointCG, endPointCG);

```

because the line must have a length. So I'm trying to measure the angle between those two points and then trace a line from start point towards that angle.

Something like this:

```
CGPoint endPoint = CGPointMake(startX + cos(direction) * 100, startY + sin(direction) * 100);

```

However, I can't manage to get it done properly. How do I calculate the angle direction?

# Answer
> 3 votes
Your solution is:

```
float offX = startX - endX;
float offY = startY - endY;
float direction = atan2f(offY, offX);
CGPoint p1 = CGPointMake(startX, startY);
CGPoint p2 = CGPointMake(startX + cos(direction) * 100 * -1, startY + sin(direction) * 100 * -1);

```

The reason for the `-1` is because you calculate the angle from end point to the start point. If startX was 5 and endX was 10, the offX is -5. Which is counter-intuitive. Swapping start and end in the calculation of off would remove the need for the -1 in the calculation of p2.

But then, why do you need the angle. Knowing a bit of vector maths would be really useful:

```
float dx = endX - startX;
float dy = endY - startY;
float scale = 100 / sqrt (dx * dx + dy * dy);
CGPoint p1 = CGPointMake (startX, startY);
CGPoint p2 = CGPointMake (startX + dx * scale, startY + dy * scale);

```

Even with the sqrt this should be more optimal than the atan2 solution and if you've got it, an inverse square root will be quicker still, like this:

```
float scale = 100 * inv_sqrt (dx * dx + dy * dy);

```

This works because the sqrt gives the length of the vector from start to end and dividing the vector start-\>end by the length normalises the vector (makes it length one unit) and then multiplying by 100 gives a vector of length 100.

# Answer
> 2 votes
I'm not sure I understand the requirement for a line length, but your implementation (while valid) shouldn't require angles..

I'll replicate your solution from the comments and explain:

**Explanation**

```
float offX = startX - endX;    // <--- take note of this for later
float offY = startY - endY;
// atan2 calculates the angle in radians given the height and width of a triangle
// we calculate the delta so that startPoint is effectively at 0, 0
// tl;dr: atan2 converts from cartesian offsets to the angle needed to reach them
float direction = atan2(offY, offX);
CGPoint p1 = CGPointMake(startX, startY);
// here you're converting back from the angle to cartesian coordinates
// cos() calculates the x offset based on direction, sin() does the y
CGPoint p2 = CGPointMake(startX + cos(direction) * 100 * - 1, startY + sin(direction) * 100 * -1);

```

**Cleaning up a little**

it's worth noting that you're multiplying by `100` (your scaling factor) but also by `-1` which is unnecessary: Ideally offX and offY should be how far you have to travel to get **from** start **to** finish, but you've got that backwards, so:

```
float deltaX = endX - startX;    // the distance from start to end on the horizontal
float deltaY = endY - startY;    // in case it's not immediately apparent, I've switched the start and end
// ... SNIP ...
CGPoint p2 = CGPointMake(startX + cos(direction) * 100, startY + sin(direction) * 100);

```

**Get to the point already**

but even that is unnecessary - you're converting one way and then back. If you really want just the length, use Pythagoras' Theorem:

```
float deltaX = endX - startX;
float deltaY = endY - startY;
float distance = sqrt( deltaX*deltaX + deltaY*deltaY );

```

*But I really must say:* I still don't follow why you can't just put endX and endY into the CGPointMake function?

```
// this should work given your code in the comments, unless that `100` is a scaling factor for a weird coordinate system?
CGPoint p2 = CGPointMake(endX, endY);

```

ooh and another thing:

```
// if it _is_ a scaling factor, just normalise the point and then multiply by the desired scale:
float deltaX = endX - startX;
float deltaY = endY - startY;

// take away the minus sign and then return the maximum value
float maximum = max( abs(deltaX), abs(deltaY) );

deltaX /= maximum;
deltaY /= maximum;

CGPoint p2 = CGPointMake( startX + (deltaX * 100), startY + (deltaY * 100) );

```

I highly recommend having a google party for trigonometry tutorials, a lot of the straight math texts can be a little dry and unsatisfying, but have try adding "for programmers" in the query :) (alas I'm not at my usual machine so I can't recommend any right now - I shall return with resources).

(Sorry to put this in an answer; I can't reply in comments yet)

# Answer
> 1 votes
You do not need the angle itself, just the direction, which is given by vector `End - Start`. For convenience it's good to **normalise** that vector, *ie.* divide it by its length. You will then **extrapolate** or **interpolate** the position of the second point.

Let `L` be the length of the segment you wish to draw.

The distance between `Start` and `End` is:

```
D = sqrt((End.X - Start.X)^2 + (End.Y - Start.Y)^2)

```

If `D = 0` you cannot draw the line. Just abort, or draw it in an arbitrary direction.

If `D < L` you may wish to plot only until the endpoint. If you really want a segment of length `L`, go to next step.

If `D > 0` the desired point is:

```
Mid.X = Start.X + L / D * (End.X - Start.X);
Mid.Y = Start.Y + L / D * (End.Y - Start.Y);

```

# Answer
> 0 votes
Calculating the angle between two points is done using atan2()

If you think about simple trigonometry, you can use tangent to relate an angle in a right triangle to the opposite and adjacent sides. You can easily determine the lengths of the sides by subtracting the start point from the end point.

Well the reverse of tangent is arc-tangent, so you can calculate the angle that way. However that won't take into account which quadrant the triangle is facing (ie. the angle returned will always be between 0 and 90) so the special "arc-tangent 2" function was created to return angle values in a full 360 circle.

---
Tags: mathematics, vector
---


# Question
Title: Rotating a group of sprites - How to calculate origin
I am rotating a group of sprites in XNA, which I developed with the help of the following example: http://msdn.microsoft.com/en-us/library/bb194912%28v=xnagamestudio.10%29.aspx

It all works very well, however, the rotations rely on a point of origin, which it will rotate around. The problem is that I do not know how to calculate the point of origin, so that it is exactly in the center of the sprite group.

I am able to set the point of origin to where I want it, but as soon as the sprite group changes, the origin is typically off, and it doesn't rotate from the center of the group.

My main question, is there a way to calculate the center of a group of sprites? My original idea was to calc the boundaries (left, right, top, bottom), and place the origin the the center, but this doesn't work properly.

# Answer
If you have three sprites (or if they have very specific relative positions, which almost never happens) there is a special point called the circumcentre which is at an equal distance of each sprite. However, this doesn't scale to more than 3 sprites and doesn't work if they are aligned.

The best solution would probably be to compute the **barycentre of all sprites**, which is guaranteed to remain at the same position when rotating objects around it. In its basic form it's just a matter of **averaging all X and Y coordinates**. Also, it allows you to set separate weights for each sprite, if necessary.

Here is some C# code for a list of points:

```
Point bary = Point.Zero;
foreach (Point p in list)
{
    bary.X += p.X;
    bary.Y += p.Y;
}
/* Final division by list.Count. Since we handle integers,
 * we add list.Count/2 beforehands for rounding */
bary.X = (bary.X + list.Count / 2) / list.Count;
bary.Y = (bary.Y + list.Count / 2) / list.Count;
return bary;

```
> 8 votes

---
Tags: xna, 2d, sprites, rotation
---


title: How can I create NPCs and scenes?

text:
# Question
Title: How can I create NPCs and scenes?
How would I go about creating NPC Events/Scenes? For example, any RPG will have a ton of different in-game cut scenes where you can express a story line.

What I have thought of so far is having different triggers and a number indicating the state of the story the player is at. When the player hits one of these triggers I will check the state and progress from there. Am I sort of on the right page?

After that how do I animate the scenes? Do I just hard code them into the game? I was thinking this is where a scripting language might be handy? I'm not really sure

I realize this is probably a large question, but if someone could point in the right direction that would be great.

I'm using c# and XNA if that matters at all.

# Answer
> 2 votes
C#/XNA doesn't matter too much. I assume you want to build a (2D?) RPG, with events, and a map/event editor.

If that's the case, you need to create an event API, and tools to create/consume it.

For example, you will probably create a "show message" method (takes a string to display when you talk to someone); your map editor will allow you to place this event somewhere, specifying the text; and the game engine shows it when you step on that location.

Scripting languages are good (you might be making your own mini-language), but anyway, that won't prevent you from having to write your own "event API."

This is how I do it, and this is also what RPG Maker XP does.

# Answer
> 1 votes
The way I currently have my systems set up, events spawned by objects trigger scenes, as you stated you can have player triggers cause scene changes, and you can certainly use a state machine. You can make your own animation scene protocol, so it doesn't have to be hard coded. You also have the option of playing actual movie files if you so desire, but generally they're quite large.

I think you're definitely on the right page, since this is your program- you can go about it any way you desire. Creating functionality for things like this is intriguing and fulfilling.

I've never seen any real documentation on this subject so I'd be interested to see anyone else's take.

# Answer
> 0 votes
Not sure if you wanted more of a code sample than theory but have a look at this question

# Answer
> 0 votes
You've got the right idea of setting triggers in your game and game maps to fire off events (note, I don't necessarily mean the events in the C# language). Scripts are optional, but they can be a more flexible way to add these triggers to your game, and re-load new ones if a change in the storyline requests it.

Whether you'd be using scripts or not, generally, it would be good to have some "event loader" that can pass a new group of events or triggers to the game maps whenever it needs it. With scripts, it will be considered a script loader and that will be responsible for populating the game world with new events at specific locations, including events that can load another script.

For example, at the start of the game the first script (or event loader object) will be called automaticaly, and fill the game with event triggers. One of those events may be triggered after beating the first boss, and this event in turn will load another script that replaces some or all of the event triggers in the game. Now you have a new set of interactions or objectives you can explore. This adds a layer of flexibility for branching paths in quests and story, but with this also remember to plan out the branching paths of your storyline well, so you know all your events make sense within the story.

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


# Question
Title: Cross-platform, free (for commercial use) C/C++ 2d game library or rendering engine?
I need a C/C++ engine that should be *really* cross platform (or at least windows, android, and iphone).

The 2d engine should be written in C or (better) C++, should permit the rendering of animated sprites, permit transparency, collisions (but I can integrate box2d for that), rotations (eventually with opengl support to accelerate things), handle tile-based games. If it could be a game engine (with support for events/actions, scripting and generally have the features needed when developing a 2D game) it would be fantastic.

There are a lot of open source free 2d engine out there, but soon or later you find that:

1. the documentation is not so good and/or the tutorials are not so good (or there are no tutorial at all), the examples are missing (or are too few or are missing)
2. the community is too small and not so supportive
3. the engine doesn't abstract system things enough. That is bad, because you soon find out that there is support for X and Y but not Z. With abstraction, you can use even Z adding system specific code
4. the engine is a game engine but does not have an associated editor. scripting is good, but an editor would save a lot of time I think
5. the engine writers have spent too much time to develop a complex (that will probably fails) compilation tools.

It would be useful to have something that:

```
#define WIN_PLATFORM
#define IOS_PLATFORM
#define ANDROID_PLATFORM
#define UNKNOWN_PLATFORM

```

In that way, using an empty implementation of the relevant interfaces, you can simply code what you need

6 . You come to the conclusion that usually there is not a sufficient conceptual separation from what really needs to be abstracted and what can be supposed to be found on almost all systems (e.g. opengl).

Ok. The question is, regarding a free, open source 2D rendering engine or a 2D rendering engine+2D game engine for at least iOS and Android: in your experience, what would be a good/wise choice?

# Answer
1. SDL.
2. Allegro.
3. SFML.

SDL is probably the most popular and known for producing AAA-quality titles. Allegro is the oldest (first built for Atari ST I believe) and has seen a huge amount of use. It's fast and efficient 2D, like SDL. SFML is a much newer contender and, as I understand, assumes OpenGL support. However both SDL and Allegro support OpenGL seamlessly in their most recent versions.

Allegro and SDL are written in C, and plot pixels about as fast as a software renderer could be expected to (which is pretty damn fast on today's systems). SFML is C++.

Documentation is decent for all of these, but with SDL and Allegro you may sometimes be slightly confused by articles online that are out of date. The official docs *are current*, however.

As for editors, well, you may have to pay for something like Torque2D if that's what you really need. I haven't heard the greatest things about that library's in terms of stability, though. Else go for Java / jME, or C# / Unity.
> 4 votes

# Answer
> but soon or later you find that:

You're not going to find anything that user-friendly in the open-source world. Not full-fledged game engines.

If you don't want to spend money on an engine, then you're going to have to accept one immutable law: *you get what you pay for*. Let's go through your points:

1. People who don't get paid have little incentive to write documentation, unless they're particularly anal about it. Remember: free programmers get into a project to *code*, not to document.
2. There are a lot of tools out there. Some are going to be more popular than others.
3. Each engine is designed for a specific purpose. You can't make everything abstract, because then everything is abstract and nothing is *defined*. You'd have a library that does nothing. Every engine must decide what it is going to make easy to do and what it isn't. The kind of games that the engine is made for fall in the former category, and the kind of games that it isn't made for fall in the latter.

This is true regardless of whether the engine is free or not.
4. Pretty much the same as #1. If you're making an engine, you're not making a game. And people who are interested in making engines aren't necessarily interested in going through the other 80% of the work necessary to make a game. Part of that work is a good suite of tools.

Also, editors are very closely tied into the kinds of games they make. It's hard to "abstract" an editor. So if you have a general-purpose engine, it's going to be hard to create an editor for it that doesn't in some way limit what the user can do. Editors also require a lot more planning than many open-source projects get.
5. I've generally never seen this. Usually, the build process will be CMake, some form of Autoconfig stuff, or just straight-up Makefiles. If they do use a more complex build system, it is only because they want to give the user the ability to configure the software as they wish. SFML and Allegro allow you to pick-and-choose different tools to work with.

Ultimately, there are plenty of C/C++ tools out there which you can pull together into a game engine. But there is no one-stop-shop for them. There is no one engine that ties them all together in a nice, well-documented package. Which is why serious indie game developers either pick tools they like using and build what they need, or just buy something off-the-shelf.
> 4 votes

# Answer
There is a gameengine named cocos2d-x. it's c++ port of well-known cocos2d-iphone engine. So far this engine supports iOS, Android, Windows and some other platforms (there is a complete list here). But according to it's own site windows should only be used for development and debug purposes but I think with a little modification you can release windows version of your game using this engine too.
> 1 votes

---
Tags: android, ios, open-source
---


# Question
Title: What tools are available for game script writing?
I'm looking to find some software options on OS X that are geared toward writing game scripts. Features like the ability to craft dialogue trees and other non-linear script formats would be appreciated.

I own Celtx and love its ability to store character information along with various other media assets, but it's very linear and straight, film-style script based which doesn't exactly work well for game applications.

Any dedicated or more appropriate software options out there?

# Answer
The only thing I can think of that might work is Org-Mode for Emacs. Here’s an excited rant about how Emacs with `visual-line-mode` and `org-mode` is awesome for scriptwriting. As for nonlinear scripts, Org-Mode lets you make internal links wherever you want.

**Warning:** Emacs is designed for power users, and it takes time to become effective with it.
> 1 votes

---
Tags: macos
---


title: Game server position tracking

text:
# Question
Title: Game server position tracking
How would you go about determining a players position server side based off player input?

The Setup: Player sends packet to server containing the command and view angles. Server takes the direction and multiplies it by speed.

Say a player is going up a hill. How would the server make the players position reflect that the player is going up a hill.

The way i see doing is taking the ground height under the player and calculating if the height change in direction x is too high. However calculating that info for n players say 1000 would be very intense. So what is the proper way of determining a players position based on input with a client/server setup with the server being authorative. There is 10 updates per second.

# Answer
I think this is actually usually done retroactively; that is, the client sends their position and allows the player to move, anticipating that the server will allow it. The server verifies it, and rejects it/disconnects the user if it's invalid. You can of course calculate speed by taking the difference between two positions and dividing it by the time between the position updates. And the server will also want to check that the position doesn't collide with geometry; this check will need to be mirrored on the client side. Then with the server checking on the client, it's immediately obvious if the client is cheating (i.e. if they send an invalid position) and can be kicked off. For anything that's not blatant cheating, like a collision with a moving object where the object might be in slightly different positions between server and client, the server simply tells the client where it should be, and the client can jump the player to that position (or smoothly but quickly slide them over there; either way, discrepancies need to be handled and they probably aren't going to be pretty).

All in all, this allows for a much more responsive player experience. When they try to walk forward, their character can move forward immediately and the client notifies the server, and then in the rare cases where the client receives a rejection response back, the character can be pushed back to where the server says it needs to be.

This is talked about in some detail in the book Massively Multiplayer Game Development. Also see the question "Synchronizing clients with a server and with each other".
> 5 votes

# Answer
So after reading thousands of posts on how to handle collision server side I have decided to use the bounding box technique. After all for a MMO really all collisions are made between players and static objects. No npc to player or player to player collisions etc.

So what does this mean? Objects are a bunch of boxes.

Example of server side object 1 Main bounding box which surrounds the entire object. Coordinates of the object center Horizontal Distance Max(x,y) Vertical Distance Max (z) List of Boxes Count of objects region identifier

Box Example: Vector3 point1 (x,y,z) Vector3 point2 (x,y,z) Horizontal Max Distance Vertical Max Distance Vector3 Center Point (x,y,z)

Each object can contain multiple boxes that make up its shape. Like a house for example with just a door, no windows and no chimney would have 10 boxes and 1 box around it all. Instead of checking each individual box for every object the player must touch or try to enter the main bounding box.

Basically each movement the server compares the players position to each object in said region. If the player is x distance away from object A and is less than or equal to it then do further checking. If object is too high or too steep for player to get on it then stop the player. Otherwise let the player go on the box. If a player tries to jump on a table or something make sure that the height of said table is less than or equal to players jump height. If not then stop the player from getting on it.

Hmm that sounds like a lot of work if you do that for 300 players 10 times a second?!?!? Well basically the client wont encounter many of the boxes (At least server side). Client side the colliders will be slightly bigger and stop collision client side. So if the client can do it then why does the server have to try? Cheaters. Client side will restrict movement just enough many server side checks shouldn't have to happen. Really the only thing server side will have to check against collision wise most of the time will be whats under a players feet and what a player can jump on along with terrain. 80% of server side collisions will just be there if a client tries to cheat. Think of it this way... You have a chess board right? Server has colliders just outside the board around the whole thing. The client has them just barely on the inside around the whole thing. The client side colliders should stop the player just before they reach the server side colliders. If a client finds a way around the client side ones the server colliders kick in and basically say NOPE. This prevents much of the load actually taking place but its there if needed. This means the server really only has to compare against terrain and object height.
> 0 votes

---
Tags: server, unity
---


# Question
Title: How to handle keyboard in worker thread in XNA
I am using multithreading in my XNA application and run my update logic s in a update thread(witch is a worker thread) and rendring is being done by main thread, now the problem is updation is required there on keyboard event, and key Board handling can be done only in main thread.

Note that my application was single threaded and I have implemented threading, synchronization is being done by 'data partitioning', both the threads are working correctly, except my keyboard is not working..

if any one have any suggestion or example, please allow me to know.

thanx in advance.

# Answer
> 3 votes
Input in XNA is not thread-safe and must be handled on the main thread. Simple as that.

**Move your input polling to the main thread.**

This is the thread safety of the XNA Framework (info is from XNA 3.1, but is probably still applicable):

> * `GraphicsDevice` is somewhat thread-safe
>
> + Cannot render from more than one thread at a time
>     + Can create resources and `SetData` while another thread renders
> * `ContentManager` is not thread-safe
>
> + Ok to have multiple instances, but only one per thread
> * Input is not threadable
>
> + Windows games must read input on the main game thread
> * Audio and networking are thread-safe

Source: "Understanding XNA Framework Performance" by Shawn Hargreaves (Slide 27)

---
Tags: xna
---


# Question
Title: Can I make a Flash version of an actual game?
> **Possible Duplicate:**
> Legal issues for a “fangame” of a commercial franchise?

For example, some of you may have seen Portal: The Flash Version. I was wondering what the legal background on this kind of stuff is, for example what legal things I'm supposed to say, give credit to the original's creators and all.

Obviously, I'm presuming that I'm not allowed to make money off of it, but I just want to know what restrictions there are of making a free Flash version.

For example, would I be allowed to make a Yu-Gi-Oh! game based off the Power Of Chaos series? And if so, would I be allowed to use the Yu-Gi-Oh name or would I have to call it something else?

# Answer
You can't without prior permission from the copyright holders use trademarks or graphics assets. You can however to a large extent imitate the gameplay of another game, though copying the exact Yu-Gi-Oh! rules is as far as I can tell too much.

As for relying on a company simply ignore the infringement, I'd doubt that it will work with Yu-Gi-Oh! They have to keep the value of their cards high, if you give away virtual cards in your game it could have a negative impact on peoples willingness to buy real cards.

Giving stuff away for free doesn't change whether or not a copyright infringement is an infringement. It may change the copyright owners incentive to take action, and depending on court it could affect the degree of punishment, but that is all.
> 1 votes

---
Tags: flash, legal
---


# Question
Title: Does using Creative Common data in a GPL game mean the code must be CC-BY-SA?
Let's assume we have a game where the code is GPL-licensed, and all the resources (like music, textures, etc.) are licensed under the CC-BY-SA license.

Now, the first issue would be that the GPL is not compatible with the CC-BY-SA, but since it only applies when actually linking code, it's okay in this case. Am I right?

The real problem is that, arguably, the game is "built upon" (to use the same terms as the license) the music, textures, etc. So wouldn't the CC license require the code to be released under the CC-BY-SA as well?

# Answer
I am not a Lawyer, but with respect to CC-BY-SA content virally affecting the code:

The CC-BY-SA legal code specifically says

> This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License.

And from their definition of `Collection` (emphasis mine):

> "Collection" means a collection of literary or artistic works, such as \[...\], by reason of the selection and arrangement of their contents, constitute intellectual creations, **in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole**. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License.

So it seems like a game would be considered a `Collection` rather than an `Adaptation`, and as specifically stated in their legal code, would not need to be made subject to the terms of CC-BY-SA.
> 8 votes

# Answer
**NOTE: I am not a lawyer**

Code and artistic assets are completely capable of being distributed under two separate licenses. In fact, the people over at Creative Commons recommend not using their licenses for code because other licenses cover that domain more completely (such as the GPL).

http://wiki.creativecommons.org/Frequently\_Asked\_Questions#Can\_I\_apply\_a\_Creative\_Commons\_license\_to\_software.3F

The GPL refers only to the linking of other **code** with the GPL-licensed code. It does not apply to assets used by the application.
> 5 votes

---
Tags: legal, licensing
---


# Question
Title: Which console systems can indie developers officially develop for?
As an independent developer, I would like to know what platforms I can use to reach what consoles, and under what prices. I'm assuming a small team (1-3 people) and low or non-existent budget (under $1000).

For the purpose of this question, a "console" is "anything other than a PC." So this includes mobiles phones and other devices.

For this question to be useful and not a collection of every game engine and platform in the world, maybe we should restrict it to technologies that support at least two platforms.

# Answer
> 9 votes
XNA can deploy to a Windows 7 Phone and Xbox 360.

# Answer
> 5 votes
Android is how I got started with game development. It's completely free to develop for and has a one time $25 fee to upload to the Android Market.

# Answer
> 4 votes
**iOS:** You only need $199 per year to deploy on the App Store. This includes $99 per year for membership in the iOS Developer Program, plus $500 every five years to buy a Mac mini once Apple stops producing new versions of macOS and Xcode for the old model. Cocos2d is a free 2d engine and chipmunk or box2d for physics engines. For 3D there is NinevehGL and cocos2d is releasing a 3d engine (yes, the name is cocos3d)

**Android:** You can deploy to android with the PC you already have and a one-time $25 fee. There is a cocos2d version for android, but I think it's not as advanced as the IPhone one. You can check andengine to.

You have XNA for xbox and windows phone and it cost $99 to deploy on XBox and windows phone.

Using unity do deploy on android and IPhone cost $800 ($400 each). I guess this is a bit expensive for your budget but it's still a good option for indie development.

I think the only technologies that work on multiple platforms with almost no work are XNA and Unity.

---
Tags: console
---


# Question
Title: Selectively applying overlay shadows in a 2D tile based game
I'm currently building a top down 2D tile based game using OpenGL. There are three tile layers, the background layer, player/sprite layer & foreground layer. The foreground layer is pretty much used to place translucent tiles that give the impression of a shadow when blended over the two underlying layers. The problem is that many textures for tiles in the background layer already have a shadow applied in their source images. I would like to exclude these background tiles from having the shadow overlaid whilst still applying it to sprites that may be above these tiles. Any ideas as to how I could go about accomplishing this? In the accompanying image notice how I only want the forground shadow applied to the character in the sprite layer to get the result.

# Answer
The following answer will assume that you are trying to do the following:

There are certain tiles in your background which already have shadows baked into their images. You don't want your shadowing layer to affect them *at all*, but you do want your shadowing layer to affect everything else.

There are several ways to accomplish this.

### Multitexture

No "foreground layer" at all. Instead, have each tile tell whether it is shadowed or not. Render the non-shadowed tiles as normal. The shadowed tiles are rendered with two textures and two texture coordinates: one that picks from the background texture atlas (or however you're doing your rendering) and one that picks from the foreground atlas. You simply do the "layering" as part of your shader/texture environment. It's a simple multiplication, or perhaps an alpha blend, depending on how your shadowing works.

The same goes for sprites.

This method only works on a per-tile granularity.

### Stenciling

You can employ a stencil buffer (if you do, make sure you also have a depth buffer. 24/8 depth/stencil in size). This brings layering back, but you still need to mark which background tiles need to be shadowed and which ones don't.

At the beginning of the frame, clear the color, depth, and stencil buffers. The stencil buffer should be cleared to 0.

Tiles that do not need shadows should be rendered with a stencil value of 0. Tiles and sprites that need them should be rendered with a stencil of 1. Make sure that your sprites use alpha tests/discards to cut out the area around them.

The code for this would be (warning: untested):

```
glEnable(GL_STENCIL_TEST);
//Change the second parameter to 0x01 for objects that should be shadowed.
glStencilFunc(GL_ALWAYS, 0x00, 0x01);
glStencilOp(GL_NEVER, GL_REPLACE, GL_REPLACE);

```

When you draw your shadowing layer, what you do is turn on the stencil test and have the test function be equals. All of your foreground should be rendered with a stencil value of 1. The code you would use before rendering your shadowing layer would be (warning: untested):

```
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0x01, 0x01);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

```

Again, this has a per-tile granularity.
> 3 votes

---
Tags: opengl
---


# Question
Title: Options for UDK and version control repositories?
Another developer and I have begun to experiment with the Unreal Development Kit and have installed the UDK to our local computers. He's been toying around and experimenting and has some basic code and assets already developed. **We want to set up a VCS repository so we can collaborate on development of a UDK project.**

Some things we've noticed:

* Source code goes in Development/Src/GameName/.
* Binary Content and other assets go in UDKGame/.
* The rest of the folders in the root directory are for the core UDK installation.

**In terms of repositories, we've already come up with several options:**

* **Commit everything (even the core UDK code).**
    + Pro: Easy
    + Con: We're committing lots of code that, while a dependency of our project, isn't technically part of the project.
* **Commit the two folders we contribute to in two separate repositories.**
    + Pro: Isolates versioned code to stuff we create.
    + Con: Slightly more difficult to set up, commits for one fix span multiple repositories, and we're committing a lot of binary content.
* **Change the config so both the src and the assets live in one folder, then commit that.**
    + Pro: Isolates versioned code, commits for changes are in one repo.
    + Con: Committing binary content.
* **Commit SRC to one repo, use another solution for assets (FTP, Dropbox, etc)**
    + Pro: Isolates versioned code, no extra overhead in versioning binary content.
    + Con: Changes span multiple places and manual updates to a remote storage solution are needed.

As we assess the best way to go about this so we don't back ourselves into a corner later, I'm wondering if there are other options and what their pros and cons are. I realize we could easily just pick a solution and change it up once we ran into scaling issues, but version control has always been one of those things I like to do once upfront and then forget about when I work on projects.

# Answer
If Perforce is an acceptable option for you, then I can suggest a solution.

### Repository layout

Try to separate UDK and your game, but keep them in the same repository. Don't forget that Perforce has client view for vHere is a possible depot layout:

```
+- UDK
|  +- 2011-09
|  +- 2011-08
|
+- YourGame
|  +- Src
|  +- Assets
|
+- YourOtherGame
   +- Src
   +- Assets

```

And one possible corresponding workspace (I don't have the exact UDK layout in memory, but I hope the idea is clear):

```
//depot/UDK/2011-09/... //client/UDK-LATEST/...
//depot/YourGame/Src/... //client/UDK-LATEST/Development/Src/YourGame/...
//depot/YourGame/Assets/... //client/UDK-LATEST/YourGame/...

```

One advantage is that you can switch a single workspace line and replace the current UDK version. And at any time you may create another workspace that has `YourOtherGame` instead of `YourGame`.

### A note about Git and P4

Personal story: my company uses Perforce for an Unreal Engine project. When I arrived there I refused to use Perforce because of the huge step backwards it was compared to Git, and decided to use `git-p4`.

`git-p4` religiously keeps all P4 revisions in my `.git` directory. After 3 months of preproduction this was no longer an acceptable solution. `.git` had grown to several dozen gigabytes. `git-import` crashed on files larger than 400 MiB.

So I went for the dual workspace solution: one workspace for the data, and one workspace for the source. The former I still manage with P4 and the latter with Git. They are interleaved in my working tree, but P4 ignores the files managed by Git, and Git can ignore the P4 files with a few `.gitignore` entries.

In the end I get the best of both worlds: the speed of P4 when dealing with large files, and the features of Git when branching, rebasing or blaming. One major drawback is that I cannot do a single atomic commit that touches both workspaces.
> 6 votes

---
Tags: udk, version-control
---


# Question
Title: Is there a way to create a cellular automaton mod for Minecraft?
I basically want to create a mod for Minecraft that does the following:

```
if(a sand block is next to lava block) {
   change the sand block to a glass block
}

```

Is it possible to create a mod like this without editing multiple Java classes?

# Answer
Something that a lot of people don't understand is that it is *possible* to make ANY mod. And also, you *need* to modify java classes at one point. There is no way around either of these simple facts.

So, yes. Yes you can. :)
> 6 votes

# Answer
That depends. To do specifically what you are describing, you will probably need to create a mod for a new block type. Here's a tutorial on doing so -- it's not terribly complex and you primarily just need to create one additional source file (for the block itself). The code for the block itself may be more involved, however. You can see an example of this kind of cellular automaton block mod on YouTube here.

You can, of course, just build the simulation you want using redstone circuits. It might be a bit involved, and it won't function exactly the way you want (toggling block types), but it's doable without a mod.
> 2 votes

---
Tags: minecraft-modding
---


# Question
Title: Which free HTML5-based game engine meets these requirements?
I am experienced with traditional JS and HTML but new to HTML5. I want to develop games in HTML5 so that it can work on all devices and browsers, including IE. Additionally, I require the following features:

* Physics Engine
* Animation
* Some AI
* Vector drawing and manipulation
* Better user/player controls, et cetera

I know there are many options, but just want some one that can give most flexibility... so I want some thing that can also be compiled to achieve maximum functionality.

One that is in my mind is GameKit; but please tell what you guys would suggest that meets my requirements.

# Answer
> 6 votes
Check out crafty.js, it has a lot of the features you're looking for and is in active development.

# Answer
> 6 votes
Here is a list of lots of javascript game engines. Out of those, I like crafty, Hydra and LimeJS

# Answer
> 3 votes
MelonJS isn't bad either. And it works together with Tiled for use of .tmx files. You can also layout your level and set up your collide-able tiles straight from within Tiled.

# Answer
> 0 votes
I'm from Scirra and (of course!) would recommend you take a look at our game maker, Construct 2.

It meets all the requirements you specify, however for the more complex ones like AI you would need to write your own JS plugins for this!

Here's a video showing how easy it is to add 2D physics to your games: http://www.youtube.com/watch?v=fASJyCABFMU&feature=channel\_video\_title

Also we offer a free edition which is very generous and should meet your requirements!

# Answer
> 0 votes
The list that Spooks posted is not up to date.

This is the same list, updated and wikified: https://github.com/bebraw/jswiki/wiki/Game-Engines

But what you are looking for exactly is this feature matrix: https://github.com/bebraw/jswiki/wiki/Game-engine-feature-matrix

Feel free to add your own findings as the wiki is open for modification!

---
Tags: javascript, html5, browser-based-games
---


title: Pseudo-code examples of A*?

text:
# Question
Title: Pseudo-code examples of A*?
I'm looking for pseudo-code examples of the A\* pathfinding algorithm that actually **works**. I tried plenty of different ones where it's not really clear how to implement them at all times. Keep in mind that I'm a newbie, so if everything could be detailed, that'd be great.

# Answer
> 6 votes
I think the pseudocode in the Wikipedia article is sufficiently detailed. If you need more details and a working implementation then A\* Pathfinding for Beginners is a good article. It has C++ sample code with comments.

# Answer
> 3 votes
On my site I have an A\* implementation I did in Actionscript based on this tutorial.

---
Tags: path-finding
---


# Question
Title: How do I get the height of an XNA SpriteFont?
I have some text in a spritefont and I need to know the height in pixels.

I would have thought that MeasureString() would get me close to it, but it seems to just be about length.

# Answer
> 12 votes
MeasureString() returns to you a Vector2 where the X is the width and Y is the height of the text.

Also the SpriteFont class has a LineSpacing member that gives you the height of a line, including text and blank space.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritefont\_members.aspx

---
Tags: xna, fonts
---


title: OpenGL, Offset and Camera Space

text:
# Question
Title: OpenGL, Offset and Camera Space
I was reading chapter 4 of the Arcsyntesis OpenGL tutorial when I came across this line in the GLSL shader.

```
vec4 cameraPos = position + vec4(offset.x, offset.y, 0.0, 0.0);

```

About it, the tutorial says

> The first statement simply applies the offset to get the camera space positions of the vertices.

I understand what cameraPos is but I don't get what the offset is. It's defined as a uniform and it's passed to the shader by the main program like this:

```
glUniform2f(offsetUniform, 1.5f, 0.5f);

```

So offset.x = 1.5f and offset.y = 0.5f. But I see no mention of that offset in the rest of the tutorial and its values seem quite random to me. I know that the offset from the projection plane to the eye is always -1 but that refers to a value of Z. Where do X and Y come from? Are they arbitrary values? What they mean, what they do? I understood everything up to the point but I can find no reference to said offset in the tutorial and I'd like to know if someone can explain it to me, please.

Edit: the last line I posted was probably forgotten by the author of the tutorial and can be find in the book's source distribution here.

# Answer
It's the same offset used in chapter 3 to move the vertices around in circular motion. The offset uniform is supplied in the display function

```
float fXOffset = 0.0f, fYOffset = 0.0f;
ComputePositionOffsets(fXOffset, fYOffset);

glUniform2f(offsetLocation, fXOffset, fYOffset);

```

and the position was updated identically in the shader:

```
vec4 totalOffset = vec4(offset.x, offset.y, 0.0, 0.0);
gl_Position = position + totalOffset;

```

Chapter 4 uses offset similarly:

> The vertex shader is a combination of things we know. It passes a color through to the fragment stage, but it also takes a vec2 offset uniform that it adds an offset to the X and Y components of the position.

So what I think the tutorial means by

> The first statement simply applies the offset to get the camera space positions of the vertices.

is that the vertices are initially defined in their own model space (around the origin), and by applying a transformation on each vertex we get a new position. This will become clearer in chapter 6, where you learn additional ways to transform vertices (to resize an object or rotate it for example) and a better way of implementing such a transformation. For now offset is used to make the examples more interesting without having to introduce you to more advanced concepts.
> 1 votes

# Answer
> I understand what cameraPos is but I don't get what the offset is. It's defined as a uniform and it's passed to the shader by the main program like this:

It's the same offset used in the non-perspective version of the tutorial. This is the orthographic shader:

```
#version 330

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;

smooth out vec4 theColor;

uniform vec2 offset;

void main()
{
    gl_Position = position + vec4(offset.x, offset.y, 0.0, 0.0);
    theColor = color;
}

```

This is the perspective version:

```
#version 330

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;

smooth out vec4 theColor;

uniform vec2 offset;
uniform float zNear;
uniform float zFar;
uniform float frustumScale;

void main()
{
    vec4 cameraPos = position + vec4(offset.x, offset.y, 0.0, 0.0);
    vec4 clipPos;

    clipPos.xy = cameraPos.xy * frustumScale;

    clipPos.z = cameraPos.z * (zNear + zFar) / (zNear - zFar);
    clipPos.z += 2 * zNear * zFar / (zNear - zFar);

    clipPos.w = -cameraPos.z;

    gl_Position = clipPos;
    theColor = color;
}

```

See how they both start out the same way? `position + offset`. The important part is what is different about them. And since I'd covered the offsetting in Tutorial 3, I didn't feel that it was necessary to bring it up again in Tutorial 4.

However, I did add a clarification that points out that the offset is the same as previous offset values.
> 1 votes

---
Tags: opengl, 3d, glsl, geometry
---


# Question
Title: Keeping per-client data, when using singleton-based states
In my game, I deal with a lot of units. Every unit implements a state machine, and changes states quite often. As a result, I'd like to keep my states as singletons, since I want to avoid the creation of one and the same state over and over again.

This works quite OK for most case, except when I need to introduce some time intervals, e.g. in 5 seconds the unit has do something. Of course, everyone knows that singletons cannot keep per-client data, which is exactly what I want to achieve. The state should be aware of the time elapsed since it was initiated for a specific unit.

One way to do this would be to keep timers within the units themselves, but that doesn't make a good abstraction.

Another one, which I am currently working on, is to keep the per-client state, i.e. timers on a Dictionary/Hash within the state. When a client initiates the state, the timer gets activated, and a dictionary record gets set. Every time when the specific timer is needed, the dictionary is queried with the id of the specific client. Then on state exit, the record is deleted.

Which is in general the proper way to deal with these problems?

# Answer
> 1 votes
This is pretty much why "don't use singletons" is recommended every time the subject comes up.

I'm not sure what you mean by "per client," so I'm translating that as "per instantiated object in your application." If you elaborate on how your application is organized I might be able to get more specific.

The first sin you committed was premature optimization. How many units is "a lot?" Why do you want to avoid creating new state objects? Afraid of typing, estimated memory constraints, measured performance on a test with "a lot" of states, just felt like it?

Solution 1) Get rid of the singletons. Make your states proper objects and allocate them, only if you have measurable speed problems go further than this.

Solution 2) If you measure that your allocations are eating your performance then make a pool of those states, pre-allocated, and whenever you need a new state get one from the pool and initialize it.

Solution 3) If your states carry no data (other than the timer) and are merely logic? You can then keep the singleton, use a local timer, and pass the timer to your singleton as a parameter. Yes, you will need to allocate the timer, which is why I recommended #1 first.

Solution 4) If your states also have data and not just logic, see Solution 1.

# Answer
> 1 votes
If your states are parametric, e.g. "waiting until time *T*" instead of just "waiting", then they shouldn't be singletons. Conceptually, each combination of parameters is really a separate state, and it doesn't make sense to create separate singletons for, say, every possible time a unit might want to wait until.

If you also have other states that don't require any parameters, and want to implement those as singletons, then it's up to you to come up with an interface that hides the difference from the outside. That is, of course, assuming that you *do* want to hide it, which might not be the case.

Note that, strictly speaking, things like the position of each unit, and any other properties they might have, should also be considered part of the state of the unit — the "state objects" you have really only represent a part of the unit's state (or the state of a part of the unit; you could think of the "state machine" as a literal machine that exists inside the unit and sometimes interacts with the rest of it). These additional state variables are what allows you to represent a state like "stand still" as a simple state, without having to parametrize it as "stand still at position *X*". If you find that a lot of your states are of the form "do something until time *T*", you might indeed want to consider equipping your units with a timer property, and changing those states to "do something until the timer is triggered".

# Answer
> 0 votes
You can make an object to store the relation between manager and unit instance

```
struct InstancedUnitRelationWithManager
{
    public Unit TheUnit;
    public float TheTime;
}

```

and in your manager add a list of relations for each object...

---
Tags: xna, state
---


# Question
Title: How can I reference multiple XNA content projects from my game project?
I'm developing an engine in XNA and would like to have two different ContentManagers: one for the game (sprites, sounds, etc.) and one for the engine (shaders, dlls, etc.)

Right now, I have this:

```
using Microsoft.Xna.Framework;
....
public class Engine
{
    public ContentManager GameContent;
    public ContentManager EngineContent;
    public IServiceContainer Services = null;

    public Engine(GraphicsDeviceManager Graphics, ContentManager Content)
    {
        Services = new ServiceContainer();
        Services.AddService(typeof(IGraphicsDeviceService), Graphics);
        Services.AddService(typeof(IGraphicsDeviceManager), Graphics);
        GameContent = Content;
        EngineContent = new ContentManager(Services, "EngineContent");
        ...
    }
}

```

The GameContent and EngineContent projects root directories are set to GameContent and EngineContent, respectively. I have a content reference to EngineContent in the Engine project and references to both GameContent and EngineContent in the Game project.

Why can I access my GameContent but not my EngineContent?

# Answer
> 1 votes
I found the problem. Something about referencing the engine content from both the game and the engine was messing it up. Removing the EngineContent reference from the game cleared it up.

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


# Question
Title: Is it okay to use STL in my iPhone C++ 2d game?
I've read a couple posts on the subject and it sounds hairy. But I think people are talking about using STL containers for Objective-C objects. I'm using pure C++.

# Answer
Short answer: yes

Long answer: depends on your use case. But probably yes.
> 8 votes

---
Tags: c++
---


# Question
Title: How do I save and load settings on the Xbox?
I'm using XNA 4.0. How can I load and save settings when on the Xbox? And can I write to and read from files?

# Answer
> 10 votes
You will be able to read and write from any flat file (XML, JSON to name two), you can also use SQLite with XNA 4.0

Here are some samples from microsoft

# Answer
> 3 votes
You should use `IsolatedStorage` for settings specific to a particular console (resolution, volume, etc.), and `StorageContainer` for save game data (that gamers should be able to back up & take with them).

`StorageContainer` data allows the player to select on which storage device to write the data, whereas `IsolatedStorage` writes on the same device where the game is, no questions asked.

For your game to successfully pass review on XBLIG, you'll need to ensure all cases work correctly (cancelling the device selection dialog, handling removal of a storage device, etc.)

Useful links:

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


# Question
Title: How can I draw a line rotated some number of degrees away from an original line?
I have a line ahead of my moving object to serve as a raycast and its aligned with the object's movement direction. But I want also some extra lines according to an angle related to the 'head' of the moving object.

This position is always changing; I also have a velocity vector to see the direction of the object as well, I use that to trace the front line ray of my object but not sure how to use to calculate this new line.

In this picture, my object is moving to the right and up. I want to trace a new line but 30 degrees from this one. How do I do that?

# Answer
Assuming you're talking about 2D, the rotational matrix in general is ...

Or, for 30 degrees to the right () specifically ...

Multiply your directional vector by this matrix to get your new directional vector.

Alternatively, you can use complex numbers for rotation. Your directional vector is then *d = x + iy* with *i2 = -1*, and the number to multiply it by to get a rotation by is - or in your specific case:

In 3D, you'll need to define what you mean by "30 degrees to the side" first. As Peter Taylor correctly comments, there is a whole *cone* of directional vectors which fulfil this constraint.
> 2 votes

---
Tags: mathematics, vector
---


# Question
Title: Changing game object type: reinstantiating the object, or switching an object state
I work on a strategy game, where the player occasionally has to transform ordinary citizens into the so called "leaders". Leaders are temporary units, which the player can control directly, in order to interact with the other citizens. After some time, the leader gets transformed back to a normal citizen.

My question is if I should stick to the classical OOP approach of keeping citizens and leaders in two separate classes, whereas the leader class extends the citizen class, and every time when I need a leader, I simply re-instantiate the current citizen instance.

I personally dislike this approach, however. I already have a state machine implemented, and am more likely to keep only the citizen class (or rather, human class). Rather, I'd like to keep the citizen/leader separation into two different states. When I need one or the other type, I simply switch the current state.

# Answer
Most games don't have different classes for different entity types, because it's not very flexible. Your example is a classic case of why this is so! Classical OO with one-class-per-noun is great for toy problems but not so good in the real world.

I'd suggest using the Strategy pattern, and swapping out a behaviour object that encapsulates the key differences between the two types of character, leaving the rest of the entity unchanged.
> 5 votes

# Answer
With a components-based entity system, you can simply do

```
if (citizen.leaderComponent)
{
    leaderComponent.update() //...or ".processLeaderDirectives()", or whatever.
}

```

Obviously this leaderComponent has references to whatever it modifies, such as group state/motivation tables or whatever. So it is a data member of every Entity, but is only non-null if the citizen is a leader (i.e. you've assigned a leaderComponent to this Entity). Think of it like a leader hat. Anybody can wear one, but only the bigshots wear the stovepipes.
> 1 votes

# Answer
You can add a flag for the citizen to know if it's leader or not.

And you can separate the Logic/IA and made Behaviours, this way units can behave in different ways easily.

There is technique called Behaviour Trees, but maybe it will be enough for you encapsulating the state machines.
> 0 votes

---
Tags: architecture, state, objects, fsm
---


# Question
Title: Packaging Jar with External Libraries in Eclipse
I have a class called Game in the package net.aGameName and am trying to export a runnable Jar using eclipse. In the project I have two external Jar files added, lwjgl.jar and lwjgl\_util.jar.

When I go to File-\>Export-\>Runnable Jar File and choose the Launch configuration I use for testing (which works successfully) I am able to export the Jar file without any errors. Finally I open cmd and use `java aGameName.jar` and receive the following error:

```
Exception in thread "main" java.lang.NoClassDefFoundError: aGameName/jar
Caused by: java.lang.ClassNotFoundException: aGameName.jar
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: aGameName.jar.  Program will exit.

```

When I open the manifest file it says:

```
Manifest-Version: 1.0
Class-Path: .
Main-Class: net.aGameName.Game

```

Can anyone easily spot the error that would be causing this? Thanks

# Answer
> 1 votes
I actually found a small little program that would allow me to join multiple jar files together. I used this along with all the dependencies I needed and the jar that Eclipse generated to create a runable jar. Simple enough and for this small project it works fine.

http://ninjacave.com/jarsplice

# Answer
> 1 votes
Try `java -jar aGameName.jar`.

`java aGameName.jar` will try to run a class file named aGameName/jar.class.

# Answer
> 0 votes
To run the jar you have to specify java -jar JARFILENAME as @skyuzo indicated.

Below is an ant xml file that should generate the correct runnable jar using eclipse's jar in jar loader. Feel free to add any libraries to the Rsrc-Class\_Path (space seperated), also make sure your jars are in a folder called lib (or edit that part in the xml) and make sure jar-in-jar-loader.zip is next to your build.xml (or change it to an absolute location of that file, I think it is somewhere in the eclipse installation folder)

Note: this might require minor changes to suit your project.

```
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="jar" name="Create Runnable Jar with Jar-in-Jar Loader">
    <property name="src" location="src"/>
    <property name="build" location="bin"/>
    <property name="dist" location="dist"/>
    <property name="lib" location="lib"/>

    <path id="master-classpath">
        <fileset dir="${lib}" includes="*.jar"/>
    </path>

    <target name="clean">
        <delete dir="${build}"/>
        <delete dir="${dist}"/>
    </target>

    <target name="compile" depends="clean" description="Compiles the project's source code">
        <mkdir dir="${build}"/>
        <javac srcdir="${src}" destdir="${build}" debug="on" source="1.5" target="1.5" includeantruntime="false">
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${dist}"/>
        <jar destfile="${dist}/aGameName.jar">
            <manifest>
                <attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/>
                <attribute name="Rsrc-Main-Class" value="net.aGameName.Game"/>
                <attribute name="Class-Path" value="."/>
                <attribute name="Rsrc-Class-Path" value="./ lwjgl.jar lwjgl_util.jar"/>
            </manifest>
            <zipfileset src="jar-in-jar-loader.zip"/>
            <fileset dir="${build}"/>
            <zipfileset dir="${lib}" includes="*.jar"/>
        </jar>
    </target>

</project>

```

---
Tags: java, lwjgl
---


# Question
Title: What special requirements are there for making game art that supports High Definition?
What special requirements are there for making game art that supports High Definition? Does it require big changes in the way you model or texture your game objects? For instance, do models need really high resolution textures to support HD? If so, how high? And do you have to have a particular game engine that supports HD or would any game engine do? (I'm using Unity - would Unity work?). Also, are PS3 and XBox 360 the only platforms for HD or could PC and Mac handle HD games? Thanks.

# Answer
Saying your game supports (or is) HD, basically means that it can be output (/displayed/rendered) in an HD resolution (for television screens). For a 1080p TV the display resolution is typically 1920x1080 pixels and for 720p it's 1280x720 pixels, assuming a widescreen aspect ratio of 16:9.

Most modern computer monitors are able to display these resolutions and others crisply without a problem. However, older TV input standards (i.e. "standard-defition") required that the display resolution was much smaller and so older video game systems such as the N64 and PS1 would effectively be outputting to resolutions of 640×480 (NTSC, 480i). There's also the issue of 1080i vs 1080p but that's outside of the scope of this question.

If a game says it's HD, it means it supports, *and was designed for,* a high definition resolution. So when you run the game at 1080p, the graphics will be crisp and clear, and the framerate will be consistent1.

> What special requirements are there for making game art that supports High Definition? Does it require big changes in the way you model or texture your game objects? For instance, do models need really high resolution textures to support HD?

The fact that you have so many more pixels than if you were rendering to, say, 640x480, means that if your textures are low resolution, you'll be able to tell, or more importantly, your *players* will be able to tell. As for models, if your models are square and blocky, then yes, this will be noticeable and you'll also want to make new versions that look round and smooth in higher resolutions. Perhaps this can be solved with textures, but that's for you to decide when you're designing it.

> If so, how high?

I think that's something you'll have to figure out once you run it in an HD resolution. The better the quality of the textures, the better things will look in game (theoretically). But they also take up more memory and may take longer to load. Maybe you'd want to prioritize what textures have the best resolution (i.e. the main character that the player is going to see ALL the time) vs ones that may not necessarily be important (i.e. the top of a mountain).

> And do you have to have a particular game engine that supports HD or would any game engine do?

I think most game engines should support changing to/defining a new resolution. But they may not be able to render at certain resolutions. For example, an engine may support 720p but not 1080p. This does, of course, depend mostly on the game content. Any engine can render a black screen at 60fps at 1080p. :-)

> Also, are PS3 and XBox 360 the only platforms for HD or could PC and Mac handle HD games?

PS3 and Xbox 360 support HD resolutions up to 1080p (depending on model for Xbox; also, despite the max resolution, I believe most HD 360 games are 720p). The PC/Mac depends on the model and monitor so there's not really a firm "yes/no" in that category.

---

1) Consistent Framerate - At least on console, since you know the hardware limitations. It's difficult to ensure the framerate won't fluctuate on PC since you can't control the player's hardware.
> 4 votes

# Answer
HD isn't really a PC term at all. It's a TV term. All it means is that the TV has a high resolution. Nothing else. So if you make a game for PC, then an HD TV would show it just as crisp as it is on the PC. Although HD is just 1080, so if your PC screen has more, then not really... I mean, my laptop has more...
> 4 votes

---
Tags: unity, art
---


# Question
Title: How should I actually enforce the effects of components?
I asked a question about implementing components here:

Am I on the right track with this component architecture?

But I had more questions I'd like to ask.

What's the best way to actually enforce the effects of components?

For instance, I have an item object, and an optional HealingComponent. The HealingComponent allows the item to be used as a HealingItem (for restoring HP/MP/etc.). I compose the HealingComponent from up to 3 StatAffectorComponents (one for HP, MP and SP). That Affector dictates the target stat, the target amount of change, and the type of change (%, absolute, etc.). All the basic components are being implemented in C++, but I intend to make the basic components extendtable from my scripts (python)

Now my question is, how do I actually enforce this?

I had three ideas about how to do it.

1. Allow the HealingComponent to contain a Use function that takes in the appropriate parameters and applies the StatAffector components against them. This has the advantage of making it much easier to override/customize the behaviour if I extend it with scripts, but I'm also tightly coupling the mechanics of usage with the item.
2. Allow the game mechanics to enforce the components. When the item is used as a Healing Item, the mechanics will extract the stat affectors and apply them against the appropriate targets its self. This has the advantage of seperating the item/component from it's usage, but at the same time, I'll have to change the mechanics anytime I decide to add expanded functionality/components to healing items. Healing items may not change their effects too often in development, but certain item classes might
3. Allow the item itself to define it's Use function and make it responsible for checking against it's components. This is further specializing Item away from a base entity, but has the advantage of being overridable with scripts to allow custom components

In general, what is the best way to do this?

# Answer
> 1 votes
> What's the best way to actually enforce the effects of components?

Through the public interface of the component base class. Don't over-think it -- that's a trap lots of people fall into with components. Designing them is no different than designing any other subsystem. If the interface of your item components is thus

```
interface IItemComponent {
   void Use();
}

```

Then that's all you should enforce -- and if you want to enforce other things, encode that into the interface as well. There is no need to, for example, enforce that `Use` implementations actually affect stats -- what if you wanted to make a "booby-trapped healing potion" that instead of healing anybody when used, set off a bunch of explosions?

> In general, what is the best way to do this?

This is kind of a dangerous question, as Kylotan commented. Of the three options you've posted, the first sounds the most ideal to me based on how I've interpreted what you wrote (which may be wrong). However I would advocate in fact for an option you haven't listed when you actually have fewer components that accomplish a broader range of functionality.

Having individual components for stat modification seems granular to an extreme, and is essentially taking you down the path of shoehorning your component composition system into a domain-specific scripting language. Rather, I might consider abandoning some of these overly-granular components for a simple "script" component instead, which simply executes some Python (or Lua, et cetera) code of the author's choice, passing an interface to a script API for the component/entity in question that allows it to do things like affect statistics or create explosions or whatever.

# Answer
> 0 votes
I'd choose option 1. I don't see how this is tightly coupling mechanics at all - you can have your item Components all implement a Use() function which determines how they act when the item is used, but only the HealingComponent needs to actually do anything in that function. It will need to understand what the StatAffector components do and apply them.

Do be wary of making a system that is 100% generic at the top (eg. a bunch of components, each doing absolutely anything) and 100% specific at the bottom (eg. specific components that the owner must understand in order to use in a very individual context). In trying to convert a generic 'use' action into specific 'heal this person in these ways' actions you can end up writing a whole domain-specific language in components. Personally I prefer much coarser-grained components to avoid needing to worry about all these architectural dilemmas, in exchange for accepting I can't have a fully data-driven design.

# Answer
> 0 votes
I would actually caution you against breaking components down to that fine level of detail. This is always a hard judgement call as to where do you draw the line in breaking things into smaller components but, especially with items, smaller isn't always better.

Having an Item component with a DoSomething() method where the healing ones just happen to heal whatever the target was for use is still entirely functional and they can look like whatever their rendering component wants them to and adhere to any usage flags that are general across all item components.

Reducing components down to too fine of a level leaves you with the programming language you are working in, because at the end of the day the value to heal a stat with is actually just a small integer component.

Hope this helps.

---
Tags: game-mechanics, component-based
---


title: Microphone sound into game propagation

text:
# Question
Title: Microphone sound into game propagation
Had been any efforts made to stream real-time sound from the microphone (user's voice) into the game currently played?

This way you could hear echo of your own voice when you walked into enclosed space, strong or faint voices in a multiplayer game depending on distances between players, ...

# Answer
Mumble supports positional audio by means of plugins for various games. So you'll hear other players speaking seemingly from the relative position their avatars inside the game are to you.

But yeah, it's not exactly what you are talking about. I love your idea btw., I hope someone uses that concept in a novel way.
> 1 votes

---
Tags: sound, sound-effects
---


# Question
Title: How often to update a Game Client about the World?
Using socket.io, I have a communication similar to that of other MMORPGs, a steady connection with messages.

In my design so far, the client sends the player's position and animation frame with every update frame. When the server gets that message, it broadcasts it to all the clients, which will then move the graphic accordingly.

Would it be a better idea to 'collect' these and broadcast them, say, once in 1/10 of a second?

Also, should the client send many different messages (exp gained, clicked on item) as soon as they occur or rather just one collected? The first would be implemented easier.

# Answer
> 17 votes
I am going to approach this from a high-level discussion and then work towards your questions. For the sake of disclosure, I have no personal experiencing using socket.io but a lot of exposure to the problem space with regards to MMORPGs.

The design of an MMORPGs engine's network architecture and/or the selection of a middle-ware or open source project to provide the functionality is one of the more challenging decisions influenced by the game design, budget and technical expertise of the team. The ultimate choice will influence other architectural decisions (and sometimes design decisions as well).

As developers of MMORPGs, we plan for great success (often also known as catastrophic success) where large numbers trigger warning lights and sirens. One of the scary large numbers that crops up is in algorithms that are N-squared (N^2 hereafter), in your question the first thing that jumped out to me is that it sounded like the design called for an entity to broadcast information to all other connected entities. This is the classic example of an N^2 problem.

MMOs generally approach addressing N^2 issues by attacking the problem in several different ways; awareness systems (situational, spatial, etc) where an entity is aware of some subset of all of the other entities, partitioning players into different "shards", partitioning players in "zones" and/or instancing, implementing game mechanics that discourage too many players from congregating together (Asheron Call's teleport storms), etc.

Most MMORPGs and many FPS engines have fairly sophisticated networking architectures that support a variety of features including:

* reliable and unreliable communication pathways (TCP, custom implementations of reliable UDP and UDP packets)
* bandwidth shaping (prioritization, lifetimes, etc)
* automatic replication of field/viarable data and function calls
* atomic sets of data (i.e. data that is communicated together)
* discrete updates (i.e. where every transition is important)
* latency correction
* a variety of tricks to make the client feel responsive

I find that the Unreal Networking Documentation and Valve Networking Documentation provide a good primer on a variety of the issues.

So, now lets approach the questions.

> Would it be a better idea to 'collect' these and broadcast them, say, once in 1/10 of a second?

It's hard to provide a simple yes or no answer here...because it depends on the scale (number of observing entities), frequency of updates and size of updates. For example, collecting them all might be horridly wrong if the size of the updates could blow a buffer somewhere.

The client for MMORPGs and FPS games are generally designed such that they will visualize something that "looks" right even if they do not receive an update for many more update frames than is "normal". When using unreliable communication (UDP) you can just expect to lose some number of updates into the void, clients can make up for this by sending more frequent updates than might be used with a reliable transport.

From a cursory review of the socket.io documentation, it looks like it supports both reliable and unreliable (volatile in its terminology) communication pathways.

I'd approach this first by tackling, at what frequency are updates needed...

If a player is moving in a straight-line at a constant rate, a lower update frequency is fine because the observing clients can predict with high accuracy where the player will be at any point in time. When a player is turning in a tight circle or making rapid direction changes, then much more frequent updates are required. Conversely, when a player is not moving at all there is no reason to send out movement updates at all.

No matter what, is probably not (generally) necessary to send updates every frame from the client to the server. The server itself may choose to send messages each frame where it has them, or delay them (see bandwidth shaping, prioritization and update lifetime).

Other types of updates have different characteristics...for example consider a "health" field that is modified when a player or creature is damaged. One way to implement this is broadcast each change immediately when it happens, but this leads to wasting processing and bandwidth if the value is changed multiple times in a frame or consecutive frames (networking architectures that implement bandwidth shaping solve this issue by coalesing the updates to only the most recent is sent to an observing client when they have available bandwidth).

> should the client send many different messages (exp gained, clicked on item) as soon as they occur or rather just one collected?

Again, no simple yes or no answer is going to work here. Depending on what precisely you mean by collected...both may be right under different circumstances and also depend on implementation of the networking layer.

Collecting messages for a specific entity to be sent as one message can (depending on implementation) reduce the bandwidth overhead for sending a message (reducing your costs) conversely (depending on implementation, such as field/value mappings communicated by strings) can increase bandwidth requirements compared to a simpler specific message type.

Reviewing the socket.io documentation, it would appear to me that message overhead is on the higher end of the spectrum which would favor collecting updates to send as an aggregate message as opposed to lots of single updates.

I'd recommend reviewing all of the updates you contemplate replicating, for example most MMORPGs and FPSs do not bother to send player clicked on X events to observing clients unless that would result in a state change for an object of which they were aware as well.

# Answer
> 6 votes
Here's a real-world example: RuneScape "ticks" once every ~0.6 seconds. You can read about it here. I imagine it simplifies things from their perspective, as in their scripts they probably specify timings and delays in ticks instead of milliseconds. And of course, with such a large/slow tick rate, users with slow connections are not at a huge disadvantage compared to other players.

# Answer
> 1 votes
One way of working is to decouple the actual data changes from the broadcasting of those changes. When an object changes, make the modification and set a 'dirty' flag, and when it comes time to broadcast any changes, only send data for flagged objects, and clear the flag. Values that get changed multiple times are automatically merged here because your update only sends the state at the time of the broadcast. You can also flag sub-objects or individual properties so that you only broadcast what has changed.

Oh, and usually you wouldn't send out the animation frames to the server, or the other clients. The precise animation state is usually considered a presentation detail and left to each client to resolve, and instead you just make sure each client knows which animation is currently playing.

---
Tags: architecture, javascript, browser-based-games, websocket
---