title: Character movement on a 2D tile map

text:
# Question
Title: Character movement on a 2D tile map
I'm working at making a HTML5 game. Top down, closest thing I can equate it to is the gameboy zeldas, but open world and no rooms.

What I have so far is a procedurally generated map in a multi dimensional array. And a starting position on the map. Along with this I have an array of movable and non movable tile ID's.

I also have a class for my player and have him being rendered out in the center of the starting tile.

My problem however is getting the movement sorted out for the player. I want to be able to have the character free move around the map (pixel by pixel essentially) ontop of this 2D generated world. Ideally this would allow the user to move around the walk able area of the canvas. this is simple enough for me to do, but I am having problems now moving the world.

If the user is 20% from the edge of the screen i want the world to start panning in the direction the player is heading. But I'm rather lacking in ideas of how to do this.

I've looked around for some tutorials, but am coming up blank on ideas of how to generate the playable area (zoomed in) and to then move this generated area under the player when they reach near the end of the screen.

My current idea was to generate a certain amount of tiles full size to fill the screen and place the player i the middle. Then when the user approaches the edge of the screen start generating the tiles offset by the distance moved and the direction. I can kind of see this working but I really have no idea if this is the best or easiest to code of methods for generating the world.

sorry for the lack of code but I'm still just in the theory stages of working this all out.

# Answer
> 3 votes
Generating the world:

This is often done by dividing the world into a big rectangular areas (blocks).

You decide how big the areas are - making them big enough that one fills the whole screen is a good starting point.

You generate the area that the player starts in, and the 8 areas that go around it, like so:

```
123
4X5  < -- X is the start
678

```

When the player walks out of the first area into one of the others, you generate all the areas around that area. This means that areas will always be generated before the player walks into them.

> If the user is 20% from the edge of the screen i want the world to start panning in the direction the player is heading

Like Byte56 said this is usually done with a camera.

Have a camera object that has an x and y position.

Every time you draw something, subtract the camera's position from the thing's position.

```
drawHero(hero.x - camera.x, hero.y - camera.y)

```

Then you can make some rules to make the camera follow the hero.

```
if (hero.x > camera.x + screenWidth * 0.8) camera.x += 1; //hero is 20% from right edge of the screen, so chase after them with the camera.

```

---
Tags: 2d, javascript, html5, movement, procedural-generation
---


# Question
Title: How to draw a tileset using HTML5 canvas?
I have a tileset something like this:

```
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17, 18, 19, 20

```

My tileset draw code looks like this:

```
var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
context.drawImage(image, Math.floor(tile * tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize);

```

And this code draws the *5* tile, but how would I draw the *10* tile, or the *15* tile without adding `tileX` and `tileY`? I probably need something like `if tile is equal to 15, then draw tile 15`.

# Answer
I'm not sure I understand why adding tileX and tileY is a bad thing? If you want to draw the whole tileset, one way of doing it is with a couple of for loops like so.

```
var tileSize = 32;
var x = 10;
var y = 10;

for(var tileX = 0; tileX < x; tileX ++) {
    for(var tileY = 0; tileY < y; tileY++) {
        context.drawImage(image, tileX * tileSize,tileY * tileSize , tileSize, tileSize);
    }
}

```

JSFiddle Example

Just my preference, but the naming below might make things a bit more clear as well.

```
var tileSize = 32;
var width = 10;
var height = 10;

for(var x = 0; x < width ; x++) {
    for(var y = 0; y < height; y++) {
        context.drawImage(image, x * tileSize, y * tileSize , tileSize, tileSize);
    }
}

```

Hope that helps.
> 5 votes

# Answer
You can add tileX and tileY but hide them inside a function where they won't trouble you.

```
var drawTile = function (tile, x, y, tileSize) {
    var tileX = tile % 6; //6 is the number of tiles in each row
    var tileY = Math.floor(tile/6);
    context.drawImage(image, tileX * tileSize, tileY * tileSize, tileSize, tileSize, x, y, tileSize, tileSize);
};

```

Now you can draw any of the tiles just by giving its number:

```
var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
drawTile(tile, x, y, tileSize);
tile = 10;
x = 200;
y= 100;
drawTile(tile, x, y, tileSize);

```
> 1 votes

---
Tags: javascript, tiles, html5, html-canvas
---


# Question
Title: Rotating an object when the center in not the origin - opengl
I'm beginning with GLSL and I learning the basic, I am using glm to do the matrix calculations at this point everthing ok,the problem is how I can move the origin to the center of my object, not the other way round, for example if I have a quad whose coordinates are bottom left 0,0. bottom right 2,0. top left 0,2. top right 2,2. how can I move the origin to the center of the quat without re-writing my coordinates?

# Answer
Easy way of building the rotation matrix:

1. Start with an identity matrix
2. Translate the matrix by -centre of the object
3. Rotate the matrix by the desired amount
4. Translate the matrix by centre of the object
5. Use the resulting matrix to transform the object that you desire to rotate
> 7 votes

# Answer
In order to do that, without moving your quad, you have to use the matrices in OpenGL. In order to do this, you must,

a. Push the matrix (tell OpenGL that you will start to do some transformations, which will switch to the local coordinate system).

b. Translate to the center (Since this is the local coordinate system, you cant directly jump to a point, you must add/subtract your x, y, or z values to get there.

c. Do transformations, like rotation, and scaling. It has to be done before drawing, but it is local coordinates, so only this shape will rotate.

d. Draw the points, using the local coordinate system. Yes, you will have to reinput your vertices, but transformations are alot easier.

e. Pop the matrix (Tell OpengGL that you are done, and it will reset the transformation back to the starting point, and to the world coordinate system).

For example,

```
glPushMatrix(); //at this point, you are at 0, 0, 0, local space
glTranslatef(1.0, 1.0, 0.0); //translate 1 to the right, and up
glRotatef(45.0, 0.0, 0.0, 1.0); //rotate it 45 degrees
glVertex3f(-1.0, -1.0, 0.0); //bottom left
glVertex3f(-1.0, 1.0, 0.0); //top left
glVertex3f(1.0, 1.0, 0.0); //top right
glVertex3f(1.0, -1.0, 0.0); //bottom right
glPopMatrix(); //end that transformation sequence

```

Done!
> 0 votes

---
Tags: c++, opengl, glsl, glm
---


title: First person camera: problem

text:
# Question
Title: First person camera: problem
I have created a simple camera class, moved it from my C# (XNA) source to C++ for d3d.

Commonly it is okay, but something is wrong with rotation. If i increase its pitch/yaw values, according to received player's mouse delta (cursor move), it rotates incorrect. It rotates 'around' 'world center', not position. 'world center' is changed if i change camera position.

After i move mouse left, camera is rotated like around 0;0;0 instead of own position.

```
XMVECTOR m_vecPosition; // x,y,z camera pos
float m_fYaw, m_fPitch;// rotation

```

view matrix update function:

```
#define VectorForward       XMVectorSet(0,0,1,0)

XMMATRIX mtxRot = XMMatrixRotationRollPitchYaw(m_fPitch, m_fYaw, 0);
XMVECTOR vecPos = XMVector3Transform(m_vecPosition, mtxRot);
XMVECTOR vecLookAt = XMVector3Transform(VectorForward, mtxRot);//'forward' transformed
vecLookAt += vecPos;
XMVECTOR vecUp = XMVector3Transform(VectorUp, mtxRot);
m_mtxView = XMMatrixLookAtLH(vecPos, vecLookAt, vecUp);

```

In XNA project my camera worked fine, like in FPS games, but it is impossible to move it to C++, this code definitely not correct.

And another question about camera if some one could help me:) Do i need to limit(lock) picth,yaw abs to PI\*2 ? Or i what i need to do with always increasing yaw, for example ?

My camera rotates around 0;0;0, not around its position. Rotation camera makes always its look-at in center of the world. If i move camera position, i can offset its 'relative world center'. **I need to make my camera properly first person, or properly third person.**.

# Answer
If you want the camera to rotate about itself, it stands to reason that the camera position will be the same both before & after the update. But in your code, as soon as you change your rotation matrix, you will alter the camera position so it will not appear to rotate in place like you want.

Your camera position should have nothing to do with the camera rotation. Try commenting out the line that transforms `m_vecPosition`. Then handle `m_vecPosition` independently of the camera rotation.
> 2 votes

# Answer
Correct code (if someone will ever need it - first person camera):

```
MVector m_vecPosition;      // used as read-only current camera position
MVector m_vecTranslation;   // used for moving the camera
float m_fYaw, m_fPitch;     // rotation (Roll isn't used)

    // Pitch limitation (careful)
    #define PITCH_LIM_UP    (-XM_PIDIV2 + 0.8f) // pitch--
    #define PITCH_LIM_DOWN  (XM_PIDIV2 - 0.35f) // pitch++

```

View matrix update function:

```
// Move camera in world (using YAW rotation only):
if( !VectorEqual(m_vecTranslation, VectorZero) )
{
    MMatrix mtxYaw = XMMatrixRotationRollPitchYaw(0, m_fYaw, 0);
    m_vecTranslation = XMVector3Transform(m_vecTranslation, mtxYaw);
    m_vecPosition += m_vecTranslation;
    m_vecTranslation = VectorZero;
}

// Calculate the rotation matrix
MMatrix mtxRotation = XMMatrixRotationRollPitchYaw(m_fPitch, m_fYaw, 0);

// Calculate the new target
MVector forward = XMVector3Transform(VectorForward, mtxRotation);
MVector vecTarget = m_vecPosition + forward;

// Calculate the up vector
MVector up = XMVector3Transform(VectorUp, mtxRotation);

// View matrix
m_mtxView = XMMatrixLookAtLH(m_vecPosition, vecTarget, up);

```

Move and rotate functions:

```
void Move(MVector vecTranslation) { m_vecTranslation += vecTranslation; }

// Auto rotate camera (yaw, pitch)
void Rotate(float fYaw, float fPitch)
{
    // Rotate up/down has fixed limit angle:
    m_fPitch = Math::Clamp(m_fPitch + fPitch, PITCH_LIM_UP, PITCH_LIM_DOWN);

    // Avoid abs(Yaw) > XM_PI (360)
    m_fYaw += fYaw;
    if(m_fYaw > XM_PI)
        m_fYaw = -XM_PI + (m_fYaw - XM_PI);
    else if(m_fYaw < -XM_PI)
        m_fYaw = XM_PI - (-XM_PI + m_fYaw);
}

```

