# Question
Title: How can I implement lighting in a voxel engine?
I am creating the MC like terrain engine, and I have thought that lighting would make it look a whole lot nicer.The problem is that the blocks are not being lit properly when a block which emits light is placed (see the screenshots at the bottom on the page.

So far I want to implement minecraft's "blocky" lighting. So I created a VertexFormat:

```
 struct VertexPositionTextureLight
    {
        Vector3 position;
        Vector2 textureCoordinates;
        float light;

        public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
        (
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
            new VertexElement(sizeof(float) * 5, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1)
        );

        public VertexPositionTextureLight(Vector3 position, Vector3 normal, Vector2 textureCoordinate, float light)
        {
            // I don't know why I included normal data :)
            this.position = position;
            this.textureCoordinates = textureCoordinate;
            this.light = light;
        }
    }

```

I guess if I want to implement lighting I have to specify a light for each vertex... And now in my effect file I want to be able to take that value and light up the vertex accordingly:

```
float4x4 World;
float4x4 Projection;
float4x4 View;

Texture Texture;

sampler2D textureSampler = sampler_state  {
    Texture = <Texture>;
    MipFilter = Point;
    MagFilter = Point;
    MinFilter = Point;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VertexToPixel  {
    float4 Position     : POSITION;
    float4 TexCoords    : TEXCOORD0;
    float4 Light        : TEXCOORD01;
};

struct PixelToFrame  {
    float4 Color        : COLOR0;
};

VertexToPixel VertexShaderFunction(float4 inPosition : POSITION, float4 inTexCoords : TEXCOORD0, float4 light : TEXCOORD01)  {
    VertexToPixel Output = (VertexToPixel)0;

    float4 worldPos = mul(inPosition, World);
    float4 viewPos = mul(worldPos, View);

    Output.Position = mul(viewPos, Projection);
    Output.TexCoords = inTexCoords;
    Output.Light = light;

    return Output;
}

PixelToFrame PixelShaderFunction(VertexToPixel PSIn)  {
    PixelToFrame Output = (PixelToFrame)0;

    float4 baseColor = 0.086f;
    float4 textureColor = tex2D(textureSampler, PSIn.TexCoords);
    float4 colorValue = pow(PSIn.Light / 16.0f, 1.4f) + baseColor;

    Output.Color = textureColor;

    Output.Color.r *= colorValue;
    Output.Color.g *= colorValue;
    Output.Color.b *= colorValue;
    Output.Color.a = 1;

    return Output;
}

technique Block  {
    pass Pass0  {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

VertexToPixel VertexShaderBasic(float4 inPosition : POSITION, float4 inTexCoords : TEXCOORD0)  {
    VertexToPixel Output = (VertexToPixel)0;

    float4 worldPos = mul(inPosition, World);
    float4 viewPos = mul(worldPos, View);

    Output.Position = mul(viewPos, Projection);
    Output.TexCoords = inTexCoords;

    return Output;
}

PixelToFrame PixelShaderBasic(VertexToPixel PSIn)  {
    PixelToFrame Output = (PixelToFrame)0;

    Output.Color = tex2D(textureSampler, PSIn.TexCoords);

    return Output;
}

technique Basic  {
    pass Pass0  {
        VertexShader = compile vs_2_0 VertexShaderBasic();
        PixelShader = compile ps_2_0 PixelShaderBasic();
    }
}

```

And this is an example on how i apply lighting:

```
            case BlockFaceDirection.ZDecreasing:
                light = world.GetLight((int)(backNormal.X + pos.X), (int)(backNormal.Y + pos.Y), (int)(backNormal.Z + pos.Z));

                SolidVertices.Add(new VertexPositionTextureLight(bottomRightBack, backNormal, bottomLeft, light));
                SolidVertices.Add(new VertexPositionTextureLight(bottomLeftBack, backNormal, bottomRight, light));
                SolidVertices.Add(new VertexPositionTextureLight(topRightBack, backNormal, topLeft, light));
                SolidVertices.Add(new VertexPositionTextureLight(topLeftBack, backNormal, topRight, light));
                AddIndices(0, 2, 3, 3, 1, 0);
                break;

```

And last of all here is the algorythim that calculates it all:

```
    public void AddCubes(Vector3 location, float light)
    {
        AddAdjacentCubes(location, light);
        Blocks = new List<Vector3>();
    }

    public void Update(World world)
    {
        this.world = world;
    }

    public void AddAdjacentCubes(Vector3 location, float light)
    {
        if (light > 0 && !CubeAdded(location))
        {
            world.SetLight((int)location.X, (int)location.Y, (int)location.Z, (int)light);
            Blocks.Add(location);

            // Check ajacent cubes
            for (int x = -1; x <= 1; x++)
            {
                for (int y = -1; y <= 1; y++)
                {
                    for (int z = -1; z <= 1; z++)
                    {
                        // Make sure the cube checked it not the centre one
                        if (!(x == 0 && y == 0 && z == 0))
                        {
                            Vector3 abs_location = new Vector3((int)location.X + x, (int)location.Y + y, (int)location.Z + z);

                            // Light travels on transparent block ie not solid
                            if (!world.GetBlock((int)location.X + x, (int)location.Y + y, (int)location.Z + z).IsSolid)
                            {
                                AddAdjacentCubes(abs_location, light - 1);
                            }
                        }
                    }
                }
            }

        }
    }

    public bool CubeAdded(Vector3 location)
    {
        for (int i = 0; i < Blocks.Count; i++)
        {
            if (location.X == Blocks[i].X &&
                location.Y == Blocks[i].Y &&
                location.Z == Blocks[i].Z)
            {
                return true;
            }
        }

        return false;
    }

```

Any suggestions and help would be much appreciated

**SCREENSHOTS** Notice the artifacts on the top on the terrain and how only the left part is partically lit... For some reason only certain sides of the cube is being lit and it doesn't light the ground

Figured out my problem! I was not checking if that block was already lit and if so to what degree (if it is lower light it higher)

```
    public void DoLight(int x, int y, int z, float light)
    {
        Vector3 xDecreasing = new Vector3(x - 1, y, z);
        Vector3 xIncreasing = new Vector3(x + 1, y, z);
        Vector3 yDecreasing = new Vector3(x, y - 1, z);
        Vector3 yIncreasing = new Vector3(x, y + 1, z);
        Vector3 zDecreasing = new Vector3(x, y, z - 1);
        Vector3 zIncreasing = new Vector3(x, y, z + 1);

        if (light > 0)
        {
            light--;

            world.SetLight(x, y, z, (int)light);
            Blocks.Add(new Vector3(x, y, z));

            if (world.GetLight((int)yDecreasing.X, (int)yDecreasing.Y, (int)yDecreasing.Z) < light &&
                world.GetBlock((int)yDecreasing.X, (int)yDecreasing.Y, (int)yDecreasing.Z).BlockType == BlockType.none)
                DoLight(x, y - 1, z, light);
            if (world.GetLight((int)yIncreasing.X, (int)yIncreasing.Y, (int)yIncreasing.Z) < light &&
                world.GetBlock((int)yIncreasing.X, (int)yIncreasing.Y, (int)yIncreasing.Z).BlockType == BlockType.none)
                DoLight(x, y + 1, z, light);
            if (world.GetLight((int)xDecreasing.X, (int)xDecreasing.Y, (int)xDecreasing.Z) < light &&
                world.GetBlock((int)xDecreasing.X, (int)xDecreasing.Y, (int)xDecreasing.Z).BlockType == BlockType.none)
                DoLight(x - 1, y, z, light);
            if (world.GetLight((int)xIncreasing.X, (int)xIncreasing.Y, (int)xIncreasing.Z) < light &&
                world.GetBlock((int)xIncreasing.X, (int)xIncreasing.Y, (int)xIncreasing.Z).BlockType == BlockType.none)
                DoLight(x + 1, y, z, light);
            if (world.GetLight((int)zDecreasing.X, (int)zDecreasing.Y, (int)zDecreasing.Z) < light &&
                world.GetBlock((int)zDecreasing.X, (int)zDecreasing.Y, (int)zDecreasing.Z).BlockType == BlockType.none)
                DoLight(x, y, z - 1, light);
            if (world.GetLight((int)zIncreasing.X, (int)zIncreasing.Y, (int)zIncreasing.Z) < light &&
                world.GetBlock((int)zIncreasing.X, (int)zIncreasing.Y, (int)zIncreasing.Z).BlockType == BlockType.none)
                DoLight(x, y, z + 1, light);
        }
    }

```

Altough the above works, would anyone know how I would make it more performace efficent?

# Answer
I've implemented something similar to this. I wrote up a post about it on my blog: byte56.com/2011/06/a-light-post. But I'll go into a little more detail here.

While the codeflow article linked in another answer is pretty interesting. From what I understand, it's not how Minecraft does its lighting. Minecraft lighting is more cellular automata then traditional light source.

I assume you're familiar with water flow in MC. Lighting in MC is essentially the same thing. I'll walk you through a simple example.

Here are a few things to keep in mind.

* We're going to keep a list of cubes that need their lighting values checked
* **Only transparent cubes and light emitting cubes have lighting values**

The first cube we add is the light source. A source is a special case. It's light value is set accordingly to the light source type (for example torches get a brighter value than lava). If a cube has its light value set above 0, we add all the transparent cubes adjacent to that cube to the list. For each cube on the list, we set its light value to its brightest neighbor minus one. This means that all the transparent cubes (this includes "air") next to the light source get a light value of 15. We continue walking the cubes around the light source, adding cubes that need to be checked and taking lit cubes off the list, util we no longer have any to add. That means that all the latest values set have been set to 0, which means we've reached the end of our light.

That's a fairly simple explanation of lighting. I've done something a little more advanced, but I started with the same basic principle. This is an example of what it produces:

Now that you have all your light data set. When you're building the color values for your vertices, you can reference this brightness data. You could do something like this (where light is an int value between 0 and 15):

```
float baseColor = .086f;
float colorValue = (float) (Math.pow(light / 16f, 1.4f) + baseColor );
return new Color(colorValue, colorValue, colorValue, 1);

```

Basically I'm taking the light value from 0 to 1 to the power of 1.4f. This gives me a slightly darker darks than a linear function. Ensure that your color value never goes above 1. I did that by dividing by 16, instead of 15 so I'd always have a little extra room. Then moved that extra to the base so I'd always have a little texture and not pure blackness.

Then in my shader (similar to an effects file), I get the fragment color for the texture and multiply that by the lighting color I create above. This means full brightness gives the texture as it was created. Very low brightness gives the texture as very dark (but not black because of the base color).

**EDIT**

To get the light for a face, you look at the cube in the direction of the normal of the face. For example, top face of cube gets the light data from the cube above.

**EDIT 2**

I'll attempt to address some of your questions.

*So what I would do is something like recursion in this case?*

You can use a recursive algorithm or iterative. It's up you you how you want to implement it. Just ensure you're keeping track of which cubes have been added already, otherwise you'll keep going forever.

*Also how would the algorithm "light downwards"?*

If you're talking about sunlight, sunlight is a bit different, since we don't want it to decrease in brightness. My cube data includes a SKY bit. If a cube is marked as SKY that means it has clear access to the open sky above it. SKY cubes always get full lighting minus the darkness level. Then cubes next to sky, that are not sky, like cave entrances or overhangs, the normal lighting procedure takes over. If you're just talking about a point light shining down... it's the same as any other direction.

*How would I specify the light for a single face only?*

You don't specify light for a single face only. Each transparent cube specifies the light for all the solid cubes that share a face with it. If you want to get the light for a face, simply check the light value for the transparent cube it's touching. If it's not touching a transparent cube, then you wouldn't be rendering it anyway.

*Code samples?*

Nope.
> 16 votes

# Answer
Read through the following article as it should give you a lot of information on what you seek. There are many sections about lighting, but in particular read the sections about Ambient Occlusion, Observer Light and Light Gathering:

http://codeflow.org/entries/2010/dec/09/minecraft-like-rendering-experiments-in-opengl-4/

But trying to answer the core of your question:

* If you want to *darken* a color, **multiply** it by another color (or simply by a float between 0 and 1 if you want to darken all components equally), where 1 in a component stands for full intensity while 0 stands for full darkness.
* If you want to *lighten* a color, **add** another color to it and *clamp* the result. But be careful not to choose values that are so high that it would make the result saturate to pure white. Choose dark colors, with an hint of the hue that you're looking for, such as a dark orange (#886600).

or...

After adding the color, instead of *clamping* the result (i.e. clamping every component of the color between 0 and 1), *scale* the result instead - find which of the three components (RGB) is the largest and divide all of them by that value. This method preserves the original properties of the color a bit better.
> 4 votes

---
Tags: c#, xna, lighting, raycasting
---


# Question
Title: Javascript/html5 2d Canvas Context - Getting X, Y relative to canvas (opposed to transformed object)
I have scenario where there are several items on a the context stack and I need to get an x, y coordinate relative to the canvas itself.

The situation is I am writing a 2D game in HTML5 and I want the "character" being controlled by the user to be able to aim towards the mouse. The character is nested in transformations. There is a camera object that transforms the canvas to follow the character and perform zooms/rotations, and of course the character itself is transformed downwards, and at times rotated away from it's centre.

If I could get the position of my character relative to the canvas, I could do an atan2 to aim towards the mouse. Alternatively, if I could get the mouse coordinates relative to the centre of my character, then I could do the same.

Is there any way to do this other than to reverse all of my transform calculations?

# Answer
Unfortunately I ended up manually reversing the transformations. The following code is what I put into the camera object:

```
/**
Transforms mousex and mousey to the positions within the game.
*/
this.transformMouse = function(mousex, mousey){
    var xScale = screenWidth / (currentMaxX - currentMinX);
    var yScale = screenHeight / (currentMaxY - currentMinY);

    this.tmousex = (mousex - screenWidth / 2) / xScale + (currentMaxX + currentMinX) / 2;
    this.tmousey = (mousey - screenHeight / 2) / yScale + (currentMaxY + currentMinY) / 2;
}

```

the tmousex and tmousey are the transformed x and y positions of the mouse. This does not account for rotation - the reversal of the transformation will have to go into the character code (rotation of camera and character will just be added after the atan2 code).

Hope this helps anyone with the same problem.
> 1 votes

# Answer
Well, I need more info about your game (basically where is the character situated). If the character is always in the center of the canvas you can use this:

```
window.addEventListener('mousemove', function(event) {
        var x =event.clientX - canvas.width/2;
        var y =event.clientY - canvas.height/2;
        var ang = radToDeg(Math.atan2( y , x ));
        ang = y<0 ? (-1)*ang:360 -ang;
        self._player._orientation=ang;

    },false);

```

Which is pretty self explanatory.

In the case that your player is not centered, then you need to use gluProject on the center of your character to convert that point from object coordinates (x,y,z) to screen coordinates (x,y).
> 0 votes

---
Tags: javascript, html5
---


# Question
Title: What game engines can publish to Android and iOS?
I am about to start on a project which, at a minimum, will release to Android and iOS. Are there any game engines, other than Unity, which can publish to both? I fear that Unity might contain more overhead then we need, for what is essentially a 2D game.

# Answer
Those I know about are:

Unity3D: A good 3D game engine, which is well known.
Cocos2d-x: A C++ port of the Cocos2d engine for iPhone, which is a fully-featured 2D game engine.
UDK: Another 3D game engine, which provides professional 3D tools at cost of being a little hard to learn.
Corona SDK: I didn't test this one but I've read it's name in many threads (as well as comments here).
Unigine: This one is also a 3D game engine which lets you develop games using c++ language (and UnigineScript).
Airplay SDK: Another game engine (which seems to focus on 2D games) with support for almost all types of mobile devices.
> 5 votes

---
Tags: android, ios
---


title: How can I bend an object in OpenGL?

text:
# Question
Title: How can I bend an object in OpenGL?
Is there a way one could bend an object, like a cylinder or a plane using OpenGL?

I'm an OpenGL beginner (I'm using OpenGL ES 2.0, if that matters, although I suspect, math matters most in this case, so it's somehow version independent), I understand the basics: translate, rotate, matrix transformations, etc. I was wondering if there is a technique which allows you to actually change the geometry of your objects (in this case by bending them)?

Any links, tutorials or other references are welcomed!

# Answer
> 11 votes
What you'd need to do to "bend" an object is to apply some appropriate combination of translation/rotation/scaling to only some subset of the vertices of the object in question -- probably weighting that transformation accordingly.

Doing this is a pleasant-looking fashion will necessitate using more vertices than may be otherwise strictly necessary to describe the original mesh. For example, a simple cylinder may only have vertices at either end, but if you want that cylinder to bend in the middle, you'll need vertices there as well.

If all you are interested in is very specific, one-off deformations of very simple shapes (like your aforementioned plane) you could probably just do this manually. For example, decide on the "bend axis" for your plane and compute appropriate transformations for each row of plane vertices to achieve the appropriate rotation about that bend axis depending on their distance from it, and then apply that to the geometry (possibly on the CPU as it would be the most straightforward, at least initially). But such a technique would not scale well and would be very tedious.

Since it can be so cumbersome to correctly figure out how to weight a transformation to each individual vertex in a set to achieve the desired deformation (especially for more practical and complicated objects), many games use a technique called skeletal animation. At a high level this involves associating a separate set of geometry (the "skeleton") with your mesh. That geometry represents the bones of your object, and you define (often in modeling tools) a mapping between vertices of the real model and the bones of the skeleton -- which bones are associated with each vertex, and how much that bone affects the deformation of that vertex. Then the skeleton is animated directly, and the animation is transferred to the real model via the relationship between the bones and their vertices.

Typically in this technique, the mapping between skeleton and real mesh is defined at asset production time. The animations can also be built then, or they can be built procedurally at runtime. The application of the animation transformations to the real mesh occurs at runtime. Generally no new vertices are generated at runtime, which means the range of good-looking deformations is implicitly fixed in the mesh when it is originally created.

In theory, one could also apply tessellation and subdivision to the mesh at runtime based on analysis of the transformations in the animation, and thus produce the appropriate vertices to create an animation that was not necessarily planned for. I'm not aware, offhand, of any papers on this subject.

See also:

# Answer
> 9 votes
For the actual math of warping, this can get very complicated, why don't you start here?.

I'll now talk about how you can apply this, assuming you've already got the math for how you will do your deformations down.

2 ways:

1) Every frame, visit every vertex in the cylinder model and offset it in some way.

