# Question
Title: How do I handle collision detection so fast objects are not allowed to pass through walls?
I'm creating a 2d sidescrolling shooter, and I'm having a little trouble with collision detection for the bullets. Everything including the bullets are objects with their own polygons / update methods.

The trouble is that bullets go fast, and at 60 frames per second (what the game runs at) a bullet will often skip right through a wall -- since it moves more than the width of the wall during in the update interval -- and continue happily on its way since the polygons will never actually overlap.

What can I do about this? The only thing I've been able to come up with is to draw a line from the old position to the new position and do collision detection on that, but line drawing for collision detection is recommended against by the slick2d documentation. How can I solve this?

# Answer
The standard approaches are (pick one):

1. Increase your boundary width AND/OR reduce the maximum speed of your bullet so that it can never jump through a wall in a single update (requiers a bit of Pythagoras to figure out the maxium distances / minimum boundary widths);
2. Perform continuous collision detection (CCD), usually by raycasting to detect collision with linear (2) or planar (3D) surfaces ahead of the moving object. This is more expensive, but is a more well-rounded solution. Raycasting against 2D lines is pretty basic, but you do need to define all your boundaries as straight-edge polygons in this case.

For that matter, you can model your bullets as rays instead -- if that fits with the look & feel of your game, as in left4kdead. That way you don't need to approximate bullets as rays, because they already are rays. From the viewpoint of looks, this can look decent if you draw the line with a brighter spot on the bullet end, or just draw the line as a gradient from light (bullet end) to dark (tail end), giving it an appearance of motion.

I would agree that under most circumstances, using graphics for collision detection is a bit misguided, however pixel-perfect collision detection is exactly that, and is an accepted technique. I guess it all depends on what you want to achieve, and how quickly. If you don't need a very fast game with many bodies + action, go for it. Else better to use one of the approaches I outlined above.
> 10 votes

# Answer
If you want your bullets to behave like realistic physical objects (eg. your bullets are more like arrows or stones from a catapult rather than gun-fire), then you could also try to increase the frequency of your physics-updates.

So while your game might run with 60 frames per second, your physic-simulation could run at 120 updates per second (here's the ubiquitous fix your timestep article that explains a good physics setup that can run at different speed than the render-loop).

Of course, increasing the update-interval on the physics-engine will put a bigger load on the CPU. So this approach is only sensible if your projectiles aren't very fast moving (which I was assuming since you are able to tell that your projectiles are moving in arc).
> 3 votes

---
Tags: collision-detection, slick
---


# Question
Title: Which 3D graphic engine to use to target old pc's and old graphic cards?
I would like to build 3d applications that are targeted at old PCs for education. Which 3d engine do you recommend to use? What technology should I use or approach? I would like to avoid Unity3d or any other non-free frameworks, as this work I'm doing is voluntarily.

It's main idea is to make learning fun, using 3d simple gaming. The target PCs are old single cpu Pentium4, or maybe even p3 (:

Thank a lot for helping.

# Answer
> 3 votes
Check out the Unity engine. They've done a lot of work on making their tech work with a very wide range of hardware, and have nice tools like graphics emulation so you can see what an older machine would be drawing while on a newer machine. It's relatively cheap and has a really good workflow, so as long as you're not trying to squeeze all the performance you can out of an older machine it's hard to beat it's price/value ratio.

Fundamentally, though, if you're dealing with old PCs, you're going to be limiting yourself to something probably DX7 level or so. OpenGL drivers are notoriously bad, so I'd suggest going the DirectX route. You're probably not going to have pixel shaders (those came out with DX8/9 cards I think), so you need to do everything fixed function. Unity handles all of this for you.

Edit: You can download an use Unity free of charge, with certain restrictions. It doesn't play well with team development, but if you're doing small things by yourself then it's more than capable.

# Answer
> 1 votes
You might check out Ogre3D (http://www.ogre3d.org/) as a starting point. Ogre3D isn't necessarily a full game development engine, but it is a solid 3D rendering system. There are various demos you can down

Also, check out http://www.ogre3d.org/tikiwiki/Projects+Using+OGRE where a number of game engines listed that use Ogre3D.

# Answer
> 0 votes
There are many solutions. You have to make sure you know the following

* What are your skills with programming languages?
* What license is acceptable?
* Which OS(s) do you target? (Unix, Linux, Windows, Mac OS...)
* What 3D software will you use to create the assets?
* How will you manage your assets?
* What kind of interaction and environment do you want to create

You can answer a few of these questions while looking for an engine, but the more specific you are the more efficient you will be at choosing a 3D engine.

The SDL engine is a great fit usually if you keep a low polycount. http://www.libsdl.org/

If you need a first person perspective maybe a game engine will do? id Tech 3 Is well known and has support in its own community. I can attest it is good at running on "old hardware". ftp://ftp.idsoftware.com/idstuff/source/quake3-1.32b-source.zip

In the meantime Google and Wikipedia lists might be helpful.

Good luck.

---
Tags: education
---


# Question
Title: What are developers using for voice chat on Windows?
On Xbox360 XHV2 is used for dealing with voice data, and XAudio2 is used for the low-level processing of that data. What is the XHV2 equivalent under Windows, assuming FMOD is used for the low-level audio processing? Previously DirectPlay.Voice was used to facilitate this.

# Answer
There isn't any standard feature built into Windows for this that I know of. There are libraries that will do it for you like RakVoice for example, although that's integrated with RakNet. I believe the Steam APIs also have it built in.

Unfortunately Fmod lists it's voice chat support as coming in a future version - see http://www.fmod.org/index.php/products/fmodexdetailed and click on "Enhanced Internet Features".

That means you'll probably have to do it manually:

1. Record audio from a microphone.
2. Optionally process the audio to improve voice clarity. Compress it for example.
3. Encode it using a low bandwidth and low latency codec like SPEEX.
4. Send it across the network.
5. Decode it at the other end.
6. Play it back.

Fmod obviously has APIs for steps 1 and 6. It also has audio codec support so it should help a bit with step 3 and 5. The main thing you need to do is step 4.
> 2 votes

---
Tags: windows, voice, fmod
---


# Question
Title: How does an HLSL shader actually end up affecting the render output?
I understand the syntax of HLSL, for example let's pretend I have this as my HLSL:

```
struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = position;
    output.position.xy *= 0.7f;    // "shrink" the vertex on the x and y axes
    output.color = color;

    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

and I compile it like this:

```
D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);

```

How does it like... know to change... I'm confused about exactly what the pipeline between HLSL and the actual pixels/vertices on the screen is.

Is this what actually "applies" them?

```
dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);
dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pPS);

// set the shader objects
devcon->VSSetShader(pVS, 0, 0);
devcon->PSSetShader(pPS, 0, 0);

```

Keep in mind I'm like a literal *beginner* at this stuff. Can someone maybe explain *what* it's doing? I'm assuming the vertex HLSL function goes through every vertex and then changes them to whatever I have in the function, and the output is what was changed... and similarly for the pixel shader?

Another confusion, I know what a pixel is, and I understand what a vertex is... but what exactly does the pixel shader do?

# Answer
> 10 votes
> How does it like......know to change....Im confused exactly at the pipeline between HLSL and the actual Pixels/Vertex on the screen.

It works roughly like this: when you issue a draw call (DrawPrimitives, DrawIndexedPrimitives in D3D, Draw in 10+, et cetera), the geometry data you've bound to the pipeline (your vertex buffers) are processed. For every vertex, the vertex shader is executed to produce an output vertex in clip space.

The GPU then performs some fixed functions on that clip space vertex such as clipping/culling and bringing the vertex into screen space, where it begins to rasterize the triangles. During rasterization of each triangle, the GPU interpolates vertex attributes across the surface of that triangle, feeding each interpolated attribute to the pixel shader to produce a semi-final color for that pixel (blending is applied after the pixel shader executes, thus "semi-final").

> is this what actually "applies" them:

The code you posted first compiles the shaders, then binds them to the pipeline where they remain active for any subsequent draw calls until changed. It doesn't actually cause them to be executed.

> Can someone maybe explain WHAT it's doing, im assuming the Vertex HLSL function goes through every vertex (as the input Position:POSITION and color: COLOR) and then changes them to whatever I have in the function, and the output is what was changed....(same goes for Pixel Shader).
>
> Another confusion, I know what a pixel is, and I understand what a vertex is.....but what exactly does the Pixel shader do......

The vertex shader is responsible for transforming vertices from model space to clip space.

The pixel shader is responsible for computing the penultimate color/depth for a pixel based on interpolated vertex attributes.

# Answer
> 9 votes
I'll try to explain how things work without using much jargon.

If simplicity rather than interactive speed is your concern, a 3D surface in the computer would be just a huge cloud of points in space, dense enough so we can just render each point individually, without gaps between them.

You want to store a model only once in memory, but you need to display it at various sizes and from various angles, so when you render a 3D model, you need to "transform" all the points as you read them from memory. For example, to render the model 50% as big, you need to scale the positions of the points by half:

```
out.position = in.position * 0.5;
out.color = in.color;

```

This is almost the simplest "vertex shader" one can conceive: in goes a vertex position from memory, and out comes a new vertex position, half-as-big. The half-as-big vertex is not stored back to memory - it's used immediately for rendering and then thrown away.

Though a *gross oversimplification that lacks key concepts*, this *in spirit* describes aspects of how movies do graphics.

Interactive graphics (games) can't afford to be this simple, because they need to render graphics several orders of magnitude more quickly than a movie.

In games, we can't afford to render one point for each pixel on screen, plus extras to cover the gaps. So as a compromise, the gap between each three nearby points is rendered as a triangle, which for various technical reasons prefers to be at least 10 pixels big on the screen.

A 3D triangle can be *projected* onto a 2D screen, then divided into a stack of 1D lines, which can each be divided into a stack of 0D pixels. We can thus divide-and-conquer the problem of rendering a 3D triangle into the simpler problem of rendering a lot of 0D pixels in isolation. A computer can solve simpler problems in less time.

A pixel shader is a little program that we run on each pixel so generated from disassembling a triangle.

```
out.color = in.color;

