title: Transforming normal vector in GLSL

text:
# Question
Title: Transforming normal vector in GLSL
I'm looking at a basic diffuse light shader here http://en.wikibooks.org/wiki/GLSL\_Programming/Unity/Diffuse\_Reflection.

Diffuse light needs the normal vector in eye-space, so that it can dot it with the light position (also in eye-space), and figure out the diffuse contribution. (eye-space not world-space is used, because that simplifies calculating specular contributions).

The code calculates the normal vector in the following way:

```
        mat4 modelMatrixInverse = _World2Object; // unity_Scale.w
           // is unnecessary because we normalize vectors

        vec3 normalDirection = normalize(
           vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));

```

A linear algebra calculation shows that given a matrix M, Transpose(Inverse(M)) transforms normals. The Wikipedia on normals page contains a derivation of the required formula: http://en.wikipedia.org/wiki/Normal\_%28geometry%29#Transforming\_normals (I've actually rewritten that section myself, as it was not lucid).

So does this mean that the 'vector * matrix' overload in GLSL is implemented as:

```
    Transpose(vector) * Matrix

```

just holding a row-vector instead of a column-vector in the output, i.e.:

```
    Transpose( Transpose(vector) * matrix )

```

or more simply:

```
    Transpose(matrix) * vector

```

?

---

I've also found what appears to be alternative: gl\_NormalMatrix

But in lines 9-11 here http://pixelsorcery.wordpress.com/2010/07/13/fisheye-vertex-shader/ ) I see the following code:

```
normal = vec4(gl_NormalMatrix * gl_Normal, 0.0);
vec4 vVertex = gl_ModelViewMatrix * gl_Vertex;
light_dir = gl_LightSource[0].position - vVertex;

```

Would I be right to assume that gl\_NormalMatrix gives a normal in eye-space, and gl\_LightSource\[0\].position gives the light location also in eye-space?

http://www.opengl.org/discussion\_boards/showthread.php/172231-gl\_NormalMatrix-Replacement suggests gl\_NormalMatrix is deprecated.

Does that mean the first implementation is the preferred approach?

EDIT: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-8-basic-shading/#The\_Diffuse\_part

# Answer
> 1 votes
`gl_NormalMatrix` ***is*** deprecated, but there was never anything special about it in the first place.

It is just the inverse transpose of the upper-left 3x3 part of your ModelView matrix. This extra bit of math effectively gets rid of any issues caused by non-uniform scaling and gets rid of translation by removing the 4th column of the ModelView matrix.

Rather than doing this operation in your vertex shader for each vertex, if you need to transform normals you should pre-compute the normal matrix on the CPU whenever you update your ModelView matrix. That was what GL did back when `gl_NormalMatrix` still existed.

---
Tags: glsl, normals, normal-mapping
---


# Question
Title: Do I need to create an HLSL in XNA to display textures without content pipeline
I currently have a jpeg texture stored as a Color array in XNA as RGBA. I also have the vertices of a cube in OBJ format mapped to VertexPositionColor vertex buffer using the VertexBuffer and Indices of the GraphicsDevice class. The OBJ has my jpeg mapped as a UV texture. I think I have all the Texture Coordinates as well(not sure, the array has 24 Vector3D values). I'm not sure where to go from here. I'm not using the Content Pipeline for my cube model or its texture though I'm wiling to add a custom .fx file if i need to. I realize I will have to add info about texture coords and color to my VertexDeclaration but do i need to write a custom effects file in HLSL to display my textured cube model or is there another way?

# Answer
A custom shader is not required; you can accomplish this with `BasicEffect`. You will need to set the `Textures` and `TexturesEnabled` properties. Those properties will tell the shader:

1. Expect and enforce texture coordinates in your vertex data
2. Which texture data to sample.

This relevant article discusses drawing a textured quad with `BasicEffect`, and it's a short step from that to drawing a textured cube.
> 1 votes

---
Tags: xna, textures, hlsl, vertex, effects
---


# Question
Title: How can I make EaselJS' skew behave like canvas'?
The skew property of a bitmap in EaselJS (given as angle) rotates the image such that it also flattens. I'd like to skew it without "squashing" it, as canvas does.

JSFiddles, to demonstrate:

Canvas skew | EaselJS skew

# Answer
Ah, an unfortunate side effect of EaselJS being *too clever*. You can undo the cleverness by vertically scaling the resulting shape by the ratio of the desired height *h2* to the actual height *h1* that Easel calculated for you.

Here's a diagram to go help think about the trigonometry:

I modified your JSFiddle to demonstrate how it might look in code. The important parts:

```
function degToRad(angle) {
    return angle * Math.PI / 180;
}

var angle = -35;
var shouldBeHeight = 80;
var isHeight = 80 * Math.abs(Math.cos(degToRad(angle)));
var heightRatio = shouldBeHeight / isHeight;

...

skewedShape.scaleY = heightRatio;

```
> 1 votes

# Answer
Just to provide and example how to use the easel Matrix2D to archive the skew:

```
var ctx = canvas.getContext("2d");
ctx.save();
var matrix = new createjs.Matrix2D();
var tile = new createjs.Bitmap('img/tile.png');
matrix.prepend(
            1, 0.5, // the 0.5 is the skewing
            0, 1,
            0, 0);
tile.draw(ctx);
ctx.restore();

```

But then you can not rely on the easel update mechanism but you must do this yourself whenever you need to render it.
> 1 votes

---
Tags: html-canvas, transformation, easeljs
---


title: Running state in Behavior Trees

text:
# Question
Title: Running state in Behavior Trees
What happens, in a behavior tree, when a priority node chooses another branch over a running branch?

Small example:

```
Priority 1: Fight
    Sequence:
        -Enemy near?
        -Fight!
Priority 2: Move
    Sequence:
        -Is there a hole?
        -Jump!
    Run 5m!

```

Now in the first iteration there is no enemy, but a hole, so the action `Jump!` gets executed. It's a rather lengthy animation so it returns running.

For what should happen in the next iteration I found kind of contradictory statements. According to this answer the priority node always begins at the first priority disregarding if another priority is running. In this article however while the examples follow the same scheme, the explanation also mentions that it's possible to lock the tree in the `Running` state until it's finished.

If the tree is locked in the `Running` behavior, the character can't react until he walked all the way to his walking target, so this can't be the right interpretation.

If always the first priority gets checked again, the character can react to enemies while he's running (he stops and fights) - that's the desired behavior. If however he's in the air jumping, he can not just stop and fight, he has to land first, so this time I can't choose priority `Fight` over `Move`!

How should I handle those cases? Am I even approaching it the right way?

# Answer
The answer you reference assumes tasks that are interruptible. As with nearly all things game development, you can always break the mould to make it work for you. It's certainly possible to make a `non-interruptible` flag, and set it on the tree when you're running animations and other non-interruptible tasks. When the `non-interruptible` flag is set, the tree will not restart evaluation from the beginning, it will go straight to the running node.

Also remember that *when* you evaluate the tree is up to you. You can have a variable wait timer between evaluations or only evaluate when needed. So, for example, you can evaluate only when the character needs a new action to perform, or is available to switch actions. In this case, the tree would not be reevaluated until the animation was complete.
> 5 votes

---
Tags: ai, game-loop, behavior
---


# Question
Title: odd line artefacts on my screen? (C++ DirectX11)
I'm getting some odd lines on my screen in my program:

They seem to be in a static location on the screen and occur at regular intervals. They are also on the horizontal too but are harder to see in the image.

So far I have tried:

turning anti-aliasing off, turning multi-sampling off, rendering my images at full size (no scaling) and using texture sizes of a power of 2.

And none of that seems to work. Right now I am working on adding fonts in, but this issue means that lines of the fonts can disappear (the bottom of an 'o' the middle of a 'B' (so it looks like a 'D'), etc).

# Answer
> 2 votes
A frequent cause of this is running in windowed mode, and making the back buffer a different size to the client area. D3D will automatically stretch the back buffer to fill the client area, but it doesn't do it with a good quality filter.

This is easily fixed either by using AdjustWindowRectEx() when creating the window, or by calling GetClientRect() to get the client area size when creating the back buffer.

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


# Question
Title: libgdx: How do you remove a cell from TiledMap?
I am making a Terraria-style sidescrolling game with an open world. I am using a TiledMap to render all of the tiles. If I want to remove a tile, like if it is broken, how would I stop it from being rendered?

# Answer
> 2 votes
first we make an instance of map layer that contain the tile that we want to remove

for example:

**TiledMap map=new TiledMap();**

//lets say we want to remove some tile from layer with index of 0

**TiledMapTileLayer layer=map.getLayers().get(0);**

//so if we need to remove the tile in layer at position 0,1

**layer.getCell(0, 1).setTile(null);**

# Answer
> 0 votes
I'm not to familial with TiledMaps but when I create a proceduraly generated 2d game I use a boolean array and in my render method check if the boolean at the index is true if it is draw the tile if not don't draw the tile. But after reading the javadoc I see that a method removeTileSet(int index) so possibly when you break something get the index and try to removeTileSet(x);

---
Tags: java, 2d, libgdx, tiles, terrain-rendering
---


title: How to load resources in LWJGL

text:
# Question
Title: How to load resources in LWJGL
I've been searching for days. When I export and create my fat jar it loads and disappears. It can't find my images.

This is what it all looks like. I used something like this to load them:

```
File a;
a = new File("res/theimage.png");

   wood = TextureLoader.getTexture("PNG", new FileInputStream(a));

```

This works just fine in eclipse but the jar can't find the image. I tried putting the first jar with the fat jar in a folder. It still didn't work so I put all project files in there too. Somehow it couldn't find it still. How do you get your res to be in your lwjgl game. I mainly just want to have a jar file that you click and start easily instead of a zip folder with all the files. I don't know how to do any of this. My game without images works just fine. I rather a visual way of doing this.

Can Images be draw without being textures in LWJGL?

# Answer
> 0 votes
Files embedded in jars are not "files" in the java File object sense, that's why it works just fine when running from Eclipse but not from a Jar. Jar files are zip files. To actually use a file embedded within a jar (a zip file) the file must be decompressed first. You're going to have to extract the images from the jar to the local harddrive when running your game or open your image files as InputStreams.

See https://stackoverflow.com/questions/15423560/java-how-to-use-an-image-within-a-jar-file, https://stackoverflow.com/questions/12437752/loading-images-in-a-jar, and Java getResourceAsStream as local resource for examples.

---
Tags: java, textures, lwjgl
---


title: Collision detection in Pong clone

text:
# Question
Title: Collision detection in Pong clone
Well I'm trying to create a pong clone using SDL and I had some problems with the frames and some times the ball would go through the paddles despite the fact that at other times the collision worked perfectly. So I searched it a bit and I came to the conclusion that it was because in one frame the ball was already through the paddle and in another frame the ball was not or something like this. So thought that if I would manually adjust the position of the ball, like move it a couple of pixels away the moment it hits a paddle or the walls too, this would solve the problem. But now when the ball goes right past a paddle its movement is getting weird and it goes right in the playing field. for reference also some code if you want to look it . I feel bad for doing the whole collision like these but I couldn't think some other way. Please enlighten me if there are better ways to do it that I can avoid the frame problem I mentioned above. Here is the code that handles the ball's movement :