Rotate() is a little present from me if some one will need to make camera limited with up/down correctly, and make it possible to rotate infinite with Yaw (left/right) in bounds of XM\_PI.

In my code i have some macroses or external stuff which is easy to understand what it does.
> 0 votes

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


title: Client side prediction on FPS game

text:
# Question
Title: Client side prediction on FPS game
I've recently attempted to develop a simple client prediction for an FPS based on Gaffer on Games famous blog (http://gafferongames.com/game-physics/networked-physics/).

Now I've gotten to the point that everything works (more or less), my main problem is crossing the message sent from the server and finding the appropriate snapshot on the client. I can use the last/average ping time to find a very near state, but it will never be exactly timed/placed as on the server.

So my question is - how exactly can I sync and find the time stamp sent from the server to the client and find which snapshot is the correct one on the client?

# Answer
Just read this: http://www.gabrielgambetta.com/?p=22

1. On every recording record current time/frame
2. On every RPC sent to server attach frame/time
3. Server sends back result with frame/time
4. Now the client knows exactly which frame the server's result is about
5. Commence "player prediction" + rewind & replay
> 6 votes

---
Tags: multiplayer, server, client-server
---


# Question
Title: Is it legal to reuse a 3D model as long as it has a new texture?
If I create a 3D model and texture for a client, say a house. Can I reuse that same 3D model, but apply a new texture and then legally use that in my own game? Is that enough of a difference?

Thanks!

# Answer
It depends on the contractual agreement you have with your client. If they own all source art assets you create, then the safe answer is "no".
> 11 votes

# Answer
I would comment, but there is a 50 rep requirement for some reason. Anywho, this is the same as asking "Can I reprint an author's book as long as it has a different cover?".

If you make it to sell to a client, then I would say the answer is one big no. It is that client's property, not yours.
> 2 votes

# Answer
I agree with the contract statements, but if I were you, I would use the original mesh as a base, then expand/improve/modify it to a point where it is no longer the same as it was but has helped you to save time when making the new model - the term for this is 'kit bashing' - creating a bunch of reusable assets that you re-use whenever you need a similar mesh to save time.
> -1 votes

---
Tags: 3d, textures, models, legal, art
---


# Question
Title: Should Draw method calculate the element's screen location?
Should Update take care of calculating the drawing position of element or should it be done exlusively in Draw method?

If I calculate the drawing position of element in Update and then store it as element property then I can reuse it in Draw method. I can only run the update if the element (or camera) moved so it seems it would be good for performance. Is this good approach? Or should I never store the draw position of an element and always calculate it in Draw method?

EDIT:

It seems my question wasn't clear enough. I'm not talking about elements Draw method but the Draw method of manager/renderer that draws them on the screen. The elements themselves do not have Draw method.

# Answer
Trick question. The correct answer is that elements should *not* have a `Draw` method. A renderer of some sort should contain the collection of objects to draw which it then can efficiently pack or instance in one big go after culling.

The final drawing position will be dependent on a camera, which the renderer is likely to have easy access to but the individual elements would not. You'd usually do the actual draw position calculating on the GPU (either with fixed function or programmable pipelines). A common HLSL shader for this might be:

```
float4x4 ModelMatrix;
float4x4 CameraMatrix;
float4x4 ProjectionMatrix;

void main(in float3 input : POSITION, out float4 output : SV_POSITION) {
  output = mul(float4(input, 1), ModelMatrix);
  output = mul(output, CameraMatrix);
  output = mul(output, ProjectionMatrix);
}

```

The position of the element itself is written to the `ModelMatrix` as a translation. The actual drawing position is calculated using the camera and projection.

There are cases where you want to do this on the CPU. The math is the exact same, you just use whatever your CPU-side math library is instead of using HLSL.

A big win for the renderer approach - especially if you're doing sprites (you didn't specify) or particles - is that you can avoid drawing each element individually. It can be much more efficient to using *hardware instancing* or to do the CPU-side math and pack all the objects into a single vertex buffer (profile to find out which is faster for your specific uses on your target hardware, of course).

In general, focus on approaches where systems or manager of some kind operate on collections of objects rather than having an approach where objects operated on themselves. The extreme (IMO overly so) version of this is an Entity Component System.

Another approach which I'm coming to prefer lately is to simply have separate hierarchies. You have a scene graph of some kind that is nothing more than a collection of renderable objects efficiently managed by a renderer. You have a physics simulation which is nothing except bodies and physics materials managed by the physics engine (which is exactly what you get when you use physics middleware like Bullet, Box2D, Havok, PhysX, etc.). Your game objects then simply handle the game-specific logic and "glue" to keep these hierarchies meaningfully up to date. Your renderer or physics engine are typically going to be *heavily* specialized in purpose and design and don't really need or want to be constrained by game objects, nor do you want your game objects constrained by every special system. It is definitely more common in most custom engines to integrated graphics/physics with the game objects/components directly, though, and that's a perfectly valid approach.
> 2 votes

# Answer
To store the Screen location in the Element is not a good approach, because

* drawing of components should be as loosly coupled as possible
* Screen location calculations are done with tansformations of the Camera, so the object has to know the location/transformation of the camera -\> bad
> 1 votes

# Answer
You should separate logic space coordinates from rendering space coordinates.

Usually at logic space coordinates (world coordinates), your tiles will be size(1,1), your calculations will be easier and simpler.

and when you draw the tiles you will apply a camera transform that depending on scale will let you draw tiles with the size that you need, without affect your logic calculations.

Using a camera transform lets you perform screen oeprations as scrolls, zooms and rotations in an easy way, and is easy to determine the visible tiles too.

it has a lots of benefits... so NO.. is a bad idea at logic stage to calculate the screen position and size of a tile... is much better to use a camera to transform from world coordinates to screen coordinates.
> 0 votes

---
Tags: xna, xna-4.0
---


# Question
Title: GLSL Shader - Change Hue/Saturation/Brightness
I'm trying to change the hue of an image using a GLSL fragment shader. I want to achieve something similar to Photoshop's Hue/Saturation Adjustment layer.

In the following image you can see what I've got so far. I want to change the hue of the green square so it looks like the red square on the right, but with this shader I get a half red half pink square (the square in the middle).

What I'm doing in the fragment shader is converting the texture's color to HSV, then I add the HSV color that I get from the vertex shader to it and I convert the color back to RGB.
What am I doing wrong?

Fragment shader:

```
precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vHSV;
uniform sampler2D sTexture;

vec3 convertRGBtoHSV(vec3 rgbColor) {
    float r = rgbColor[0];
    float g = rgbColor[1];
    float b = rgbColor[2];
    float colorMax = max(max(r,g), b);
    float colorMin = min(min(r,g), b);
    float delta = colorMax - colorMin;
    float h = 0.0;
    float s = 0.0;
    float v = colorMax;
    vec3 hsv = vec3(0.0);
    if (colorMax != 0.0) {
      s = (colorMax - colorMin ) / colorMax;
    }
    if (delta != 0.0) {
        if (r == colorMax) {
            h = (g - b) / delta;
        } else if (g == colorMax) {
            h = 2.0 + (b - r) / delta;
        } else {
            h = 4.0 + (r - g) / delta;
        }
        h *= 60.0;
        if (h < 0.0) {
            h += 360.0;
        }
    }
    hsv[0] = h;
    hsv[1] = s;
    hsv[2] = v;
    return hsv;
}
vec3 convertHSVtoRGB(vec3 hsvColor) {
    float h = hsvColor.x;
    float s = hsvColor.y;
    float v = hsvColor.z;
    if (s == 0.0) {
        return vec3(v, v, v);
    }
    if (h == 360.0) {
        h = 0.0;
    }
    int hi = int(h);
    float f = h - float(hi);
    float p = v * (1.0 - s);
    float q = v * (1.0 - (s * f));
    float t = v * (1.0 - (s * (1.0 - f)));
    vec3 rgb;
    if (hi == 0) {
        rgb = vec3(v, t, p);
    } else if (hi == 1) {
        rgb = vec3(q, v, p);
    } else if (hi == 2) {
        rgb = vec3(p, v, t);
    } if(hi == 3) {
        rgb = vec3(p, q, v);
    } else if (hi == 4) {
        rgb = vec3(t, p, v);
    } else {
        rgb = vec3(v, p, q);
    }
    return rgb;
}
void main() {
    vec4 textureColor = texture2D(sTexture, vTextureCoord);
    vec3 fragRGB = textureColor.rgb;
    vec3 fragHSV = convertRGBtoHSV(fragRGB);
    fragHSV += vHSV;
    fragHSV.x = mod(fragHSV.x, 360.0);
    fragHSV.y = mod(fragHSV.y, 1.0);
    fragHSV.z = mod(fragHSV.z, 1.0);
    fragRGB = convertHSVtoRGB(fragHSV);
    gl_FragColor = vec4(convertHSVtoRGB(fragHSV), textureColor.w);
}

```

**EDIT:** Using the functions Sam Hocevar provided in his answer, the problem with pink bands is solved, but I can only reach half of the color spectrum. I can change the hue from red to green, but I can't change it to blue or pink.

In the fragment shader, I'm doing this now:

```
void main() {
    vec4 textureColor = texture2D(sTexture, vTextureCoord);
    vec3 fragRGB = textureColor.rgb;
    vec3 fragHSV = rgb2hsv(fragRGB);
    float h = vHSV.x / 360.0;
    fragHSV.x *= h;
    fragHSV.yz *= vHSV.yz;
    fragHSV.x = mod(fragHSV.x, 1.0);
    fragHSV.y = mod(fragHSV.y, 1.0);
    fragHSV.z = mod(fragHSV.z, 1.0);
    fragRGB = hsv2rgb(fragHSV);
    gl_FragColor = vec4(hsv2rgb(fragHSV), textureColor.w);
}

```

# Answer
As Nicol Bolas suggested in the original post's comments, I'm posting the solution to my problem in a separate answer.