```

This is almost the simplest "pixel shader" one can conceive: in goes a blend of the colors of three triangle vertices, and out goes the same color. The inputs come from the outputs of the "vertex shader" and the outputs are written to the screen in memory.

So - the "vertex shader" is a program that runs inside the GPU chip. Its input is a "vertex buffer" in GPU memory, and its output is fed directly into a "pixel shader." A "pixel shader" is also a program that runs inside the GPU chip. Its inputs are a blend of three vertices from the vertex shader, and its output is a pixel on the screen.

# Answer
> 1 votes
Besides the other answers, here's a little picture of what goes on

From pipeline stages, d3d10 (same as d3d11).

See also

# Answer
> -2 votes
Don't worry about a pixel shader right now. If you're complete beginner, you should being hello world of GLSL / HLSL with vertex and fragment shaders only. Once you're familiar and you start to understand variable movement and such, then expand your horizons.

I highly recommend a text book to get the nitty gritty as to how the API works. OpenGL books also do a good job illustrating how things have **changed** over the years from the fixed pipeline to the dynamic programmable pipeline.

Go champion!

---
Tags: directx, hlsl
---


# Question
Title: Where can I find a BRDF reference implementation?
Does anyone have a link to a sample implementation of how to create/handle 4D BRDFs?

I found a few interesting papers and websites,

but cannot seem to find any reference implementation to play with. Anyone have any?

Image from Predicting reflectance functions from complex surfaces

# Answer
> 4 votes
There are quite a few implementations of BRDFs in pbrt, the (open-source) raytracer described by the Physically Based Rendering book. That book is also a great reference for anyone interested in 3D graphics, even if you're not interested in raytracing.

---
Tags: rendering, raycasting, reflection-rendering, pbr
---


# Question
Title: How can I deploy an Android game without going through the marketplace?
How do I deploy an Android app without publishing it in the marketplace?

Let me back up a minute. I have short release cycles (2-4 weeks or less), and I would like to release a *partially complete, unpolished* game on my website so people can try it out and give me feedback.

I believe with Android, I need to go through the "Marketplace" and some rigorous process to release my app (which is not something I would do for an in-development version anyways).

So how can I get my under-development version in the hands of players?

# Answer
> 5 votes
For beta test, you can host your own APK on your webserver. Just send an email to your users with the link. That's the eaysiest way todo.

If you don't have a webserver, you can use Dropbox to host your APK and create a public url to download it.

If you want a private beta, you can use Dropbox to share with your trusted users.

# Answer
> 4 votes
Twitter and QR codes could be your best friend for this. If you create a link directly to the apk, they should be able to download and install provided that they enable the installation of non-market apps. You could write a short tutorial on doing that and use DDMS for your screen captures.

I've written Android tutorials of IT matters for the very non-technical populous of my campus, they manage to get through it. Unless your audience is particularly deficient in their ability to follow simple directions, you should be ok.

# Answer
> 1 votes
It looks like it's possible to do this by building the application and either hosting it on some local server you control (and then downloading it on the device in question) or manually copying the binary via a USB connection.

---
Tags: android, release
---


# Question
Title: How should I calculate world and projection matrices in this scenario?
I'm trying to understand transformation matrices. Suppose I use the camera from this StackOverflow answer, this is how my view matrix would look:

```
Matrix.Identity *
Matrix.CreateTranslation(-Position.X, -Position.Y, 0) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateTranslation(Scale, Scale, 0) *
Matrix.CreateScale(new Vector3(Scale, Scale, Scale));

```

How'd I calculate my World and Projection matrices then?

# Answer
> 8 votes
Well, if you want to use it for 2D games (assuming from the tags), you only need a `Transform` matrix to apply to the `SpriteBatch`, you don't need `World` and `Projection` matrices.

So, when you're drawing an object that should be drawn *inside* your game world (e.g. the main player), you use the following `Begin` method from `SpriteBatch` (XNA 4.0, replace the other parameters by what you need):

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, effect, camera.Transform);
/*
Draw the world objects like walls, players, weapons, etc.
...
*/
spriteBatch.End();

```

This will apply the camera's effect to the drawing, simulating a camera within your world.

For other visual elements that are not part of the world (like the HUD with player health, etc.), you just use the regular `Begin` method (without the camera's matrix as a parameter) to draw it, because you don't really want them to move all around the screen when the camera moves, you want them to be static.

The way the camera works is that it applies a translation matrix going in the opposite direction of where you want your camera to be (it explains the negative signs in `Matrix.CreateTranslation(-Position.X, -Position.Y, 0)` to simulate a camera moving inside a world. In fact, what you're really doing is that you're moving the world around so that the camera's view is represented by the game's window.

So, say you want your camera to move to the right by 20 pixels, you want to move your whole world to the left by 20 pixels to give the user the *feeling* that they moved to the right. This is achieved by applying the camera's matrix to all the world objects, to sort of move them around.

The same goes for scaling and rotation, you move the world around when you're drawing them to give a `feeling` of change.

# Answer
> 0 votes
The world Translation affect object in your world, so usually it will be a simple Translation. But if you want scale, rotation, ... is done this way;

```
Matrix World = Matrix.CreateTranslation(-origin,0) * MatrixCreateRotationZ(angle) * Matrix.CreateScale(scale) * Matrix.CreateTranslation(Position,0);

```

The View Matrix is the Camera matrix, i usually use:

Matrix.CreateTranslation(-Position.X, -Position.Y, 0) * Matrix.CreateRotationZ(Rotation) * Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Viewport.Center.X, Viewport.Center.Y,0);

This is the projection Matrix used by SpriteBatch (source)

```
Matrix projection = Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

projection = halfPixelOffset * projection;

```

The final transform is: World * View * Projection.

---
Tags: xna, 2d, matrix, projection
---


# Question
Title: How can I navigate to a target between bodies moving along fixed paths?
The problem: An autonomous ship starts at the outskirts of a solar system, and wants to move to a moving target, which is one of the planets. There are also many other planets moving at the same time, and these should be considered the only obstacles. I want to find the optimal path to the target. To keep it simple, the world is 2D, and the planets are moving in uniform circular motion around the sun as opposed to how planets actually behave. Also, assume the ship knows pretty much everything about the world. Most importantly, the location, speed, and orbit radius of every planet.

With complete knowledge, this seems conceptually simple. For any planet and any time, you can find its location by doing some fairly simple math. But how would you apply this to pathfinding? Would it be just to pathfind in 3 dimensions: x, y, and t? In theory this makes sense, but I think working that out to an actual solution would involve a lot of complications. Is it really as simple as 'setup a\* on a grid with x,y,t values'?

# Answer
> 5 votes
Without precision requirements, there's no way to get an optimal solution, because traditional pathfinding must consider the time / space discretely at some level. But I don't recommend traditional pathfinding for this problem anyway, at least not for the entire problem. It won't look particularly realistic, and it will use a lot of resources.

Assuming the motion of the target planet is described by `planet(t)`, ignoring obstacles, there is a closed form solution to find the intersection:

```
position + velocity * t  = planet(t)

```

Doing some basic algebra,

```
velocity * t             = (planet(t) - position)
||velocity|| * speed * t = (planet(t) - position)
||velocity||             = (planet(t) - position) / (speed * t)

```

Space is mostly empty and that holds true of most space games as well; 99% of the time, the ship can simply follow that vector to intercept the planet. This equation is trivial to solve in both CPU time and memory required.

To avoid collisions, I would use steering behaviors, notably obstacle avoidance. Once obstacles are avoided, you evaluate the equation again.

This is much lighter-weight than A\*, and probably better approximates what an actual pilot would do. It also works even if there are unpredictable obstacles, and for targets following any motion function, regardless of whether it is circular or not.

# Answer
> 1 votes
In my experiment, i tried to do something like Joe Wreschnig is sugesting. Important thing is, find out WHEN i want intercept target. I do it simply by iterating coputing how long will it take to target, where it will be by then and how long it will take there.

But my ships have inertia. But i combined collision avoidance and seeking. Basicaly, ship want to 1) be where target is 2) avoid everything else. From relative position RP to other things i compute position where ship want be (POS + k1\*RP\*(1/RP.length^n), (n something around 3-5) + k2\*(RP.x,-RP.y)\*(1/RP.length^m) so other things affect ship only little if far enough (and ship have limited sight, so most does not affect it at all) and ship want to avoid them by flying away and sideways from them, so even if it cannot even break before impact, it can miss.

Then I combine 1) and 2), so ship goes to target and once it see obstacle, it starts evading it. As obstacles gets nearer, ship evades more strongly and once it gets far, target seeking becomes dominant again.

# Answer
> 1 votes
Joe has already pointed out the important issue with the difference between discrete states and continuous states, so I'll just ignore that problem and pretend that you can pick a discrete time-step that is big enough to not be too expensive to use and small enough to have the precision you need.

Conceptually, there's no problem with your approach. Remember that A\* is not a "pathfinding" algorithm - it is a search algorithm. It doesn't require that the states it searches through correspond to geography in any way. In this case, each node of the search would include not only the ship's position but also the position of every other body in the system. (But as you already figured out, you don't need to *store* their positions for each node, as you can derive them from the current time, so you could store that instead.)

Formulating a good heuristic can be a bit more tricky - if your ship moves fast enough, then the planets won't move much during the path and so the estimated distance will decrease fairly linearly as the ship approaches. But if the ship is slow compared to the planets, you'll need a better approximation. An iterative solution is probably good here: you can estimate the time to arrive at the planet assuming it doesn't move, recalculate where the planet will actually be at that time, then estimate the actual time to reach that position, estimate where the planet will be at that second time, and so on. Hopefully the values will converge after a few iterations towards something useful - but you'll need to test this. If the values don't converge then it implies the planet is moving too fast to track and a different high-level strategy is needed (eg. pathfind to the orbit and then move along it to the destination.)