```
   void Ball::move(float xLeftPaddle, float yLeftPaddle,float xRightPaddle, float yRightPaddle, Uint32 deltaTicks)
{

    y +=  yVelocity * ( deltaTicks / 1000.f );
    x +=  xVelocity * ( deltaTicks / 1000.f );

    if(   y + BALL_HEIGHT > SCREEN_HEIGHT )
    {
        x = x-1;
        y = y-1;
        yVelocity = -yVelocity;

    }
    else if( y < 0 )
    {
        x = x+1;
        y = y+1;
        yVelocity = -yVelocity ;
    }
    else if(x + BALL_WIDTH >= xRightPaddle && y <= yRightPaddle + PADDLE_HEIGHT && y >=yRightPaddle  )
    {
        x = x-1;
        y = y-1;
        xVelocity = -xVelocity;

    }
    else if( x <= xLeftPaddle + PADDLE_WIDTH && y <= yLeftPaddle + PADDLE_HEIGHT && y >= yLeftPaddle)
    {
        x = x+1;
        y = y+1;

        xVelocity = -xVelocity ;
    }
    else if(x < 0 || x > SCREEN_WIDTH)
    {
        x = SCREEN_WIDTH/2;
        y = SCREEN_HEIGHT/2;
    }

```

}

# Answer
> 2 votes
Most reliable is to not check positions but *movement*: use your motion vector to check whether the ball's line of movement intersects with the paddle. This way it never goes through the paddle even if FPS is slow / ball movement really fast. We achieve this by using a physics library (Bullet) in our Pong (https://github.com/playsign/PongThreeJS) but it is well doable with own code too.

If your movement never gets too fast compared to the update rate (FPS) then what was discussed earlier works too.

---
Tags: collision-detection, sdl, c
---


# Question
Title: How to create two objects from one vertices array with translate?
I have an object and I can render it but I want to use its vertices twice but I don't know how to.

this is my code reading object from txt:

```
fin.open("piyon.txt");
fin >> vertexCountpiyon;
verticespiyon = new SimpleVertex[vertexCountpiyon];

for(int i=0; i<vertexCountpiyon; i++)
{
    fin >> verticespiyon[i].Pos.x >> verticespiyon[i].Pos.y >> verticespiyon[i].Pos.z;
    fin >> verticespiyon[i].Tex.x >> verticespiyon[i].Tex.y;
    fin >> verticespiyon[i].Normal.x >> verticespiyon[i].Normal.y >> verticespiyon[i].Normal.z;
}
fin.close();

bd.ByteWidth = sizeof( SimpleVertex ) * vertexCountpiyon;
ZeroMemory( &InitData, sizeof(InitData) );
InitData.pSysMem = verticespiyon;
hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer_piyon );
if( FAILED( hr ) )     return hr;

```

and my render code:

```
  g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer_piyon, &stride, &offset );
    cBuffer.vMeshColor = XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f );
    XMMATRIX mTranslateBeyazPiyon = XMMatrixTranslation( -17.5F, 0, -12.5F );
    cBuffer.mWorld = XMMatrixTranspose( mTranslateBeyazPiyon );
    g_World_Piyon = mTranslateBeyazPiyon;
    g_pImmediateContext->UpdateSubresource( g_pConstantBuffer, 0, NULL, &cBuffer, 0, 0 );
    g_pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
    g_pImmediateContext->VSSetConstantBuffers( 2, 1, &g_pConstantBuffer );
    g_pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
    g_pImmediateContext->PSSetConstantBuffers( 2, 1, &g_pConstantBuffer );
    g_pImmediateContext->Draw( 7050, 0 );

```

# Answer
> 1 votes
You must call IASetVertexBuffers function once on the vertices, but call the Draw function twice. Also set the transformation matrix before each draw call and update the constant buffer (UpdateSubResource). You don't need to set your shaders or constant buffers twice.
That is it if you want to **render** your vertices twice, if you want to **use** them twice for something else on the CPU you should duplicate them. The best would be if you didn't duplicate them and used them only on the GPU if you could get away with that.
**Update:**
Seems like you also have to write hlsl shaders: a vertex shader which will be automatically run for each of your vertices, and a pixel shader which will determine the output color of your rasterized geometry (short story: you can alter the pixel colors). It would be too much to write down everything like how to create the shader files, compile them, etc look up a tutorial for that, for example RasterTek tutorials. In the shader you have to declare a constant buffer on a specific slot which you upload to in you c++ program and it should be have the same members as in the type of your *cBuffer* variable's structure, like for example:

```
cbuffer BUFFERNAME:register(b2) //a constant buffer bound to the second slot which you are already uploading data to
{
 float4 mMeshColor;
 float4x4 mWorld;
}

```

Then in your entry point function you will have to multiply your vertices' positions with your world matrix:

```
float4 main(float4 inPos:POSITION):SV_POSITION
{
 return mul( mul(inPos,mWorld),YourViewProjectionMatrix ); //YourViewProjectionMatrix is a float4x4 which you also upload in a constant buffer like the world matrix
}

```

This short example doesn't accunt for the color, just transforms a vertex by world position, then transforms and projects it by the camera matrix then returns the value which will be used by the rasterizer.

---
Tags: directx, directx11
---


# Question
Title: Different OnMouseDown functions based on where an object is clicked
So my problem is I'd like to have one GameObject with multiple "OnMouseDown" functions. I have a target (classic looking bullseye) and I'd like to award a player say 10 points if they click on it, but 100 points if they click the center. Because the "OnMouse" functions don't pass in a collider I'm not sure how to go about doing this. I had an idea (which I think is a bad one) which would be to attach a small "empty" gameobject to my target prefab and give it a smaller hitbox with code that spits out 100 points instead of 10 and place that object "in front of" the other one while being attached. Again, seems wrong. Anybody else have to do this before or have a more elegant solution?? Thanks!

# Answer
> 1 votes
`OnMouseDown` is triggered when an object is clicked. If you have a bullseye like object, simply test to see how close to the center the click was using a piecewise function. This means you only need to have one object and one script. A script with something like the following:

```
if(distanceToCenter > 10)
   return 10;
if(distanceToCenter > 5)
   return 25;
if(distanceToCenter <= 1)
   return 100; //bullseye!

```

You can calculate `distanceToCenter` with something like:

```
//Calculate the mouse position in the game world. Get the screen coords and the depth
// into the scene by calculating the distance between the object and the camera.
Vector3 mouseScreenPosition = Input.mousePosition;

mouseScreenPosition.z =
    Vector3.Distance(Camera.main.transform.position, this.transform.position);

Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(mouseScreenPosition);

float distanceToCenter = Vector3.Distance(this.transform.position, mouseWorldPosition);

```

All this code would go inside the `OnMouseDown` method, so you know the mouse is in the correct place when calculating the distance. Alternatively, you can cast a ray and use the `point` variable from the `RaycastHit` class.

---
Tags: unity, collision-detection
---


# Question
Title: How to solve the overlap of two circles that collide
I have two circles, one of the circles is static the other is moving around. I have a method that checks whether the two circles collide. How to make the two circles don't overlap when colliding?

```
public void UpdateGame()
{
    //keyboard input and moving the circle here

    if(CollisionDetection(dynamicCircle,staticCircle)
    {
        ResolveOverlap(dynamicCircle,staticCircle);
    }
}

public class CircleBody
{
    public Vector2 position {get;set;} // top left corner
    public float CenterX;
    public float CenterY;
    public int Width { get; set; }
    public int Height { get; set; }
}

public bool CollisionDetection(CircleBody body1, CircleBody body2)
{
    float radius = body1.Radius + body2.Radius;
    float distanceBetweenTwoCircles = ((body1.CenterX - body2.CenterX) *
        (body1.CenterX - body2.CenterX)) +
        ((body1.CenterY - body2.CenterY) *
        (body1.CenterY - body2.CenterY));

    if(radius > Math.Sqrt(distanceBetweenTwoCircles))
    {
        return true;
    }
    return false;
}

public void ResolveOverlap(CircleBody body1, CircleBody body2)
{
    //answer to my question
}

```

If it wasnt clear by now here is my code for solving that with two rectangles I want the same thing to happen to the circles.

```
public void ResolveOverlap(RectangleBody body1, RectangleBody body2)
{
    double widthY = (0.5 * (body1.Width + body2.Width)) * (body1.CenterY - body2.CenterY);
    double heightX = (0.5 * (body1.Height + body2.Height)) * (body1.CenterX - body2.CenterX);

    if (widthY > heightX)
    {
        if (widthY > -heightX)
        {
            //collision - top
            body1.Position.Y = body2.Position.Y + body2.Height;
        }
        else
        {
            //collision - right
            body1.Position.X = body2.Position.X - body1.Width;
        }
    }
    else
    {
        if (widthY > -heightX)
        {
            //collision - left
            body1.Position.X = body2.Position.X + body2.Width;
        }
        else
        {
            // collision - bottom
            body1.Position.Y = body2.Position.Y - body2.Height;
        }
    }
}

```

# Answer
Here is a Method that I use for circle vs circle collision :

```
public static bool CirclesIntersect(Circle c1, Circle c2, out float depth)
    {
        float distance = (c1.Position - c2.Position).Length();
        float sumOfRadii = c1.Radius + c2.Radius;

        depth = sumOfRadii - distance;
        if (depth < 0)
        {
            return false;
        }
        return true;
    }

```

The depth float that is passed out will give you the smallest distance you need to separate the circles. You can use the depth value like this :

```
float depth;
if (CirclesIntersect(dynamicCircle, staticCircle, out depth))
{
     Vector2 direction = dynamicCircle - staticCircle;
     direction.Normalize();

     dynamicCircle.CenterPosition += direction * depth;
}

```

If you want to collide 2 moving circles you can find the direction opposite of both centers and create the "push" vector by dividing depth by 2... something like this :

```
float depth;
if (CirclesIntersect(dynamicCircleOne, dynamicCircleTwo, out depth))
{
     Vector2 direction_One = dynamicCircleOne - dynamicCircleTwo;
     direction_One.Normalize();

     Vector2 direction_Two = dynamicCircleTwo - dynamicCircleOne;
     direction_Two.Normalize();

     dynamicCircleOne.CenterPosition += direction_One * (depth / 2);
     dynamicCircleTwo.CenterPosition += direction_Two * (depth / 2);
}

```

Note I haven't compiled this code or anything so there could possibly be an issue, but I hope that this will at least help push you in the right direction.

There are probably a lot of optimizations that could be done to these methods but I haven't had the need to yet. Just something to keep in mind.
> 1 votes

---
Tags: c#, collision-detection
---


# Question
Title: Specular map: What about the specular reflection's highlight' size?
I think I know what a specular map is and what it's used for (here is an example).

http://www.rastertek.com/dx10tut21.html

One of the models of specularity that are highly popular is Phong. In Phong there is a parameter sometimes called "shininess" which basically controls the size of the highlight. A large value yields a tiny highlight.