The first issue was the image being rendered with pink bands, as the image in the original post shows. I fixed it using the functions Sam Hocevar provided in his answer (https://gamedev.stackexchange.com/a/59808/22302).

The second issue was that I was multiplying the hue of the texture's pixel by the value I was sending to the shader, which is meant to be an offset from the textures's pixel hue, so I had to perform an addition instead of a multiplication.
I still perform a multiplication for saturation and brightness because I get a weird behaviour otherwise, and I don't really need incrementing them further than the original texture's saturation or brightness at the moment.

This is the main() method of the shader I'm using right now. With this I can shift hue from 0º to 360º, desaturate the image, and reduce brightness.

```
void main() {
    vec4 textureColor = texture2D(sTexture, vTextureCoord);
    vec3 fragRGB = textureColor.rgb;
    vec3 fragHSV = rgb2hsv(fragRGB).xyz;
    fragHSV.x += vHSV.x / 360.0;
    fragHSV.yz *= vHSV.yz;
    fragHSV.xyz = mod(fragHSV.xyz, 1.0);
    fragRGB = hsv2rgb(fragHSV);
    gl_FragColor = vec4(fragRGB, textureColor.w);
}

```
> 4 votes

# Answer
These functions will perform very badly. I suggest using functions that are written with the GPU in mind. Here are mine:

```
vec3 rgb2hsv(vec3 c)
{
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));

    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}

vec3 hsv2rgb(vec3 c)
{
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

```

Note that for these functions the range for `H` is \[0…1\] instead of \[0…360\], so you will have to adapt your input.

Source: http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
> 31 votes

---
Tags: opengl, shaders, glsl, opengl-es2, fragment-shader
---


# Question
Title: Make perfect constant game animation using javascript
I tried different ways to make constant animations using JavaScript and HTML. The problem is that they are never perfect.

If I want to move a square exactly 5 pixels every 50 miliseconds I would use that code:

```
var leftPosition = 0;

function move() {
    leftPosition += 5;
    document.getElementById("square").style.left = leftPosition + "px";
}

window.onload = function() {
    setInterval(move, 50);
};

```

What I mean by not perfect is that the square will sometimes move slightly faster or slower during it's course. To notice that you have to really pay attention to the moving animation.

I already tried to using `requestAnimationFrame` but happened the same thing. Is there a way to improve it?

# Answer
> 2 votes
Realize that setInterval() is more of a target framerate than the actual framerate. As in, the browser will attempt to hit that framerate but may end up slower than that if is doing a lot of work. Thus you really just use setInterval() to set your game loop in motion and then use delta time for all movements. That's where you determine how much time has actually elapsed since the last frame and then multiply all movements by that delta time factor.

# Answer
> 1 votes
`leftPosition += 5;` will never give you smooth experience, I believe that's your main problem, you should do something like this:

```
float perFrameSpeed = positionDelta / targetFPS / animationFrames;

```

Where positionDelta is a delta between current position and position after animation, targetFPS - your loop fps (e.g requestAnamationFrame(function(){...}, 1000 / targetFPS)), animationFrames - how much frames should take performing animation.

And than, inside your loop, you will incr box position by this value until it reaches the desired position. That's your main problem i gas.

But you have one more - `document.getElementById("square").style.left = leftPosition + "px";` In case of constant speed it's much better to cache actual element before doing animation, e.g.

```
var box = document.getElementById('boxId');
// ....
box.style.left = leftPosition + "px";

```

But, actually, if you are working with DOM elements and don't really care about old browsers, it's much better in your case just to use CSS3, I believe there are a lot of libraries that can generate and attach CSS3 animations at run time, but I strongly recommend to give a try to zepto.js. It's clean, lightweight, fast, and you can solve problems like this really easily, just by doing something like:

```
Zepto(function($) {
    $('#box').animate({
        left: '50px' // animate from current position to left: 50px
    }, 500,/*speed in ms*/, 'ease-out'/*animation curve*/, function() {
        // animation done you can handle it here if you want to
    });
});

```

By doing so you will have VERY smooth looking animation (of course if browser has CSS3 support) even with really small animation deltas and it's also works, in most cases, perfectly on almost all mobile devices.

Of course there are a lot more inside this lib, you can check out the docs.

Hope this helps.

---
Tags: javascript, html-canvas, html, css
---


title: Framerate-independent acceleration

text:
# Question
Title: Framerate-independent acceleration
Is this the right way, or at least a way that works, for dealing with accelerations in variable time steps evironments?

```
    // Pseudo-code
    void onUpdate() {
        mySpeed += acceleration * timeElapsed; // More specifically, this part
        myPosition += mySpeed * timeElapsed;
    }

```

Truth to be said, I'm using a constant timeElapsed defined by `(1.0f / FPS_LIMIT)`, `FPS_LIMIT` being the value of the framerate at which I want the game to be locked. Speeds and accelerations are defined in the following ways:

```
    #define FRAME_DURATION (1.0f / FPS_LIMIT)

    #define RUNNING_SPEED 42 * FRAME_DURATION
    #define GRAVITY 42 * FRAME_DURATION

```

And I have noticed that, the further I increase my `FPS_LIMIT`, the faster things accelerate. Well, it's obvious (or not) that I'm using flawed logic to define the acceleration constants, but I'd also like to know what then I'm doing wrong and what'd be the right way to calculate these values, because what I'll pretty much be doing through my scripts will be as simple as this:

```
    void onUpdate() {
        mySpeed += acceleration;
        myPosition += mySpeed;
    }

```

As if framerate-independence didn't even exist.

If you want to get technical, I'm using simple SFML for the fixed time steps, through a `window.setFramerateLimit(FPS_LIMIT)` call.

# Answer
> 4 votes
First, your `timeElapsed` absolutely should not be fixed. Measure the actual frame time. Plenty of articles on it. Even with things like a `setFramerateLimit` call, the game loop might not run at that exact time every frame.

```
#define FRAME_DURATION (1.0f / FPS_LIMIT)

#define RUNNING_SPEED 42 * FRAME_DURATION
#define GRAVITY 42 * FRAME_DURATION

```

This part makes no sense. Why is speed dependent on a time variable? Speed is `distance/time`. For instance, `1.2 meters/second`. You multiply speed by time to get distance.

Take your elapsed frame time and multiply it by the speed to get unit cancellation.

```
timeElapsed = 7; // milliseconds --> .007 seconds
speed = 1.2; // meters / second
movement = speed * timeElapsed;

```

Working out that final bit on paper gives us:

```
movement = 1.2 meters / second * .007 seconds =
movement = (1.2 * .007) * (1 meters * 1 second / 1 second)
movement = .0084 * (1 meters)
movement = .0084 meters

```

Regarding acceleration, it's the same thing. Acceleration is in `meters/(second*second)` (meters per second squared). You get velocity (or speed in the mono-dimensional case) with `velocity=acceleration*time=meters/(second*second)*second=meters/second`.

So yes, the line in question is valid. You're usually dealing with *velocity*, not *speed*, though. The difference is direction. Speed says how fast you're going, velocity says how fast you're going on which way you're going. This is important for gravity. Gravity doesn't just make you accelerate; if you're jumping over a pit, the gravity force will cause you to slow down, stop for an instant at the zenith of your arc, then start making you speed up going downwards. You probably understood all this, I'm sure, but be precise with your terminology when you can. It'll avoid problems down the road.

```
void onUpdate() {
    mySpeed += acceleration;
    myPosition += mySpeed;
}

```

This makes little sense, and again, terminology. In this case, you're adding speed to another speed value (an acceleration premultipled with time), and then the second line makes no sense at all. Acceleration is the *second* derivative of position with respect to time, so you need to integrate time *twice* to properly calculate position. Even if you premultiply your initial speed, the result of adding the premultiplied acceleration will throw it out of whack. You *must* multiple by time in the second line, and I can almost guarantee that you'll be way better off multiplying acceleration by time in the first line.

# Answer
> 1 votes
Using Euler integration (which I assume is what you were going for here), your constants should be defined independent of your frame time. This is because you take time into account during your update loop.

So your constants become:

```
#define FRAME_DURATION (1.0f / FPS_LIMIT)

#define RUNNING_SPEED 42.0f
#define GRAVITY 42.0f

```

This should fix the inconsistency you're experiencing with the update loop.

However, you'll notice that this causes your objects to accelerate (and run) much faster than they used to. To fix this you could pick an arbitrary frame rate and use that to recalculate your constants:

```
#define RUNNING_SPEED 0.7f // 42 / 60
#define GRAVITY 0.7f

```

Though I'd recommend using more realistic values:

```
#define GRAVITY 9.8f // Earth's gravity in meters per second squared

```

This means when you go to add new objects to your game, you can base their properties off of real world objects, and you'll instantly have physics that seem consistent - e.g. your player could be 1.6 meters tall, the height of the average human.

I also agree with Sean that you need to be precise with your terminology, and next time your pseudo code should make use of the constants you've defined so we can see exactly what you're trying to achieve.

---
Tags: c++, sfml, frame-rate
---


# Question
Title: noSQL - Is it a valid option for web based game?
Out of an opportunity and boredom, a friend and I decided to make a web based game. This is the first 'game' I will be making, since usually I program web apps in django.

I've opted to use the same framework for the game, but I am not totally sure about the data storage, since I cannot foresee future requirements and DB related issues. Lately, the noSQL movement is gaining force and I would like to explore that area.

Therefore I have the following questions:

* Would a noSQL datastorage (document-based, such as MongoDB) would be suitable for a web-based game?
* What are the issues that might arise using a conventional RDBMS, such as MySQL?
* How to insurance data consistency amongst users with MongoDB, during gameplay or at timed events, such as cron jobs?

Game overview: Typical adventure game, with the player fighting monsters and gaining items and such.

* Some data is static across all players: items, weapons, potion, maps, etc.
* Some data tied to the player: inventory, metrics (stats), progress, etc.
* A player might need to know the stats and state of another player
* Scheduled tasks will be run at certain time interval

# Answer
## Would a noSQL database be suitable for a web-based game?

Absolutely! Generally speaking, non-relational databases (such as MongoDB) are much better for games, as they are more flexible in how they model data, while being more performant than relational databases (such as SQL) - making them a "win-win" choice.

## What are the issues that might arise using a conventional RDBMS?

There are two major drawbacks to using relational databases:

* Lack of flexibility in the way you model data
* Performance

Lack of flexibility in the way you model data is a major drawback, because using a relational database forces you to model data to fit the needs of the database, rather than the database accommodating the needs of the model. For example, consider you're creating the model for how you'll store items in a game using a relational database and you decide on the following model:

```
weapon_type_id | weapon_type
1 | sharp

weapon_id | weapon| weapon_type_id | damage
1 | Short Sword | 1 | 5

potion_type_id | potion_type
1 | HP
2 | Mana

potion_id | potion| potion_type_id | modifier
1 | Healing Elixer | 1| 5
2 | Mana Drainer | 2| -5

```

Now consider how you'd need to modify the model to meet do the following:

* Add a new item type
* Create a weapon with multiple weapon types
* Create a potion item that can also be used as a weapon

Certainly all these actions are doable, but you won't be the happiest person while you're doing them, and you'll probably wonder, "is there a better solution out there for what I want to do?," when you could design a much more flexible model in a non-relational database.

**Note:** If you are unfamiliar with how document-based databases store information, please check out this link before continuing. The model presented below designed to use similar logic to what is presented in the aforementioned article.

```
db.itemTypes

name: Weapon
types: Sharp

name: Potion
types: HP, Mana

db.items

name: Short Sword
weapon
    type: Sharp (db.itemTypes reference)
    damage: 5

name: Healing Elixer
potion
    type:  HP (db.itemTypes reference)
    modifier: 5

name: Mana Drainer
potion
    type:  Mana (db.itemTypes reference)
    modifier: -5

name:  Healing Potion Sword
potion
    type: HP (db.itemTypes reference)
    modifier: 10
weapon
    type: Sharp (db.itemTypes reference)
    damage: 15

```

There are a lot of good articles on the performance of NoSQL vs SQL databases, but here is one which provides application examples so you can perform your own tests: MongoDB vs. SQL Server 2008 Performance Showdown

## How do I insure data consistency amongst users with MongoDB?

MongoDB supports read/write atomic operations on single data entities (documents), so query results from MongoDB should always be accurate with what is stored within the database.

**Edit:** Provided NoSQL example of item database
> 21 votes

# Answer
Couple of words do defend SQL databases.

1 - If you have SQL database you can work with your data not only by primary key. Most of queries in MMO goes by PK but when you need to find all users with level \> 30 what will you do in NoSQL world?

2 - If you have SQL language you may create "hotfixes" to repair broken data. For example: "update player\_items set flag=0 where item\_type\_id = 100". How can you fix this in NoSQL? I think you will have to make a script which will parse all your data...

3 - SQL databases are not so slow as you can think. My collegues create the web based MMO game, wich make 5000 transaction per second in MySQL. Is it not enough for you? If not, you may use sharding to scale your database.

4 - SQL has a foreign key constraints and such good stuff, which will help you to find bugs in your code.

NoSQL is not a silver bullet. It solves only couple of problems and brings many new problems. **So my advice - think twice before choose NoSQL.**
> 20 votes

# Answer
The answer is *yes, it's a valid option* but *no, it probably isn't a great idea*.

There are two major problems with SQL that NoSQL tries to address, when it comes to games.

The first is latency, or lag. In one sense, SQL databases are blazingly fast, processing thousands of transactions or more in tenths of a second. In another sense, they're incredibly slow, because processing just a few transactions can take that same amount of time. For most database uses, this doesn't matter, but games have a real-time component so it's not just about how many transactions you can do per second, but about the average time it takes to respond to a database transaction.

This latency is a major problem for real-time games. Many developers that need large databases (usually for MMOs) build out a caching layer that sits between the database and the game servers in order to avoid these stalls, and then flush the cache periodically. The problem? You just threw out the main reasons to use a database - atomicity, consistency, isolation, and durability.

***But that problem doesn't apply to web games.*** You've already got a high-latency connection between the player and the game, so you might as well get the throughput SQL provides, as well as the benefits of mature, well-known software.

The second problem, however, does apply to you, and that's the object-relational impedance mismatch. Games deal with objects, databases deal with rows. If you're lucky an object can be made into a row just by listing its fields, but most of the time objects are hierarchical, and you've got to flatten them out in some way to get them into rows.

Document-based databases, like CouchDB and MongoDB, solve this problem by promoting the document to the top-level object, rather than row ("document" in this case is a synonym for "object"). But by doing this, they lose many of the benefits of SQL databases. The throughput is much lower, and the locking algorithms become much more complicated.

The good news is, there are already a lot of object-relational mapping (ORM) tools available for whatever language you're using. They let you translate between objects in memory and rows in the database fairly transparently. These tools are generally not appropriate for large-scale real-time games, because they can present the worst performance aspects of SQL and NoSQL databases. But it's fine for a web game - at worst, when you run into performance problems, you can go back to doing transactions the old-fashioned way. The latency problem doesn't hurt you, and the increased throughput helps you.

Finally, to belabor a point I've made elsewhere: *This isn't about static game data.* I'm not talking about your item descriptions or your weapon damage or sprites or anything here. I mean the real, mutable game data, like what's in a player's inventory or what their stats are. All you need for the static data is a data store. Maybe it turns out that the easiest thing to do is use the same database as the data store for that because you have a great ORM; maybe you'll just need the filesystem. It's two separate problems, and one answer needn't (and probably won't) fit both cases.
> 19 votes

# Answer
> * Would a noSQL datastorage (document-based, such as MongoDB) would be suitable for a web-based game?

I'd advise to give a look at couchdb

Its interface is javascript-based, so it will blend pretty well with HTML5/javascript based games.

It is also able to work 'off-line' (making a local copy of the db) and then synchronize itself with the server later on (you might use this for instanced dungeons, for example)

> * What are the issues that might arise using a conventional RDBMS, such as MySQL?

The main issue would be that no-sql databases handle pretty differently from relational databases. Making the mental switch can be difficult.

For example, take a look at how "queries" are done in couchdb. Everything is done in javascript.

> * How to insurance data consistency amongst users with MongoDB, during gameplay or at timed events, such as cron jobs?

The process of 'synchronizing' databases is called *replication* in couchdb's lingo. You will also see the term *consistency* a lot. There are several built-in services that deal with replication & consistency. See for example the incremental replication process.
> 5 votes

# Answer
Depending on what you have in your game you might end up using both, and connecting them through the models in your game. For example player could and should be in RDB (login info) but player inventory/variable storage could go to noSQL , so your player module could `login()` using RDB and `fetchInventory()` using noSQL by the primary key.

Maps for example better to be saved in NoSQL (coordinates =\> array of different objects for example) i do not imagine saving what an area contains in RDB (except a serialized string which you need to fully unserialize to read some part of ? more CPU and RAM wasted !) well you could still save areas in RDB for example area "city X" contains the following cordinates/block (\[3,4\],\[8,7\] ...)

you could and probably should use both, and take a look into volatile storage like memcache which you might need or some temporary data (would be faster than using hard-disk for sure ! and saves you a lot of CPU but sure not RAM)

so in the end \>

it depends on what you want to have in your game ! cheerz
> 2 votes

---
Tags: architecture, web, python, databases
---


# Question
Title: C# XNA: Effecient mesh building algorithm for voxel based terrain ("top" outside layer only, non-destructible)
To put this bluntly, for non-destructible/non-constructible voxel style terrain, are generated meshes handled much better than instancing? Is there another method to achieve millions of visible quad faces per scene with ease? If generated meshes per chunk is the way to go, what kind of algorithm might I want to use based on only EVER needing the outer layer rendered?

I'm using 3D Perlin Noise for terrain generation (for overhangs/caves/etc). The layout is fantastic, but even for around 20k visible faces, it's quite slow using instancing (whether it's one big draw call or multiple smaller chunks). I've simplified it to the point of removing non-visible cubes and only having the top faces of my cube-like terrain be rendered, but with 20k quad instances, it's still pretty sluggish (30fps on my machine).

My goal is for the world to be made using quite small cubes. Where multiple games (IE: Minecraft) have the player 1x1 cube in width/length and 2 high, I'm shooting for 6x6 width/length and 9 high. With a lot of advantages as far as gameplay goes, it also means I could quite easily have a single scene with millions of truly visible quads.

So, I have been trying to look into changing my method from instancing to mesh generation on a chunk by chunk basis. Do video cards handle this type of processing better than separate quads/cubes through instancing? What kind of existing algorithms should I be looking into?

I've seen references to marching cubes a few times now, but I haven't spent much time investigating it since I don't know if it's the better route for my situation or not.

I'm also starting to doubt my need of using 3D Perlin noise for terrain generation since I won't want the kind of depth it would seem best at. I just like the idea of overhangs and occasional cave-like structures, but could find no better 'surface only' algorithms to cover that. If anyone has any better suggestions there, feel free to throw them at me too.

Thanks, Mythics

# Answer
This could help you out;

http://0fps.wordpress.com/2012/06/30/meshing-in-a-minecraft-game/
> 0 votes

# Answer
well, one big problem you will ahve is the number of triangles for just rendering flat surfaces. one thing you could do is to do some kind of optimization where a 6x6x1 arrangement of cubes gets translated into one bigger cube, thereby reducing the number of primitives.

(pre: 6\*6\*2 primitives. post: 2 primitives)

This would be expanded uppon to combine large planes into simpler meshes.

I'm at work now, so I can't really spend a lot of time on it. And I have also never done it in this kind of engine (I used it in a heightmap).

It is important to balance how much processing you do on the CPU, versus how much you leave for the GPU. If you only do rendering and world-generation at the moment; Put in a Thread.Sleep(2); or something in your update to simulate gameplay-code.
> 0 votes

---
Tags: algorithm, procedural-generation, terrain, voxels, perlin-noise
---


# Question
Title: How does CryEngine track downloads of games using their engine?
CryENGINE 3 Independent Developers Platform offers a royalty-only license model, that requires you to pay 20% of your revenues.

Their website says this about it:

> CryENGINE® 3 Independent Developers Platform We want you to make games with CryENGINE® 3 that people will want to play. We hope that your work will lead to a product you can commercialise. If this is the case, before you can sell your work or your game, you must seek a development license for CryENGINE® 3. We’ll offer a royalty-only license model for Independent Developers, where Crytek require only 20% of the developer’s revenues from the commercial launch of their game.

My question is:

**What technical mechanisms, if any, are in place for CryEngine to accurately track the downloads?**

I'm wondering how they validate my sales numbers and confirm the 20% revenue.

# Answer
> 5 votes
It's a contract. You pay them what you owe them for a license to ship games using their software.

They will know how many copies you have sold because you will tell them how many copies you have sold when you are paying your licensing fees.

---
Tags: business, cryengine
---


title: tool for visualizing simple 2d shapes

text:
# Question
Title: tool for visualizing simple 2d shapes
I'm drawing simple 2D line shapes using coordinate sets (for example, `moveTo(x,y)` `drawTo(x,y)`). I would like a tool that is like a sheet of graph paper. When I click on intersection points it records the coordinates I clicked and prints them to a dialog box.

Hopefully it would be a simple website in javascript or something. Does such a thing exist?

# Answer
This tool allows you to point and click to select points, and then draw a Line, Polyline or Polygon. It will print out the points data required.

---

There's quite a few out there that offer a similar functionality, but they're meant for use on maps. This one is a decent one that displays point information right away.

---

This one is a little bit the opposite, you mark the points and it draws them, however, you can then use matrices to transform the shape you've drawn. (You may want to use it here, as it's not cut off by bad page margins)
> 2 votes

# Answer
I have made a simple tool that allows for point drawing, image overlaying, and also matrix transforms. It's open source on github. Here's the demo:

http://bmx-pointtool.meteor.com/
> 0 votes

---
Tags: 2d, tools
---


title: Coloring Terrain By Steepness Issue

text:
# Question
Title: Coloring Terrain By Steepness Issue
Also I am attempting to implement some simple coloring by "slope" onto my planet and to do this I take the normal mapped normal "y" component and subtract it from one. Yet I am getting some strange effects, using a small grid for example:

to get this image I had to use the following code:

```
float slope = 1.0 - normal.y;
if(slope < 0.89){
color = vec3(0.545,0.353,0.169);
}else{
color = vec3(0.237,0.457,0.137);
}

```

Which doesn't make much sense to me. Also, as you can see, only one side of the terrain is being colored in this way. Shouldn't lower values for slope being more level? Thanks for the help

EDIT: Here is the terrain colored according to the pixels normal:

# Answer
> 4 votes
Solved using teodron's suggestion. Slope is now set to `float slope = length(vec2(normal.x, normal.y));` and it works perfectly.

Here is the result:

---
Tags: color, normals
---


title: How to implement an event system

text:
# Question
Title: How to implement an event system
Im trying to implement an Event System for a game, where there are classes that can fire or handle an event wheter or not they implement these interfaces:

```
public interface IGameEvent<T> where T : EventArgs
{
     event EventHandler<T> OnEvent;
}

public interface IGameHandler<T> where T : EventArgs
{
    void OnEvent(object sender, T e);
}

```

everything looked great until i realized that no class can implement more than 1 IGameEvent because it would cause duplicate declaration,

Here is an example:

```
public class Event
{
    public KeyPressEvent OnKeyPress;
    public UpdateEvent OnUpdate;

    public void AddHadler<T>(IGameEvent<T> eEvent , IGameHandler<T> eHandler) where  T : EventArgs
    {
        eEvent.OnEvent += eHandler.OnEvent;
    }

    public void RemoveHandler<T>(IGameEvent<T> eEvent, IGameHandler<T> eHandler) where T : EventArgs
    {
        eEvent.OnEvent -= eHandler.OnEvent;
    }
}

```

KeyPressEvent:

```
public class KeyPressEvent : IGameEvent<KeyPressEvent.KeyPressedEventArgs>
{
    public class KeyPressedEventArgs : EventArgs
    {
        public KeyPressedEventArgs(Keys key)
        {
            Key = key;
        }

        public Keys Key { get; private set; }
    }

    public event EventHandler<KeyPressedEventArgs> OnEvent;

    private void OnCheckForKeyPressed()  //Example
    {
        if (OnEvent != null)
            OnEvent(this, new KeyPressedEventArgs(Keys.Space));
    }
}

```

Would be better to manually store the suscribers in a list in the EventSystem ?

How slower or faster than this approach that would be?

Thanks!

# Answer
Although you can use the existing event model in C#, it might not always give you the flexibility that you require.

You can for instance not sort events based on their priority, clear events of a specific type or add a queued/delayed event.

Example)

To signup for an event the object needs a method with the same signature as the CallbackMethod delegate. The call might look like this:

```
class SomeObject
{
    private void OnDamageTaken(object sender, IGameEvent e)
    {
        ...
    }

    ... void Initialize()
    {
        ...
        EventManager.Subscribe("EVENT_PLAYERINJURED", this.OnDamageTaken);
        ...
    }
}

//Somewhere in the application
EventManager.Notify("EVENT_PLAYERINJURED", new PlayerInjuredEvent(...));

```

If you don't like using hardcoded eventIds everywhere you could introduce a property on your game event classes.

```
public PlayerInjuredEvent : IGameEvent
{
    public static string EventType
    {
            get
            {
                return "EVENT_PLAYERINJURED";
            }
    }
}

```

Now you can write:

```
EventManager.Notify(PlayerInjuredEvent.EventType, ...

```

I hope this gives you some ideas on how to solve your problem.
> 6 votes

# Answer
You're basically re-inventing `event` here. Your entire system is basically an ugly re-implementation of the existing `event` infrastructure in C#. You should try and use `event` directly instead.

Or you could even consider doing what most games do, which is to simply use methods instead of events. Have an `Update` method and (if you like) a `KeyPress` method. Then just call those methods. Very, very simple. This is preferable over events for frame-based simulations (anything with an `Update`/`Draw` loop).

(Personally I like to make key-press information available globally (not architecturally perfect, but extremely practical), or passed into an `Update` method as an argument, rather than as a separate method call.)

Along the lines of the of methods, if you're finding you have too many methods, you might want to consider a component-aggregation architecture.
> 2 votes

---
Tags: c#, performance, events
---


# Question
Title: Structure examples for web-based chat for web-based game
What would be the best tools to use to create a web based chat/messaging system ? for client we have : Browser (any JS solution - preferably without using flash like in jsocket)

for server we have : PHP / Python / (node.js not sure of this one yet) scalable MySQL structure scalable MongoDB clusters scalable redis server couple of memcache servers (128GB ram each) bunch of servers with routers (socket base load balancers stage-4) zero -MQ and/or rabbitMQ

* we will have guild chat, area chat (within Xkm) / territory chat / PM
* we have more than 1M players, 20K concurrent/online players who will be chatting in groups
* every group will have around 100-2k players depending on geo-location
* clients will have mobile apps (android and iphone) and will receive push notifications if they select to (and push notifications for PMs as well)

my question is what would be the best combination of client-server technologies to use ?

thanks

# Answer
> 1 votes
The "best" is hard to say, you should test different technologies.

I my case, I used C++ to create the server and js for client:

* The client comunicate by ajax with the server, but never close the socket. To allow that, it should expect steaming data.
* The server is made with C++, using a very fast http/https sub-set. When a client send a chat text, the server parse/log it/etc. and send it back to all clients (of the same chat room).

If the server detect a client is not active for a while (about 5min), it inform him and close the socket.

Python is not native executable, that mean slower code (and for 20k players you need high efficiency.

PHP has the same problem, and usually it is called by apache, that mean 1 running apache thread (which cost unnecesary memory).

---
Tags: mmo, php, websocket, messaging, mysql
---


# Question
Title: Implementing axonometric bird-view in XNA
I made all kinds of logic (waypath, aso) for my strategical game, based on XNA (monogame). Now I "misused" the Vector2 a little bit: As I'm working from a "top-down" perspective, I'm using the Y-axis of Vector2 as Z-axis.

My next step is to draw the elements on the screen: I think the axometric-view called "bird view" would suit the game most.

I spent most time of the weekend searching for a way to achive this, but without any luck.

I know how I would draw the objects and defining the depths, but I have no idea how to "calculate" the top-down-position to the one with the perspective.

Here's a picture of what I want to do:

How do I calculate the "real" position (here on the right-side) to the perspective-view (on the left side)? From my research I know the key-word is matrix, but that's all I’ve got.

I don't know to define this bird-view, nor how to proper set up the matrix. I guess with something like Matrix.CreateLookAt? And if so: Would I have to change all my Vector2s to Vector3, to use the "real" axis, or is there another way I could achive this?

Any help would be greatly appreciated.

Cheers, Richard

# Answer
An axonometric projection is basically an orthographic projection with a rotation. You can create an orthographic projection with `Matrix.CreateOrthographic` or its friend `CreateOrthographicOffCenter` (MSDN).

Transformation matrices are basically used to take coordinates from one "space" to another. For example, a **projection** matrix takes points in "view" space (or "camera" space - where everything is relative to the camera's position and direction) into a space appropriate for the GPU to rasterize.

One nice property of matrices is that you can combine them through matrix multiplication.

For example, if you wanted an axonometric projection, you could do something like this:

```
Matrix m = Matrix.CreateRotationX(MathHelper.PiOverTwo)
         * Matrix.CreateRotationY(MathHelper.PiOverTwo)
         * Matrix.CreateOrthographic(...);

```

(Note: I haven't checked or tested the above code - it's for illustration only.)

The rotation matrixes here are somewhat equivalent to a **view** matrix, that takes points from "world" space to "view" space. In this case it's just the orientation component. (Finally a **world** matrix takes points from object space, where your model is defined, and places them in the world).

Normally you combine these matrices like so:

```
 Matrix transform = world * view * projection;

```

Generally effects, like `BasicEffect`, do this for you.

In this context, `CreateLookAt` is generally used to create your view matrix. The matrix that it outputs transforms the entire world so that it's sitting in front of your camera.

Finally: You can use matrices to swap axes, if you need to (I'm not sure you do). Although you might have to manually create your matrices, rather than using the built-in `Create` methods, in this case.
> 2 votes

---
Tags: xna, matrix, perspective
---


# Question
Title: What are some effective methods of documenting packet protocols?
I'm working with a few developers on a hobby project and we have a lot of different APIs. What are some popular methods of creating documentation on the potential requests, and what can be expected to be returned? Is there any fancy automatic generation tools for this?

# Answer
> 1 votes
Take a look at how RFCs are done. Here's one for the client-side IRC protocol.

There is no set standard but Backus-Naur form (and extensions) are widely used. The upside of using BNF is that there exist tools that will output the code that obeys the protocol.

This means that instead of doing Manual C# =\> Autogenerated Document protocol, you could do Manual Document Protocol =\> Autogenerated C# code.

---
Tags: c#, networking, documentation
---


# Question
Title: Learning Web Development and Game Development at the same time?
I'm a junior-level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame/XNA, and love that as well.

For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full-time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. :(

# Answer
This question is probably off-topic but here's my 2 cents anyways.

Working on what you love, when you feel like it is probably going to yield the best benefits. By that I mean that if you don't feel like working on a game when you get home but force yourself to do it anyways, you won't grow as much and you'll probably get burned out really quickly. So work on what you feel like working on.

Also, a lot of people work on unrelated projects in their spare time and make it work. You don't *need* to do web dev at home as well as during your job to be good at it, although it certainly doesn't harm you in any way.

Another thing to keep in mind is that the skills you learn in one area of programming aren't necessarily exclusive to it. The concepts you'll learn in either area will definitely be relevant in the other a lot of the time. For example, Entity systems are used a lot in games but the concepts can be applied to a wide range of applications.

Lastly, give yourself some time. You don't need to rush to be a guru in something as fast as possible. Work on what you love and one day you'll realise you know a lot about it and you're not a jack of all trades, master of none anymore. Not that there's anything wrong with having very broad knowledge, it's actually a desirable skill in the industry!
> 5 votes

---
Tags: xna, monogame
---


# Question
Title: Drawing game objects that are bigger than tiles
Problem:

I have 32x32 world tiles, and a 64x64 object. I am only drawing visible tiles around the player. The object has its x and y coordinates in the tile world. I am drawing the object after I've drawn the visible area.

I'm drawing the object like this :

```
for (int y = firstY; y < lastY; y++) {
        for (int x = firstX; x < lastX; x++) {
            if (object.visible(x, y))
                object.draw();
            }
        }
    }

```

The visible(x,y) method :

```
public boolean visible(int x, int y) {
    if (this.x == x && this.y == y) {
        return true;
    }
    return false;
}

```

Now what happens is this :

Image 1. Character stands alongside the object, everything is ok.

Image 2. Character triggers screen move left, half of the object gets drawn outside the map.

Image 3. Character triggers screen move right, half of the object should be visible but its not.

I know that this happens because I'm checking only if the upper left corner of the object is visible. I'm stuck. What should I do to remedy this?

Thank you for any ideas.

# Answer
> 1 votes
Generally you don't store object positions in tiles. You can if the objects are small enough but as you found it gets tricky when they're larger.

Try storing the objects in a separate data structure like a quad tree. This way you can still quickly find all objects near the player without needing to loop over each tile position. Even for smaller objects, this has the potential of being much more efficient if your world is "sparse" (most tiles don't have objects).

Another option, if you want to stick with using the tile grid, is to delay drawing until after a sort and prune duplicates steps. Something like:

```
visible = empty array of objects

// find all visible objects, may include duplicates
for y in height:
  for x in width:
    add object at x,y to visible

// handle duplicates
sort visible
remove duplicates from visible

// draw the unique visible objects
for object in visible:
  draw object

```

You could also achieve the above with a simple flag.

```
// reset all objects
for object in world:
  object.checkDrawn = false

// draw unique objects in visible tiles
for y in HEIGHT:
  for x in WIDTH:
    if not object.checkDrawn:
      object.checkDrawn = true
      draw object

```

And yet another way would be to keep a frame number in each object (avoiding the need to "reset" the object list before rendering).

```
for y in HEIGHT:
  for x in WIDTH:
    if object.frame is not currentFrame:
      object.frame = currentFrame
      draw object

```

Still yet another way would be to take the array approach I list earlier and use a unique set (`std::set` in C++) data structure of some kind, which avoids the need to sort and prune duplicates as the set won't allow duplicates in the first place.

I do recommend the quad tree more, though. Use the tile grid for the tiles themselves and nothing else. Use separate data structures for separate purposes; tile grid for the map rendering and tile collision, quad tree for object rendering and collision, etc. You might even end up with separate data structures for object rendering vs collision, though you probably don't need it.

# Answer
> 1 votes
There's a really simple solution to this if you just want to create a quick check, and draw if it's even remotely visible.

Construct a rectangle from your camera frustum and construct a rectangle from your tile. Make sure these are both in world cordinates. Then, simply check if they intersect. If they do, draw the object. If not, don't.

# Answer
> 0 votes
A possible solution is to have a 2 dimensional array in which you store which tile/object with which offset should be displayed for each world tile.

A other possible solution is to check against the tiles one step more left

```
for (int y = firstY; y < lastY; y++) {
    for (int x = firstX; x < lastX; x++) {
        if (object.visible(x, y))
            object.draw();
        }
    }
}

for (int y = firstY; y < lastY; y++) {
    if (object.visible(x-1, y))
        object.draw(-1); // with offset
    }
}

```

---
Tags: rendering, tiles
---


title: How to create HDR and bloom in Unity3D?

text:
# Question
Title: How to create HDR and bloom in Unity3D?
Unity3D's reference describes the HDR Bloom as:

> Using HDR allows for much more control in post processing. LDR bloom has an unfortunate side effect of blurring many areas of a scene even if their pixel intensity is less than 1.0. By using HDR it is possible to only bloom areas where the intensity is greater than one.

My question is how to achieve it in a `surface shader`? I have tried to output both the `Albedo` and `Emission` greater than 1, but still when I set the Threshold of Bloom equal to or greater than 1, no visible effect can be seen.

The relevant part of shader snippet is:

```
float rim = saturate(dot(normalize(IN.viewDir), o.Normal));
if (rim >= 0.98) {
    o.Emission = 1.5; // or any large value
}

```

Which basically outputs a bright white circle when view angle and normal are at almost same angle, and I want to enhance it with HDR. But outputting a value greater than 1 is not being registered and setting the threshold almost equal to 1 (0.98 or above) creates the Bloom on areas other than the bright white spot, which is not what is needed. I have tried to output extremely large values of `Emission` and have also tried output `Albedo` \> 1.

Please tell what I am doing wrong or missing. I think I have not been able to figure out what is the meaning of `pixel intensity` \> 1 and what settings does this translate to.

# Answer
Ok, after trial and error and reading the Unity3D documentation again, and some help from the link in the comment by Blue, I have been able to figure this out:

In the shader, if emission is greater than 1, then the camera must have HDR switched on (which I missed). Then one can write in shader like this:

```
float rim = saturate(dot(normalize(IN.viewDir), o.Normal));
if (rim >= 0.98) {
    o.Emission = 1.5; // or any large value
}

```

And set threshold greater than 1, and only the areas with pixel intensity \> 1 are picked by Bloom. Also without using custom shaders, in my experiment, the default specular shader can also have pixel intensity \> 1, and is also picked up by the HDR.

One last thing, while using HDR on the camera, if Anti Aliasing is switched on, it gives a little warning:

> HDR and Multi-Sampling Anti Aliasing (in Forward Rendering path) is not supported. This camera will render without HDR buffers. Disable Anti Aliasing in Quality settings if you want to use HDR.

And HDR doesn't work. So I switched Anti Aliasing off.

This is what I missed earlier. Now the shader emits \> 1 and is easily picked by Gloom. Here is the effect before enabling HDR on the camera: Here is the effect after enabling HDR on the camera:

In the Bloom (Script), Intensity is 8.96, and Threshold is 1.1 Also to create a slight yellow color in Bloom, Color Threshold is (165, 172, 255). The car's body and windscreens have a custom shader, and the rims have the Unity's default Specular shader. Bloom with HDR works on both.
> 0 votes

---
Tags: unity, shaders, special-effects, bloom, hdr
---


# Question
Title: Multiplayer Network Game - Interpolation and Frame Rate
Consider the following scenario:

Let's say, for sake of example and simplicity, that you have an authoritative game server that sends state to its clients every 45ms. The clients are interpolating state with an interpolation delay of 100 ms. Finally, the clients are rendering a new frame every 15ms.

When state is updated on the client, the client time is set from the incoming state update. Each time a frame renders, we take the render time (client time - interpolation delay) and identify a previous and target state to interpolate from. To calculate the interpolation amount/factor, we take the difference of the render time and previous state time and divide by the difference of the target state and previous state times:

```
var factor = ((renderTime - previousStateTime) / (targetStateTime - previousStateTime))

```

Problem: In the example above, we are effectively displaying the same interpolated state for 3 frames before we collected the next server update and a new client (render) time is set.

The rendering is mostly smooth, but there is a dash of jaggedness to it.

Question: Given the example above, I'd like to think that the interpolation amount/factor should increase with each frame render to smooth out the movement. Should this be considered and, if so, what is the best way to achieve this given the information from above?

# Answer
> 3 votes
I've written an article (http://www.gabrielgambetta.com/fpm3.html) which deals with this problem, I think in a slightly different way than what you're doing. May still be useful to you, though.

---
Tags: algorithm, rendering, networking, multiplayer, interpolation
---


# Question
Title: Interpolating positions in a multiplayer game
In order to save bandwidth in my multiplayer game, I do not update every object every server tick, instead each object has an updateRate which tells the game that this object is expected to be updated every X server ticks.

When I receive an update message for an object I calculate the time I expect the next update to come in:

```
origin = serverCurrentPosition
diff = serverNextPosition - origin
arriveTime = now + timeBetweenTicks * updateRate

```

When I draw the object I calculate the time that's left till the next update and interpolate the position accordingly:

```
step = 100 / timeBetweenTicks * updateRate
delta = 1 - step * ((arriveTime - now) / 100)
position = origin + diff * delta

```

It works... but there's still a bit of jitter in the drawing, although in my theory every thing should work out fine, since the scaling should take care of *some amount* of lag, should it?

So the question here is, is this the best approach? Should I put actual lag into the computation? If so, how would I do that? I did some experiements, but the jitter only got worse.

# Answer
> 12 votes
You have jitter, because you lag is changing constantly. This means, that while server sends updates exactly every `timeBetweenTicks` ticks, the *client* receives them after some variable time. That time is probably close to `timeBetweenTicks` on a good connection, but not exactly equal (And besides, you may have server lag and different clock speeds on server and client).

So, when you rely on receiving the update in exactly the specified time, you constantly arrive at the destination a bit before/after the actual update. Hence, jitter.

Simple approach to reduce jitter is using "rubber-banding", which is what Martin suggests in another answer. Basically, when you receive update, you don't immediately change the object's position. Instead, if client position and server position differ only slightly, you begin interpolating client position, so that after some specified time (say, halfway to next update) client and server positions converge.

Another idea to reduce jitter in your setup: since you transmit both "current" and "next" coordinates, you can calculate the velocity of the object. Then, when update lags, you don't stop the object at its destination (i.e. "next" position), but continue moving it with the same velocity. If your objects don't change their speeds abruptly, this will really improve motion smoothness on the client.

# Answer
> 9 votes
I have solved this problem before with some success with an approach I call "network shadows". I don't know if this is something other people do, but it's always worked for me.

Each entity which is being synchronised across the network has an invisible network shadow entity. When an update comes in from the network, you teleport the shadow directly to the position the network says it should be at, then you slowly interpolate the local visible entity towards the shadow over time.

I included a lot of detail about this approach in my previous answer here

# Answer
> 4 votes
I've written an article detailing a slightly different approach, which produces *very* smooth results: http://www.gabrielgambetta.com/fpm3.html

---
Tags: multiplayer, client-server, interpolation
---


# Question
Title: Realtime multi-player game design principles for Node.js
I've been reading the Valve article on multi-player networking which has been adapted from Yahn Bernier's 2001 paper called Latency Compensating Methods in Client/Server In-game Protocol Design and Optimization. I'm making a realtime multi-player game using a node.js server connected to clients through socket.io and I have a few questions regarding the principles detailed below:

Entity Interpolation

> \[Interpolation\] prevents the jittery motion this would ordinarily lead to by buffering server updates then playing them back with the gaps smoothly interpolated between. It can also protect against glitches caused by packet loss.

Client-Side Prediction

> Prediction is the notion of the client predicting the effects of the local player's actions without waiting for the server to confirm them. An entity's predicted state is tested against server commands as they arrive until either a match or a mis-match is detected.

Lag Compensation

> Lag compensation is the notion of the server using a player's latency to rewind time when processing \[user input\], in order to see what the player saw when the command was sent. In combination with prediction, lag compensation can help to combat network latency to the point of almost eliminating it from the perspective of an attacker.

* Do the principles apply to TCP as they do to UDP and would there be any differences in implementation? I can see that the entity interpolation would not need to protect against packet loss but thats about it.
* Can I even communicate between a server and web-browser and vice-versa using UDP and Node.js?
* Since the paper is over a decade old are these principles still in use or has other technology appeared?

Any help would be much appreciated.

# Answer
> 6 votes
* Principles for reducing effects of lags are the same regardless of the transport protocol. Packet loss is a another topic - for many kinds of packets losing some is not critical because the next update is probably already on its way - here UPD has the advantage, but when you need to make sure a certain packet is delivered, you need custom acknowledgement code to do that with UDP
* Node.js supports UDP, but web browsers don't (without plugins). The best real-time method for communicating between the two is Web Sockets, which is basically TCP. But for the communicating, you might want to use Socket.IO, which provides fallbacks for browsers that don't support web sockets.
* The principles remain the same.

# Answer
> 4 votes
You should check out this article about Real Time Multiplayer Games in HTML5 posted on the buildnewgames.com site by Sven Bergstrom, he talks about the same things and he is using Node.JS. I have something similar going myself. I am just now researching more about the client-side prediction and interpolation and the like myself before trying to tackle the rest of it.

I believe it is definitely possible to do this with Socket.IO and Node, however the technology is still new so there is going to be little documentation and little to nothing in the way of guides on implementation. I would recommend doing what I'm doing and studying the subject in great detail in abstract high level terms and then try to implement it yourself.

# Answer
> 1 votes
I believe the technology is pretty much the same. Also, the concepts don't depend on what language you use or whether you do UDP or TCP. I've written a very detailed explanation of the whole thing here http://www.gabrielgambetta.com/fpm1.html, including pretty diagrams :)

---
Tags: game-design, javascript, networking, multiplayer, node.js
---


title: Measuring GPU time from managed code

text:
# Question
Title: Measuring GPU time from managed code
To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously.

The questions is simple: Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique/pass.

# Answer
> 3 votes
You seem to be using DirectX, so you can probably use the techniques described in this article. It explains how to use ID3D11Query objects to profile GPU code.

Since you're in managed code, you might have to use some clever P/Invoke to get to that API if SharpDX doesn't expose the functions itself, although it seems like it does.

---
Tags: xna, monogame, sharpdx
---


# Question
Title: Effort of impementing interpolation in networked Asteroids
Questions: When we draw with interpolation, where should the collision detection code be? Is it worth implementing interpolation in the following situation?

This is for Scrolling Asteroids. I have my game working at the moment without interpolation. It does physics updates using fixed step time deltas. The frame display rate is decoupled from this. So, it might be doing 40 Physics updates per second and 75 frame draws per second. Up until now, it is in the physics update routine that I do the collision detection and response. Your ship can collide with a rock. Your photons (bullets) can collide with a rock.

Now I am considering improving it to use interpolation as per all the good articles recommend:

http://www.koonsolo.com/news/dewitters-gameloop/

and

http://gafferongames.com/game-physics/fix-your-timestep/

So when this is implemented, I might be making the following calls:

```
update(dt)
draw(0.24)
draw(0.64)
update(dt)
draw(0.24)
draw(0.76)

```

The floating point numbers shown are examples of actual calculated interpolation value i.e. the proportion of the physics update that is complete at the time the frame is being drawn. I am going to have to change the draw code to draw the objects at a fraction of the distance between their previous and current value positions and rotations. That is yet to be done.

Question: Will I also have to do move my collision detection code out of the update routine and into the draw routine, seeing as I will be drawing these interpolated frames ?

Bear in mind, my highest priority goal is to make this networked: multiple player ships on as large a Universe as possible. So a physics update solution that is compatible with the networked game that is required. Is the interpolation worth the effort? Right now. I rarely if ever see a problem with smoothness. If I reduce my physics updates to 25 per second which I have only done as an experiment then it is a bit jerky. But the game easily runs at higher rates than that so there may never be a problem.

So the two questions:

* Collision detection where?
* Is introducing interpolation worth the effort or should I proceed to networked version straight away?

Thanks in adance:

# Answer
> 0 votes
The point of the interpolation usually is that it is done client side, while your server keeps track of the 'true' state. There are many problems arising, depending on game, and no perfect solutions available. All networked multiplayer games have to deal with this to some exxtent, be it WoW or a racing game. You will, if you compare two games side-by-side over the internet, notice significant lags in all triple A quality games, signifies: there is no perfect solution. Best you can do is just to make it work, as smooth as possible.

Short version: if collision is your main point, PvP collision will be the hardest challenge, while PvEnvironment can be relatively easily handled.

# Answer
> 1 votes
I think server side. It's one who holds the authoritative state of the world. You still can (and should) do client-side interpolation, but this is only for cosmetic purposes. I've written a detailed explanation of how all of this fits together here: http://www.gabrielgambetta.com/fpm1.html

---
Tags: c++, collision-detection, game-loop, interpolation
---


# Question
Title: Getting mousemovement despite mouselock - unity
I have lockcursor so the cursor doesn't leave the screen, but now i have to rotate an object based on mouse movement (think garrys mod item rotation) but the mouse cursor is obviusly locked to the center, is there anyway of getting the input from the mouse?

```
 public void GetRotated()
{
    Debug.Log(Input.GetAxis("Mouse X").ToString() + ", " + Input.GetAxis("Mouse Y").ToString());
    gameObject.transform.localRotation = new Quaternion(Input.GetAxis("Mouse X") * RotationSpeed * Time.deltaTime, Input.GetAxis("Mouse Y") * RotationSpeed * Time.deltaTime, 0, 0);
}

```

# Answer
If you lock it, the mouse won't move at all.

Maybe you can just hide it and you can move the cursor to the center manually after you read the movement info from it.

So, it'll be hidden, it'll stay centered, you'll be able to read the movement.

Does that work for you ?

Notice that this is an operating system specific issue. For example you won't need to lock the cursor on mobile platforms. You may only need it on Windows or on Mac. So, you should make some operating system calls to be able to change the position of the mouse to the center.

On windows you should use this link after adding the required DLLs (System.Windows.Forms.dll and maybe some others required by this dll) into your unity project (btw, I didn't try this by myself) http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx

On mac, the same method should work because Unity runs on Mono framework which is equivalent of Windows .Net framework.
> 1 votes

---
Tags: unity, rotation, input, mouse
---


title: 2D vector to Quaternion

text:
# Question
Title: 2D vector to Quaternion
I have a 2D vector (with only X and Y), and my engine only supports orientation through Quaternions.

How do I translate a 2D vector to a quaternion?

The X and Y represent the direction (so X = 0 and Y=1 means going forward, X=0.707 and Y=0.707 means rotate 45 degree, etc).

# Answer
> 2 votes
In Ogre3d's docs:

```
void Ogre::Quaternion::FromAngleAxis(
    const Radian & rfAngle, const Vector3 & rkAxis )

```

Your `rkAxis` will always be UnitZ, because you are constraining yourself to the X-Y plane.

---
Tags: mathematics, vector, ogre, quaternion
---


title: Parsing Blender obj with Opengl And C++

text:
# Question
Title: Parsing Blender obj with Opengl And C++
I wrote an example attempting to parse blender \*.obj file in OpenGl/C++ , to get it done : I have to open the file, exploding it's lines ...and returning the result.

This is how the shape.obj file looks like :

```
v 0.010271 -0.953897 0.097835
v 0.010271 -0.941667 0.194652
v 0.010271 -0.921285 0.289430
v 0.010271 -0.892750 0.381151

```

the previous file can contain lines starting with "f" as well.

and this is the c++ code (with glut include)

```
    #include <stdarg.h>
    #include <math.h>
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <vector>
    #include <GL/glut.h>

    using namespace std;

    void display();
    void specialKeys();
    float stringToDouble(string& s);
    vector<string> explode(const string& str,const char& ch);

    double rotate_y=0;
    double rotate_x=0;

    void display(){

      float x,y,z;
      string v;
      string a,b,c;

      glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
      glLoadIdentity();

    /**perform object rotation using keyboard arrows in specialKeys function**/
      glRotatef( rotate_x, 1.0, 0.0, 0.0 );
      glRotatef( rotate_y, 0.0, 1.0, 0.0 );

      ifstream myfile("shape.obj"); // open file
       if (myfile.is_open())
      {

        while ( myfile.good())
        {
          string line;
          getline (myfile,line); // get current line
          vector<string> subs;
          subs=explode(line,' '); //explode line by space
          v=subs[0];
          if(v.compare("v")){ //if the line begins with v

          /***draw polygon***/
          glBegin(GL_POLYGON);
          a=subs[1];
          b=subs[2];
          c=subs[3];
           x=stringToDouble(a);
           y=stringToDouble(b);
           z=stringToDouble(c);
           /****draw 3D vertex*****/
           glVertex3f(x,y,z);
           glEnd();

           }

        }

      }
      myfile.close(); //close file

    glFlush();
    glutSwapBuffers();

    }

    /**** special key***/
    void specialKeys( int key, int x, int y ) {

      if (key == GLUT_KEY_RIGHT)
        rotate_y += 5;

      else if (key == GLUT_KEY_LEFT)
        rotate_y -= 5;

      else if (key == GLUT_KEY_UP)
        rotate_x += 5;

      else if (key == GLUT_KEY_DOWN)
        rotate_x -= 5;

      glutPostRedisplay();

    }

/*** main***/
    int main(int argc, char* argv[]){

      glutInit(&argc,argv);
      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
      glutCreateWindow("Hello world");
      glEnable(GL_DEPTH_TEST);
      glutDisplayFunc(display);
      glutSpecialFunc(specialKeys);

      glutMainLoop();

      return 0;

    }

/**converts string to double***/
    float stringToDouble(string& s )
     {
       std::istringstream i(s);
       float x;
       if (!(i >> x))
         return 0;
       return x;
     }

/***Explode : exploding strings***/
      vector<string> explode(const string& str, const char& ch) {
        string next;
        vector<string> result;

        // For each character in the string
        for (string::const_iterator it = str.begin(); it != str.end(); it++) {
            // If we've hit the terminal character
            if (*it == ch) {
                // If we have some characters accumulated
                if (!next.empty()) {
                    // Add them to the result vector
                    result.push_back(next);
                    next.clear();
                }
            } else {

                next += *it;
            }
        }
        if (!next.empty())
             result.push_back(next);
        return result;
    }

```

The previous code:

1- initializes glut. 2- defines display and specialKeys functions. 3- opens and parses the obj file. 4- creates polygons using the extracted vertex coordinates.

Note also, that the parsing works fine, because I tested it in another program and the result reads :

```
coordinates x:0.010271 y:-0.953897 z:0.097835
coordinates x:0.010271 y:-0.941667 z:0.194652
coordinates x:0.010271 y:-0.921285 z:0.289430
coordinates x:0.010271 y:-0.892750 z:0.381151

```

When I compile this exemple, there's no error, But when I execute ... the window shows nothing but the black screen. It doesn't show the 3d object I created on blender.

To those who've done this before. Is there something I missed here?

Thanks.

# Answer
> 1 votes
I found where's the problem... I wonder how I couldn't notice it before:

it's in this line

```
 if(v.compare("v")){

```

v.compare("v") returns always false, so I changed it to :

```
if(v=="v")

```

and it's working now

Thanks

---
Tags: c++, opengl, 3d, blender
---


title: Avoiding use of XMVECTOR in XNAMath

text:
# Question
Title: Avoiding use of XMVECTOR in XNAMath
I don't want to use XMVECTOR which i currently use in my DirectX 11 C++ game code. Because it is too much for me in memory. I want to use XMFLOAT3 or 4, but **the problem is there is no matrix/vector XNA Math function available for XMFLOAT**\*. It is pointless to use 6 fields or pass to the shader (XMVECTOR), if object represents only 3 or 4 (and operate with them only).

I don't want to convert types in any case just to do calculations. Can you please recommend me what to do? I really like using XNA math, but XMVECTOR is just dirty variant...

# Answer
> 2 votes
XMVECTOR is superbly optimized, packed and aligned, etc... I doubt it is causing you any real trouble. You're probably prematurely optimizing something that is not on the hot-path or in the memory-hog part of your application. I'm also pretty sure that when using XMVECTOR loaded with an XMFLOAT4 you only pass 4 variables to the GPU.

# Answer
> 1 votes
While I still recommend to use `XMVECTOR` & `XMMATRIX`, if you really don't want to use them you can find `XMFLOAT` wrappers for vector/matrix math in DirectX Tool Kit (SimpleMath.h).

These wrappers use `XMVECTOR` & `XMMATRIX` as well, it's just hidden from you.

# Answer
> 0 votes
You can use XMLoadFloat3 and XMStoreFloat3 to convert your storage-oriented XMFLOAT3 uses into usage-oriented XMVECTOR values and back again. The code is ugly, but it works. If you're doing non-trivial math kernels (which you should strive for) it's more efficient this way, too, if you leave SIMD on.

---
Tags: c++, directx, directx11
---


title: Android Bitmap: Collision Detecting

text:
# Question
Title: Android Bitmap: Collision Detecting
I am writing an Android game right now and I would need some help in the collision of the Pawns on screen. I figured I could run a for loop on the Player class with all Pawn objects on the screen checking whether or not Width\*Height intersects with each other, but is there a more efficient way to do this?

And if you do it this way, many of the transparent pixel inside the rectangular area will also be considered as collision as well. Is there a way to check for collision between Bitmap on a Canvas that disregard transparent pixels? The class for player is below and the Pawn class uses the same method of display.

```
Class Player {
  private Resources res; // Used for referencing Bitmap from predefined location
  private Bounds bounds; // Class that holds the boundary of the screen
  private Bitmap image;
  private float x, y;
  private Matrix position;
  private int width, height;
  private float velocity_x, velocity_y;

  public Player (Resources resources, Bounds boundary) {
    res = resources;
    bounds = boundary;
    image = BitmapFactory.decodeResource(res, R.drawable.player);
    width = image.getWidth();
    height = image.getHeight();
    position = new Matrix();
    x = bounds.xMax / 2; // Initially puts the Player in the middle of screen
    y = bounds.yMax / 2;
    position.preTranslate(x,y);
  }
  public void draw(Canvas canvas) {
    canvas.drawBitmap(image, position, null);
  }
}

```

# Answer
More efficient: you could do some sort of spatial partitioning to early-discard some of the collisions, maybe compare the squared distance of their centers and the sum of their squared radii? But if you don't have that many pieces, it's probably not worth it.

More precise: checking every pixel against every other pixel is precise but cumbersome. I've done this before using quadtrees, which you can generate at load- or even compile-time, are a lot faster, and partially solves your problem above. You may find a resolution of 2, 3 or even 5 pixels is precise enough.
> 1 votes

---
Tags: java, android, collision-detection, game-mechanics
---


title: ArrayList mixing up indexes?

text:
# Question
Title: ArrayList mixing up indexes?
Working title.

I'm warming up to libgdx and I'm trying to remove objects from an ArrayList when pressed/touched. The Objects are rectangles and about 70% of them get removed, the other 30% just stays on screen or gets removed when I press on another indexes position, its like its mixing up indexes.

Adding Enemy:

```
    public void updateEnemy(float dt){
    enemyTimer += dt;
    if(enemyTimer > 3){
        enemyArrayList.add(new Enemy(enemyImg.getWidth(), enemyImg.getHeight()));
        enemyTimer = 0;
    }
}

```

Drawing enemy:

```
    public void drawEnemy(float dt){
    for(int i = 0; i < enemyArrayList.size(); i++){
        batch.draw(enemyImg, enemyArrayList.get(i).getX(), enemyArrayList.get(i).getY());
    }
}

```

Setting bounds for enemy:

```
    public void setBounds(int width, int height){
        bounds.set(position.x, position.y, position.x + width, position.y + height);
    }

```

Checking for touch on enemy:

```
    @Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    for(int i = 0; i < screen.getEnemyArray().size(); i++){
        if(screen.getEnemyArray().size() > 0){
            System.out.print(screenX + " - " + screenY + ", ");
            if(screen.getEnemyArray().get(i).getBounds().contains(screenX, screenY)){
                screen.getEnemyArray().remove(i);
            }
        }
    }
    return false;
}

```

I can't see where Im going wrong, any suggestions is appriciated.

# Answer
> 4 votes
in general, if you're going to remove items from an ArrayList, you're going to skip over stuff with the pattern.

```
for(int i=0; i<list.size(); i++)
    if (something)
        list.remove(i);

```

You should get better results iterating backwards while removing so the indices don't shift, or simply decrementing 'i' when you delete:

```
for (int i=list.size()-1; i>=0; i--) ....
//or
for(int i=0; i<list.size(); i++) {
    if (something) {
       list.remove(i);
       i--;
    }
}

```

However, you may later run into issues because you're removing enemies while in the middle of your game logic. Often we have to use a two-step removal process, where we mark an enemy 'deleted' and then at the end of the frame when everything is done, we can remove them from the list.

# Answer
> 1 votes
You don't want to iterate over an array and remove items from it at the same time. I am surprised you didn't get a `concurrentmodificationexception` thrown by Java. There are a few tricks you can do with the iterator, like the one Jimmy mentioned. However, they are unsafe and can lead to unexpected results.

Libgdx has a few collection classes along with ArrayList that you can use. Detials here: https://code.google.com/p/libgdx/wiki/Collections

**Snapshot Array** Has .begin() and .end() functions that allow you modify an array with an iterator. Any modifications after .begin() are not applied until .end() is called. Internal backing array is copied, and you continue to iterate over the old array once .begin() is called. Require the iterator to be constructed in a particular way. (.size must be called)

**DelayedRemovalArray** Similar with SnapShot Array, but works slightly differently. Removal is actually just delayed until .end() is called.

You can also creates an ArrayList call toBeRemoved. Any items needed to be removed are added this array. Then iterate over toBeRemoved and remove items in it from the first ArrayList.

# Answer
> 0 votes
You can also use an Iterator to do the job:

```
Iterator<Enemy> it = enemyArrayList.iterator();
while (it.hasNext())
{
   Enemy e = it.next();
   if (something)
   {
      it.remove();
   }
}

```

---
Tags: java, libgdx
---


# Question
Title: Implementing a time scale in game with fixed physics update
I'm currently putting together my game loop based on the "Fix Your Timestep" article at gafferongames.com. This is going fine, but I'm also trying to implement a 'time scale', i.e. a way to control the game speed.

Currently, the delta time is added to an accumulator, and then a loop iterates the physics as many times as there are multiples of the fixed time step in the accumulator.

Now, if I want to add a time scale, I should multiply the delta time by some factor, 0.5 for half speed or something, yes?

Here are my questions:

Should I still use the real fixed time step (prior to multiplication) to determine how often the physics is iterated, but perform the actual calculations with the increased or decreased time step? Or should I use the new time step for both, but surely this would just result in the same behaviour but with higher resolution calculations?

Wait, wait, wait. I have to affect the accumulator too, right? Then it would increase by a smaller frame time, but it would do the right amount of iterations with smaller dTs, over the right amount of time (the real delta time). That'd do it, right?

Given that the purpose of the fixed time step is to perform stable physics calculations, how can I combine these two concepts without jeopardising that stability?

Is it simply that LARGE time steps cause instability? Can I therefore slow down as much as I like? Or is it the variations in time step that causes instability?

Thanks

# Answer
Regarding the first question, I believe that using the altered delta time to increase the accumulator, and the altered fixed step to decrease it, should keep everything working correctly. In reality, I only need to add the time scale behind the scenes, and the type of game loop specified in Fix Your Timestep should still work.

According to @teodron, the answer to my second is that a variable physics timestep is acceptable within a certain tolerance, given by the stability interval of the integrator used. In other words, I should be able to apply the time scale safely, within reason.

I'm going to implement this and test. If there is anything incorrect about what I said above, I'll edit to reflect that.
> 2 votes

---
Tags: mathematics, physics, game-loop, fixed-timestep
---