# Answer
> 0 votes
A\* is an optimization of the simpler Dijkstra algorithm, in it's base form that optimization assumes that the target is standing still. Basic Dijkstra is perfectly applicable to a moving system. You could try to gain some of A\*'s advantage by calculating a simple interception vector to use instead of distance in A\*.

Though all this does assume that your spaceship moves in a simple grid, the problem will be much harder if it has a more complex movement structure.

---
Tags: path-finding
---


title: Browser based MMO

text:
# Question
Title: Browser based MMO
We are a team of 4 trying to develop a browser based MMORPG. Its partially text based in a way like Might and Magic. The world map would be in 3D and actions would be automatically resolved. The game involves a lot of exploring. We are mainly design students and don't have much of a technical background. So our first choice to develop this game was Unity3D. Would like some advice on creating browser based game and game engines that can handle server-client interactions. Also, our game is centered around players creating communities and groups. The game should allow players to do so. While this is not our primary concern now, I would simply like to get some direction in terms of creating a browser based MMORPG.

**Edit:** Sorry for asking such a broad question, I will try to ask more specific questions

1. What technology can I use to build the client? Will simple HTMl/JS will do? How would Java work? Can I use XNA also to deploy to the web using Silverlight?
2. On the server side, what kind of software should we be looking to use? Will a linux box with LAMP work well? If I am using Unity3D can I communicate to an SQL database?
3. What kind of bandwidth am I looking at for roughly 100 users? The server will have to synchronize player position, chat, and events like quest completion and skill unlocking.

# Answer
I assume since you're students, you are building this as a class project. Please let me first suggest that you scale back your ambitions. Making games is hard, making good games is harder still. I HIGHLY recommend that you and your team

1. Greatly reduce your design. If you have a short timeframe and have to learn everything as you go, you will run into problems and it will be hard to get anything done.
2. Think single player first. Making a multi-player game is tricky and will most likely require some programming to get working. In general multi-player must be thought of and designed for early on, but I recommend your first game be a single player one.
3. Stay motivated and ask specific questions you have here when you get stuck. If you have a specific question and you show how you have tried to solve it on your own, its very likely someone on this site will be able to assist you.

The main point, is that multiplayer is hard to do, so I recommend you work on your game design skills in a single player environment. Then if you are wildly successful, maybe try adding multiplayer and/or start a new game with client/server architecture from the getgo.
> 8 votes

---
Tags: mmo, client-server, browser-based-games
---


# Question
Title: How should I update vectors, et cetera, in a time-based fashion?
I'm trying to write something I believe is straightforward but wanted to check that I'm doing it right.

All I want is to update the position of a 2D sprite based an acceleration and velocity. I'm using time based modelling so I have time deltas at my disposal. My current approach looks a little like this:

```
int rotDuration = btnRight.GetDuration() - btnLeft.GetDuration();
ship.Facing += (ANGULAR_VELOCITY * (rotDuration)); //angular displacement (rads?)

Rise::Vector2D forwardDir(sin(ship.Facing), cos(ship.Facing));
Rise::Vector2D finalVelocity = ship.Velocity + (elapsedTime * btnAcc.GetDuration() * MAX_ACC * forwardDir);
ship.Position += finalVelocity;

```

Hopefully that's pretty straightforward. I get the duration that rotation was occurring for, then multiply this by the speed I wish to allow my ships to rotate. For the velocity, I applied the equation from here. I'm very unsure as to why it says to scale the whole thing by max acceleration, though...

Does this look correct and will it produce the sort of rotation you would expect? For context I'm simulating space- or ice-like inertia.

# Answer
> 2 votes
This bit:

```
elapsedTime * btnAcc.GetDuration() * MAX_ACC

```