2) Offset the vertices in the **vertex shader** as you are rendering. OpenGL ES 2.0 supports vertex shaders. So you're in luck, in a way.

Do you want to only warp the object **as it appears on the screen**, or do you want to warp the object **so every object in the game knows that it has been deformed?**

If you warp the object in the vertex shader, **then that happens only immediately prior to display/rasterization**, so this means **none of the game objects will know about the deformation**. This is fine if you're simply making a screen saver, or if the deformations are so small that they have no impact on the collidable shape of the object.

When you warp the geometry in the **vertex shader** **the original vertices of the model actually *don't* move**, (they only *appear to move*).

# Deformation in vertex shader

## Undeformed:

## Deformed

This is from chapter 6 of the cg tutorial, (program #14).

The shader code to produce this deformation is something like

```
// choose a displacement amount
float displacement = scaleFactor * 0.5 * sin(position.y * frequency * time) + 1 ;

// displace it in the direction of the normal
float4 displacementDirection = float4(normal.x, normal.y, normal.z, 0) ;

// move the vertex
float4 newPosition = position + displacement * displacementDirection ;

// transform (as normal)
oPosition = mul(modelViewProj, newPosition) ;

```

So you can see, this happens RIGHT BEFORE display (vertex shader happens on GPU) so CPU code has practically no way to access the transformed vertex position (there are ways to send data from the GPU to the CPU (primarily via textures) but we won't go there).

# Answer
> 8 votes
What you're trying to achieve is basically a subset of the topic of mesh deformation. But since you're a begginer, I'm afraid this type of information might be a bit too strange for now. I'll try to lay down the basic notions though.

In order to do this you'll need two things:

1. **Your mesh needs to have enough vertices for you to transform.** For instance if it's a plane, you'll need to make sure it's actually created as a sort of grid, with many vertices for you to deform. Same thing with a cylinder. Might be possible to achieve this at runtime with tessellation but I don't know much about the subject.
2. **You need to use a vertex shader to deform the vertices.** Basically the vertex shader takes care of calculating the final transformed position of each vertex, so you can take the chance to apply any deformations to them.

I'm not sure how helpful it will be, but take a look at this OpenGL resource, as it seems to be right the sort of thing you need:

http://www.ozone3d.net/tutorials/mesh\_deformer\_p3.php#part\_3

Screenshot from that link:

**Edit**

Just saw Josh's reply and I agree, skeletal animation is also a very elegant way to encapsulate this problem, especially when your deformations start becoming more complex and harder to represent mathematically.

But remember, both points above still apply though - you can only deform vertices, so obviously they need to exist in the first place, which is why your mesh needs to have a decent amount of vertex density. And it's usually the vertex shader that drives skeletal animation and does vertex blending and such.

And by the way, you can do these on the CPU too, but nowadays it's usually a better option to do them on the GPU, which is why I put emphasis on the vertex shader, and you should look into it. It's not really all that much harder programwise than doing it on the CPU anyway.

---
Tags: opengl, opengl-es, opengl-es2
---


title: .PNG tiles to .PNG map

text:
# Question
Title: .PNG tiles to .PNG map
I was wondering how I can get my 110+ .png map tiles conveniently into a 1:1 pixel ratio size map .png. I've been scrolling through Google and forums for the free ware game that I am modding, but the app I'm using recognizes only .png files, and I want more than 1% of the map. If you guys know of a program I would be very appreciative.

# Answer
> 5 votes
Such as this (free license for bloggers and framework developers) or this (completely free but a bit less flexible)?

# Answer
> 6 votes
ImageMagick with it's convert -append can also be used for this. Though, it only does appending into one direction, but if your tiles are named ascending (f.e. tile001.png) it can still be used in a loop:

```
convert tile00*.png +append line1.png
convert tile01*.png +append line2.png
convert line*.png -append wholeImage.png

```

As pointed out by bummzack, montage will work also good.

```
montage tile*.png -geometry +0+0 wholeImage.png

```

---
Tags: tiles, maps
---


# Question
Title: What are the limits for UDK's landscape size?
With the new (as of March 2011) landscape tool, the Unreal Development Kit supports bigger and (potentially) streaming landscapes than the old terrain tool. However, in my tests trying to import or create from scratch a small island (specifically, the island of Tenerife including some of the surrounding sea at 2m horizontal resolution, resulting in a roughly 35.000x20.000 pixel heightmap image - downright *tiny* in comparison to your usual GIS raster datasets), the UDK simply crashes. No error message or anything like that, simple program crash.

It seems as if I run against some kind of internal limit there, but without any clue as to where it happens and with the tool being rather new and undocumented, it's hard to say where those limits are.

Thus the question - what's the maximum size of a heightmap which can be used with the landscape tool in UDK, both in terms of the "amount of heightmap points" and the "width and height in Unreal Units"? In addition, if there are special tricks possible to break those limits (Streaming in the landscape? Portals?), some pointers would be nice ...

# Answer
> 4 votes
From the page you linked :)

> Because of its powerful LOD system and the way it makes efficient use of memory, heightmaps up to 8192x8192 are now legitimately possible and feasible.

---
Tags: udk
---


title: Platformer collision detection problems

text:
# Question
Title: Platformer collision detection problems
I'm having a few problems with collision detection in my game (written in C# with SDL.Net). Detecting the floor and roof is fine, as does detecting sides of tiles when not jumping/falling. My problem comes when the player jumps and hits one of the sides of a tile.

Sometimes the player (blue) enters the tile, like this: https://i.stack.imgur.com/SSjtR.png At first I thought this was because it was checking for a collision then moving the player then drawing, but changing it has no effect.

Other times it will randomly move from the overlapping position above to here: https://i.stack.imgur.com/0esSw.png

```
    public void PlayerCollision2 (ref Player player)
    {
        Rectangle rectLeft = new Rectangle (new Point ((int)player.x, (int)player.y), new Size (1, Player.HEIGHT));
        Rectangle rectRight = new Rectangle (new Point ((int)(player.x + Player.WIDTH), (int)player.y), new Size (1, Player.HEIGHT));
        Rectangle rectTop = new Rectangle (new Point ((int)player.x, (int)player.y), new Size (Player.WIDTH, 1));
        Rectangle rectBot = new Rectangle (new Point ((int)player.x, (int)(player.y + Player.HEIGHT + 1)), new Size (Player.WIDTH, 1));

        List<TileDirectionRelPlayer > lst = new List<TileDirectionRelPlayer> ();
        foreach (List<Tile> r in map) {
            foreach (Tile c in r) {
                if (c.tileType == TileType.Air)
                    continue;
                TileDirectionRelPlayer t = new TileDirectionRelPlayer ();
                t.tile = c;
                if (c.rect.IntersectsWith (rectBot)) {
                    t.below = true;
                    lst.Add (t);
                } if (c.rect.IntersectsWith (rectTop)) {
                    t.above = true;
                    lst.Add (t);
                } if (c.rect.IntersectsWith (rectLeft)) {
                    t.left = true;
                    lst.Add (t);
                } if (c.rect.IntersectsWith (rectRight)) {
                    t.right = true;
                    lst.Add (t);
                }
            }
        }

        if (lst.Count == 0 && !player.jumping) {
            player.falling = true;
        } else {
            foreach (TileDirectionRelPlayer t in lst) {
                MovePlayer (ref player, t, new Rectangle[] {rectLeft, rectRight, rectTop, rectBot});
            }
        }
    }

    private void MovePlayer (ref Player player, TileDirectionRelPlayer tile, Rectangle[] rectangles)
    {
        if (tile.above && rectangles[2].IntersectsWith(new Rectangle(new Point((int)tile.tile.x,(int)tile.tile.y+Tile.HEIGHT), new Size(Tile.WIDTH,7)))) {
            player.falling = true;
            player.jumping = false;
            player.ySpeed = 0;
            player.y = tile.tile.y + Tile.HEIGHT + 1;
        }
        if (tile.left && tile.tile.y < player.y) {
            player.x = tile.tile.x + Tile.WIDTH;
        }
        if (tile.below && !player.jumping && rectangles[3].IntersectsWith(new Rectangle(new Point((int)tile.tile.x,(int)tile.tile.y), new Size(Tile.WIDTH,7)))) {
            player.y = tile.tile.y - Player.HEIGHT - 1;
            player.falling = false;
            player.ySpeed = 0;
        }
        if (tile.right && tile.tile.y < player.y) {
            player.x = tile.tile.x - Player.WIDTH - 1;
        }
    }

```

I have no idea why this is happening or how to fix it, can someone point me in the right direction please?

EDIT: There is a video here if it helps

# Answer
One major problem seems that you are adding `t` several times to `lst`.

```
            if (c.rect.IntersectsWith (rectBot)) {
                t.below = true;
                lst.Add (t);
            } if (c.rect.IntersectsWith (rectTop)) {
                t.above = true;
                lst.Add (t);
            } if (c.rect.IntersectsWith (rectLeft)) {
                t.left = true;
                lst.Add (t);
            } if (c.rect.IntersectsWith (rectRight)) {
                t.right = true;
                lst.Add (t);
            }

```

Try this instead:

```
            t.below = c.rect.IntersectsWith (rectBot);
            t.above = c.rect.IntersectsWith (rectTop);
            t.left = c.rect.IntersectsWith (rectLeft);
            t.right = c.rect.IntersectsWith (rectRight);
            if (t.below || t.above || t.left || t.right)
                lst.Add (t);

```
> 2 votes

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


# Question
Title: How can I scroll sprites when swiping using Cocos2D?
I'm adding 3 sprites (layers) to `CCParallaxNode`:

```
BGLayer = [CCSprite spriteWithFile:@"Layer.png"];
[_backgroundNode
    addChild:BGLayer
    z:2
    parallaxRatio:layer1Speed
    positionOffset:ccp(screenSize.width/2,screenSize.height/2)
];

```

How can I create the scroll when swiping?

# Answer
> 0 votes
Found it! Add the `sprites` or `layers` to a `parralaxNode` object and `enable touch` on your `init method`, `Cocos2D` will do the magic for you.

---
Tags: iphone, cocos2d-iphone, cocos2d, touch, parallax-scrolling
---


# Question
Title: Display differences between iPad 1 and iPad 2
When you're trying to develop and iPad game what will be the differences between iPad 1 resources and iPad 2? Seen some example but what's the difference?

# Answer
> 5 votes
The displays are the same. Meaning that you'll have 1024x768 pixels on both models. So you can use the same assets on both devices. The iPad2 has a better CPU, GPU and more memory, so you can technically build more complex applications and load more resources into memory.

You can compare the exact specs on Wikipedia.

---
Tags: ipad, resolution
---


# Question
Title: What is the best way to store temporary selected characters and their insertion order?
I'm developing word game, similar to *"Word Mole"*. I'm having a hard time determining how to store temporarily selected characters, which in turn, will changed into a word.

For example, say, I have the following characters:

> 0 1 2 3
> 0 **O B O S**
> 1 **S F R H**
> 2 **T N E Z**
> 3 **R B D I**

I store all this information in a character array named `playCharacter`, and I also created a character array named `markedCharacter`, with the default value of `' '` for each element. Every time I select each cell, say `cell[1,0]`, I set `markedCharacter[1,0] = 'b'` an so on, until I'm done with current word. How do I store the step information? For example, if I choose to play `bored`, I'll be marking:

```
markedCharacter[1,0] = 'b'
markedCharacter[2,0] = 'o'
markedCharacter[2,1] = 'r'
markedCharacter[2,2] = 'e'
markedCharacter[2,3] = 'd'

```

Do I need another array? if so, what data should I store in it?

In turn, I'll want to use this `markedCharacter` as a way to check

* if certain moves are valid (eg, are they marked within an already marked neighbor cell?)
* if stored words are valid or not (this part is already covered)
* I don't need to do undo operation

# Answer
> 5 votes
**TL;DR**

A simple `List<int>` is enough to store all the information you need. Read on for the details.

**Context**

I'll drop in a little trick here then. Are you aware that when working with 2D matrices there's a way to index them with a single number, instead of having to provide a (x,y) pair?

For instance, where is the letter *d* in the following matrix?

```
  | 0 1 2
--|-------
0 | a b c
1 | d e f

```

Using the usual (x,y) notation the answer would be (0,1) - the letter *d* can be found on the first column of the second row (remember, zero based indexes).

But you could also index your matrix like this:

```
a b c    =>    0 1 2
d e f          3 4 5

```

In which case the answer would simply be (3) - the letter *d* is the fourth element in the matrix starting from the top and to the right (once again, zero based).

**Conversion**

You can convert from a (X,Y) pair to a simple (index) by doing:

```
int index = x  + y * width

```

And you can convert an (index) back to a (X,Y) pair by doing:

```
int x = index % width;
int y = index / width; // Note: Integer division (truncate)

```

Where `width` is simply the width of the matrix.

Here's two simple methods to do this:

```
int encode(int x, int y, int width)
{
    return x + y * width;
}

void decode(int index, int width, out int x, out in y)
{
    x = index % width;
    y = index / width;
}

```

And how to use them:

```
int width = 3;

// Encode (1,2)
int index = encode(1, 2, width);

// Decode
int x, y;
decode(index, width, out x, out y);

```

**Answer**

On to your question. Using this little encoding you can store a sequence as simply as:

```
List<int> sequence = new List<int>();

```
* The order in which you store elements in the list becomes the order in which the letters were selected.
* It's easy to check for duplicates or collisions. Just do a `List.Contains` or `List.Find`.
* Undoing is simply a matter of removing the last index from the list.
* Starting a new sequence is as simple as calling `List.Clear`.
* You can check which letter corresponds to any element in the sequence by doing `board.GetLetterAt(index % board.Width, index / board.Width)`.
* Just repeat the previous line for each element in the sequence to reconstruct the word.

And to answer your specific example, if you chose to play *bored*, that would be stored as:

```
sequence.Clear();
sequence.Add(new []{encode(1,0), encode(2,0), encode(2,1), encode(2,2), encode(2,3)});

```

# Answer
> 2 votes
Why not create a `Sequence` object that is a list of marked words in the order they were chosen?

Something like this..

```
class Sequence {
  List<Letter> letters;
  int index = 0;

  public void addLetter(char letter, Point position) {
    letters.add(new Letter(letter, position, index++);
  }

  public boolean checkIfThereIsAMatchInThisLevel(List<string> words) {
    return words.contains(letters);
  }

  /* OTHER COOL AND USEFUL METHODS HERE */
}

class Letter
  char letter;
  Point position; // Just a struct/class with x,y values stored.
  int index;

  //Constructor omitted
}

```

Then you can just create a new object or reset it, or whatever floats your boat, when a new sequence is created/finished etc.

I hope I understood your question correctly!

---
Tags: data-structure
---


# Question
Title: Why is my quaternion camera rotating  around strange axes?
I can't get it to work for the life of me. Its rotating the camera in the global coordinate system, or some other random coordinate system, not the camera local coordinate system. WASDEC work perfectly, right until I start rotating. Here's the annotated code:

```
  //eye.r is the quat camera rotation
  //eye.p is the vec3 camera position

  // Get the local axes we're going to do transformations with
  var axes = {
    x: quat4.multiplyVec3(eye.r, [1, 0, 0]),
    y: quat4.multiplyVec3(eye.r, [0, 1, 0]),
    z: quat4.multiplyVec3(eye.r, [0, 0, 1])
  };

  // If a movement key is down, add the appropriately scaled local axis
  // to our position
  if(keystate[W]) vec3.add(eye.p, vec3.scale(axes.z,  10, []));
  if(keystate[S]) vec3.add(eye.p, vec3.scale(axes.z, -10, []));
  if(keystate[A]) vec3.add(eye.p, vec3.scale(axes.x,  10, []));
  if(keystate[D]) vec3.add(eye.p, vec3.scale(axes.x, -10, []));
  if(keystate[E]) vec3.add(eye.p, vec3.scale(axes.y, -10, []));
  if(keystate[C]) vec3.add(eye.p, vec3.scale(axes.y,  10, []));

  // If a rotation key is down, create a scaled rotation about the appropriate
  // local axis, and multiply it into the current rotation
  if(keystate[UP])    quat4.multiply(quat4.rotation(-0.05, axes.x), eye.r, eye.r);
  if(keystate[DOWN])  quat4.multiply(quat4.rotation( 0.05, axes.x), eye.r, eye.r);
  if(keystate[LEFT])  quat4.multiply(quat4.rotation(-0.05, axes.y), eye.r, eye.r);
  if(keystate[RIGHT]) quat4.multiply(quat4.rotation( 0.05, axes.y), eye.r, eye.r);

```

Thanks for your help!

Edit: Since it might not be clear what the functions do. This is javascript and the glmatrix linear algebra/quat library.

```
quat4.multiplyVec3(quat, vec) // vec = quat * vec

vec3.add(vec, vec2) // vec = vec + vec2

vec3.scale(vec, scalar, dest) // dest = vec * scalar

quat4.rotation(angle, axis) // creates a quaternion rotation about the given axis, by the given angle

quat4.multiply(quat, quat2, dest) // dest = quat * quat2

```

# Answer
> 1 votes
So, my friend on facebook sorted me out. Here's his answer:

> Hmm.. I suspect part of the problem might be that quaternion rotation transformations use a sandwiching product form.
>
> If: v = vector to be rotated q = quaternion representing the intended rotation v' = v after rotation
>
> The rotation should be described by:
>
> v' = qvq^-1
>
> where q^-1 is the the inverse or the conjugate of q.
>
> See: http://en.wikipedia.org/wiki/Quaternions\_and\_spatial\_rotation#From\_the\_rotations\_to\_the\_quaternions
>
> specifically the second section "Describing rotations with quaternions"

So as a result, my local axis vectors are completely half-baked, and can't be used as such. Fortunately, all they need is another inverse quat multiplication.

EDIT: Or not. On close inspection it looks like the multiply function actually does the two multiplies, one with the quat and one with it's conjugate. The mystery continues...

# Answer
> 1 votes
Might be a pre-multiply/post-multiply issue. Sometimes the order in which you need to apply transformations can be a little counterintuitive.

I would try changing this:

```
quat4.multiply(quat4.rotation(-0.05, axes.x), eye.r, eye.r)

```

to one of two possible things:

```
quat4.multiply(eye.r, quat4.rotation(-0.05, axes.x), eye.r)

```

or maybe

```
quat4.multiply(quat4.rotation(-0.05,[1, 0, 0]), eye.r, eye.r)

```

(and obviously make similar changes for the other rotations).

---
Tags: 3d, javascript, camera, webgl, quaternion
---


# Question
Title: Get information about my SW:TOR character
I'd like to get some information about my character from the game Star Wars: The Old Republic.

Is there some API available? If not, has someone reverse-engineered their protocols, so that I could get the same information by capturing the communication between the game servers and my computer?

# Answer
Here are some quotes from the END USER ACCESS AND LICENSE AGREEMENT (Part 2-B) you probably signed as it is required in order to play the game.

> Except to the extent permitted under applicable law, **you may not** decompile, disassemble, translate, derive source code from, **create derivative works based on**, or reverse engineer **the Software by any means whatsoever**. *You may not extract code from all or part of the Software, or authorise any third party to perform or to attempt to perform such operations on the Software. You may not remove, alter, circumvent or obscure any product identification, copyright, or other intellectual property notices in the Software.*

...

> It is also **strictly prohibited to use any third-party software or any other device with a view to** modifying the Software in any way, **intercepting or scanning Game traffic or communications**, changing the way the Game plays or playing in an abnormal manner or in a way that could impair the correct operation of the Game. *Such prohibited third party software or devices can include, but are not limited to, those in the nature of "addons", "hacks", "cheats", "trainers", "mods", or the like by any name. The authorizations granted to you in accordance with this EUALA may under no circumstances be used for the purpose of creating or supplying any opportunity for third parties to access the Game, including through server emulators or similar devices. To the fullest extent permitted by applicable law, you agree that EA may scan your computer’s memory or hard disk drive to detect or locate any such unauthorized third party program or devices, with or without any prior notice to you at any time.*

So I definitely do not think gamedev.stackexchange.com is the good place to ask this question as people evolving here are probably prone to respect game licenses as they are mostly game creators themselves.

However, technically speaking the question is interesting and could probably have some instructive answers on stackexchange.com
> 3 votes

# Answer
Most of the hacking you describe, though I don't recommend you do it because it's illegal, is actually not hard to as far as interrupting their network goes. I don't know how they have theirs set up, but it's likely that due to it being a modern MMO, has powerful prevention methods, not to mention the legalities that I mentioned before hand. I doubt there is an API for it sorry.

NOTE: MY DISCLAIMER ABOUT THE LEGALITIES, AND THAT I'M NOT ENCOURAGING YOU TO TRY THE HACKING

That being said, through hacking there are various work arounds that I won't discuss here. That you could find online with some googling.
> 0 votes

---
Tags: modding
---


# Question
Title: How to make Moving road/track for android game?
I am very much new to Android game development. and i have little idea about the canvas and open GL. in one of my requirement i wanted to draw a moving road/track(Jazzy). how should i start. please suggest me some approach/tutorial. Thanks

Below is the link for the reference..please take look at the road only

http://www.miniclip.com/games/zoo-racer/en/

# Answer
There's not much to say about it, just look into basic 2D game tutorials and they should give you enough information. I've never worked with Android so I don't have any links at hand, but you need the following:

1. Draw the track; for simplicity your track can be one complete image and you simply draw it on the background.
2. A 2D camera that changes your point of view of the scene. Basically it creates a View Matrix for you to pass OpenGL when drawing.
3. A player/car object with X,Y position in the track. Draw the player on top of the track at that position.
4. Fix the 2D camera to your player (e.g. `camera.Position = player.Position;`).
> 1 votes

---
Tags: opengl, android, movement, cocos2d, html-canvas
---


title: Tile pair matching algorithm

text:
# Question
Title: Tile pair matching algorithm
I'm trying to make a tile matching game. User can select a pair of tiles from a square grid, and if they match, both are removed from the grid.

Tiles are matched if:

* they are of the same type (many types of tiles are in the grid) *AND*
* they can be connected in the grid (either adjacent, or has a clear path of empty spaces between them in the grid)

I would like to scan the grid in advance and find the currently matching pairs (desirably with the path that connects them). Thus I can:

* give hint to users if they're stuck in finding a pair
* detect a situation when no more pairs can be matched (so the tiles will be reordered)

Ideally during the scan each tile pair of the same type should be taken and checked for matching. Is there any algorithm/technique I can use in here to obtain an optimized approach in finding the connecting paths?
Also, is there anything I should take care of while initializing the grid (currently just random assignment) so as to ensure at least some tiles are adjacent in the beginning (and that I won't have to reorder them too much during the game) ?

# Answer
**Question 1**

A few details that might need clarification...

---

1. Are tiles considered to be a match if they aren't at the extremities of a clear path? E.g:

############

###

# ###O####

# ######O

# #######

### ##
2. What about diagonals, are they considered adjacent? E.g:

############

###

########## #

# #O####

####O##### # ######## ##
3. Can there be more than one pair of the same type on the grid, or just one?

---

Either way the solution to your problem will be fairly similar, so I'll assume all three are true for this explanation (I'll use C# as example). Read on for the full set of ideas...

**Implementation**

*Part 1 - Storing and look up*

After you finish filling your grid with tiles, you should scan each tile and group tiles of each type together to make it easier to lookup. I'll use a Dictionary, like so:

```
Dictionary<TileType, List<Tile>> tilesRegistry;

```

By the way I'll consider a Tile to have this structure:

```
class Tile
{
    int x, y;
    TileType type;
}

```

And as you go over each tile in the board, you'll register it on the dictionary doing something similar to:

```
void RegisterTile(Tile tile)
{
    if(!tilesRegistry.Contains(tile.type))
    {
        tilesRegistry[tile.type] = new List<Point>();
    }
    tilesRegistry[tile.type].Add(tile);
}

```

Using this Dictionary you can easily find all tiles of any type on the board. For instance, if given one tile, you'd like to find if there's a match you could do:

```
Tile FindMatch(Tile tile)
{
    List<Tile> tiles = tilesRegistry[tile.Type];
    foreach(Tile t in tiles)
    {
        if(t == tile) continue;
        if(AdjacentTiles(t, tile) || ConnectedTiles(t, tile))
        {
            return t;
        }
    }
    return null;
}

```

I suppose you can figure out other uses for this registry to fulfill your needs.

*Part 2 - Matching tiles and pathfinding*

The other relevant detail of this implementation is how to create the AdjacentTiles and ConnectedTiles methods.

The AdjacentTiles method should be pretty obvious, just compare the X and Y coordinates of both tiles. The tricky one is ConnectedTiles.

Are you familiar with any pathfinding algorithm, such as A\* (which I learned from this resource)?

Since your matching algorithm needs to find tiles connected by a clear path, your best course of action will probably be to use A\*.

By treating the board as a sort of game map, with empty cells being considered as open, and other cells being blocked tiles (except for the ones of the tile type you're currently searching), you should be able to easily find the path between two tiles using A\*.

Ideally you'll want to encapsulate it so that you may do:

```
List<Point> GetPath(Tile from, Tile to) {}

```

And it will return you the path (if any) between both cells.

**Question 2**

The solution to your second quest seems overly obvious. Start by adding a few pairs directly in adjacent positions on purpose. Then fill the remaining gaps randomly.
> 5 votes

# Answer
To add to David Gouveia's answer.

Path finding is not strictly necessary. Adding to the tile structure as defined by David.

```
class Tile
{
    int x, y;
    TileType type;
    List empty_set; //reference to empty-tile set
}

```

And the following list:

```
List<List<Tile>> all_empty_sets;

```

The following three concepts are implemented into the `setEmpty()` method for tiles (ie when a pair is confirmed, both tiles are set as empty).

* When a tile is declared empty, and it is not adjacent to other empty tiles, it can simply be added to a new array, which is added to the list.
* When a tile is declared empty, and is adjacent to one other empty tile, the newly declared empty tile is added to the adjacent tiles empty\_set.
* When a tile is declared empty, and is adjacent to several other empty tiles (not necessarily connected), the adjacent empty sets are joined (via a Union). The union then replaces all set references in the affected tiles (via `t.setEmptySet(union)`).

My attempt at these rules, is shown in my attempt at C# below:

```
List<List<Tile>> adj_sets = new List<List<Tile>>();
foreach(Tile t in tiles) {
    if(t == tile) continue;
    if(areAdjacentTiles(t, tile) && !t.isEmpty()) {
        if (!adj_sets.Contains(t.getEmptySet())) {
            adj_sets.add(t.getEmptySet());
            empty_set = t.getEmptySet(); // for the adj_sets.Count() == 1 case
        }
    }
}
if (adj_sets.Count == 0) {
    empty_set = new List<Tile>(); // set our empty set
    empty_set.add(this); // add this tile
    all_empty_sets.add(empty_set); // add to the global list
} else {
    if (adj_sets.Count > 1) {
        List<Tile> union = new List<Tile>();

        foreach(List<Tile> l in adj_sets) {
            union = union.Union(l);
            all_empty_sets.remove(l); // remove from the global list
        }

        foreach(Tile t in union) {
            t.setEmptySet(union);
        }

        union.add(this); // add this tile to the resultant set
        empty_set = union; // set our empty set
        all_empty_sets.add(union); // add to the global list
    }
}

```

And then, in `ConnectedTiles(Tile t1, Tile t2)`, it is as simple as:

```
for (Tile ti in t1.adjacentTiles()) {
    for (Tile tj in t2.adjacentTiles()) {
        if (ti.getEmptySet() == tj.getEmptySet()) {
            return true;
        }
    }
}
return false;

```

Albeit, you will need to make a method `adjacentTiles()` which returns a set of tiles that are classified as adjacent tiles (ie, if you classify a empty square that is diagonal away, as connected, then it must be in this list, but it must also be in the logic for `areAdjacentTiles(t, tile)`).

*NOTE: I have renamed Davids `AdjacentTiles(t1, t2)` function to `areAdjacentTiles(t1, t2)`, for the sake of clarity.*
> 2 votes

---
Tags: algorithm, tiles
---


# Question
Title: How can I throttle certain player actions?
### Background

I have a variable time step, component based game, with components that collectively hold an entity's properties and different systems that act on entities with certain required components.

The player controls a ship that can fire bullets. I have an input system that works on entities with a `PlayerControlComponent` (nothing more specific yet) and creates an entity every frame if a key is held down.

---

### Question

How should I manage limiting or throttling this so that it can't occur closer than 1 second apart in a reusable way?

# Answer
Maybe I'm missing the point because it seems so simple but isn't something like this enough?

```
public class Component
{
    protected limit = 1.0f;
    private float timer = 0.0f;

    public virtual void Update(float dt)
    {
        timer += dt;
        if(timer >= limit)
        {
            timer -= limit;
            LimitedUpdate();
        }
    }

    public virtual void LimitedUpdate() {}
}

```

And then you override `LimitedUpdate` and put anything that you only want triggering from `limit` to `limit` seconds there.

**Edit**

And to fulfill the idea on your comment about making it into a centralized component and event driven (instead of polling driven):

```
public class ActionManager
{
    private struct ActionEntry
    {
        public Action Action;
        public float Limit;
        public float Timer;
    }

    private Dictionary<string, ActionEntry> entries = new Dictionary<string, ActionEntry>();

    public RegisterAction(string id, Action action, float limit = 1.0f)
    {
        // Note: I made Timer = limit so that the first call is 'free'
        entries[id] = new ActionEntry { Action = action, Limit = limit, Timer = limit };
    }

    public void TryAction(string id)
    {
        if(entries[id].Timer >= entries[id].Limit)
        {
            entries[id].Action();
            entries[id].Timer = 0.0f;
        }
    }

    public void Update(float dt)
    {
        foreach(var entry in entries)
        {
            entry.Value.Timer += dt;
        }
    }
}

```
> 3 votes

---
Tags: input, events, timing
---


# Question
Title: How does double dispatch help collision detection?
There are a few specific techniques to test if one object has hit another object in a game. One of them is called "double dispatch." Can someone explain what double dispatch is, and how it can be used to test hit objects?

# Answer
> 5 votes
Double-dispatch doesn't help with collision detection *per se*, it helps with the prelude to collision detection: given two arbitrary shapes, determine which collision detection algorithm to use (ray-triangle, ray-circle, ray-box, triangle-circle, et cetera).

In many programming languages -- like C++ -- dynamic dispatch (what happens when you call a virtual member function) resolves based only on the type of a single parameter to that function (the "this" pointer, in other words the type of the invoking object). Double-dispatch is a way to resolve a function call based on *two* of the function's arguments.

In a collision detection scenario where you have two `Shape` objects (`Shape` being the base class for all possible concrete collision shapes), you want to select a collision detection function based on the actual run-time type of both objects.

There is a lot of information on implementing double dispatch (or its more general cousin, multiple dispatch) in C++ floating around. Many of them apply equally well, excepting in syntax, to whatever other C++-like language you may be using:

Google can locate you many more. Note that "double dispatch" refers *almost exclusively* on the wide internet to a technique involving virtual methods, and many implementations C++ rely on constructs like templates or RTTI to alleviate some of the tedium of the technique (since it's not built-in to the language).

This can actually make those techniques poor choices for game development or other scenarios where very high performance may be required of a simulation that processes a large number of potential collisions per step, because the overhead of some of those techniques may be non-zero (and in particular may have cache coherency issues or issues on restricted platforms like consoles). Additionally, because it relies on dynamic dispatch, the implication is that all shape primitives must inherit a common base class -- which is not always a desirable design.

If nothing else, double-dispatch code may become overly complex, making it hard to maintain or extend.

For this reason you may want to explore alternative approaches, such as simply reducing the number of simple primitives you have in your game to the point where a simple function table is sufficient for resolving the collision function, or otherwise implementing the "dispatch" part of the technique manually. Double-dispatch is not a be-all, end-all solution.

---
Tags: collision-detection, algorithm
---


# Question
Title: How can I generate floating land masses for a Minecraft-like engine?
I am creating a Minecraft-like engine in XNA. What I want to do is create floating islands similar to the one shown in this video:

http://www.youtube.com/watch?v=gqHVOEPQK5g&feature=related

How would I replicate this using a world generator? Would I have to use some Perlin noise algorithm? I don't know how that would help me make land masses like that.

Here is the code for the perlin noise generator that I am using:

```
    private double[,] noiseValues;
    private float amplitude = 1;    // Max amplitude of the function
    private int frequency = 1;      // Frequency of the function

    /// <summary>
    /// Constructor
    /// </summary>
    ///
    public PerlinNoise(int freq, float _amp)
    {
        Random rand = new Random(System.Environment.TickCount);
        noiseValues = new double[freq, freq];
        amplitude = _amp;
        frequency = freq;

        // Generate our noise values
        for (int i = 0; i < freq; i++)
        {
            for (int k = 0; k < freq; k++)
            {
                noiseValues[i, k] = rand.NextDouble();
            }
        }
    }

    /// <summary>
    /// Get the interpolated point from the noise graph using cosine interpolation
    /// </summary>
    /// <returns></returns>
    public double getInterpolatedPoint(int _xa, int _xb, int _ya, int _yb, double x, double y)
    {
        double i1 = interpolate(
            noiseValues[_xa % Frequency, _ya % frequency],
            noiseValues[_xb % Frequency, _ya % frequency]
            , x);

        double i2 = interpolate(
            noiseValues[_xa % Frequency, _yb % frequency],
            noiseValues[_xb % Frequency, _yb % frequency]
            , x);

        return interpolate(i1, i2, y);
    }

    public static double[,] SumNoiseFunctions(int width, int height, List<PerlinNoise> noiseFunctions)
    {
        double[,] summedValues = new double[width, height];

        // Sum each of the noise functions
        for (int i = 0; i < noiseFunctions.Count; i++)
        {
            double x_step = (float)width / (float)noiseFunctions[i].Frequency;
            double y_step = (float)height / (float)noiseFunctions[i].Frequency;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int a = (int)(x / x_step);
                    int b = a + 1;
                    int c = (int)(y / y_step);
                    int d = c + 1;

                    double intpl_val = noiseFunctions[i].getInterpolatedPoint(a, b, c, d, (x / x_step) - a, (y / y_step) - c);
                    summedValues[x, y] += intpl_val * noiseFunctions[i].Amplitude;
                }
            }
        }
        return summedValues;
    }

    /// <summary>
    /// Get the interpolated point from the noise graph using cosine interpolation
    /// </summary>
    /// <returns></returns>
    private double interpolate(double a, double b, double x)
    {
        double ft = x * Math.PI;
        double f = (1 - Math.Cos(ft)) * .5;

        // Returns a Y value between 0 and 1
        return a * (1 - f) + b * f;
    }

    public float Amplitude { get { return amplitude; } }
    public int Frequency { get { return frequency; } }

```

But the thing is the author of the code uses the following to generate noise, and I don't understand it in the least.

```
    private Block[, ,] GenerateLandmass()
    {
        Block[, ,] blocks = new Block[300, 400, 300];

        List<PerlinNoise> perlins = new List<PerlinNoise>();
        perlins.Add(new PerlinNoise(36, 29));
        perlins.Add(new PerlinNoise(4, 33));

        double[,] noisemap = PerlinNoise.SumNoiseFunctions(300, 300, perlins);

        int centrey = 400 / 2;

        for (short x = 0; x < blocks.GetLength(0); x++)
        {
            for (short y = 0; y < blocks.GetLength(1); y++)
            {
                for (short z = 0; z < blocks.GetLength(2); z++)
                {
                    blocks[x, y, z] = new Block(BlockType.none);
                }
            }
        }

        for (short x = 0; x < blocks.GetLength(0); x++)
        {
            for (short z = 0; z < blocks.GetLength(2); z++)
            {
                blocks[x, centrey - (int)noisemap[x, z], z].BlockType = BlockType.stone;
            }
        }

        //blocks = GrowLandmass(blocks);

        return blocks;
    }

```

And here is the site I am using: http://lotsacode.wordpress.com/2010/02/24/perlin-noise-in-c/.

And I am trying to implement perlin noise in the way specified by Martin Sojka.

Ok, so this is what I have got so far:

# Answer
For the base land, make two 2D continuous noise fields (Perlin, Simplex, Wavelet, a combination thereof - whatever works for you), one with mostly low frequency. low amplitude parts for the upper limit of the land, the other with both high frequency, high amplitude parts and low frequency, high amplitude for the lower limit of the land. Where the lower limit is above higher limit, don't include any land voxels (or whatever your game will be using to represent the terrain). The end result looks roughly like this ...
> 21 votes

# Answer
Would something like this be enough?

If so, check this article. Quoting the most relevant parts:

> In order to get more interesting noise multiple octaves of simplex noise can be added together. \[...\] Since I want to get a roughly spherical floating rock of sorts, I need to multiply the noise with its distance from the center. \[...\] I also want the rock to be flatter on the top than on the bottom, hence a second multiplication factor is a gradient in y direction. Combining these together and stretching y for noise while compressing x and z a bit, we get something like a floating rock. \[...\] Excavating caves with another instance of noise offset a little also makes it more interesting.

* So basically you will start with a data set generated from simplex or perlin **noise** (or rather *multiple octaves of noise added together*).
* Then shape it into something closer to a floating landmass by making it more **spherical** (by multiplying the noise by its *distance from the center*).
* And create ground by making it **flatter** near the top (by multiplying it by a *vertical gradient* i.e. starting with low values at the top and getting higher towards the bottom).
* Combine these three and adjust the shape by **scaling** the noise along the X/Y/Z axes (the article suggests *stretching on the Y axis and compressing on the X and Z axes*).
* An additional pass of noise may be used to excavate **caves**.
> 15 votes

# Answer
1. Using your existing 3D grid, decide on the height at which you want island tops to be. Create a set of islands in that 2D plane (lets call it the XY plane) by scattering points through the plane, then placing cubes at those points. Use cohesion to pull them closer together in clumps. Fill in any holes and you have a set of island-tops.
2. Use a CA-similar method to grow the islands downwards. (a) Starting at the Z level where you plotted your initial points, for each cell in that current Z level, determine the chance to extend down to the next lower level given the number of neighbours in the XY plane, from 0 to 8 (diagonal neighbors are included), e.g. assign a 10% chance for each neighbour, up to max 80% chance. Calculate this for each cell in the starting plane. (b) Then randomise against this chance and extend downward if you are within the percentage range. Rinse, repeat step 2 (go to next level, determine neighbours for each voxel, extend downwards for that voxel) until no more extensions occur. Your downwards extension should form a cone due to the number-of-neighbours approach, because those voxels towards the XY-centre of the island will typically have more neighbours.

Pseudocode for step 2:

```
int planeNeighbours[x][y]; //stores how many neighbours each voxel in this plane has

for each z level (starting at level where you plotted your points)
    for each x, y voxel in z level
        for each neighbour space bordering this voxel
            if neighbour exists
                ++planeNeighbours[x][y];
    for each x, y voxel in z level
        chance = random(0,8); //depends on your RNG implementation
        if chance < planeNeighbours[x][y]
            worldGrid[x][y][z+1] = new cube

```

Once your islands are done generating, you can optionally shift them up and down in space to have them at different heights.
> 4 votes

---
Tags: algorithm, procedural-generation, random, minecraft-modding, voxels
---


title: Design of a camera system

text:
# Question
Title: Design of a camera system
Thinking about a common game, doesn't matter the type of the game, it's very likely that we need some camera type. For example:

* Debug camera: controlled by keyboard and mouse, with that we are able to move around in any place of our scene.
* Scripted camera: with that we can instruct the camera to move around, following a determinate path.
* Player camera.
* ...

Each of these camera types has its own update function. The easiest (and bad) system,is to have a camera manager class with a generic update function and specialized update functions for every camera type. Inside the generic update function we have a switch statement that, based on the camera type, calls the proper update function.

Instead of this I've thought to another approach: strategy pattern. We move each camera behavior (update method) in an appropriate class that implements a common interface. In the camera manager we have a member to that interface, and we can set dinamically any behavior we want.

What do you think about that? What other systems do you suggest me? Thanks.

**Additional info:** there is the are real possibility that I need more than one camera active, for example for reflections. In short, I must take account also of that.

# Answer
The strategy patterns seems like a good bet to me. To take it a step further, your camera manager should remain ignorant of the concrete camera types. You would register and change camera implementations externally by id (I used a string for flexibility but could be an enum or an int too), for instance (without any error checking):

```
public interface ICamera
{
    void Update(float dt);
    Matrix View { get; }
}

public class CameraManager
{
    private Dictionary<string, ICamera> cameras;
    private ICamera currentCamera;

    public void RegisterCamera(string id, ICamera camera) { cameras[id] = camera; }
    public void SetCamera(string id) { currentCamera = cameras[id]; }

    public void Update(float dt) { currentCamera.Update(dt); }
    public Matrix View { get { return currentCamera.View; } }
}

public class DebugCamera : ICamera {}
public class PlayerCamera : ICamera {}
public class ScriptedCamera : ICamera {}

void Test()
{
    // Create camera manager
    CameraManager cameraManager = new CameraManager();

    // Register cameras
    cameraManager.RegisterCamera("Debug", new DebugCamera());
    cameraManager.RegisterCamera("Player", new PlayerCamera());
    cameraManager.RegisterCamera("Scripted", new ScriptedCamera());

    // Change active camera
    cameraManager.SetCamera("Player");
}

```

---

**Edit**

> Additional info: there is the are real possibility that I need more than one camera active, for example for reflections. In short, I must take account also of that.

That's trivial to add. Just change `currentCamera` to:

```
List<ICamera> activeCameras = new List<ICamera>();

```

Change `SetCamera` to ToggleCamera (or add a boolean to SetCamera, your choice):

```
void ToggleCamera(string id)
{
    ICamera camera = cameras[id];
    if(activeCameras.Contains(camera))
        activeCameras.Remove(camera);
    else
        activeCameras.Add(camera);
}

```

And change the `Update` method to update all active cameras instead of only the current one:

```
void Update(float dt) { activeCameras.ForEach(c => c.Update(dt)); }

```

In my example, you'd also need to replace the `View` property with a `GetView` method taking the id of the camera as parameter. But that's a detail that depends on your camera interface anyway:

```
// You could optionally add a check to see if the camera is active
Matrix GetView(string id) { return cameras[id].View; }

```
> 12 votes

---
Tags: camera, design-patterns
---


# Question
Title: How to place objects/entities randomly in JS?
I'm making a game and I have a script (running it with Node) on the server that currently just randomly places things on the map... I'd like to change that. I saw something about Perlin noise but I'm not sure if that's the thing I want and I'm even less sure how to implement it...

I want something like this, green dots represent trees, red ones represent enemies and grey ones represent rocks. Where can I get a simple JS algorithm to achieve this?

# Answer
From your picture there seems to be a bit of randomness and clustering. Here's a way to do something similar without using noise.

You could start by dividing the playing field into sections. For instance, in the image above you could have divided it into a 5x3 grid.

```
|-----|-----|-----|-----|-----|    ---
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|-----|-----|-----|-----|-----|     |
|     |     |     |     |     |     |
|     |     |     |     |     |     | Map Height
|     |     |     |     |     |     |
|-----|-----|-----|-----|-----|     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|-----|-----|-----|-----|-----|    ---

|-----------------------------|
           Map Width

```

Then for each cell in that grid you generate a probability for each type of entity existing in that tile. This is where you can add some entity specific clustering.

For example you could start by filling everything with some default probabilities: Tree = 50%, Rock = 50%, Enemy = 0%

```
// Default probabilities
// Equal chance of tree and rock, no enemies

|-----|-----|-----|-----|-----|
|T=50 |T=50 |T=50 |T=50 |T=50 |
|R=50 |R=50 |R=50 |R=50 |R=50 |
|E=0  |E=0  |E=0  |E=0  |E=0  |
|-----|-----|-----|-----|-----|
|T=50 |T=50 |T=50 |T=50 |T=50 |
|R=50 |R=50 |R=50 |R=50 |R=50 |
|E=0  |E=0  |E=0  |E=0  |E=0  |
|-----|-----|-----|-----|-----|
|T=50 |T=50 |T=50 |T=50 |T=50 |
|R=50 |R=50 |R=50 |R=50 |R=50 |
|E=0  |E=0  |E=0  |E=0  |E=0  |
|-----|-----|-----|-----|-----|

```

And then let's consider that you'd like your map to have exactly one cluster of enemies, and one zone with higher concentration of rocks.

You'd pick one cell at random and change the values of that cell to Tree = 20%, Rock = 0%, Enemy = 80%. Then do the same for rocks. You can also use a radius of cells if you like to make the transitions smoother. You'll end up with something like:

```
// Added two random clusters:
// One enemy cluster on the bottom right
// One rock cluster on the top left

|-----|-----|-----|-----|-----|
|T=0  |T=30 |T=50 |T=50 |T=50 |
|R=100|R=70 |R=50 |R=50 |R=50 |
|E=0  |E=0  |E=0  |E=0  |E=0  |
|-----|-----|-----|-----|-----|
|T=30 |T=40 |T=50 |T=80 |T=70 |
|R=70 |R=60 |R=50 |R=10 |R=0  |
|E=0  |E=0  |E=0  |E=10 |E=30 |
|-----|-----|-----|-----|-----|
|T=50 |T=50 |T=50 |T=70 |T=20 |
|R=50 |R=50 |R=50 |R=0  |R=0  |
|E=0  |E=0  |E=0  |E=30 |E=80 |
|-----|-----|-----|-----|-----|

```

Finally, with this information in place, you only need to decide the maximum number of entities there can be in any cell (i.e the density of the cell) and start adding entities in random positions and using the probabilities above to decide the type of each of them.

This will provide you with a nice mix of randomness, and at the same time clustering based on the rules you define when filling in the probabilities grid.
> 3 votes

# Answer
If you just want a number of items placed randomly within a range (which, from your description, sounds like that may be all you want) that could be done pretty easily. Randomly choose a number of trees to place, then iterate through a loop where you randomly pick an X and Y coordinate and put a tree there. Do similarly with enemies, rocks, anything else. This simple method would be easy (a few random numbers and a few loops that make more random numbers) to set up but wouldn't necessarily clump things together.

If you mean you want actual terrain randomized, Perlin noise is a commonly used way to generate heightmaps or other clustered groups. You could use it to determine forest areas or enemy campsites, etc. in addition to a simple heightmap by changing some of its generation parameters.

EDIT:

Googling "Javascript Perlin Noise" provides a good number of results if you want code to adapt. I came across this code which may be useful for you.

As for how to use it, you can generate 2D textures using whatever code you decide and use one as a height map, another as tree density, or enemy density, or rock density, or water depth, or whatever.
> 2 votes

---
Tags: algorithm, javascript, entity-system, terrain, random
---


# Question
Title: What is the best way to funnel input to the correct entities?
I have an input pipeline that stores InputObjects into a queue, which I then iterate through once every frame.

```
while(!inputQueue.isEmpty())
{
    InputObject inp = inputQueue.pop();

    boolean handled = false;
    for(Entity entity : inputRecievingEntities)
    {
          //entity.manage() returns true if it wants to consume the event, false otherwise
          handled = entity.manage(input);
          if(handled)
               break;
    }
}

```

This works fine to make sure the input is handled by only one entity. However, consider this situation:

There is a button overlaying the screen. The user can either click the button to jump or press anywhere (else) on the screen to shoot in that direction (which is handled by the player entity). If the player entity happens to be before the button entity in the inputReceivingEntities list, the player will shoot and not jump. If the button is before the player, the player will jump, and not shoot (which would be correct). Obviously I could assign some sort of priorities to the objects and sort the list but is there a better way to do this?

# Answer
In your example, isn't the reason why the button press should take precedence simply because the button is **on top**?

So you don't really need to assign priorities, or sort your list, as you already have such an order in place somewhere else - **the draw order**. Just handle mouse events in the inverse order that you're drawing your entities.

For example, in my 2D engine I have entities placed on a display list, which is divided into layers and sorted in draw order. Then my input manager gets a list of all entities from my display list (but only the ones I mark as `Interactive`) and events are handled front to back, top layer to bottom layer.

At the bottom of everything, if nothing else handled the event, I also have a class called `Stage` which exists simply to handle events that were not consumed by entities (such as clicking outside of all entities).

Entities consume events by default, but if one them should be *non-blocking*, I simply return a different value from the event handler like you're doing (which is a design pattern called chain of responsibility by the way).

---

> Can you further explain the display list? Or should I ask another question about it?

Sure. But bear in mind that this just my personal solution to a specific problem. Feel free to take from it anything that might be useful to you, but with a grain of salt; each project is different, and this solution just happened to fit well with my needs. It won't fit every project, and I don't claim it to be the best way or anything.

My display list is made up of two separate parts:

1. The **sprite hierarchy** representing every type of sprite I can display.
2. The display list (which I call the **stage**) which groups and manages my sprites.

Here's a basic overview of this system, in some C# inspired pseudocode mostly:

**Part 1: The Sprite Hierarchy**

```
class Sprite
{
    mixed Position, Rotation, Scale, Origin
    bool Visible, Interactive
    bool IsInside(x,y);
    void Update();
    void Draw();
}

class ImageSprite : Sprite {}
class TextSprite : Sprite {}
class PolygonSprite : Sprite {}
class CompositeSprite : Sprite { List<Sprite> Children; }
class AnimatedSprite : Sprite { List<CompositeSprite> Frames; }

```

**Part 2: The Display List**

```
class Stage
{
    List<Layer> Layers;
    Camera Camera;

    List<Sprite> GetSpritesAt(x,y);
    void HandleInput();
    void Update();
    void Draw();

    event StageMouseDown, StageMouseUp, SpriteMouseEnter, SpriteMouseLeave;
    event SpriteMouseDown, SpriteMouseUp, SpriteMouseClick, SpriteMouseMove;
}

class Camera {}

class Layer
{
    CompositeSprite Root;

    void Add(sprite);
    void Update();
    void Draw();
    List<Sprite> GetSpritesAt(x,y);
}

```

And the only part relevant to your initial question lies on the Stage.HandleInput method. It goes roughly like:

```
void HandleInput()
{
   // Note: GetSpritesAt already returns sprites ordered by the drawing order
   List<Sprite> sprites = GetSpritesAt(mousePosition);

   // Handle input starting from the topmost sprite on the topmost layer
   // Trigger events along the way
}

```

**Example:**

Here's an example of how I use it:

```
Stage stage = new Stage(2 /* Number of Layers */);
stage.SpriteMouseClick += sprite => Diagnostics.Debug.WriteLine(sprite.Id + " clicked!");

stage.Layers[0].Add(new ImageSprite(texture1){Position=new Vector2(300, 300)});
stage.Layers[0].Add(new ImageSprite(texture2){Position=new Vector2(200, 200)});
stage.Layers[1].Add(new TextSprite("Message text"){Position=new Vector2(100, 100)});

stage.HandleInput();
stage.Update();
stage.Draw();

```

That's pretty much all I need to create my scene and add interaction and events on my sprites.
> 2 votes

# Answer
I would define input types and make your entities handle different input types differently.

So you would derive PlayerInput and ButtonInput from InputObject. Derive PlayerEntity and ButtonEntity from Entity (if you haven't already).

Then your manage function can be different for each entity type, and handle input from each input type in the correct manner.

This might be slightly over engineered, but it allows you to have entities that handle more than one type, as well as allowing different entities to handle different input types in diverse ways.
> 0 votes

---
Tags: input, touch
---


title: Is the Humble Bundle reasonable?

text:
# Question
Title: Is the Humble Bundle reasonable?
I **love** the humble bundle. They are getting more and more generous, now including Pack #3 with Pack #4.

I am so confused. Will they last? Are they doing ok? They're putting so much out there, and if you donate less than $1, you get this image :

And that's it!

Is this really working?

# Answer
> 15 votes
## The Concept

The concept this runs around is that most people who pirate are people who wouldn't purchase, regardless of circumstances.

Generally speaking, most of the people who paid little, or nothing, are people who wouldn't have purchased the game anyway, so very little potential profit is being lost from that sector. Furthermore, most of the games involved have been out for a while, and have already peaked, meaning their rate of sale is rapidly declining.

Meanwhile, hundreds of thousands of gamers are exposed to these games, which raises the profile of each of the studios involved. Basically, they use the collective appeal of all of the games combined to boost their studio's fame. This results in the studios having a stronger pedigree, which in turn will lead to increased sales of their future titles.

> "Hey, they're the guys that had that great game in the last Bundle; This new game could be good!"

So, by sacrificing the last little dribble of sales from their existing titles, they get to gain (relatively) massive public exposure, public goodwill, and help out charities.

---

## The Reality

The third humble bundle sold over 370,000 copies, at an average of $5.80 per sale. The total amount raised was roughly 2.2 million dollars. There were 7 studios involved, with the average consumer giving 30% of profits to the developers (these numbers gathered from Wikipedia and a variety of other sources, none of which are supremely credible). So, each studio on average made $94,000 in the space of 2 weeks.

Considering that 6 of the 7 games were over 12months old (4 were over 2 years old), which for an indie game typically means it's well past its prime, that last boost in revenue is nothing to sneer at.

# Answer
> 5 votes
In terms of the humble bundle itself, all the iterations have made over $1,000,000 each (divided among charity, the "humble bundle company", and various developers). The Humble Bundle #4 has made about $1,758,970 as of this second. According to the humble bundle #3 stats, it brought in $2,169,341.93. So, the numbers say that the bundle itself is doing well.

Will it be successful in the long term? That's actually something that is up for debate. Opponents of the bundle idea make claims that the money brought in with bundles is actually quite lower than what a game would otherwise make, and it's lowering the expected price point for indie games. It's impossible to say if the bundles are a good thing or not, and anything else is mostly going to be speculation.

---
Tags: sales
---


# Question
Title: How do I get started making Android games?
I am new to game development. I am interested in developing 2D games for the Android platform. What is the best place to start with (i.e) What are the basics and how to proceed? I already have programming experience in Java but don't have any experience with graphics or animation.

# Answer
Android might not be the best choice for starting game development because you would be learning several different things at the same time (Android SDK, making games, optimization, different phone models, etc.). Consider making some simple Java games on your computer to get familiar with making games in general; this tutorial looks like a good place to start.

Once you're comfortable with both Java and game development, start with the Android tutorials. The development guide is very useful, in particular you need to know Android fundamentals and activity life cycle, as well as graphics. Get the Android samples and check out the Lunar Lander and Snake game samples (there's also JetBoy, but that's focused on the JetPlayer).

The canvas class is actually good enough for most 2D games, but if you need better performance or want to move to 3D graphics later you will have to learn OpenGL ES. However, this is beyond the scope of getting started (unless you already know OpenGL).
> 83 votes

# Answer
There are lots of results at Stack Overflow for `android game`. Lucky for you, I went through all of them and picked out the relevant ones to your question.
> 66 votes

# Answer
If you're already familiar with Android and doing basic UI applications with it, then you'll want to take a look at this multi-part tutorial that explains drawing graphics to an Android screen.
> 18 votes

# Answer
All of these are really good answer. But I am a little surprised that no one has mentioned jMonkeyEngine yet.

Its java, its shader based, its super easy to begin with, very good documentation, awesome community, fast bug fixes, comes with a game development enviroment(jMP based on NetBeans platform) & its evolving very very fast.

I would emphasis more on it because, game development and making a library that someone will be using to make a game is quite different. So, *if you want to make a game* not a game engine, just jump right in jMonkey Engine with your eyes closed. :)
> 4 votes

# Answer
Processing.org is another good place to start for (somewhat simplified) coding/development before diving into the Android SDK. It works on Max/Windows/Linux and has a version developed specifically for Android deployment. I highly recommend it - as long as you have an Android phone you can deploy games/apps to your phone that you make with that version of Processing. Hope it helps.
> 3 votes

# Answer
I am also new to android game development, and I find the open source game engine AndEngine a pretty good tool to start with. It's got a bunch of examples and a fairly active community.

http://www.andengine.org/
> 2 votes

# Answer
I strongly recommend the Airplay SDK as it works on windows and deploys to most smart phones. They also have a great Indie license.
> 0 votes

---
Tags: graphics, books, animation, android
---


# Question
Title: Touching on the particular sprite from the spritesheet
I want to click on the particular sprite from the sprite sheet. For instance i have fruits sprite sheet i want to click on the particular fruit.

Thanks, Jubin Mehta

# Answer
A general solution would be:

1. Get the cursor position.
2. Transform the position into the tiles local coordinate space.

pixelPositionX = cursorPositionX - (tilePositionInWorldX - screenPositionX)

pixelPositionY = cursorPositionY - (tilePositionInWorldY - screenPositionY)
3. Find out if the position is inside the tile.

tilePositionOnSpritesheetX \< pixelpositionX \< tilePositionOnSpritesheetX + tileSizeX

tilePositionOnSpritesheetY \< pixelpositionY \< tilePositionOnSpritesheetY + tileSizeY
4. If it is, check if the alpha value of the pixel at that position is over a certain treshold.

Step 4 is optional, without it, you're checking against the tiles bounding rectangle, with it, clicking is pixel perfect.

Please note that all positions and sizes are assumed to be in pixels.
> 1 votes

---
Tags: android, cocos2d
---


# Question
Title: Extracting blend values from uint32 not working as expected
I have the following shader configuration code :

```
uint gBlendValue = 0xffffff00;
Terrain.Effect.GetVariableByName("gBlendValue").AsScalar().Set(gBlendValue);

```

And I have the following shader code :

```
// extract blend weights from gBlendValue - produces bVn values in the range [0,1]
float bV1 = ((gBlendValue >> 24) & 0xff)/255.0;
float bV2 = ((gBlendValue >> 16) & 0xff)/255.0;
float bV3 = ((gBlendValue >> 8)  & 0xff)/255.0;
float bV4 = (gBlendValue & 0xff)/255.0;

// sum lerped blends
float3 finalColor = float3(0,0,0);
finalColor += lerp(float3(0,0,0), float3(1,0,0), bV1);
finalColor += lerp(float3(0,0,0), float3(0,1,0), bV2);
finalColor += lerp(float3(0,0,0), float3(0,0,1), bV3);

// return finalColor
return float4(finalColor,1);

```

But this doesn't behave as expected. The geometry is a dark red, when it should be white. What the turtle is going on here.

# Answer
> 1 votes
You appear to have solved your problem by sending a raw value, but I suggest you do not attempt to send packed values to the shader unless you have a good reason to do so.

Right now computing `bV1` to `bV4` requires three shifts, four integer operations, four conversions to floating point, and four floating point multiplications by a constant. All these operations are done **for every fragment**. If you replaced `gBlendValue` with an array of floats that are already normalised to `[0,1]`, the computation would be done only once on the CPU and your shader would be a lot simpler.

Also, this code chunk:

```
float3 finalColor = float3(0,0,0);
finalColor += lerp(float3(0,0,0), float3(1,0,0), bV1);
finalColor += lerp(float3(0,0,0), float3(0,1,0), bV2);
finalColor += lerp(float3(0,0,0), float3(0,0,1), bV3);

```

Can be replaced with:

```
float3 finalColor = lerp(float3(0,0,0), float3(1,1,1), float3(bV1, bV2, bV3));

```

Though I suppose `(0,0,0)` and `(1,1,1)` were only test values, I think it's worth noting that this is also equivalent to:

```
float3 finalColor = float3(bV1, bV2, bV3);

```

# Answer
> 0 votes
You should enable BlendState. BlendState is not enabled by default.

1. Make BlendState structure like below.

```
BlendState BlendAlpha {
    AlphaToCoverageEnable = FALSE;
    BlendEnable[0] = TRUE;
    SrcBlend = SRC_ALPHA ;
    DestBlend = INV_SRC_ALPHA ;
    BlendOp = ADD;
    SrcBlendAlpha = ONE;
    DestBlendAlpha = ZERO;
    BlendOpAlpha = ADD;
    RenderTargetWriteMask[0] = 0x0F;
};

```
2. Add (BlendAlphaParticle, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF); to your pass in your technique.
3. After alpha blending is ended, call device-\>OMSetBlendState(NULL, 0, 0xffffffff); to set blendstate back to default.

# Answer
> 0 votes
I can't find a way to simply set a uint to a shader constant variable. But the following is a workaround :

```
uint[] gBlendValue = new uint[1]{0x00ffff00}; // this is the packed blendweights
DataStream data = new DataStream(gBlendValue, true, true);
Terrain.Effect.GetVariableByName("gBlendValue").SetRawValue(data, 4);

```

If anyone knows how to set a uint to the shader that would be useful. Though now that I know the 'unpacking' works ok, I'll be passing in the blendweights via a Texture2D.

---
Tags: hlsl, directx11, slimdx
---


# Question
Title: What is the point of this hard-coded vector when calculating luminance in glow/bloom effects?
I have looked at two different vertex shaders that calculate luminance and both use a "magic" vector that I'm not sure the meaning of the the actual values. For instance:

```
const mediump vec3 Perception = vec3(0.299, 0.587, 0.114);

void main(void)
{
    mediump vec3 color = texture2D(Sampler, TextureCoord).xyz;
    mediump float luminance = dot(Perception, color);
    gl_FragColor = (luminance > Threshold) ? vec4(color, 1) : vec4(0);
}

```

This was taken from the iPhone 3D programming book.

This perception vector is the magic vector I'm trying to figure out. I added the rgb/xyz values and the add to 1.

I saw another example that used vec3( 0.2125, 0.7154, 0.0721), which also adds to 1.

Can someone explain how one comes up with these values and what they really mean?

# Answer
> 11 votes
When you want to obtain the relative luminance from a RGB color, you are mapping the three values to a single grayscale one. This is achieved by multiplying each of the components by a constant and adding them together, so the final result is in the 0-1 range. That's why the two vectors you found so far are added to 1, because applying the operation to pure white (`vec3(1, 1, 1)`) will return 1.

The logic behind having a higher green and red components is because the photoreceptor cones in your eye's retina are more sensitive to these components than blue; a little variation of green color (the most sensitive one) can dramatically change the perception of the total luminance perceived by your eye.

And I would stick with the `vec3(0.2126, 0.7152, 0.0722)` values, since they are the ones used for sRGB color spaces. The first example you posted corresponds to the YCbCr color encoding, and it can cause incorrect results in your calculations.

---
Tags: mathematics, shaders
---


title: Rotation based on movement

text:
# Question
Title: Rotation based on movement
How can i calculate angle based on movement in C# XNA when i'm moving object with accelerometer? If object is moving up, sprite would rotate in corresponding direction. Should i use two vector coordinates(old, new) to calculate angle using Atan2?

# Answer
Short answer: **Yes**.

Slightly longer answer: Maybe you want to add the accelerometer input to the objects velocity variable, so that there are no very sudden movement changes, when the accelerometer fluctuates. Then you would use the current velocity to calculate the objects angle (still using `atan2`).
> 1 votes

---
Tags: xna
---


# Question
Title: How should I add level-specific gameplay code to a level?
What are best practices to add gameplay, to specific level? I have some event types, and my game logic now looks like. OnEnterSensor is virtual and is different for each level(01,02 ...). Game type platformer and what about other types of games and their logic description.

```
    virtual bool OnEnterSensor( Entity* sensor, EventArgs* args )
    {
      if (str_equal(sensor->Name(), "button_sensor"))
      {
        door_closed = false;//door_closed internal level variable
      }
      else if (str_equal(sensor->Name(), "door_sensor")) ........ and so on.
    }

```

Is it good practice to use such kind of code. I'm not sure about this long IF construction when level logic is complex then it becomes large, and hard to read. Will be glad to hear any recommendations (maybe some in-level events) and other methods to describe level gameplay.

# Answer
> 3 votes
The data you loaded and parsed can be accessed just as you've indicated, using standard conditional logic. If you're looking for conciseness, there are other ways to do conditional logic:

* `switch` keyword is one (found in most imperative-style languages), while the `?:` operators are another. Neither is much more elegant than `if`, except for small sets of conditionals.
* There is a more elegant way that takes two forms: function pointers (also known as "functors" or in C#, "delegates"), or the structural equivalent frequently used in OO languages, the Strategy Pattern.

Function pointers are simple:

```
foo()
{
   //do something
}

boo()
{
   //do something totally different
}

run(bool a)
{
   function myFunc;
   if (a)
      myFunc = boo;
   else
      myFunc = foo;

   myFunc(); //we use this in place of an if statement + resultant logic. It's a "strategy" that's been assigned based on the value of something else.
}

```

The Strategy Pattern is really just a way to package up the same mechanism into classes, where one or another problem with the language makes it hard or impossible to do the assignment and/or direct function call on `myFunc`, above. It's purpose is "to allow an algorithm to be selected at runtime". The "algorithm", in this case, is exactly what you have between the braces of your `if` statements. As for nesting, yes you can use function pointers within calls to other pointed-to-functions. Same goes for Strategy Pattern, it can operate at many different, nested levels.

**As an aside...**

You have two choices at the higher level as to *when* to handle changes to the game world:

* What you're doing above, which is to respond to events
* Polling: On every game update, you simply re-run all of the logic that looks at the level data (as you're doing above) and makes changes to your game's data model as a result.

---
Tags: levels, game-design
---


# Question
Title: Shader issues when creating projection using CreateOrthographicOffCenter instead of CreateOrthographic
**Pre.** Having these matrix transformations:

```
var scale = Matrix.CreateScale(50f);
var eye = new Vector3(0, 0, 10.0f);
var view = Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up);
var projection = scale * Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 1.0f, 1000f);
var rotation = Matrix.CreateRotationX(-MathHelper.PiOver2)*Matrix.CreateRotationY(MathHelper.PiOver2);

```

and then for each mesh producing “world” like this:

```
var localWorld = transforms[mesh.ParentBone.Index] * rotation;

```

and then applying these parameters to the effect:

```
effect.Parameters["World"].SetValue(localWorld);
effect.Parameters["View"].SetValue(view);
effect.Parameters["Projection"].SetValue(projection);
effect.Parameters["Bones"].SetValue(boneTransforms);
effect.Parameters["WorldInverseTranspose"].SetValue(Matrix.Transpose(Matrix.Invert(localWorld)));

```

I’m getting nice model like this:

**Post.** But after I changed **CreateOrthographic** to **CreateOrthographicOffCenter** like this:

```
var projection = scale * Matrix.CreateOrthographicOffCenter(-GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Height / 2f, -GraphicsDevice.Viewport.Height / 2f, 1.0f, 1000f);
var rotation = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationY(-MathHelper.PiOver2);

```

I’ve got this:

Can someone give me a hint what am I doing wrong?

# Answer
Found an error.

```
Matrix.CreateOrthographicOffCenter(-GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Height / 2f, -GraphicsDevice.Viewport.Height / 2f, 1.0f, 1000f);

```

That’s not the same as

```
 Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 1.0f, 1000f);

```

CreateOrthographicOffCenter sets **M11** as *2f / (right - left)* and so we’re getting value equal to **GraphicsDevice.Viewport.Width**, but **M22** is set as *2f / (top - bottom)* resulting in height equal to **-GraphicsDevice.Viewport.Height**

Thus, correct setup for the **CreateOrthographicOffCenter** is

```
Matrix.CreateOrthographicOffCenter(-GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Width / 2f, -GraphicsDevice.Viewport.Height / 2f, GraphicsDevice.Viewport.Height / 2f, 1.0f, 1000f);

```
> 1 votes

---
Tags: xna, shaders, projection
---