How is that value expressed in the specular map? It appears to me it is common to use the specular map to control the brightness but not the size of the specular highlight in games.

Am I wrong in thinking so? Mind you I'm not adept in game rendering and well aware that the naive implementation of Phong (with ray-tracing) raises the dot product of the vector from the camera source with the reflected vector of the light beam by the power of shininess which appears computationally heavy but still I wonder:

Are specular maps by definition without Phong's shininess value? Is that rarely or never used at all in interactive rendering? Is the value simply set to a small constant?

# Answer
Many games nowadays use both specular maps, which control the intensity of the specular reflection, and shininess maps, which control the size of the highlight. With Phong or Blinn-Phong shading, an increasingly common way to do this is to use an exponential mapping:

```
specularPower = pow(2.0, 13.0 * shininessMap)

```

Often times this is called a "gloss map", and the value stored in the map is called "gloss". This enables the texture map to have a range from 0 to 1 just like most other textures, so standard authoring tools and formats can be used. But after applying the `pow()` function, the range of specular powers is 1 to 8192 in the function above (of course, different constants can be used to get a wider or narrower range). So you can get a useful range of specular powers from a standard texture map.

(By the way, raising a value to a high specular power as in Phong and Blinn-Phong shading isn't necessarily computationally heavy; it can be done using exp and log functions so that it takes a constant number of operations no matter how large the power is.)

In the past, people often went without a shininess/gloss map and simply set a constant shininess per material, reasoning (I suppose) that the intensity part was more important. However, nowadays people are realizing that this is actually the wrong way around - most of the interesting detail in the specularity of a surface is due to variations in gloss, not variations in intensity. It turns out that realistically, almost all materials except metals have a specular intensity value of somewhere between 0.02 and 0.05 (in linear color space). Metals have higher intensity, between 0.5 and 1.0, depending on the type of metal.

The key point is that the intensity just depends on what the material is made of, but the gloss depends on the actual surface texture - whether it's smooth or rough, does it have scratches or other defects, and so on. So the gloss is arguably the more important quantity to have, and you can often get away with setting the intensity to a constant.
> 1 votes

---
Tags: textures, rendering, lighting
---


# Question
Title: I need some help with stopping individual sound effects in OALSimpleAudio
I'm trying to find out how to stop a specific sound effect rather than having to stop all of them.

I'm using OALSimpleAudio.

I can't seem to find how to do it. simple google searches result in nothing, which means my searches are crap, it's REALLY easy to do and i'm ... stupid :p, or it isn't possible.

I hope you guys can help me.

In the background i have a humming engine sound, but when the object takes damage, the humming sound is stopped, that's not what i want.

```
case kStateTakingDamage:
        CCLOG(@"Ship taking damage");
        [self playTakingDamageSound];
        self.characterHealth = self.characterHealth - 1.0f;
        action = [CCActionAnimate actionWithAnimation:damageAnimation];
        [[GameManager sharedGameManager] stopSoundEffect];
        break;

- (void) playSoundEffect: (NSString *) soundEffect {
    [self playSoundEffect: soundEffect andLoop: NO];
}

- (void) playSoundEffect: (NSString *) soundEffect andLoop: (BOOL) loop {
    [[OALSimpleAudio sharedInstance] playEffect:soundEffect loop: loop];
}

- (void) stopSoundEffect {
    [[OALSimpleAudio sharedInstance] stopAllEffects];
}

- (id) isSoundPlaying {
    //TODO: find out how this works ;
}

```

# Answer
> 0 votes
All you need to to is to store the return value of `[OALSimpleAudio playEffect]`. The method returns an instance of type `id<ALSoundSource>`, which means a class that implements the `ALSoundSource` protocol. This is the actual sound effect object used internally by OAL. If you refer to the documentation, you'll find that `id<ALSoundSource>` has a `stop` method.

So all you need to do is basically:

```
id<ALSoundSource> soundSrc = [[OALSimpleAudio sharedInstance] playEffect:"my_sound.mp3" loop:true];
// play for a while...
if (soundSrc != nil)
{
    [soundSrc stop];
}

```

---
Tags: cocos2d-iphone, objective-c, sound-effects
---


# Question
Title: How to deal with raw values and percentages?
What is the standard practice for dealing with attribute modifiers in games where units have attributes, such as RTSs, MOBAs and RPGs? Specifically, in which order are "buffs" given to the unit?

Suppose the case where unit X has 10 blah-points (BP). It obtains two modifiers that add +10% blah-points, and another one that adds 30 blah-points. Finally, a enemy unit applies a -40% blah-points modifier. What is the usual way of processing this, for player familiarity's sake?

### Aggregate by grouped type

> (10+30)\*(1.0+0.1-0.4) = 28

### Obtention order

> (10\*(1.1)+30)\*(0.6) = 24.6

### Aggregate iteratively by type

> (10+30)\*1.1\*0.6 = 26.4

### Some other way?

# Answer
It's really up to you how you implement these modifiers and it heavily depends on your game, the type of stats and items you have. Aggregating by grouped type is probably the safest option, because values won't spike as fast as with an iterative approach. A calculation based on the order when you obtained a buff is probably a bad idea, because the user might get different stats with the same buffs (obtained in different order) and wonder why that's the case.

As far as I know, popular games like Diablo 2 aggregate by grouped type. Pretty much what you did in your first example.

However there are some things to consider:

* Armor and Weapon pieces usually have separate percentage-based calculations (eg. +60% damage on the weapon will be calculated for the weapon only (`fixed-damage * 1.6`) whereas +% damage modifiers on the armor will come into the calculation later. So basically the weapon(s) get evaluated first, resulting in the "base-damage" for the total damage calculation from skills, buffs and armor stats.
* An enemy could have a -40% physical damage modifier, which will only be evaluated once you hit that enemy. You'll deal `total-damage * 0.6` damage to the enemy. Enemy effects on you (eg. a curse or a buff vs. an enemy type) will be factored into your base stat calculation.

There's a pretty detailed list of how calculations work in Diablo 2 on the Arreat Summit website (scroll to "Character Attributes"). This might be a good starting-point for your own formulas.
> 2 votes

---
Tags: game-design
---


# Question
Title: Draw call optimization for multiple meshes in DirectX11
I have a large scene in a B3D model, which includes about 120 meshes as in the following pictures:

large B3D scene http://s22.postimg.org/d1h75hr0v/Untitled.png

Each mesh contain a vertex buffer and material information such as diffuse, specular, ambient...

I'm using Directx 11 for rendering, and it takes me about 120 IndexedDraw calls per frame, and the frame rate is down to 30f/s. This speed is so slow and I can't apply physics to the application.

Now I want to group these IndexedDraw call into only one DrawCall per frame. To do this, I'm thinking about creating multiple vertex buffers in Directx, and each of these will own its own material information. For each draw call, DirectX will loop over such vertex buffers and pass the corresponding material information.

I want to ask you there's any way to do this in DirectX11, and if not, could you please suggest me some way to optimize my application.

Detail information of IndexedDraw calls.

```
    19 ID3D11DeviceContext::DrawIndexed(5898,0,0)
    25 ID3D11DeviceContext::DrawIndexed(20664,0,0)
    31 ID3D11DeviceContext::DrawIndexed(3000,0,0)
    37 ID3D11DeviceContext::DrawIndexed(5340,0,0)
    43 ID3D11DeviceContext::DrawIndexed(3540,0,0)
    51 ID3D11DeviceContext::DrawIndexed(2760,0,0)
    59 ID3D11DeviceContext::DrawIndexed(3444,0,0)
    65 ID3D11DeviceContext::DrawIndexed(1680,0,0)
    71 ID3D11DeviceContext::DrawIndexed(1680,0,0)
    79 ID3D11DeviceContext::DrawIndexed(72,0,0)
    85 ID3D11DeviceContext::DrawIndexed(1920,0,0)
    91 ID3D11DeviceContext::DrawIndexed(1332,0,0)
    97 ID3D11DeviceContext::DrawIndexed(618,0,0)
    105 ID3D11DeviceContext::DrawIndexed(720,0,0)
    111 ID3D11DeviceContext::DrawIndexed(6,0,0)
    117 ID3D11DeviceContext::DrawIndexed(174,0,0)
    123 ID3D11DeviceContext::DrawIndexed(360,0,0)
    129 ID3D11DeviceContext::DrawIndexed(78,0,0)
    137 ID3D11DeviceContext::DrawIndexed(1368,0,0)
    143 ID3D11DeviceContext::DrawIndexed(324,0,0)
    151 ID3D11DeviceContext::DrawIndexed(900,0,0)
    157 ID3D11DeviceContext::DrawIndexed(216,0,0)
    165 ID3D11DeviceContext::DrawIndexed(900,0,0)
    171 ID3D11DeviceContext::DrawIndexed(216,0,0)
    179 ID3D11DeviceContext::DrawIndexed(900,0,0)
    185 ID3D11DeviceContext::DrawIndexed(216,0,0)
    193 ID3D11DeviceContext::DrawIndexed(504,0,0)
    199 ID3D11DeviceContext::DrawIndexed(6,0,0)
    205 ID3D11DeviceContext::DrawIndexed(174,0,0)
    211 ID3D11DeviceContext::DrawIndexed(360,0,0)
    217 ID3D11DeviceContext::DrawIndexed(78,0,0)
    225 ID3D11DeviceContext::DrawIndexed(108,0,0)
    231 ID3D11DeviceContext::DrawIndexed(24,0,0)
    239 ID3D11DeviceContext::DrawIndexed(900,0,0)
    245 ID3D11DeviceContext::DrawIndexed(216,0,0)
    253 ID3D11DeviceContext::DrawIndexed(108,0,0)
    259 ID3D11DeviceContext::DrawIndexed(24,0,0)
    267 ID3D11DeviceContext::DrawIndexed(144,0,0)
    273 ID3D11DeviceContext::DrawIndexed(504,0,0)
    279 ID3D11DeviceContext::DrawIndexed(6,0,0)
    285 ID3D11DeviceContext::DrawIndexed(174,0,0)
    291 ID3D11DeviceContext::DrawIndexed(360,0,0)
    296 ID3D11DeviceContext::DrawIndexed(78,0,0)
    304 ID3D11DeviceContext::DrawIndexed(372,0,0)
    310 ID3D11DeviceContext::DrawIndexed(30,0,0)
    316 ID3D11DeviceContext::DrawIndexed(360,0,0)
    321 ID3D11DeviceContext::DrawIndexed(78,0,0)
    327 ID3D11DeviceContext::DrawIndexed(144,0,0)
    335 ID3D11DeviceContext::DrawIndexed(108,0,0)
    341 ID3D11DeviceContext::DrawIndexed(24,0,0)
    349 ID3D11DeviceContext::DrawIndexed(540,0,0)
    355 ID3D11DeviceContext::DrawIndexed(540,0,0)
    363 ID3D11DeviceContext::DrawIndexed(5322,0,0)
    369 ID3D11DeviceContext::DrawIndexed(540,0,0)
    377 ID3D11DeviceContext::DrawIndexed(792,0,0)
    385 ID3D11DeviceContext::DrawIndexed(1800,0,0)
    393 ID3D11DeviceContext::DrawIndexed(540,0,0)
    399 ID3D11DeviceContext::DrawIndexed(540,0,0)
    407 ID3D11DeviceContext::DrawIndexed(36,0,0)
    413 ID3D11DeviceContext::DrawIndexed(36,0,0)
    420 ID3D11DeviceContext::DrawIndexed(36,0,0)
    428 ID3D11DeviceContext::DrawIndexed(450,0,0)
    436 ID3D11DeviceContext::DrawIndexed(36,0,0)
    442 ID3D11DeviceContext::DrawIndexed(36,0,0)
    449 ID3D11DeviceContext::DrawIndexed(36,0,0)
    456 ID3D11DeviceContext::DrawIndexed(36,0,0)
    464 ID3D11DeviceContext::DrawIndexed(396,0,0)
    470 ID3D11DeviceContext::DrawIndexed(396,0,0)
    476 ID3D11DeviceContext::DrawIndexed(396,0,0)
    482 ID3D11DeviceContext::DrawIndexed(396,0,0)
    488 ID3D11DeviceContext::DrawIndexed(396,0,0)
    494 ID3D11DeviceContext::DrawIndexed(396,0,0)
    500 ID3D11DeviceContext::DrawIndexed(396,0,0)
    506 ID3D11DeviceContext::DrawIndexed(396,0,0)
    512 ID3D11DeviceContext::DrawIndexed(396,0,0)
    518 ID3D11DeviceContext::DrawIndexed(396,0,0)
    524 ID3D11DeviceContext::DrawIndexed(396,0,0)
    530 ID3D11DeviceContext::DrawIndexed(396,0,0)
    536 ID3D11DeviceContext::DrawIndexed(396,0,0)
    544 ID3D11DeviceContext::DrawIndexed(1512,0,0)
    548 ID3D11DeviceContext::DrawIndexed(1512,0,0)
    556 ID3D11DeviceContext::DrawIndexed(78,0,0)
    562 ID3D11DeviceContext::DrawIndexed(540,0,0)
    568 ID3D11DeviceContext::DrawIndexed(36,0,0)
    576 ID3D11DeviceContext::DrawIndexed(78,0,0)
    582 ID3D11DeviceContext::DrawIndexed(360,0,0)
    588 ID3D11DeviceContext::DrawIndexed(24,0,0)
    596 ID3D11DeviceContext::DrawIndexed(180,0,0)
    602 ID3D11DeviceContext::DrawIndexed(12,0,0)
    608 ID3D11DeviceContext::DrawIndexed(624,0,0)
    616 ID3D11DeviceContext::DrawIndexed(180,0,0)
    622 ID3D11DeviceContext::DrawIndexed(12,0,0)
    628 ID3D11DeviceContext::DrawIndexed(624,0,0)
    636 ID3D11DeviceContext::DrawIndexed(180,0,0)
    642 ID3D11DeviceContext::DrawIndexed(12,0,0)
    648 ID3D11DeviceContext::DrawIndexed(624,0,0)
    656 ID3D11DeviceContext::DrawIndexed(180,0,0)
    662 ID3D11DeviceContext::DrawIndexed(12,0,0)
    668 ID3D11DeviceContext::DrawIndexed(624,0,0)
    676 ID3D11DeviceContext::DrawIndexed(180,0,0)
    682 ID3D11DeviceContext::DrawIndexed(12,0,0)
    690 ID3D11DeviceContext::DrawIndexed(864,0,0)
    698 ID3D11DeviceContext::DrawIndexed(648,0,0)
    704 ID3D11DeviceContext::DrawIndexed(648,0,0)
    710 ID3D11DeviceContext::DrawIndexed(648,0,0)
    718 ID3D11DeviceContext::DrawIndexed(216,0,0)
    726 ID3D11DeviceContext::DrawIndexed(180,0,0)
    732 ID3D11DeviceContext::DrawIndexed(12,0,0)
    740 ID3D11DeviceContext::DrawIndexed(180,0,0)
    746 ID3D11DeviceContext::DrawIndexed(12,0,0)
    754 ID3D11DeviceContext::DrawIndexed(180,0,0)
    760 ID3D11DeviceContext::DrawIndexed(12,0,0)
    766 ID3D11DeviceContext::DrawIndexed(624,0,0)
    774 ID3D11DeviceContext::DrawIndexed(180,0,0)
    780 ID3D11DeviceContext::DrawIndexed(12,0,0)
    786 ID3D11DeviceContext::DrawIndexed(624,0,0)

```

Thanks in advance.

# Answer
> 1 votes
A modern gpu can easily handle around 3k Drawcalls ( This is well optimized of course ) and most likely even 2k with out any superb optimization. So I´m assume your FPS is down due to some CPU Bottleneck that's happening. ( could be related to rendering )

And to answer your question. One smart way of storing your Mesh to a compact and well optimized vertexbuffer for the cost of some extra memory and bandwidth is to combine all of it´s static values to vertex data. you specificly dont need to interpolate the data on the gpu later to get accurate values. So in general the vertex layout could be like this :

```
float4 positionXYZ,AmbientScale( could be anything )
float4 normalXYZ,SpecularScale( could be anything )
float4 uvcordsUV,ExtraLightBakedUV( could be anything )

```

What happens here is that you are packing your stuff into the vertex data which will always remain the same. You could basically pack what ever you want into this vertex layout. And it will most likely be faster than having more vertex buffers to iterate over.

---
Tags: directx11, instancing, vertex-buffer
---


# Question
Title: Blender wont export textures (materials) to OGRE3D .mesh
i am exporting a model from `BLENDER` to `OGRE3D` using the blender2ogre script. the desigre output is a single `.mesh` file but i know there should be also `materials` scripts that i should copy to my ogre path. the problem is that blender does not export those files for me it export only 1 mesh file (after i joined all objects) this is the model. in blender it looks fine but in my demo Ogre app it looks like :

i can use a little help here.

# Answer
> 1 votes
I just tested your model with Blender 2.70 and blender2ogre 0.60. The export worked fine. I got the `*mesh.xml` file as well as multiple `*.material` files. Update to the latest versions, if you haven't yet. Also make sure that during the export dialog, the checkbox "Export materials" is selected.

If it then still renders without any material in Ogre, there are two possible causes:

1. You have to ensure that your exported model contains UV texture coordinates, since otherwise Ogre doesn't know how to apply the texture to your model.

In order to create those UV confidantes with Blender, you have to unwrap and UV map your model. To verify that those coordinates are there afterwards, have a look at the intermediate file from the export process, `*.mesh.xml` file. If you can see UVs in there it should be fine.
2. Have a look at your Ogre.log file, if the UV part should be correct and look for any error messages, especially related to your `*.material` file. Maybe the texture file could not be found/loaded by Ogre.

---
Tags: blender, ogre
---


# Question
Title: Canvas - darken sprites rendered by drawImage
I am implementing lighting in a tile engine, and I need a way to darken tiles, based on their light level.

For the ground tiles, I can clear the context to black, then set the `globalAlpha` and use `drawImage` normally. But what about foreground tiles, such as trees? I don't want them to be translucent, just darker. Is there any way to filter the output of drawImage?

# Answer
> 1 votes
I figured it out. My solution was to use a "light mask" - an image with a progression of tiles of varying translucency. The darkening is achieved by simply rendering from the light mask over the finished scene.

http://jsfiddle.net/kX58L/

# Answer
> 0 votes
When you want to have full control over the color values of an image, you can draw it to an off-screen canvas like this (NOTE: This code assumes the image is already loaded!)

```
    var offscreenCanvas = document.createElement('canvas');
    offscreenCanvas.width = image.width;
    offscreenCanvas.height = image.height;
    var context = offscreenCanvas.getContext('2d');
    context.drawImage(image, 0, 0);

```

You can then use context.getImageData to get an array of raw RGBA values. You can then manipulate these color values in any way you desire and write them back with context.putImageData.

```
// get raw pixel values
var imageData = context.getImageData(0, 0, image.width, image.height);
var pixels = imageData.data;
// modify each pixel
for(var i = 0; i < pixels.length; i += 4) {
   // red is pixels[i];
   // green is pixels[i + 1];
   // blue is pixels[i + 2];
   // alpha is pixels[i + 3];
   // all values are integers between 0 and 255
   // do with them whatever you like. Here we are reducing the color volume to 75%
   // without affecting the alpha channel
   pixels[i] = pixels[i] * 0.75;
   pixels[i+1] = pixels[i+1] * 0.75;
   pixels[i+2] = pixels[i+2] * 0.75;
}
// write modified pixels back to canvas
context.putImageData(imageData, 0, 0);

```

When you want to draw the modified image to the main canvas, you can use the offscreen canvas as a source parameter just like any normal image.

---
Tags: html-canvas
---


# Question
Title: Pointer to member function of another class
I have two classes, `CEffect` and `CEffectPool`. A third class `CLevel`, is doing most of the stuff in my code.

In every frame, it checks each `CEffect` in `CEffectPool`, and if it is currently inactive, it disables it.

What I would like to do is to give `CEffect` the pointer to the `CEffectPool` member function called `Destroy()`, so I don't have to check every single `CEffect` by another class whether it shall be destroyed or not.

With this function pointer, `CEffect` would simply call a function, which would destroy it.

Also, I am not talking about destroying in the C++ way (I don't want memory to be freed or to call the destructor).

Here is some code, that i have, but it unfortunately don't work and I am not sure why:

CEffect.h

```
class CEffectPool;
class CEffect {
    public:
        CEffect();
        CEffect(const CEffect& eff);
        CEffect& operator=(const CEffect& eff);
        void Initialize(CEffectPool* pool,
                        ushort id,
                        real x,
                        real y,
                        ushort timer);
        void Frame();
        void Draw();
        bool IsActive() const;
    private:
        CEffectPool* _pool;
        ushort _id;
        CSprite _sprite;
        ushort _anmfrm;
        ushort _timer;
};
void DestroyEffect(CEffectPool* pool,
                   ushort id);

```

CEffect.cpp

```
void CEffect::Frame() {
    if(_timer) {
        --_timer;
        return;
    }
    ++_anmfrm;
    if(_anmfrm == 24) {
        DestroyEffect(_pool,_id);
    }
}

```

CEffectPool.cpp

```
void CEffectPool::Destroy(ushort index) {
    if(index >= _size) {
        return;
    }
    CEffect temporary = _pool[index];
    _pool[index] = _pool[_size-1];
    _pool[_size-1] = temporary;
    --_size;
}
void DestroyEffect(CEffectPool* pool,
                   ushort id) {
    pool->Destroy(id);
}

```

Could you help me with this? What is the best approach to do this?

# Answer
If what you are looking for is a pointer to a member function of `CEffect`, then it would be something in the lines:

```
// Assuming the type CEffect is a class with a Destroy() method
// as shown below:
class CEffect {
public:
    void Destroy() { ... };
};

// Declare a pointer-to-member type, for convenience:
typedef void (CEffect::* DestroyFunc)();

```

Then you declare a member function pointer just like you would with a normal C function pointer:

```
DestroyFunc destroy = &CEffect::Destroy;

```

To call it, it is a bit different then with a C function. You will need a class instance:

```
CEffect * effect = new CEffect(...);

// Call CEffect::Destroy for 'effect':
(effect->*destroy)();

```
> 1 votes

# Answer
I think you don't need a pointer to a method. You already have a pointer to the CEffectPool instance.

You should do like the following code :

```
void CEffect::Frame()
{
    //...

    if(_anmfrm == 24)
    {
        _pool->Destroy(_id);//you call directly the method of CEffectPool
    }
}

```

`CEffectPool::Destroy` should be public to be used by another object.
> 0 votes

---
Tags: c++
---


# Question
Title: Why does my side-scroller character move in the wrong direction?
I'm trying to understand why my rectangle moves in the opposite direction I want it to.

I have a `float` for translation:

```
 glTranslatef(translate_x, 0, 0);

 if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
        translate_x += 5;
 }

```

This is the rectangle I'm drawing (I did use `glpush` and -`pop`):

```
glColor3f(250, 0, 0);
glBegin(GL_QUADS);
    glVertex2i(400, 400); // Upper-left
    glVertex2i(450, 400); // Upper-right
    glVertex2i(450, 450); // Bottom-right
    glVertex2i(400, 450); // Bottom-left
glEnd();

```

Whenever I press the spacebar, the rectangle moves to the opposite direction of where I want it to move. Why is this?

# Answer
> 1 votes
glTranslatef moves the camera, and not what it is looking at. So adding 5 to the x-axis will make the camera move to the right, hence making it look like the rectangle is moving to the left. Subtracting 5 will make the rectangle go to the right.

# Answer
> 1 votes
If you want your rectangle to move on the same axis but in the opposite direction, you have to change the sign of the translation value.

```
glTranslatef(-translate_x, 0, 0);

```

---
Tags: camera, movement, lwjgl
---


# Question
Title: How to handle runtime exceptions that occur on a loading process delegated to newly spawned thread
I am looking to multi-thread the resource allocation routines (i.e world loading) in my game so that they can occur in the background whilst rendering a loading screen etc... The problem is, I used to have code like this (pseudo)

```
void foo()
{
    ...
    try
    {
        mWorld = world.create(...)
    } catch(EntityNotFoundException e)
    {
        ...
    }
}

```

However, now that the world is being loaded on another thread, I need to register a listener that will recieve notification when the world is ready. The problem is that if an exception occurs inside of the newly created thread, I cannot surround it in a try-catch like I have here. How is this problem solved?

I am thinking of having the loading thread interface with a handler that looks like this:

```
public interface IInitializationMonitor<T> extends IInitializationProgressMonitor
{
void begin();
void completed(T item);
void failed(Throwable error);
}

```

The problem being that error would need to be tested against multiple times with instanceof, or rethrown inside of a try block. I am curious if there is a more elegant solution...

Thanks.

# Answer
The `Future` interface will help here, when the call function of the Callable throws then the get of the Future will throw a `ExecutionException` where its cause is the original exception.

You can subclass `FutureTask` and override the `done` which will notify the world when the computation is either successful or failed and let the world handle the failure condition.
> 2 votes

---
Tags: java, multithreading, loading, resource-management, exceptions
---


# Question
Title: Best visual way to build a "near isometric" 2D view
I'm working hard in a 2D platform game, as far as I got is a standard 2D view (only x and y are visible)

But I want to change the perspective so I can see the floor also.

But the MapBuilder I developed works perfectly based on TILES (so my 2D works very well)

I wanna know the easiest way to add the ground on top of the floor without switching to full 3D with rotationed Rectangles.

The best I tought is to create a "magic" rectangle on top of my ordinary floor to make this fake perspective. But this still lead me to problems on multi-floors.

# Answer
## These are the two main solutions I can think of:

* **If you use tilesets**, add a rectangle on top of your tiles. You should also move the collision detection up a bit, not to have your character walking on the edge of the blocks. However, this can easily look like the character's feet are passing through the ground but it mostly depends on the quality of the tiles. Here is an example where it looks very good to me.

* **If you use "plain" images** you have to draw the upper part too, where the characters are walking. The collision detection should be a little upper or else it will look weird.

This is just a display change, it can't bring other problems than looking weird or ugly.
> 3 votes

---
Tags: 2d, tilemap, isometric, perspective, map-editor
---


# Question
Title: Unity Move sprite from point A to point B
Pretty new to Unity and i'm trying to make a very simple iphone game. , I'd like to know how to move a sprite (2D) move from random point A to random Point B not just that, but i want it to change direction halfway through.

here is my attempt:

```
public float speed;
public float minForce;
public float maxForce;
public float counter;
private float counter2;

void Start ()
{
    Push ();

}

void Update ()
{
    counter2 -= Time.deltaTime;
    if ( counter2 < 0)
    {
        Push ();
        counter2 = counter;

    }

}

void Push ()
{
    float force = Random.Range(minForce, maxForce);
    float x = Random.Range(-1f, 1f);
    float y = Random.Range(-1f, 1f);

    rigidbody2D.AddForce( force * new Vector2(x, y) * speed);
}

}

```

I'm not quit satisfied with using force, also tried Vector2.lerp but for some reason it just teleported instead of smoothing. Also i want to make it randomly change position only once.

here is my perp attempt:

```
 private Vector2 startPoint ;

public float speed ;
public float counter;
private float counter2;

void Start ()
{
    startPoint = transform.position;
}

// Update is called once per frame
void Update ()
{
    counter2 -= Time.deltaTime;
    if ( counter2 < 0)
    {
        RandomPosition ();
        counter2 = counter;

    }

}

void RandomPosition ()
{
    float counter = speed * Time.deltaTime;
    float x = Random.Range(-50f, 50f);
    float y = Random.Range(-100f, 100f);
    Vector2 endPoint = new Vector2(x, y);
    transform.position = Vector2.Lerp(transform.position, endPoint,       Time.deltaTime * speed);
}
}

```

# Answer
So, first: If you want to use `Vector2.Lerp`, you have to call it every frame(Update), with a parameter between 0 and 1 - what you did, is create a new line, `Lerp` to some random point on it, and discard everything on the next frame.
You also used a lot of local variables for stuff that needs to be class members, because other functions need access to them.

A simple way to do what you want would be

```
float timer;
Vector3 startPos;
Vector3 endPos;

void Start()
{
   RandomPosition();
}

void RandomPosition()
{
  timer = Time.time;
  startPos = transform.position;
  endPos = new Vector3(Random.Range(-50f, 50f), Random.Range(-100f, 100f), 0);
}

void Update()
{
  if (Time.time - timer > 1)
  {
    RandomPosition();
  }
  transform.position = Vector3.Lerp(startPos, endPos, Time.time - timer);
}

```

This is if course quite trivial, p.e. it moves the transform from a to b in one second, without caring about speed, but should get you on the right direction.

Also, if you want to just change direction half way to a new random direction - is that not the same as simply moving only half the way, and then starting again? No need to make it any more complicated.
> 1 votes

---
Tags: unity, movement, random
---


# Question
Title: How can I improve my collision detection's performance?
I'm new to programming and want to speed up the collision detection in my C++ 2D platformer game engine.

Currently, only the player's collision detection works: Every frame, the player's update function iterates through every level tile (which is pretty many) and checks if the player hitbox collides with it.

I may be way off on this, but this seems like a really chunky way of doing it. Is this bad practice? If the level gets large enough, is iterating through this list going to take forever like it seems it should?

My second question builds off of that: If I start adding for example enemies into the engine and give them a similar method for collision detection, can I expect performance drops? I'd like some insight from more experienced people on a better way of setting this up. I would just imagine that having ~20 enemies on the screen all iterating through all possible objects for collision with a list could get slow fast.

# Answer
**Preliminary warning**: *Optimisation* is a dangerous cast-from-life-type magic. You should always optimise as late as possible, because machine time is cheap. Obfuscate your code for performance only when you know you need to. Many small games manage just fine with the simple method you've described.

---

That said, here's the news:

**The bad news** is that you're right: Giving larger inputs to any algorithm will eventually slow it down. Bigger problems are harder—that's a physical certainty.

**The good news** is that different algorithms slow down at different rates. The rate at which an algorithm slows down with respect to the input size is called its computational complexity.

I'll first explain computational complexity theory (what efficiency is) then some techniques to speed up your specific problem.

# A *slow* dumb algorithm

Let's start by making a slow algorithm, in a way no sane person would do it, because it's easier than making a fast one and better illustrates *how to measure* an algorithm's efficiency.

The way you're doing it, *iterating through a list* to find whether any tile collides with your player has *linear complexity* (often written as *O(n)-complexity* or *order-n-complexity*). This means that if you double the size of the input (how many tiles you have), that also doubles the time the algorithm takes to run.

Iterating over a...
...1-element list: `1`
...2-element list: `1 2`
...3-element list: `1 2 3`
...4-element list: `1 2 3 4`
...5-element list: `1 2 3 4 5`
...6-element list: `1 2 3 4 5 6`
...7-element list: `1 2 3 4 5 6 7`

Iterating over a large list of `n` elements this way has complexity `O(n)`.

Some algorithms slow down even more easily: For example, imagine if every time you wanted to access one of the tiles in your list, you had to start over and iterate to that tile all over again from the start of the list. (No sane programmer would actually do this, but hey, it's a *possible* algorithm.)

Iterating over a whole list of different lengths would cause reads something like this:

Dumb-iterating over a...
...1-element list: `1`
...2-element list: `1 1 2`
...3-element list: `1 1 2 1 2 3`
...4-element list: `1 1 2 1 2 3 1 2 3 4`
...5-element list: `1 1 2 1 2 3 1 2 3 4 1 2 3 4 5`
...6-element list: `1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6`
...7-element list: `1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7`

That blew up pretty fast in comparison. Given a list of `n` elements, this algorithm takes `0.5 * n * (n + 1)` time. In computing, we often shorten this by calling it `O(n ^ 2)`, because the n-squared term dominates as the list grows.

I'm sure we could come up with an *even dumber* way of iterating over a list with an exponential or even factorial complexity. Let's not do that. Instead, let's go to the other extreme.

# A *fast* dumb algorithm

Can we find the collision response of a player character with a large number of static walls in **constant time**? This is the fastest possible time complexity: It would mean taking the same amount of time regardless of the input size.

**Yes!** We could precompute and store *every possible position* that your player character could *possibly* be standing at and the appropriate precalculated collision response, in memory.

Assuming your game world is 2000 by 1000 pixels large and that your player and walls are positioned at integer coordinates, then you'd have to store a

```
struct CollisionResult {
    int collisionResponseX;
    int collisionResponseY;
}

```

for every possible position your player could be in (`struct CollisionResult[2000][1000] collisionResponseCache`) and you'd have a complete and immediately queryable cache of what collision to expect when a player is in any position.

This is a constant time algorithm: Indexing into an array (something like `collisionResponseCache[player->posX][player->posY]`) is just as fast for every possible input—mere milliseconds.

We've traded memory space and flexibility to gain time complexity.

How much memory space? Assuming your machine has 4-byte integers, that big array would take up 2000 * 1000 * 2 * 4 = 16000000 bytes of space—that's 16MB. That's quite a lot of memory and it increases linearly with the size of your game world, though it's not too bad for a modern PC with gigabytes of RAM!

How much flexibility? This constant-time method assumes all of the things you want to test for collisions against are present and static (and hence precomputable). This is often limiting, as it prohibits moving enemies, collectibles, breakable walls and such.

# Spatial subdivision; worlds between

A better algorithm would allow more flexibility (changing inputs) but still be faster than linear time. How might we do that?

Consider a two-dimensional game world with some game entities in it.

We could easily double the collision detection algorithm's efficiency by keeping two lists of objects instead of just one: A list for objects on the left half of the level and another for the right half:

Whenever an object crosses the boundary, we'd move it to the other list. This way, we only need to check for collisions against the objects in the list corresponding to the side of the stage the player is on.

We can take this further by introducing two more lists and splitting the level in four instead.

Or into twelfths. Hundredths? We can parametrise this as we like, to control how much flexibility and memory we want to trade for speed. Making each list represent a 1×1 area (a single pixel) makes this essentially degenerate to the "store absolutely everything"-approach above.

This is the gist of a spatial subdivision technique called spatial hashing. The details are a little more complex, as you have to account for entities' sizes (they might be in many cells at once). C++ implementation details are the domain of another question.

A *quadtree* works in a similar manner, but it subdivides cells only as needed:

Many thanks to David Eppstein of Wikipedia! The image page includes Python source code!

If your game objects are relatively sparse, quadtrees may be significantly faster than a spatial hash, so they're also worth investigating. Again, implementations and guides exist that I won't replicate here, but this is the gist of it.
> 18 votes

# Answer
You can use a QuadTree: See (here) and (here).

It allows an O(n^2) naive algorithm (iterating every object over every other object) to drop to an O(n) algorithm (only the objects in the same cell or objects contained in visible cells via a selection area (usually the camera's visible area).
> 2 votes

---
Tags: c++, collision-detection, performance, sfml
---


# Question
Title: Axis Aligned Spatial Division : Divide space into random rectangles?
I need a method to divide 3d space into random axis aligned box shapes. For now I am currently dividing the 2d space for testing purposes. The most immediate approach I came up with was to define a rectangle of size (1, 1) and then recursively split all existing rectangles to two uneven rectangles alternating between axis X and Y.

The problem here is obvious. This approach results in long stretching lines (marked in red)

What I would like is something more organic looking (I included an example)

See, no long straight lines from top to bottom or left to right.

The only constraint is that I may wish to limit the minimal size of the rectangle without affecting the granularity of the sizes. i.e. if the smallest rect is 1 square centimeters than the seconds smallest room should not be 2 square units.

So ideally the algorithm should meet all three following constraints:

1. Rectangles are not infinitesimally small.
2. Rect sizes aren't discrete multiplication of the smallest rect size. i.e. if the smallest rect is 3 square unit than larger rects are not constrained to be 6, 9, 12 and so forth square units and instead could be 3.2 or 4.7 for that matter).
3. The algorithm runs in polynomial time (needs to compute fast).

# Answer
> 12 votes
The approach you outline is simple and useful, but suffers from terrible artifacts as shown. Avoid it. You need a parallel growth algorithm; for a single-threaded model, a round-robin approach follows:

1. Randomly place various points in your map space. Normalise their distribution (avoids ugly clustering) using Gaussian distribution or by applying an iterative relaxation algorithm to move randomly placed points away from one another, as per Lloyd relaxation for Voronoi Diagrams. These points represent the centroids of your rooms-to-be.
2. (Parallel / Repeat round-robin for all rooms) From each point, grow 4 vertices outward (a rectangular room), moving from the centre point per global iteration (you can grow different rooms at different rates in each axis rather than the same for all, and see how this turns out -- possibly for a more organic / varied result). At some point, some of your rectangles will begin to press against each other. At that point, limit growth in that axis, ensure the two rooms' adjacent edges are exactly touching, and move on.
3. Repeat step 2, growing every room incrementally, till all growth is restricted by adjacent rooms or the bounds of the map.
4. This will still leave some empty spaces. The problem now becomes one of locating and making rooms out of non-occupied spaces. In fact, if your underlying space is a (integer-indexed) grid (and every growth iteration snaps to that grid), then this is much easier to deal with, since you can maintain lists of occupied and unoccupied grid cells: Once you've placed and grown all your rooms, search through the unoccupied list for discrete spaces consisting of groups of adjacent cells. As many unused spaces will have non-rectangular shapes, you'll need to pick a cell at random from within that non-rectangular space, and grow it to its maximal size just as you did with rooms in step 2. Repeat within said non-rectangular space, till it is completely filled.
5. Repeat step 4 till your map is 100% occupied.

# Answer
> 3 votes
As you can see, I managed to rid the world of these artifacts. The idea is very similar.

1. Divide the 2d space into a non-uniform grid. If two lines are too close, remove one.
2. Pick a rectangle in random, check if it's been modified across axis-y (in height) and if it's direct neighbor was modified across axis-y. I both were not modified, have them renegotiate the segment between them (one will donate some space to the other).
3. Do the same as in step 2 only this time on the other axis.
4. Repeat the process until you modified as many as possible.

Non-uniform grid (1):

Negotiating on axis x (2):

Negotiating on axis y (3):

Result (4) :

---
Tags: algorithm, procedural-generation, random, space-partitioning
---


title: Blending issue with framebuffer

text:
# Question
Title: Blending issue with framebuffer
I'm trying to get some particles to work properly - they should blend among themselves but not with the background color. For this I'm using additive blending, textures with premultipled alpha and set the color as (r\*a, g\*a, b\*a, 0) on textures I want to add up. I'm using the blend mode: glBlendFunc(GL11.GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA); for everything.

I found out that what I want to do can be achieved by rendering and additively blending the particles in a framebuffer and then render that framebuffer on top of the background with standard alpha blending. In theory I think this should work..however i'm still getting the same result as I did before which is very bright particles at bright areas of the background.

So what I'm doing is simply: 1)Render the background as usual with color (r\*a,g\*a,b\*a,a)

2)Bind my fbo

3)Use GL11.glClear(GL11.GL\_COLOR\_BUFFER\_BIT); GL11.glClearColor(0f, 0f, 0f, 0.0f);

4)Render all the particles with color as (r\*a,g\*a,b\*a,0)

5)Unbind the fbo and render it on top of the bg with (1,1,1,1) color.

Why doesn't this work?

# Answer
I think you may not entirely understand how destination blending works.

You claim that you set your output to `(r*a, g*a, b*a, 0.0)` and then use `GL_ONE_MINUS_SRC_ALPHA` for the destination blend factor. Because source ***alpha*** is constant (**0.0**) in this example, that works out to be equivalent to `GL_ONE`.

Likewise, if you apply `GL_ONE, GL_ONE_MINUS_SRC_ALPHA` in your second pass that effectively discards anything already in the color buffer:

```
SrcColor.rgba * 1.0   +   (1.0 - 1.0) * DstColor.rgba    =  SrcColor.rgba  =  (1,1,1,1)

```

In this case, you would be better off simply disabling blending in the second pass.
> 1 votes

---
Tags: lwjgl, particles, blending, alpha
---


# Question
Title: What are the performance and size tradeoffs of Eigen::Transform versus Eigen::Matrix4f?
We finished migrating from `DirectXMath` to the `Eigen` math libraries for our 3D-Game Engine last week for portability reasons. After implementing transformations with matrices as we know them, we found out about `Eigen::Transform`, which seemed like a really cool idea at the time.

Now, after a lot of fiddling things still don't quite work and we don't seem to have as much control over the way that Transformations are made. With `Eigen::Matrix4f`, you're making the multiplications directly and can change in which order they are made. `Eigen::Transform` appears to be way less transparent and flexible.

So we thought about reverting to our commits from last week, and head on to work with matrices again. But there are a few things we are concerned about:

1. Saving things like translation in a 4x4 Matrix takes up more space than using `Eigen::Translation`
2. Generating a new `Matrix4f` for the complete transformation every tick seems like a tedious process

So I wanted to know how `Transform` compares to regular `Matrix4f` in terms of speed and if my impression that `Transform` is not as flexible is actually true or not.

# Answer
> 2 votes
Your first concern, regarding size(\*), is a non-issue. You can note in the source that `Eigen::Transform` just stores a matrix of an appropriate size to transform a homogeneous coordinate in the specified dimensionality (that is, a 4x4 matrix for a 3D transformation). This appears to be because `Transform` is allowed to represent projections, rather than just translation/rotation/scale (which could be stored in few floats).

Your second concern, about generating a new matrix every update, is also a non-issue. Construction of a matrix *in general* shouldn't be that slow. Plus, you usually want to do this because persisting your transformation data (position, orientation and scaling) in different forms usually makes them easier to access and manipulate. For example, it's a lot easier to interpolate position and orientation and vectors and quaternions, respectively, than it is to try an interpolate a transformation matrix representing the combined operation.

Plus, due to floating point inaccuracies if you persist the transform as a matrix and constantly update into it, you can create rendering bugs as drift is introduced into what was originally (for example) a uniform scale portion of the matrix.

`Eigen::Transform` appears to exist main as a way to simplify the creation and usage of a matrix for many typical transformations. As with any such simplification, yes, it forces certain conventions on you. If those conventions don't work for you, you shouldn't use the class and should instead operate with the underlying matrices directly (which sounds like what you want to do in this case).

(\*) Edit: I had assumed your reference to `Eigen::Translation` was a typo for `Eigen::Transform`, but when I went to confirm by browsing the source it turns out there *is* such a class. In this case, you are correct that the `Translation` class will be smaller than a full matrix.

---
Tags: c++
---


# Question
Title: What's a clean way to find (up to) 3x3 squares within a 6x6 grid?
I have a 6x6 grid where every cell have a color property (simply integer value).

Player can change one cell at a time to form rectangles of the same color inside of the grid. New rectangles can only be 2x2, 3x2, 2x3 and 3x3 in size.

Is there a cleaner way to find those rectangles rather than having to manually search for `[i][j]`, `[i+1][j]`, `[i][j+1]` and `[i+1][j+1]` (et cetera) color matches?

# Answer
> 1 votes
If your shapes never get bigger than 3x3, your described approach should be sufficiently fast. A 3x3 maximum square means that whenever a player changes a tile's color, you only need to search two tiles in all directions (that is, a 5x5 search space). That's a total of 24 checks in the worst case (you don't need to check the center), which is not *that* taxing. Especially since the overall size of your grid means you will short-circuit out of many of those checks anyway (since they'd be out of bounds).

A potential optimization is to track the state of "partially assembled" squares as they are built. This reduces the number of checks you generally need to make to approximately 8 (the eight surrounding tiles of the clicked tile) to see if the clicked tile should be added to an existing potential solution, and whatever checks you need to see if a potential solution has just become valid (probably two or three more `if`s, to check it horizontal and vertical bounds).

However, this approach not only requires more memory but also requires a way for you to tell if a given tile is part of an existing potential solution, which is generally efficiently done with some kind of spatial partitioning technique. It is thus much more complex for what is a questionable performance gain at the scale you are working at.

---
Tags: 2d, grid
---


# Question
Title: How to make a sidescrolling effect in lwjgl
I use the following methods and the screen moves away from the player.

```
glTranslatef(h.x - width/2, h.y - hieght/2, 0);

        if ((Keyboard.isKeyDown(Keyboard.KEY_D))) {

            h.x += 10;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
            h.x -= -10;
        }

```

How do I make it so the player and the screen moves? Also shouldn't I just use the camera?

# Answer
Your keyboard events should **move the player**. And the camera should **follow the player**. That seems the most logic, you have a moving object and you track it with the camera.

They are trying to do a similar thing here.

I don't know how you move your player, but your code would look something like that

```
if (Keyboard.isKeyDown(Keyboard.KEY_D))
{
    //Move player to the right
    player.x += 10;
}

if (Keyboard.isKeyDown(Keyboard.KEY_A))
{
     //Move player to the left
    player.x -=10;
}

glTranslate2f(-player.x,-player.y,0);

```

This is just to give you an idea, this can't be used as is. You have to adapt it to your needs.
> 0 votes

---
Tags: java, lwjgl
---


# Question
Title: How to achieve cavalier projection using OpenGL fixed pipeline?
I want to make a quick demo program showing a cube, or a user loaded model, rotating in screen rendered with one of three projections: perspective, isometric and cavalier.

Using the fixed pipeline, how can I build a projection matrix for cavalier projection?

I think I can start with the orthographic projection matrix and then tweak the values, by eye, until I get the z of the vertices go to the right and up as farther the z is. I want the lines parallel to the z axis rendered as vertical lines 45 degrees rotated to the right.

# Answer
For a cavalier projection, it looks like you would want to start with an orthographic projection and then apply a shear to the z-axis.

In other words, for OpenGL you would want to multiply the projection matrix on the left by a matrix of the form:

\begin{matrix} 1 & 0 & a & 0 \\ 0 & 1 & a & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{matrix}

where `a` is the shear factor, which you'd tune to taste. (You could also use two separate shear factors along x and y, if you wanted an angle other than 45 degrees.)
> 7 votes

---
Tags: opengl, mathematics, matrix, projection
---


title: RPG - storing player data

text:
# Question
Title: RPG - storing player data
Given the following tree structure, where each player logged in can have data for current and completed levels, quests per level, NPCs per quest, and multiple tasks per NPC... I'm trying to figure out the best way to store the current and completed data per player.

I asked the question before, albeit with too much detail. It was requested that I generalize the question... So if you'd like more context, see here:

https://stackoverflow.com/questions/23587430/rpg-storing-player-data-for-semi-complex-tree-structure

Some information about my RPG structure:

* Levels, Quests per Level, and Tasks per NPC are completed in chronological order.
* NPC dialog and task dialog data is stored in a js object in a `npc_dialog_1.js` file in the following structure:

```
var dialog = {
quests : {
    questName : {
        NPCName: {
            TaskName:  {
                 "english" :
                  [
                      "Hello, here is some dialog",
                  ],//more items per task
            }, //more tasks per NPC
        }, //more NPCs per quest
    }, //more quests options per "quests"
}, //more options in dialog besides "quests" if I want
};

```

I am storing each `dialog` object in a separate `npc_dialog_n.js` file per map, that I'm retrieving with `requireJS`. This will reduce clutter in a single npc\_dialog file.
* NPCs per Quest, however, can be started in any order... this is trying to mimic a GTA-style quest queue, as the game follows a general linear progression, yet for each quest you can talk to multiple NPCs and start, pause, and resume the NPC's tasks at any point.

Since the player can start, pause, and resume tasks per any NPC at a given time, I'm trying to figure out the best way to store the current and completed data per player.

**mfirdaus** recommended the following DB table with M:M relationship b/t user & npc... yet this would add up quickly as each player can have multiple NPCs per quest, and multiple tasks started per NPC... Any way around this set up?

My current db schema:

Thank you

# Answer
* Having *username* in *userstats* is redundant.
* You probably would want to key *userstats.id\_user* and *users.id\_users*.
* *userstats.id\_stats* as auto incremented would be ok to reference from an npc interaction.
* Remove Coords from userstats.

table: **playerLocation**

```
id_user | playerX | playerY | levelName
   1    |   211   |   105   |  myMap2
```
* Remove experience from user stats.

table: **playerExperience**

```
id_user | exp
   1    | 200
```
* Modify quest tracking integers.

table: **userstats** *(see below)*
* Remove the questname from userstats.
* Add a column for quest complete.
* Change the quest Ids to a more useable format.

101, 102, 103 (combination of level and quest number)
* Create a quest table:

table: **questInfo** (This can have some optional fields depending on how you do quest rewards)

```
questnum |   questname   | npc_id | reward_xp | reward_items | reward_money
  201    | "ride or die" |   5    |    200    |  1001, 1005  |     500
```

table: **npc**

```
npc_id | Quest 1 | Quest 2 | Quest 3 | ...
  5    |   101   |   102   |   103   | ...
```
* Your **userstats** would end up looking like:

```
id_stats | id_user | questnum | questcomplete
    1    |    3    |   102    |      0
    2    |    2    |   101    |      1
    3    |    4    |   103    |      0
```

I hope this gives you some guidance... the main thing is to normalize your DB. It will make it 1000x easier as you expand and build your game.

EDIT:@growler about NPC's.

Are you implying quest 1 with 4 npcs,
NPC 1 complete task
Allowed access to NPC 2
NPC 2 complete task
Allowed access to NPC 3 etc?

If so, I would treat them all as individual quest even though they aren't in the large scheme.

Quest 1 could be ID'ed as 101, quest 1 part 2, 102.

I usually add quest handling in the engine itself...but perhaps for a larger MMO style you might add in a questpreq table listing required completions.

```
questnum | prereq
     202 | 201

```

and just chain off that.

The reason the tables are split up so much is because you should always normalize your data. Depending on how you track player location...IE writing to the DB every move, or holding location on the server in memory and just writing to the DB "saving player stats" every 2~10 minutes would influence your structure. It's going to be less costly to make hits on a 3-4 column table every .6ms then a 5\> table. When the user gains exp, it's a quick update. It's not something that happens very often.
If you are writing mobile/single player/ something that isn't being controlled by a reliable server/source...I would 100% keep the location table small as is and write back to it. If you're on mobile and they lose connectivity or power outages etc and you haven't "saved" data they will experience a roll back.
This is a pretty good article to take into consideration as well on updates to the DB

How often to update a Game Client about the World?
> 3 votes

---
Tags: databases, savegame, storage, profiling
---


# Question
Title: Particle system: BlendMode of particle's draw call
I noticed by reading some tutorial around the web, that when dealing with particle systems, you can both use these approces:

* Black background on the single particle and additive mode as blending mode for drawing
* Transparent background on the single particle and alpha blend mode for drawing.

What are the differences between the two approces?

# Answer
> Transparent background on the single particle and alpha blend mode for drawing.

This should be the most common method for general particles. The problem of this method is you have to sort the particles and rendering them back-to-front to get the alpha blending works correctly. It would bring a heavy burden on CPU when there is a lot of particles. And if the particles are not simple billboards and may intersect with each other, it may be unsolvable with simple sorting.

> Black background on the single particle and additive mode as blending mode for drawing

You don't need to sort the particles, as the order of particles doesn't matter in additive blending. However, this method only works for a smaller set of effects, like fire.
> 1 votes

---
Tags: particles
---


# Question
Title: How to use facebook sdk on a cocos2dx-project
I'm doing a game cocos2d-x, when user gets a high score, I want them to touch on the Facebook icon and share the high score on their Facebook account timeline.

tutorials on facebook.developer.com using for objective-c project

Can anybody help me:(

# Answer
The Graph API is based completely on HTTP requests and JSON encoded data. Therefore all you have to do is be able to do HTTP requests and encode/decode JSON and you're set.

For HTTP, you can use libcurl

For JSON there's a lot of libraries, so be sure you check the ones at the bottom of its official webpage. I've used libjson and it works pretty well.
> 1 votes

# Answer
Check out https://github.com/hiepnd/Screw. It comes with rich functionalities and detailed document.
> 1 votes

# Answer
You can take a look HERE. Actually it works on iOS but is not working in Android.

You can follow the forum´s post HERE
> 0 votes

---
Tags: cocos2d-x
---


# Question
Title: How do I calculate legal moves in a travelling board game?
I'm making a traditional roll-the-dice-and-move style board game. Players move along the white squares on the board (see image) and may move in any available direction from a junction. Players must move the full distance of their roll.

Other than a brute force calculation, how can I efficiently calculate the destination squares of all legal moves?

# Answer
One solution is to use a recursive function (Video explaining recursion). So for example the player is on the red square and he can do 5 moves :

The function should see that the square on the right is white so it calls the same function but with the square on the right (it does the same to the left but we will just look at the right to simplify). Except that this time, it tells the function that the player can only do 4 moves and not to the left.(the pink square represents the place the player can't go anymore)

The function sees that the square on the right is white. Again, it calls itself but now there is only 3 moves left.

Now the function calls itself again but with 2 moves left for the square on the right and the square on the bottom (it calls the function 2 times).

and again and again... Until there is no move left! When the function is called with no move left, it writes its position in an array.

At the end the array contains all the possible position for the player to go.

I don't know what language you use, so I will writte an example in C. So we will need a structure to contain the position of the legal moves :

```
struct Rect
{
    unsigned short x;
    unsigned short y;
};

```

Let's say you have these variables, to simplify we'll say they are global but you could just send their pointers to the function.

```
Rect legalDest[20];                     // This array contains the legal destinations
unsigned short numberOfSolution = 0;        //number of solution in the array
bool map[30][30];                       //2d array containing your map, 1 = white, 0 = black

```

Let's also say that you have a variable named commingFrom, if commingFrom egal 1 the previous square is on the right, 2 the previous square is on the top, 3 the previous square is on the left and 4 on the bottom. 0 means no previous square.

```
void get_legal_dest(Rect currentPosition//The square that is being analysed
unsigned short numberOfMoveLeft,        //the number of move left
unsigned short commingFrom)             //position of the previous step
{
    Rect nextPosition;

    if (numberOfMoveLeft == 0) // if we can't move anymore, we reached a legal destination location
    {
        legalDest[numberOfSolution].x = currentPosition.x
        legalDest[numberOfSolution].y = currentPosition.y // we write the current position inside the array containing the solutions.
            numberOfSolution ++;//One more solution !
    }
    else
    {
        numberOfMoveLeft --;//we did a move

        if (commingFrom != 1 && map[currentPosition.x+1][currentPosition.y])//if not comming from the right and the square on the right is white
        {
            nextPosition.x = currentPosition.x+1;
            nextPosition.y = currentPosition.y;//the next position is on the right
            get_legal_dest(nextPosition,numberOfMoveLeft,3);//3 = next time we are comming from the left
        }
        if (commingFrom != 2 && map[currentPosition.x][currentPosition.y-1])//if not comming from the top and the square on the top is white
        {
            nextPosition.x = currentPosition.x;
            nextPosition.y = currentPosition.y-1;//the next position is on the top
            get_legal_dest(nextPosition,numberOfMoveLeft,4);//4 = next time we are comming from the bottom
        }

        //same for left and bottom

    }
}

```

Utilisation of the function, for example the player in on position 10, 10 and can move 6 squares :

```
Rect currentPosition = {10,10};
void get_legal_dest(currentPosition, 6, 0); //0 = comming from nowhere : first test.

```

I really hope that makes sense, I will edit it if it doesn't. It is a lot harder to explain than I thought.
> 5 votes

# Answer
I'd actually move away from the square/grid representation and use loose nodes instead:

Each valid position is one node and nodes are linked with each other (using connections) to form valid moves or directions:

Based on your game design, those connections could have additional properties like costs, directions etc. This allows you to do all kind of interesting things, such as one-way shortcuts, shorter but more expensive to pass ways, etc. (see the dashed arrows in the center ):

When the user tries to move, you're using a pathfinding algorithm such as A\* to look for a route between his current position and the target position. You'd have to explore all possible paths till you're running out of options (impossible move) or you've found a valid distance (the move is valid). Whether you'd like to allow "too short" paths is a different story.

While this is more complicated to implement (and setup), you'll have to clear advantage that your board doesn't have to be aligned to a grid. You don't even have to use uniform positions (e.g. some could be square, others round etc.). For presentation, you'll just need coordinates assigned to each node (they're not game logic related).
> 2 votes

---
Tags: ai, simulations, graph-theory, board-game
---


title: Give people your app for free

text:
# Question
Title: Give people your app for free
I was wondering how developers can give some people (like family) their paid apps for free? Or even give paid in app purchases for free. I'm not talking about the promo codes, i believe they only last a few months? Do they use some kind of custom developed promo code system?

Your insights are much appreciated

# Answer
There're two ways to do that. If you have an `enterprise developer account`($199 one), you can create an `Ad-hoc` or `enterprise provision` to sign your `ipa` file and then can send the app to be used by any of your friend. It'll ask for confirmation while running for the first time on the device.

Another method is when you don't have the enterprise account, rather you have a simple developer account($99 one), you'll need to add your UDID of your friend's device to your devices' list and create a developer provision which needs to include that device.Just to warn you, you can only add 100 devices at max and once added you won't be able to remove that device unless you renew your developer account. Now you can use this developer provision to sign your ipa.

In both ways the ipa needs to be installed via `IPCU(iPhone Configuration Utility)` and not via iTunes(I am not sure if iTunes will allow installation of these ipa). Just drag and drop the ipa, select the connected device and hit install.

You can add their apple id in your test user's list, which will make their IDs as sanbox ids and then they can purchase anything from your app, without actually paying anything.
> 2 votes

# Answer
You can create a `App Store Package` that allow people to install your app. It is used for beta tests but I assume it also work to give it for free.

Look here around *Creating an iOS App Store Package* and after, or here at *How Do I Send the Beta Testers an Ad-Hoc Build?*

It is limited to 100 people. I have never tested it but I think that would be a solution to your problem.
> 1 votes

---
Tags: appstore
---


title: Unity - Across the wall

text:
# Question
Title: Unity - Across the wall
I have a problem here.

I animated my main character and is working. It walks run and jump however it goes across walls and ground.

As in every single video I watch in unity tutorials I put a navigation static in every single wall and game object. However the main character still go across them as thin air

The main character has a rigid body and collider as does the the wall and other game objects

I really don't understand I don't really understand what i did wrong or what I miss? Script ? other things I am not aware?The Nav Mesh Agent? \]

I really hope someone can help me

Thanks in advance

CL

# Answer
Read up on the `IsTrigger` variable. Specifically:

> **Is Trigger**: If enabled, this Collider is used for triggering events, and is ignored by the physics engine.
> 3 votes

# Answer
As Byte56 already told you have `IsTrigger` checkbox turned in your wall. You need to turn it off, so that it can collide with any other object which has collider in it. If you do not want your wall to collide with some other object, you can put both wall and other object in separate layer and then can turn off collision between those layers by going to `Edit->Project Settings ->Physics`. However this will turn off any `OnTriggerEnter` (or any trigger related call) between these layers too.
> 0 votes

---
Tags: unity, collision-detection, physics, navmesh
---


title: How do I set up Unity for Eclipse?

text:
# Question
Title: How do I set up Unity for Eclipse?
I want to use Unity on Android. How can I integrate Unity with Eclipse?

I searched this site and various forums, but found nothing useful.

# Answer
The solution depends upon why you'd want to use Eclipse. If you want to use it for Script editing, you can do that via `Edit->Preferences->External` tools. However you'll be able to use it just as a text editor for C# (I am not aware if you can get syntax highlighting etc. feature for C# in eclipse or not), but for UnityScript you can use it as a full IDE.

If you just want to use an Eclipse Android project, then you can export the unity project as `Google Android Project` from `build settings`.
> 2 votes

---
Tags: android, unity, eclipse
---


# Question
Title: Packaging HTML5 games as applications for iPhone/Android
Is it possible to package HTML5 game for iPhone and Android as an application or does it have to be accessed through a browser?

# Answer
There's http://www.phonegap.com/ which is open source and cross-platform. Besides packaging your HTML 5 as a native app, it also lets you access native features of the mobile phone.
> 16 votes

# Answer
I can't vouch for iPhone, but in Android, a simple application with an Activity that just has one WebView would do the trick. The activity would look something like this:

```
public class WebApp extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        WebView wv = new WebView(this);
        wv.loadUrl("http://www.myapp.com/");
        setContentView(wv);
    }
}

```

That would make the WebView the entirety of the screen; then you would just need a loading message. Or a better option is to load HTML in the WebView so that the app can be used offline; examples of this are on the API page for WebView.
> 9 votes

# Answer
From ImpactJS Tools page there are:

* PhoneGap
    + Package your games into an iPhone or Android App, ready to be distributed in the App Stores.
* appMobi
    + Easily integrate and distribute your games into native iPhone and Android Apps. You don't even need a Mac or XCode to get your game into the iPhone App Store.
> 6 votes

# Answer
Have you checked out CocoonJS? It's by far one of the best ways to get hardware accelerated HTML5 games on iOS and Android plus they have a cloud compiler where you can upload a single zip and it will build out for multiple platforms.
> 2 votes

# Answer
If you want to port your game to even more platforms Nokia has a web tool application for porting to Symbian S60 devices... Web Tools for S60

They also have a newer one, which probably supports more HTML5 but I have yet to try it out...

Web Tools 2.3 for Series40

The SDK in the first one is fairly good as it also comes with a simulator so you can get an idea of how your app will
> 0 votes

# Answer
I have published few HTML5 games in the android market place and from my experience I would recommend you to use Crosswalk in order to package your games for Android.

It's really easy to use and it's damn fast! It's developed by Intel. It's faster than phonegap, because it uses an optimized webview derived from the chromium project.

The stock webview on Android 4.x device (the one used by phonegap) is very slow and it doesn't support WebGL nor WebAudio APIs.
> 0 votes

# Answer
What about cocos2d-x ?

Cocos2d-x is a framework for using javascript to develop across all platforms, and it's completely free.
> -1 votes

---
Tags: iphone, android, html5
---


# Question
Title: Pixel Buffer Object (PBO) does not work correctly
I've written a very simple OpenGL application. Its goal is to load a texture and draw it on a plane using a PBO. If I use the function 'glTexSubImage2D' the plane is not textured and the function 'glGetError' returns the error '1281' (invalid value). However if I use the function 'glTexImage2D' my plane plane is textured correctly (and I have no error).

Here's the code for the texture loading :

```
#define OFFSET_BUFFER(offset) ((char*)NULL + offset)

void core::RootDevice::LoadTexture(char const *pFileName)
{
    SDL_Surface *pSurface = IMG_Load(pFileName);
    char *pPixels = reinterpret_cast<char*>(pSurface->pixels);
    uint32_t bytePerPixel = pSurface->format->BitsPerPixel;

    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_2D, textureId);
    {
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        glGenBuffers(1, &pboID);
        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboID);
        {
            unsigned int bufferSize = pSurface->w * pSurface->h * 3 * sizeof(unsigned char);

            glBufferData(GL_PIXEL_UNPACK_BUFFER, bufferSize, 0, GL_STATIC_DRAW);
            glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, bufferSize, pPixels);

            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, pSurface->w,                //NOT OK : ERROR 1281
                pSurface->h, GL_RGB, GL_UNSIGNED_BYTE, OFFSET_BUFFER(0));

            /*glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pSurface->w,               //OK : NO ERROR
                pSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, OFFSET_BUFFER(0));*/
        }
        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
    }
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

And the rendering code :

```
void core::RootDevice::Render(void)
{
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureId);
    {
        glBegin(GL_QUADS);
            glTexCoord2f(0.0f, 0.0f);
            glVertex3f(-1.0f, -1.0f, 0.0f);
            glTexCoord2f(1.0f, 0.0f);
            glVertex3f(1.0f, -1.0f, 0.0f);
            glTexCoord2f(1.0f, 1.0f);
            glVertex3f(1.0f, 1.0f, 0.0f);
            glTexCoord2f(0.0f, 1.0f);
            glVertex3f(-1.0f, 1.0f, 0.0f);
        glEnd();
    }
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

And the result is the followings:

I'm really lost. Does anyone can help me, please ?

Thanks a lot in advance for your help.

# Answer
This is expected behaviour.

If you look over your code, you'll see that you're getting a new texture name, binding it, then calling glTexSubImage.

The problem here is that when you call glTexSubImage **the texture does not actually exist yet**.

Textures are not created by glGenTextures; all that glGenTextures does is give you a free texture object name for use in subsequent calls. The texture doesn't get created ("specified" in OpenGL terminology) until you make the first glTexImage call.

So hence the fact that glTexImage works but glTexSubImage doesn't:

* glTexImage is actually creating the texture successfully for the first time.
* glTexSubImage is trying to update a texture that does not exist yet.

---

Some general comments.

You don't actually need a PBO for this; you'll get the same result by just calling glTexImage directly (it may even be a little faster as you're not going through an intermediate object). PBOs as a rule aren't useful if your usage pattern is to immediately update the texture after updating the PBO.

If all you want to do is create a new texture but not initialize it with any data you can call:

> glTexImage2D (GL\_TEXTURE\_2D, 0, GL\_RGB, pSurface-\>w, pSurface-\>h, 0, GL\_RGB, GL\_UNSIGNED\_BYTE, NULL);

Consider using *format* GL\_BGRA and *type* GL\_UNSIGNED\_INT\_8\_8\_8\_8\_REV for a faster transfer; yes, it's more data but it will more closely match the driver's internal representation and the driver will be more likely to do a direct transfer to the GPU rather than having to do any internal format conversions of it's own. This is, of course, irrelevant if you're just initializing a texture with NULL data.
> 3 votes

---
Tags: opengl, textures
---