looks suspicious to me. I don't think there should be two different times being multiplied in; either use btnAcc.GetDuration() (I'm guessing this measures how long you were pressing a button during the last frame?) or just elapsedTime if the acceleration was occurring for the whole frame. (FWIW, I've rarely seen button presses sampled more than once per frame in a game...usually you just use elapsedTime for everything and put if-statements around it that check the buttons.)

Anyway, MAX\_ACC makes sense as it's converting from the time spent accelerating to the actual velocity change due to that acceleration, and therefore tweaks how punchy the ship will feel.

Other than that it looks like correct outer-space Newtonian physics to me.

---
Tags: physics, vector
---


title: Should I use a world matrix?

text:
# Question
Title: Should I use a world matrix?
Image reference for the question:

(image from the CG tutorial)

The D3D9 API got us used to world matrices.

However, if you use world matrices, then you have to do an extra matrix multiply in the shader (which ends up being the same for a whole lot of vertices).

Hence the OpenGL convention of concatenating the modelling and viewing matrices into one matrix (the GL\_MODELVIEWMATRIX = View\*World).

What's better, and why?

# Answer
No. At no time should you ever have an *explicit* world matrix in your shader.

A detailed explanation for why can be found here, but the short version is really very simple: you never need it and it can kill your floating-point precision.

If your world space is too big, then a camera that is far from the origin can cause floating point precision problems.

All world space is is nothing more than an intermediary between model space and camera space. It's a place where you can express the camera and all other objects in the same space. But all you use it for is to generate a world-to-camera matrix, which you then apply to all of the model-to-world matrices to create model-to-camera matrices.

You can deal with precision problems in C++ by using doubles instead of floats for matrix computations. You can convert these back to floats before uploading them to the shader.

So why would you ever *need* an explicit world-space transform in your shader? In your source code, yes. But in your shader? What would you do with it that you can't do with camera space?

Lighting can be done in camera space just as easily as world space; all you have to do is transform your light positions/directions into camera space. After all, camera space has the same scale as world space. You do this transformation once per frame per light; hardly a performance burden even on the CPU.

So there is absolutely no point in ever exposing your shaders to an *explicit* world space transform. It's just an intermediate step that you fold into your matrices.
> 7 votes

# Answer
You wouldn't do the extra matrix multiply in your shader. The trick is that you do your matrix multiplication once-per-frame on the CPU, then upload the final result to your vertex shader. That gives you one position by matrix multiplication per-vertex, irrespective of whether you have world and view separate or concatenated.
> 1 votes

# Answer
In many cases, you want to have the world pos in the vertex shader anyway, for other purposes. For example, you need to compute the view vector, to pass down into the pixel shader to evaluate specular.

The local-to-world matrix is also needed to transform tangent vectors and normal vectors\[1\] into world space for shading, assuming that you do shading in world space (you might do it in tangent space, in which case you'd need a different set of matrices).

So IMO, it makes sense to have two matrices: local-to-world and world-to-clip. The latter is the product of the view matrix and the projection matrix. Pass both to the vertex shader, and do the multiplications like:

```
posWorld = mul(posLocal, matLocalToWorld)
posClip = mul(posWorld, matWorldToClip)

```

\[1\] (So long as you don't have nonuniform scaling. In that case normals must be transformed by the inverse transpose of the local-to-world matrix.)
> 0 votes

---
Tags: matrix
---


# Question
Title: How can I implement framerate-independant updates?
**Edit:** I fixed the problem by making jumpvelocity the one that is modified and added onto, and yvelocity just equal jumpvelocity * t. This is what I have right now:

```
if (GUI->Space && grounded){
    jumpvelocity = -185.f * 2  / gravity;
    grounded = false;

}

if(!grounded ){
    if(jumpvelocity < terminaly){
        jumpvelocity += 185.f * t * 4  / gravity;
        yvelocity = jumpvelocity * t;
    }
    else{
        jumpvelocity = terminaly;
        yvelocity = jumpvelocity * t / gravity;
    }
}
else{
    yvelocity = 0.f;
    jumpvelocity = 0.f;
}

```

Thanks for the help.

I am trying to get my gravity to work. The code I have so far is

```
if (jumpvelocity < 0){
   yvelocity = jumpvelocity * t *2/gravity;
    jumpvelocity += 185.f*t * 2 / gravity;
}

else if(!grounded ){
    if(yvelocity < terminaly)
        yvelocity += t / gravity;
    else
        yvelocity = terminaly;
}

```

Gravity scales upwards, the higher making falling and jumping slower. It's default value is 1. Jumpvelocity is set to 185 when the player wishes to jump. My problem is that you fall slower at a slower framerate, but you jump at the same speed as if it was a higher framerate. How would I make it frame independent? T is delta time.

# Answer
> 13 votes
On each main loop iteration:

1. Check your system timer and store as `currentTime` (eg. SDL\_GetTicks())
2. `timeDelta = currentTime - lastTime`
3. Convert `timeDelta` to seconds (usually it's in ms or ns), store as `timeDeltaSeconds`
4. `For each entity in entities: entity.position = velocityInUnitsPerSecond * timeDeltaSeconds`
5. `lastTime = currentTime` (could also be done before step 1 instead of here)

...You will need to adjust your current numbers to be in units per second, i.e. so that they would make sense at 1FPS. For example, if you expected your character's horizontal velocity to be 2 pixels per tenth of a second, then you now need to set it as 20 pixels per second. That way, the above will work out correctly.

For some applications, it is better to fix your timestep to a given amount. In this case, `timestep != timeDelta`. The latter is the amount of system time that has actually passed; the former is a quantised amount you want to consume from your time accumulator each time you apply logic updates in your game. This assists integration when you are using iterative solvers like those found in the well-known physics engines, because timesteps must be equal when doing the calculus. In this case, because you are **not simply using up all of the time you have remaining** on each tick, you will have fractions of time left over, and you need to accumulate these for use in later ticks. For more about this, read Fix Your Timestep by Glenn Fiedler.

# Answer
> 0 votes
It does not seem that `jumpvelocity` is needed at all. Jumping means instantly setting velocity to a given value: once the feet no longer touch the ground, the only thing that can change velocity is gravity (and air resistance, that you implement using terminal velocity).

Another remark: floating point divisions are extremely slow. I suggest you store `1.0f / gravity` instead of `gravity`.

Finally, there is a possibility that for one frame `yvelocity` can be larger than `terminaly`.

My suggestion:

```
if (GUI->Space && grounded) {
    yvelocity = 185.f;
    grounded = false;
} else if (!grounded ) {
    yvelocity += t * inv_gravity;
    if (yvelocity > terminaly)
        yvelocity = terminaly;
}

```

And remember that the following is not accurate:

```
ypos += t * yvelocity;

```

You need to do:

```
ypos += t * 0.5f * (old_yvelocity + yvelocity);

```

---
Tags: c++
---


# Question
Title: Reliability and suitability of 3G connection for client-server turn-based non-asynchronous game
I am working on an iOS turn-based client-server game and I am concerned with the reliability of the connection and the length of time it takes to establish the connection.

The game is turn-based but is not asynchronous, so both players must finish their game in one sitting. If one side of the connection is lost, the person who loses connection will lose. As such this is a big concern for me.

I see applications like WhatsApp losing connection quite often even with full bar of data and it takes about 2-3 seconds every time I launch or resume the application to establish a connection. Is this the norm and is there any way to keep the connection from disconnecting from the server as long as the player has 3G connection? What are some things that I can do to improve the play experience given this condition?

# Answer
I don't have any data on 3G reliability (except personal experience that suggests it's **not** reliable). But I don't see any reason for your game to drop a player whenever she disconnects. Add a gracious timeout - when a player disconnects, wait for 2, 5 or maybe 10 seconds. If she reconnects, continue the game. With a turn-based game, this shouldn't hurt the gameplay much.
> 1 votes

---
Tags: networking, mobile, client-server, turn-based
---


# Question
Title: Can anyone recommend a 3D model viewer with shading?
I am looking for a simple real-time OpenGL based render engine to show a 3D model on screen.

I prefer using 3DS Max's 'shader' materials (real-time materials) for editing.

Do you know any good simple API to include it in an OpenGL screen? Is there a simple tool to export from 3DS Max to that tool?

# Answer
Blender supports OpenGL shading, but I don't know how the material conversion is when you export to a .obj or .fbx file.

You could also try Unity3D. This one is free as well and can import your 3ds max files on the fly (but still convert them to FBX internally). You can let Unity3D emulate OpenGL if you want.

Or if it could also be DirextX, you could also search for 3ds max directx render. There doesn't seem to be much support for that, but maybe you can find the appropriate way to view your materials that way.
> 2 votes

# Answer
I think RenderMonkey is what you're looking for. Realtime rendering, ideal for shader development. but i am afraid i misunderstood the question. Sorry if that is the case.
> 0 votes

# Answer
http://xoliulshader.com/

This is on of the best real-time viewport-shaders I know of.

It's widely used and you can see its free and looks mighty fine. It's just a new material in Max. It's popular among forums like polycount and a lot of artists use it to create renders.

edit: So it might be a good idea to look at the source ;)
> 0 votes

---
Tags: opengl, shaders
---


# Question
Title: What causes "ETC1 cannot be resolved" errors when building AndEngine?
I just got the latest AndEngine code from Mercurial, added Android 1.6 to my Order/Export tab, and cleaned everything (including a "Fix" command as instructed by the console). Regardless of which version of Android I specify in my project settings (1.5, 1.6, 2.2, 3.2), I get around 523 compilation errors.

The most unique I can see is `ETC1 cannot be resolved`, accounting for 5 out of 105 errors I can see.

The other 100 are all some variation of `The method [...] must override a superclass method`.

What am I missing? I installed the JDK, Eclipse classic, SDK manager, and everything in the SDK.

# Answer
> 2 votes
You need to set the Compiler Compliance to 1.6, otherwise it will complain about almost every occurrence of an @Override annotation.

# Answer
> 1 votes
According to http://www.andengine.org/forums/post21672.html this thread on the andengine forums, the reason is:

> Hey dude! That's because you're not using Android 2.2 in your project

---
Tags: android, andengine
---


# Question
Title: How can I fix Dalvik conversion errors during the build of an AndEngine game?
Recently I started learning AndEngine for Android. I began by implementing its examples, but I am getting problem with conversion of assets to the Dalvik format. I read elsewhere that if this problem comes up it could be settled by cleaning the project, but that did not help me.

```
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/ISVGColorMapper.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVG.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGAttributes.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGDirectColorMapper.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGGradient$SVGGradientStop.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGGradient.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGGroup.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGPaint.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGProperties.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/SVGStyleSet.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/filter/SVGFilter.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/filter/element/ISVGFilterElement.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/adt/filter/element/SVGFilterElementGaussianBlur.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/exception/SVGParseException.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/opengl/texture/region/SVGTextureRegionFactory.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/opengl/texture/source/SVGAssetTextureSource.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/opengl/texture/source/SVGBaseTextureSource.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/opengl/texture/source/SVGResourceTextureSource.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SAXHelper.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGCircleParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGEllipseParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGLineParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGNumberParser$SVGNumberParserFloatResult.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGNumberParser$SVGNumberParserIntegerResult.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGNumberParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGParserUtils.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGPathParser$PathParserHelper.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGPathParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGPolygonParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGPolylineParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGRectParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/SVGTransformParser.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/constants/ColorUtils.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/constants/ISVGConstants.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx processing org/anddev/andengine/extension/svg/util/constants/MathUtils.class...
[2011-09-30 14:55:33 - AndEngineRacer] Dx 1 error; aborting
[2011-09-30 14:55:33 - AndEngineRacer] Conversion to Dalvik format failed with error 1
[2011-09-30 14:57:32 - AndEngineRacer] Refreshing resource folders.
[2011-09-30 14:57:32 - AndEngineRacer] Starting incremental Pre Compiler: Checking resource changes.
[2011-09-30 14:57:32 - AndEngineRacer] Nothing to pre compile!

```

# Answer
> 2 votes
Another possibility for the source of the error (aside from bad intermediate files that could be resolved by cleaning the build) is a `.jar` file conflict, as discussed here on SO and here in a Google Groups discussion forum.

In fact if you search Google for that error message (in quotes) and tack "AndEngine" on to the query, you find some even more specific occurrences: here is a forum thread on the AndEngine site that explains some other `.jar` conflicts you may get with AndEngine.

# Answer
> 2 votes
Usually you run multiple of these:

* Clean project
* Open/Close project
* (Eventually manually remove the contents of the bin folder.)
* Restart Eclipse

---
Tags: andengine
---


# Question
Title: How do I place a progress bar in AndEngine?
I am developing game using AndEngine. I need to place a progress bar in my game to denote time remaining in the game. Is there a built-in method for doing this in AndEngine? My searches only turned up results for Android, not for AndEngine.

# Answer
> 3 votes
If you simply need to have a progress bar alongside your game you can use the LayoutGameActivity which was added for that purpose. `LayoutGameActivity` allows you to place the andEngine View into a standard Android layout which is loaded from XML, rather than using its default layout. As mentioned in the article, this is accomplished by overriding `getLayoutID()` and `getRenderSurfaceViewID()` in your game `LayoutGameActivity` class.

For example:

```
@Override
protected int getLayoutID() {
        return R.layout.xmllayoutexample;
}

@Override
protected int getRenderSurfaceViewID() {
        return R.id.xmllayoutexample_rendersurfaceview;
}

```

Code fragment from the linked forum post.

# Answer
> 2 votes
You could also just vary the width of a simple rectangle over time, or if you want to have it nicer, stitch together a couple of sprites.

---
Tags: andengine
---


# Question
Title: Can one develop an application with Bluetooth support on iOS using Flash Builder 4.5?
I have heard about Flash Builder 4.5.1. As I have understood, one can make an application using Flex with Flash Builder 4.5.1 and also export the release build for iOS, Android and Blackberry.

Is it possible to include Bluetooth functionality in an application this way?

# Answer
Apparently for iOS specifically, there is no Bluetooth API exposed via the SDK. While the rest of this answer may apply to other platforms, you aren't going to be able to make it work in the iPhone.

For other platforms... as far as I know there's is no API for Bluetooth access in Flex. You have a few other options though:

* This document describes how to use a third party tool or library to interact with Bluetooth (specifically to interact with a Wii remote, but you could presumably extend that to more general purpose applications).
* AIR supports native extensions, which you may be able to use to access the native Bluetooth functionality on each device.

Both options may require you to handle the cross-platform nature of the problem yourself, however (unless you use a third-party Bluetooth API that is itself cross platform).

You may also want to check out this blog post, which goes in to some detail about how a user achieved a similar thing to what you may be asking for.
> 8 votes

# Answer
From my experience I don't think there is a way through flash builder.
> 0 votes

# Answer
Not with Flash Builder, I strongly recommend learning Objective C it gives you many features and advantages such as the gamekit multiplayer tools, I recommend a visit to the apple iOS developer site (http://developer.apple.com/technologies/ios/). Here is a quick tutorial of Objective-C.
> 0 votes

---
Tags: flash, actionscript-3, flex, flash-cs5, bluetooth
---


# Question
Title: Does Apple currently accept iPhone apps with embedded Lua?
I was researching this and I can't seem to find a concrete answer.

# Answer
The iOS developer program agreement section 3.3.2 reads (in part) as follows:

> An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded.

When the license agreement was updated in 2010, this change was covered by most major Apple news sites (since it was a relaxation of the earlier rules). For example, here.

To that end, Lua should be okay as long as all the code you run is bundled within the resources of your application and never downloaded remotely (so Apple can verify it). Of course, I am not a lawyer so my interpretation of legal documents should be taken with a suitably large pinch of salt.
> 12 votes

# Answer
Considering that Corona SDK exists, I'd say yes.

Apple has also allowed Adobe to make an AIR runtime for iOS.
> 5 votes

# Answer
Apple allows any scripting language, there is a catch, it must be packaged in the app or app addons that go through apple, it cannot be downloaded of an external server and the user cannot edit it.
> 2 votes

---
Tags: iphone, lua
---


# Question
Title: Problem With Smooth Animation In C++/SDL/OpenGL
I been working in the animation of a 2D platformer game in C++/SDL/OpenGL, and my team and I reach the point where we need to establish that every animation of the player (Walking, Running, etc..) needs a different framerate for our concept, but I use as a guideline the Game Programming All In One as a example for the smooth animation, and in the book recommend have variables that limits the movement and the changes of frames.

To clarify what I mean I have in my Sprite class these parameters:

```
std::vector< Vector2f > delayMovementSprite;
std::vector< int > frameDelayPerAnimation;
GLfloat countX, countY;

```

Where the vector delayMovementSprite contains all the values for the differents animations and countX increment in every frame until it's equal or greater than the value that correspond in the vector delayMovementSprite.

Something like this:

```
void Sprite::movePosXWithSpeed()
{
  playerMoveInX = false || playerMoveInX;

  countX++;
  if ( countX > delayMovementSprite.at(getCurrentState()).x )
  {
    countX = 0;
    if ( handlerAnimation->getAnimationDirection() == SpriteData::RIGHT )
    {
      if ( position.x + getSpeedX() + width < 6368.f )
      {
        position.x += getSpeedX();
        playerMoveInX = true;
        return;
      }
    }

    else if ( position.x + getSpeedX() + width  > 0 )
    {
      position.x += getSpeedX();
      playerMoveInX = true;
      return;
    }
    playerMoveInX = false;
  }
}

```

And for the frames I have a class Animation which handles the following information:

```
Uint32 frameRate, oldTime;
int frameDelay;
int frameCount;

```

And in the function that animates I do the following, much like the MoveX in Sprite:

```
int Animation::animate()
{
  if( oldTime + frameRate > SDL_GetTicks() )
  {
    return -1;
  }

  oldTime += frameRate;
  frameCount++;

  if ( frameCount > frameDelay )
  {
    animationAlreadyEnd = false;
    frameCount = 0;
    currentFrame += incrementFrame;

    if( currentFrame > maxFrames)
    {
      animationAlreadyEnd = true;
      currentFrame = returnFrame;
    }
  }

  return currentFrame;
}

```

I got working all that and everything executes apparently fine, but in some points of the game the animation doesn't look really smooth when in other points it is.

I leave the video of the "gameplay" so everyone could see what I mean.

http://www.youtube.com/watch?v=uoxKEYzwkcQ

I currently using during the execution of the game a general Timer in 60 FPS.

If anyone needs more information, don't hesitate in ask.

Thanks a lot for the help.

# Answer
Instead of delaying a set number of frames, why not only update frame if the time elapsed since the last update is xx? (for instance 100 ms)

You're animations will look great- and won't depend on your framerate.

**In other words:** have a class variable to store the update time, and when your update function rolls around, if (the current time - previous update time \> desired frame time) increment frame()
> 3 votes

# Answer
I use a slightly different approach that you may want to consider. Instead of messing around with frame rates and vectors, I simply define some constants for the 'delay' I want between each frame

```
const float PLAYER_WALK_ANIMATION_DELAY = 0.5f;

```

and then I throw around some static's in the draw function

```
static float playerWalkDelay = 0.0f;
playerWalkDelay += 0.1f;
if (playerWalkDelay > PLAYER_WALK_ANIMATION_DELAY) {
   playerWalkDelay = 0.0f;
   animateWalk();
}

```

Like every solution to a problem this has it's pro's and con's. But I have used it in a similar game and it has worked well.

I have two side notes I would like to make. Firstly, your game looks great! Give me a PM if you need some alpha testing. Secondly, I would definitely isolate my player sprite while I am coding and testing the animations (the video is great but it makes it hard to see where/what the problem occurs; if you are debugging like this you are making life hard for yourself).
> 1 votes

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


# Question
Title: How can I make the switch from immediate mode to VBOs?
I've been using OpenGL for a short time now- and I'd like some clarification on VBOs. As I understand it, a VBO is an object stored on VRAM. In immediate mode, to apply a texture we simply bind it and specify the texture coordinates before the vertex coordinates, however it doesn't seem that way with VBOs.

**Question 1:** Can I specify texture data in a VBO? What portion of the data?

Normally when I make a game in 2d I'd store all of my objects in instances of different classes, then when my drawing routine comes up- just draw the objects that are on screen. With a 3D environment it would be a bit more difficult to just draw the objects on the screen but with some math I'm sure it's doable.

**Question 2:** Once we figure out which objects need to be rendered, would it be acceptably fast to send those corresponding objects an "apply" request, and have them apply themselves? Or is there a better way?

**Question 3:** If I have a completely dynamic map, but with objects that won't change very often, are there any guidelines as to the performance differences between `GL_STATIC_DRAW` and `GL_DYNAMIC_DRAW`?

**Final Question:** Should I even consider using vertex lists? Or are VBOs just a better option?

# Answer
> 6 votes
**Answer 1:**

Of course you can, without texturing capabilities vertex buffers would be next to useless. A VBO is just a chunk of binary data with the format you specify (position channel, normal channel, texcoord channel, etc.) that gets interpreted by a shader. When drawing an object, you are telling the GPU to fetch that batch of data and apply the operations specified in the shader (vertex transform, light calculation, texture fetches, etc.).

So, take for example you have a VBO with a quad stored in it. The VBO stores the position and texture coordinate info of the four vertices. Now the only thing you have to do is bind the VBO, bind an IBO to specify the triangles that compose your quad, tell your shader to use a texture of your choice and draw the whole thing. And now that you have the VBO and IBO active, you only need to modify the texture parameter of the shader and call again the draw function to reuse your quad into a different object.

**Answer 2:**

As specified in answer 1, when you have your VBO created and stored in VRAM, you only have to update your shader variables and call `glDrawElements` again to redraw the object.

**Answer 3:**

Well, you can apply `GL_DYNAMIC_DRAW` to the entire map, if that's what you want. The difference between these two options is that the driver chooses to store dynamic buffers in the fastest portion of VRAM it can find, so if you use it for objects that won't have their geometry repeatedly changed, you are wasting it. The OpenGL reference for glBufferData gives you a hint on what is the best usage for your buffer.

**Final answer:**

`glDrawArrays` is just a primitive version of VBOs, where the data is divided in channels but re-uploaded to the GPU on every call. Just stick with VBOs if you want the best performance.

# Answer
> 1 votes
Even though i'm completely satisfied with r2d2rigo's answer, I would like to explain how i will visualize about VBO's :D

First, Even-though VBO means Vertex Buffer Object, It doesn't mean that it holds only vextex coordinates.

```
    A Vertex will have attributes such as coordinates,texture
    coordinates,normals,color.The whole thing makes a well defined vertex.

```

So here you need to understand a VBO like - "It can be able to store the whole vertex attributes". Basically a VBO is a "buffer" that you can bind to any of the vertex info.

Answer 1 : Yes (Check the above description)

Answer 2: VBO's are usually "faster" than usual vertex lists, as there is no need of pushing the vertex info every frame(if the data is static). Even If the underlying architecture is unified memory architecture, it will have benefits as there is no "overwrite" of data unnecessarily.

Answer3 : STATIC\_DRAW/DYNAMIC\_DRAW are just flags to tell the underlying GPU where to keep the buffers.The underlying GPU will decide where to keep the buffers based on the flags you give.So this should be in mind for better throughput.But, in Unified Memory Architecture(where GPU will be sharing Main RAM),I think it will not make any significant difference.

---
Tags: opengl, c++, vbo
---


# Question
Title: What is wrong with my technique for transmitting server and client game state?
I'm doing a network implementation of a fast-paced game. I have a puck on bot the server and client side of the simulation. I want to update the client puck position only if they are on the same direction and the server's puck is ahead of the client's puck. If the message comes with a delay and the server's puck is behind client's puck I will keep that way.

So I tried this, which is not working properly and sometimes causes some glitches.

```
b2Vec2 puckLocal = b2Vec2(puck->GetLinearVelocity().x, puck->GetLinearVelocity().y);
b2Vec2 puckServer = b2Vec2(vx, vy * -1);

puckLocal.Normalize();
puckServer.Normalize();

float_t dotProduct = puckLocal.x * puckServer.x + puckLocal.y * puckServer.y;

if (dotProduct < .9) {
    return;
}

```

Is it correct? I have read that if I normalize two vectors, and do the dot product I get their direction. Which -1 means opposite direction, 0 perpendicular and 1 same direction. Is that correct?

What is the best solution when the angles differs a bit? Like the result is .85 which means that they are 30 degrees from each other? Should I interpolate it? Any suggestions on that?

# Answer
> 5 votes
What can affect the movement of the puck? Is this pong?

In any case, I would recommend a different synchronization technique. I would send three pieces of information from the server to the client:

* Position
* Velocity Magnitude and Direction
* Time on a shared clock

The shared clock can be done many different ways, and it could depend on the language you are using. A common ways to achieve a shared clock is for the server to use its own system clock, and the client(s) use their own system clock with an offset to the server's clock. To calculate the offset, the server would send its time to the client(s), and the client(s) would take the difference in clocks minus half of the ping time to adjust for network latency.

**Note:** Network time synchronization is actually quite a deep subject, I have provided a very simple solution that should work over relatively short periods of time like in a networked game. If you're interested, here's some further reading: http://en.wikipedia.org/wiki/Clock\_synchronization

By the time the client receives the puck packet, the time at which the event took place should be in the past, and you can interpolate where the puck should be as of right now. If the event is not in the past, you will want to re-adjust the client's clock.

Here is a related post: https://stackoverflow.com/questions/4713582/simple-online-pong-game-network-synchronization

---
Tags: mathematics, networking, multiplayer, vector, objective-c
---


# Question
Title: How can I improve this enemy database implementation?
I'm developing an RPG and I'm at the point where I need to start building an enemy database. There's a couple challenges associated with this and a few solutions I've been considering.

Here's what I need to do in my enemy database:

I have two primary enemy classes I need to represent data about:

A base enemy class that includes the follow:

```
Base Stats
Status Resistance Table
Elemental Resistance Table
Steal Table
Drop Table
Level
Unique ID
Base XP
AI Hook
Name
Display Name

```

And a derived class that adds the ability to add equipment, adding the following fields:

```
Main Weapon
Secondary Weapon/Equipment
Armor
Accessories

```

I may add additional fields or additional classes in the future if it makes sense. I've considered two possible formats to database enemies.

**XML Files**

I'd basically do it like this:

```
<?xml version="1.0" encoding="utf-8"?>
<Enemies>
  <Enemy name="Red Dragon" type="BaseEnemy" level="56" displayname="Red Dragon">
    <Stats HP="55000" MP="2500" SP="2500" Strength="212" Vitality="125" Magic="200" Spirit="162" Skill="111" Speed="109" Evasion="100" MgEvasion="100" Accuracy="100" Luck="55"/>
    <StatusResistances>
      <Resistance name="Sleep" value="100" />
      <Resistance name="Stop" value="100" />
    </StatusResistances>
    <ElementResistances>
      <Resistance name="Fire" value="75" />
    </ElementResistances>
    <LootTable>
      <Item name="Elixir" rate="0.03" count="1"/>
    </LootTable>
    <DropTable>
      <Item name="Elixir" rate="0.03" count="1"/>
    </DropTable>
    <AIScript value="BasicBehaviour.py" />
    <BaseXP value="4800"/>
  </Enemy>
  <Enemy name="Gaverick 1" type="HumanoidEnemy" level="33" displayname="Gaverick">
  <!--Same Stuff as above here-->
    <Equipment>
      <Weapon name="Dark Eclipse"/>
      <Armor name="Terra Defense"/>
      <Accessory name="Ribbon"/>
    </Equipment>
  </Enemy>
</Enemies>

```

Advantages:

* Easy to extend if I need to add/rearrange parameters
* easy to assign default values
* I already have an XML parser (pugixml) included for config files, tiled maps and resource description loading

Disadvantages:

* potentially slow (my database will likely hit several hundred enemies)
* can't query for arbitrary enemies, so will likely need to keep all enemies in memory.
* This would mean I need to restart the game to load changed enemy data as well

**SQLite**

For this, I'd basically make a table with columns representing all the data I'd need and leave the unnecessary fields empty

Advantages

* Arbitrary querying can keep unnecessary enemy data out of memory
* Feels more structured
* Smaller file size

Disadvantages

* More difficult to extend/rearrange parameter orders
* Unnecessary overhead to to unused fields
* Will need to write a database interface wrapper for sqlite

With this in mind I was curious on getting some outside experience on what other people have done. I may be thinking about this totally wrong, and if so, please suggest an alternative to the two possibilities I have here.

Additionally, any suggestions on how to improve either of these possibilities would be appreciated. Really, I just want to know if I'm on the right track.

I'm open to using any free library and am already incorporating boost

# Answer
I see no need for the complexity of a fully relational database. Relational databases exist to make complex searching operations easy, as well as handle searching over *vast* datasets. If all you're doing in-game is indexing one of these every time an enemy spawns, you are using an incredibly overcomplicated tool to do so.

In short, SQLite is overkill.

At which point, the question isn't SQLite vs. XML. It's how you're storing it on disk and how you want to represent the data in-game. If the only kinds of queries you do in game is to search by name, a simple `std::map` would be sufficient. Indeed, you could stick them in a `std::vector` and sort them after loading for fast searching.

For the on-disk representation, you should be most concerned with the format that makes it easiest to *edit*, not to read. Reading is something you can do easily enough in code; editing you have to do once per enemy. When you're designing new enemies, you'll have to edit their data a lot.

To me, the dichotomy is between XML and *Lua*, which is perfectly serviceable as a data-description language. For example, the example XML file could be represented in Lua as:

```
return
{
    {
        name = "Red Dragon", type="BaseEnemy", level=56, displayname="Red Dragon",
        stats = {
            HP=55000, MP=2500, SP=2500, Strength=212, Vitality=125,
            Magic=200, Spirit=162, Skill=111, Speed=109,
            Evasion=100, MgEvasion=100, Accuracy=100, Luck=55
        },
        status_resistances = {
            {name="Sleep", value=100},
            {name="Stop", value=100},
        },
        element_resistances = {
            {name="Fire", value=75},
        },
        loot_table = {
            {name="Elixir", rate=0.03, count=1},
        },
        drop_table = {
            {name="Elixir", rate=0.03, count=1},
        },
        script = "BasicBehaviour.py",
        xp = 4800,
    },
    {
        name="Gaveric 1", type="HumanoidEnemy", level=33, displayname="Gaveric",
        --Same Stuff as above here
        equipment = {
            weapon = "Dark Eclipse",
            armor = "Terra Defense",
            accessory = "Ribbon",
        }
    }
}

```

The biggest advantage to a Lua-script based approach is that... it's Lua. While it can be pure data, it does not *have* to be. So if you have some repetitions of stat blocks, you can easily have the Lua script generate these data for you. All this is is a Lua script that returns a table; the table is what you read into your in-memory data structures.

The disadvantage to this approach is mainly if you are not using a tool to write these files. If you have a tool that you use to edit these enemy files, then the Lua approach is fine. But if you're hand-editing them, then that means your loading code that walks the Lua table needs to verify the input. It needs to check that the necessary fields are there, that each number value is a valid number, etc.

And while that's not exactly difficult code to write, it is exceedingly tedious. The advantage with XML is that you can validate it with a RelaxNG or WXS schema. There are even XML editors that have schema-guided editing, so that it becomes impossible to write an *invalid* XML file.

If you need to add a new field, just adjust your schema, and you're fine. If you change the file structure, again, adjust your schema and revalidate the files, correcting errors where they appear. You can even write an XSLT tool to automatically convert files from one format version to another.

Of course, you have to know how to write schemas, and you have to have a schema-driven XML format. Otherwise, the Lua script will be no worse off, since you have to validate the data either way. And the Lua script is arguably easier to parse through, since it allows you to query the data directly. Given a Lua table that contains an enemy definition, you can query for specific "elements" by name. With an XML parser, you have to process the elements as they come to you, which is generally a bit more complex to write.

> can't query for arbitrary enemies, so will likely need to keep all enemies in memory.

... so? The data structures, taken from your example XML, would consume (with no attempts at compression:

* 14 stats * 4 bytes per = 56 bytes.
* Internal name: 32-byte string.
* Display name: 64-byte string.
* type: part of the data structure; does not need to be stored.

Each weapon can also be a 32-byte string. So a grand total in the worst case of... 248 bytes. You can store more than 3500 of those in half of a MB of RAM. I wouldn't worry about it.

> This would mean I need to restart the game to load changed enemy data as well

Why? That's up to you. There's nothing that says you can't dump the enemy data and reload it in the middle of a game. If you can't do that, it would only be because you did not properly structure your code to make that possible.
> 12 votes

# Answer
> I have two primary enemy classes I need to represent data about. A base enemy class... and a derived class...

I'm not convinced that you need two classes for this; a single one should suffice. You could just as easily model this with composition rather than inheritance; modern software design techniques are trending away from deep class hierarchies because they tend to be brittle and hard to maintain. While your proposed hierarchy is not very deep, it is unnecessary (which is a first step towards "deep"). Your derived class adds only properties which could just as easily remain on the base class but left empty.

Not only would this allow you to better iterate on and tweak the behavior and properties of your individual enemies later, it allows your code to be simpler as you deal with only a single public API and the processing thereof.

> I've considered two possible formats to database enemies.

Of these two, I would choose XML. In general, you may want to look at JSON. I don't think using an actual relational database here is warranted. See this question for some discussion about why: the short version is that it's complex and less direct to access or edit, and since you need none of the advantages a relational databases offers, you are better off sticking with something similar.

Both XML and JSON have the huge advantage of being trivially human-readable and human-editable without the need for specialized tools, which can really help increase your iteration times. XML allows you to use XSLT to to bulk transformation on your data should you ever drastically change the schema or need to do some other kind of large-scale migration.

Specifically for your three "advantages" to SQLite:

* You can just as easily keep the data out of memory when its in a file on a disk (possibly depending on your XML reader), but you probably don't want to do this as the disk is "slow" and you probably don't have enough data to really cause much memory pressure.
* It's only as structured as you make it, and designing really good, normalized database schemas isn't always a trivial task. You generally only get the maximum gains from a database when you have a proper schema design. It's much harder to change the schema, also.
* You can always transition to a binary file format for shipping your game that reduces or eliminates the inherent overhead of a more verbose, text-based format like XML or JSON. It's quite easy to do.
> 6 votes

# Answer
Here is another way to look at it, create a data structure fill it with your monster values then save the data struct to a binary file and put that in a pak file like:

```
ork_footsoldier.npcdat
ork_chief.npcdat
guard.npcdat
 Into..
NPCData.pak

```

Then load the pak to memory, parse the npcdat files, then parse the data in them at request. Its faster than XML and SQLLite, and takes up much less space.
> 3 votes

# Answer
The only advantage of SQLite I can think of, is duplication reduction, i.e. if falls into "Feels more structured" advantage part of yours.

But you can query XML with XPath, if you wish. But I think for hundreds (and even thousands) storing all data in memory is not critical. With this amount of data size of either db or XML file is not critical.

I vote for XML.
> 0 votes

---
Tags: architecture, data-structure, data
---


# Question
Title: How can I seamlessly loop a background texture in XNA?
Using XNA, I made a looping background with several textures (whose widths are over 1024px). There are fewer than five of them. All the pictures are different, held in a list and their positions are looped. When it reaches the end of the loop, it flickers.

In my `Update` method I do this:

```
dt = (float)gameTime.ElapsedTime.TotalSeconds;
foreach(BackGroundObject bgo in myList)
{
    bgo.Position += speed * dt;
}

```

So that it works based on `gameTime`. Then, in my drawing function is this code:

```
foreach(BackGroundObject bgo in myList)
{
    spriteBatch.Draw(bgo.Picture, bo.Position, Color.White);
}

```

Here is the `BackGroundObject` class. The game holds a list of `BackGroundObject`s and `Update` changes their positions. If any object goes off screen, its position is set again; a `BackGroundObject` is loaded once and the game always uses same `BackGroundObject`s. `MayDraw` is a property of the picture's position. I.e. If in the screen or not.

```
public class BackGroundObject
{
    public Texture2D Picture;
    public Vector2 Position, DrawPosition;
    public bool MayDraw;

    public BackGroundObject(Vector2 position, Texture2D picture)
    {
        this.Picture = picture;
        this.Position = position;
        this.MayDraw = true;
    }

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        if (MayDraw == true)
        {
            spriteBatch.Draw(Picture, Position, Color.White);
        }
    }
}

```

Does the flicker problem occur because of the large image sizes? Could I do this with a shader instead?

My background code works on with a graphic card with 60 FPS, but on a onboard graphic card with 30 FPS.

I have 4 background layers, each layer has 4 pictures, in total about 15pictures are drawen with widths of 1920.

# Answer
It's unclear to me what `BackGroundObject` is, and how its implemented -- it's possible the problem lies in there, or elsewhere, as the code you've provided doesn't seem terribly suspect. The biggest thing that stands out to me is that you never seem to actually loop (reset) the position of the background images at all. The "Position" value will increase without bound, unless there's a modulus operation that occurs in the setter for that property or something.

You also seem to render all the background images every frame, which is potentially wasteful as probably at most two (given their sizes) will be onscreen at once.

You may want to check out this resource on 2D scrolling background in XNA.
> 1 votes

---
Tags: xna
---


# Question
Title: What's the difference between XNA Game Services and glorified global variables?
The `Microsoft.Xna.Framework.Game` class has a Services property that allows the programmer to add a service to their game by providing the type of the class and an instance of the class to the Add method.

Now, instead of having to pass an `AudioComponent` to all classes and methods that require it, instead you just pass your `Game` instance and look up the service. (Service Locator)

Now, because games have many services (GraphicsDevice, SceneGraph, AudioComponent, EffectsManager, et cetera), you will now basically be passing Game to everything.

So why not just make these instances a Singleton? Well, because Singletons are bad because they have a global state, prevent testing, and make your design much more brittle. Service locators are equally considered to be an anti-pattern to many because instead of just passing the dependency to an object, you pass a service locator (the Game) which couples that class with the rest of the services.

So then why are Services recommended in XNA and game development? Is it because games are different from regular programs and are highly intertwined with their components and having to pass every component necessary for the functioning of a class would be highly cumbersome? Are Game Services just then a necessary evil in game design? Are there alternatives that don't involve lengthy parameter lists and coupling?

# Answer
I don't think everyone agrees that service locators are bad. Service Locators provide a way to decouple important functionality that everyone needs from their actual implementation. Service locators also provide a way to swap services at run time. Also I don't think it's true that you need to pass around the service locator around everywhere. I think you can access it from everywhere. While a game class with globals would need to be passed around a thousand times per frame (which would cause bad performance).

To make the difference between the service locator and an class with globals a bit more clear consider the following example:

I'm making a game and use a gameA class object that has a global variable: the content loader. Now in my next game I don't want to use the gameA class but create a new gameB class. I now have to again add the globals of gameA to gameB which is extra work. Also it becomes hard to configure the type of content loader I want. Say I have a game that runs both on the PC and on the XBOX. On the PC I want a content loader that can also open a 'open file' dialog. While on the XBOX I definately don't want this. By having a config file I can even halfway trough the game easily change the content loader, even from somewhere else than the gameA class, without just making the globals in gameA all public.

Now consider I'm using a service locator. I can always keep using it. And even what kind of services are there can be different all the time. It is also true that I won't even care about their implementation as long as they have a common interface. (Although I could use that in a gamA like class aswell).

Anyway I think you will find the game services pretty handy. Everyone I know uses it. To help you out a bit more. I've created a small helper class around game services so that you can do quite a bit less casting all the time: http://roy-t.nl/index.php/2010/08/25/xna-accessing-contentmanager-and-graphicsdevice-anywhere-anytime-the-gameservicecontainer/ I use it quite a lot.
> 6 votes

# Answer
> So why not just make these instances a Singleton? Well, because Singletons are bad because they have a global state, prevent testing, and make your design much more brittle.

Singletons generally take a lot of useful traits and package them together in an awful hybrid that gives you several things you don't want along with whichever bit you did want. (Was it 'create-on-demand' characteristics? Global scope? Enforcement of at least one instance? Prohibition of multiple instances?)

> Service locators are equally considered to be an anti-pattern to many because instead of just passing the dependency to an object, you pass a service locator (the Game) which couples that class with the rest of the services.

You can't avoid coupling entirely. Things use other things and without that your program does nothing. So the only real question is what level of abstraction it's at.

Most texts on object orientation make a distinction between Composition and Aggregation. It's important to know the conceptual difference between something that you own and something that you know about. Unfortunately most modern languages don't have a clear distinction here, and a reference to an object could mean either of these things. (Ironically, C++ does a better job, if you use the various smart pointer types.)

One way in which you *can* make composition and aggregation clear in your code is by using services for aggregated objects. Services are one way to provide access to stuff you don't own, but which you can use.

> So then why are Services recommended in XNA and game development?

I don't think they are universally recommended in game development.
> 5 votes

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


# Question
Title: How do I create the playing field for my game?
I want to create a game with playfield as shown in the video in OpenGL

www.youtube.com/user/stanfordcs248

I have fair knowledge of OpenGL and I know this playfield can be rendered using several different cubes but that takes a lot of effort. Also it takes away the power of easily modifying the field. One idea that was suggested to me to solve this problem was to use an XML file describing almost every component of the game. Like the floor, walls , moving floors, moving obstacles etc. That way i can easily change the playfield when I want. But this approach also seems tedious. Also I couldn't figure out the structure of the XML that would make my life quite easy. So is there any better way to create or store information about the playfield than suggested above?

Note : Blender is also an option. But please provide a tutorial if you are suggesting the Blender way.

# Answer
> 1 votes
You will need to learn how to use shaders. The models are not complex, and it uses a simple bloom shader. See This tutorial here for modern OpenGL programming.

# Answer
> 1 votes
What you are really asking is how to build an entire game with this mechanic. Although this isn't really a full tutorial here is something to get you started..

1. Learn a programming language that OpenGL supports, I recomend C++ as it is excellent for game programming.
2. Learn basics of OpenGL; Setting up a scene, rendering textured models, displaying 2D sprites, displaying font, using shaders, and basic animation.
3. Learn a bit about game loops and game logic to make the base of your engine.
4. Study the mechanics of the game design and what you want to do with that.
5. Then try to bring them all together part to part in small increments and you will have a start to a game.

---
Tags: opengl, models, blender
---


# Question
Title: Rendering an explosion in 3D Studio Max to a spritesheet?
I'd like to render a 3D explosion in 3DS Max but into a sprite sheet. My main problem is that I need to use alpha values instead of the viewport background (which is usually black).

Any ideas how I could do this?

# Answer
> 4 votes
Just render to png/tga images and make sure alpha is enabled. You can enable alpha by just rendering any frame, press save and pick PNG or TGA and check the alpha checkbox. This will remembered when you render out multiple frames.

---
Tags: sprites, 3dsmax
---


# Question
Title: How should I manage game levels in a flash games?
I am still learning and I am trying to design the game levels for my first game (a platformer).

I have some straightforward questions because I feel I am on the wrong way.

**Should each level have its own class ?**

The way I am trying to do this is, when one finishes the first level I set all variables to null that belong to that class, unregister all events and remove all children from the stage, call a second level constructor, without declaring any variable, `new level2();` and set a static var to true "in order to save" that progress in case one wants to play that level again.

**However I see the code becomes messy, I run into issues, and memory management concerns arise.**

I searched for help all over the internet but I can't find any tutorial that explain it in details, so I'm trying out many ways of achieving what I want, but now I am really in need of some advices to not get lost.

# Answer
> 5 votes
Im not a great Flash programmer, but in general it's always a bad idea to mix data and code.

You should rather try to store your data in external formats like XML and write a class to interface it.

So you basically have one Level-class and your Importer-class which can transform your XML into a level.

I hope you get the basic idea.

# Answer
> 1 votes
To add to @Anonymouse's very sensible answer -- if you intend to release it to Flash game portals, it's really important that you do not assume that you can use straight XML files with your final game, i.e. as separate files. The reason is that the portals generally expect to receive one file, your SWF, and nothing else. With AS3, it can then be better simply embed your XML into a class file using the \[Embed\] tag, and wire things up accordingly. Of course, if you want to keep the XML separate during development, and then put the XML body into a class file at the end, then that's fine too.

Although it sounds counter-intuitive, anyone who has released to the game portals out there will tell you the same. Even if not all of them require this, it is better to aim for the lowest common denominator and get a wider spread without having to have different versions for different portals.

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


# Question
Title: In cocos2d's plist output, what are 'offset,' 'colorSourceRect,' and these other fields?
```
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
        <dict>
            <key>frames</key>
            <dict>
                <key>frame1.png</key>
                <dict>
                    <key>frame</key>
                    <string>{{0,0},{96,288}}</string>
                    <key>offset</key>
                    <string>{3,-6}</string>
                    <key>rotated</key>
                    <false/>
                    <key>sourceColorRect</key>
                    <string>{{80,12},{96,288}}</string>
                    <key>sourceSize</key>
                    <string>{250,300}</string>
                </dict>
                <key>frame2.png</key>
                <dict>
                    <key>frame</key>
                    <string>{{96,0},{96,288}}</string>
                    <key>offset</key>
                    <string>{3,-6}</string>
                    <key>rotated</key>
                    <false/>
                    <key>sourceColorRect</key>
                    <string>{{80,12},{96,288}}</string>
                    <key>sourceSize</key>
                    <string>{250,300}</string>
                </dict>

```

Above there is a part of a plist output in cocos2d format. each frame has own node, I do not know what is offset, sourceColorRect is. the first string node is the Rectangle of the current frame on sprite, but what are the "offset", "sourceColorRect" and "sourceSize"

# Answer
Here's an explanation of the keys.

### frame

The sprite location within the sprite-sheet as position and size values.

### offset

Most of the current texture packing tools remove transparent areas of the image before they pack it. Imagine you got a sprite with the size of 100x100, but on the left and right there are 4 columns of totally transparent pixels. The packing tool will remove these to save space, but store `offset` and `sourceSize`, so that your sprite will be 100x100 pixels in your game. Note that the offset is always relative to the center of the sprite (comparing the center of the cropped and the center of the original sprite).

### rotated

Whether or not the sprite has been rotated within the sprite-sheet (if this is true, the sprite is rotated 90 degrees clockwise).

### sourceColorRect

The rectangle with actual color information inside your source sprite. If you take the 100x100 image described above (with 4px transparent pixels on the left and on the right), the `sourceColorRect` will be `{{4,0},{92,100}}`

### sourceSize

This is the size of the original sprite (beware that some texture-packers can add padding to this if you chose to).

---

I'm making this CW, so anybody can add corrections.
> 8 votes

---
Tags: cocos2d
---


# Question
Title: How can I create a random "world" in a tile engine?
I am designing a game that is working on a classic tile engine, but whose world is generated randomly. Are there existing games or algorithms that do this? The procedural generation algorithms I have found are never using a tile system... What would be the best way to generate a whole "world" using a tile system? I am not talking about mazes of blocks, but an overall "world map" thanks

# Answer
Your question leads you into the field of procedural content generation.

**Tile-based world generation derived from continuous/analog methods**

By continuous, I means something that is not tiles, something that is analog, an example being a vectorised map. You can use any continuous technique for generation, and then quantise it. For example generate a high resolution Perlin noise image, then reduce it's resolution to fit your tilemap size, and sample the pixels to provide yourself a heightmap. (Heightmaps can be a great starting point for your world.) This because you mentioned seeing sources that didn't show you what to do in regards to how to apply it to tiles.

**Tile-based world generation using a "blinkered" carving approach**

With a tile (cell) based approach, you can do a sort of a blind generation where you generate the world bit by bit without looking further than eg. the directly neighbouring tiles, but this tends to look like the work of an insect. This is typical CA (cellular automata) stuff, and displays little larger scale intelligence.

**Tile-based world generation using a broader world view, top-down**

This takes a more intelligent approach to building the world tile by tile, since it will first build it region-by-region. In this way you get control over eg. different biomes, political regions, etc. as Tarn Adams has done in Dwarf Fortress. Of course this requires you to think a bit about how you would like to divide up your world. There are many ways, you will have to do your own research.

---

Procedural content generation is a pretty broad topic, so you'll need to do a good amount of reading before getting a solid idea of what it is you *really* want and how to go about it -- **the devil is always in the detail**. For that reason, some good sources for this are the rec.games.roguelike.development mailing list (a ton of information on tile based procedural worlds), AmitP's game programming pages (look under "Other Topics") and last but not least, the Procedural Content Generation Wiki.
> 36 votes

# Answer
Procedural generation is an immense topic. How deep are you willing to go?

Nick Wiggill's answers are top-notch. I'd add to that by suggesting that you look at some mathematical methods of creating coherent random terrain.

Perlin noise offers a great way to create smoothed randomness, and works great for all sorts of terrain. Simulating erosion can give a realistic impression of height (although you may not need that since you're doing a tile-based game)

A lot of the techniques discussed in papers like this one by Oddlabs, makers of the Tribal Trouble, work well in 2D and at low resolutions, too. If you're more comfortable with this kind of approach, learning these techniques may be worth your while.
> 7 votes

# Answer
**Spelunky's Procedural Space \- a great introduction to procedural content generation** by Darius Kazemi

Spelunky is a 2D game by Derek Yu that has some great Procedural levels.

There's also a procedural content wiki http://pcg.wikidot.com/
> 4 votes

---
Tags: algorithm, tiles, maps, procedural-generation, tilemap
---


# Question
Title: How does one disable the right-click context menu in Flash?
I happened to play around with habbo.com social game portal.

It clearly uses Adobe Flash as platform (if you look into the source code of the HTML page). But when you do right mouse click you don't get the Flash right-click menu popping up!

Does anybody have an idea how this is done?

# Answer
That's more a question for StackOverflow, but anyway ...

The idea is to disable the right-click menu in the *JavaScript* of the page, then pass that event to the underlying Flash application via the ExternalInterface class (`ExternalInterface.addCallback("rightClick", rightClickHandlerMethod);` or similar).

An example application with source code can be found on the Another-D-Mention blog in the "Right click and custom context menu in Flash/Flex" article.
> 4 votes

---
Tags: flash, browser-based-games
---


# Question
Title: Network client-server message exchange and clock synchronization help
i'm doing a fast paced physics game that is a table hockey. With two mallets and one puck. The game runs on iphone / ipad and i'm doing the multiplayer part through GameCenter.

This is how the network system works. The client wich stars the match, will be settled as the server and the one that accepts the match request is the client.

The 'server' has the physics running and the response is immediate and the client also has their physics running so it looks smooth between messages exchange. What i do as the server, is that i send to the client my puck velocity and my position and the client adjusts his puck velocity/position related to the server to keep it sync. Otherwise the physics desynchronizes and it screws it up.

When the network latency is good, bellow 100ms the results are pretty good, i got a smooth playable game on the client side and the weird behavior are minimum. The problem happens when the lag is around 150 to 200ms. In that case, happens that my client puck already hitted a edge and inverted direction but it receives a delay message from the server and it backs a bit causing a weird feeling to the ball behavior.

I've readed a few things about it:

Pong Network Example

Click Synchronization Example

Wikipedia on Clock Sync

So, how can i solve this? As far as i've read the best option that i have is to do a clock synchronization on the server/client with a timestamp so that when i get delay messages related to my clock, i just ignore then and let the clients simulation do the job. Do you guys agree with that? And since im sending data unreliable (UDP) i may get delayed messages or messages out of order.

If that is the best approach, how do i implement the clock synchronization. I've read the steps on how to but i didn't quite understand it.

It says that:

1. Client stamps current local time on a "time request" packet and sends to server.
2. Upon receipt by server, server stamps server-time and returns
3. Upon receipt by client, client subtracts current time from sent time and divides by two to compute latency. It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta. (So far this algothim is very similar to SNTP)
4. The client repeats steps 1 through 3 five or more times, pausing a few seconds each time. Other traffic may be allowed in the interim, but should be minimized for best results The results of the packet receipts are accumulated and sorted in lowest-latency to highest-latency order. The median latency is determined by picking the mid-point sample from this ordered list.
5. All samples above approximately 1 standard-deviation from the median are discarded and the remaining samples are averaged using an arithmetic mean.

Following this example i would have this:

Lets pretend the game has loaded and my client time is 0 now, so i send to the server that my time is 0.

The messages takes 150ms to get to the server but the server's clock had already started and is 1 second ahead of the client. When the server get the message the time will be: 1.15 and sends that time to client, are we good? Lets pretend our lag is constant at 150ms.

Now the client receives the time 1.15 and subtracts current time from sent time and divides by two to compute latency. Wich is: 0.3 - 0 = 0.3/2 -\> 150ms.

It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta:
Client time: 0.3 Server time 1.15
0.3 - 1.15 = .85 + latency(.15) = 1

How is that synchronized? What am i missing?

It's my first time on multiplayer and network experience, so i'm a bit confused.

Thank you.

# Answer
> 12 votes
The algorithm posted was correct, but in your example you are forgetting about the time it takes for the server packet to get to the client, so:

```
Server time: 1
Client time: 0
Client sends 0 to server

... 150ms to get to server  (ping is 300! not 150ms in this case. Ping is round-trip)

Server time: 1.15
Client time: 0.15
Server receives packet and sends client 1.15

... 150ms to get back to client

Server time: 1.30
Client time: 0.30
Client receives 1.15 from server

```

Now as you can see, if the client changed its clock to 1.15, it would be 0.15 behind the server, this is why you have to adjust for the Ping (aka Round Trip Time \[RTT\]). Here is the full delta time calculation done over many steps:

```
Server Time - Current Time + Ping / 2
= Server Time - Current Time + (Current Time - First Packet Time) / 2
= 1.15 (Perceived, not actual!) - 0.30 + (0.30 - 0.00) / 2
= 1.00

```

This gives us the correct delta time of 1.00 seconds

---
Tags: iphone, networking, multiplayer, game-center, synchronization
---