# Question
Title: Mathematics behind Phong shading and additive blending
I'm confused about the mathematics behind additive blending used in conjunction with Phong shading. Intuitively, it seems like you would need to use a floating-point framebuffer and some sort of tone-mapping to achieve the actual approximation of many lights. Since the lighting values are computed as `diffuse + specular`, multiple lights can be encoded as:

```
finalColor = ambient
for light in lights:
  finalColor += light.specular + light.diffuse

```

Now, suppose you have multiple white lights shining on a perfectly diffuse, but mostly red sphere. The more lights you add, the closer the final rendered sphere should get to the actual color of the sphere. In this case, if you use an 8-bit RGBA framebuffer, then rendering with `glBlend(GL_ONE, GL_ONE)` will actually cause the sphere to reach a white color in the limit, similar to the effect outlined in this question.

My question is twofold:

1. Is my intuition here correct?
2. If so, how do you combat this situation? If not, why not?

# Answer
The problem isn't particularly with the additive math. Contributions from multiple light sources is resolved by addition. We can clearly see that in the rendering equation.

As we see in the equation light contributions is integrated over the unit hemisphere containing all possible values for all light directions(Wi). In real time computer graphics we only take into consideration the directions(Wi) that are directly connected to the lights and not taking into consideration the full hemisphere, hence this equation is converted into summation for all light contributions.

My point is: nothing wrong with the additive math. The problem is with the small dynamic range for 8-bit numbers. Representing sun light and light bulb as Color(1,1,1) doesn't particularly reflect real world radiance/luminance values. For this tone-mapping and other techniques were invented to be able to render high dynamic range images and map it to the limited range of a 32bit frame buffer.
> 3 votes

# Answer
I dont think that would happen, i havent use it how ever, but if u think about it, you are multiplying the light contribution with the object color as the equation you provide

```
finalColor = ambient
for light in lights:
  finalColor += light.specular + light.diffuse
finalColor *= objectColor;

```

and even in real live if you have a very shiny object like car chasis after waxing it if you sees it then it would look white, so you just have to mix the setting to match your needs, one hint what you are doing now called Forward Rendering, gool luck :).

.
> 0 votes

# Answer
The final color in Phong model depends on glossiness and specular reflectance of the material. If glossiness is very high or specular reflectance is low then the final color approaches albedo of the sphere. Otherwise the color approaches light color.

If you render in low dynamic range (LDR) though you may get color saturation and unexpected results, e.g. adding reddish color like rgb=\[1, 0.5, 0.5\] will result white because rgb components are clamped to range \[0, 1\]. With HDR you get values beyond that range and they are remapped with global tonemapping operator to LDR \[0, 1\] range to be displayed on regular monitors.

Some games used to render to LDR target but perform tonemapping in a shader before writing the results out to get around the more costly and memory heavy HDR rendertargets and blending. It had the obvious issue with blending though, e.g. transparent objects blended over the regular lighting weren't tonemapped and all lighting had to be done in one pass.
> 0 votes

---
Tags: 3d, lighting, shading
---


# Question
Title: XNA tiling a sprite with a camera.viewmatrix in the Draw method
I'm looking for help fixing a small problem that I have with my XNA game project.

I currently have:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
            null, null, null, null, camera.ViewMatrix);
        spriteBatch.Draw(Stone, TestPosition, Color.White);
        spriteBatch.Draw(Person, playerPosition, Color.White);
        spriteBatch.End();

```

and

```
spriteBatch.Begin(SpriteSortMode.Deferred,
              null, SamplerState.LinearWrap, null, null);
        spriteBatch.Draw(Grass, grassPosition,
             new Rectangle(0, 0, Grass.Width * 60, Grass.Height * 1),
             Color.White);
        spriteBatch.Draw(Stone, StonePosition,
             new Rectangle(0, 0, Stone.Width * 60, Stone.Height * 10),
             Color.White);

        spriteBatch.End();

```

I am looking to combine these two spriteBatch so that the stone and grass in the second spriteBatch will be affected by the viewmatrix.

I have tried:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
                SamplerState.LinearWrap, null, null, null, camera.ViewMatrix);
            spriteBatch.Draw(Grass, grassPosition,
                 new Rectangle(0, 0, Grass.Width * 60, Grass.Height * 1),
                 Color.White);
            spriteBatch.Draw(Stone, StonePosition,
                 new Rectangle(0, 0, Stone.Width * 60, Stone.Height * 10),
                 Color.White);
            spriteBatch.Draw(Stone, TestPosition, Color.White);
            spriteBatch.Draw(Person, playerPosition, Color.White);
            spriteBatch.End();

```

However when I go to run the code, I get the following error:

XNA Framework Reach profile requires TextureAddressMode to be Clamp when using texture sizes that are not powers of two.

I hope that someone can help me achieve this, Thank You.

# Answer
> 1 votes
The error indicates that if you are using textures that are not powers of 2 (128x128, 256x256, etc), that you must set the `SamplerState` parameter of `SpriteBatch.Begin` to `SamplerState.LinearClamp` instead of `SamplerState.LinearWrap`.

Judging from your code it looks like `Grass` and `Stone` are powers of 2, but the `Person` is not.

To fix the problem you'll need to either change the `Person` texture to a power of two, use `SamplerState.LinearClamp` for everything you listed, or draw the `Person` texture with its own `SpriteBatch.Begin` and `End` using `Sampler.LinearClamp` and the rest that are powers of two using `LinearWrap`.

---
Tags: xna, c#, game-design, software-engineering
---


# Question
Title: Collision detection across multiple components
I have been reading this article: http://gameprogrammingpatterns.com/component.html which describes how a game object should be constructed out of components. It also encourages the decoupling of components, which brings up a problem with input, collision detection, and things that cause events to be triggered.

If I have a game object, which is a player and this player has 3 components; PlayerSoundManager, PlayerCollisionDetection, and PlayerStateManager, how would I go about making sure they have no references to each other? If PlayerCollisionDetection detects that a player should die, messages should be sent to the other two components telling the player to play a death sound, and change it's state.

Would it be wrong to put collision detection methods throughout all components and perform each reaction separately?

# Answer
No, but it will just be bad manners to write the same thing in every scripts and it can be a pain to debug if you have lots of function of collision detection in a lot of other scripts.

You can use the method `SendMessage()` to communicate between scripts (or inside a script). You can read its documentation here

e.g

```
if(player.health == 0){
  gameObject.SendMessage(playerStateManager.changeState, 'dead');
  //where playerStateManager is a reference to your class PlayerStateManager
  gameObject.SendMessage(playerSoundManager.play, 'deathSound');
  //where playerSoundManageris a reference to your class PlayerSoundManager
}

```
> 2 votes

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


title: Animation-based Collision Boxes

text:
# Question
Title: Animation-based Collision Boxes
### Background

I'm currently working on a top-down 2D game, roughly similar to something like Zelda for the SNES.

Certain game entities such as the player or a typical enemy will consist of multiple collision boxes. For example:

1. The **main** collision box which determines collisions with the map (i.e. walls). It also determines where the entity can be hurt.
2. The **attack** collision box which, if overlapping a main collision box, causes the owner of that collision box to take damage.

The attack collision box should only be active when the entity is actually attacking.

### One Solution

The first potential solution that comes to mind is the one used in fighting games where every frame of animation has its own set of collision boxes. This can obviously work, but it feels like it may be too over-engineered for what I need.

### The Actual Question

Other than the solution above, is there a standard or common approach for attack collision boxes? Or is having collision boxes tied to animation the standard way of doing things?

I would like to emphasize the term "standard". It would be great to know how games like The Legend of Zelda, Secret of Mana, and Castlevania handle it.

# Answer
> 1 votes
I wouldn't use any permanent collision box that's moved around or anything similar.

Instead, just play the attack animation and pick one specific frame where you're looking for collisions inside a specific area.

Since I assume the overall attack animation will be rather short/fast, there shouldn't be any way to notice any difference.

For example, the Gameboy Zeldas had like 3 frames for their sword attacks, which is all you need. If you're going for those three frames (sword horizontal, sword diagonal, sword vertical), do the collision check in the second frame and you should be fine. Once the sword is pulled, you can use another simple rectangle that's active while the sword is out.

I've tried to mark the area where I think they collide (or you could do your own checks) in red:

You don't need any more complex collision boxes or collision shapes, unless you're doing it very high res, but even then it's most likely hardly noticeable. Keep in mind that the games you've mentioned all worked on classic systems that had only a limited amount of computation power, so pretty much all of them will only utilize simple collision shapes and only in some very rare examples (like brawlers) anything more complex.

I'm not 100% sure how the actual games implemented their collisions, but at least for the Zelda games I'm sure you've got two or three different rectangles (the first frame might not have one, never bothered testing).

In a similar way, the classic Castlevania games only used two rectangles during the attack animation (first behind the player while swinging the whip, then one in front for the actual attack).

It's been a while since I've played secret of mana, but again I'm rather sure they just use simple rectangles for this, nothing complex. This is obvious with longer range weapons like the spear or whip: You're often able to hit enemies despite there being no clear collision between the graphics and the enemies.

---
Tags: 2d, collision-detection, animation, state
---


title: Strange quaternion rotation

text:
# Question
Title: Strange quaternion rotation
I was implementing some quaternion rotations in too my infant 3d game engine and the rotations were really strange? Excuses my cluelessness.

Anyways this is what I have:

```
static XMVECTOR XMConvertToQuaternion(XMFLOAT3 axis, float radian)
{
    axis = XMNormalize3(axis);
    XMVECTOR tempAxis = XMVectorSet(axis.x, axis.y, axis.z, 1);
    XMVECTOR q = XMQuaternionRotationAxis(tempAxis, radian);
    return q;
}

```

Then later on down when I apply the quaternion to the world matrix I have:

```
XMMATRIX scaling = XMMatrixScaling(scale.x, scale.y, scale.z);
XMMATRIX rotateX = XMMatrixRotationX(radianRotation.x);
XMMATRIX rotateY = XMMatrixRotationY(radianRotation.y);
XMMATRIX rotateZ = XMMatrixRotationZ(radianRotation.z);

XMMATRIX rotateQX = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.x));
XMMATRIX rotateQY = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.y));
XMMATRIX rotateQZ = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.z));
XMMATRIX translate = XMMatrixTranslation(translation.x, translation.y, translation.z);
XMStoreFloat4x4(&mWorld, scaling*rotateQX*rotateQY*rotateQZ*translate);

```

I did get a rotation. However, the character is rotating very strangely.

# Answer
the way to create your Quaternion rotations matrices (I assume from euler angles) look funny, I would expect you use unit vectors of each axis rather than `axis`

```
XMMATRIX rotateQX = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(XMFLOAT3(1, 0, 0), radianRotation.x));
XMMATRIX rotateQY = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(XMFLOAT3(0, 1, 0), radianRotation.y));
XMMATRIX rotateQZ = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(XMFLOAT3(0, 0, 1), radianRotation.z));

```
> 0 votes

# Answer
On this line:

```
XMStoreFloat4x4(&mWorld, scaling*rotateQX*rotateQY*rotateQZ*translate);

```

does changing the order to:

```
XMStoreFloat4x4(&mWorld, translate*rotateQX*rotateQY*rotateQZ*scaling);

```

make a difference? If you meant to rotate about the origin then translate outwards then you need to be careful with your ordering, though I'm making assumptions about the XM library.
> 0 votes

---
Tags: c++, directx, rotation, quaternion
---


title: Input processing performance

text:
# Question
Title: Input processing performance
I'm building a game using SDL in Linux platform.

Now I want to read user input with `SDL_GetKeyboardState`, but my doubt is wich is the best way using a thread or a timer.

I tried both and I think they work well.

# Answer
> 0 votes
If you have uncapped FPS, it should eat 100% of your CPU, but most probably you want cap FPS at some reasonable value, say 60 fps, basic implementation can be as follows:

```
const unsigned int FPS = 60;
const unsigned int DELAY_TIME = 1000 / FPS;
unsigned int frameStart, frameTime;
int spareTime;

// your main loop
while (bRunning) {
    frameStart = SDL_GetTicks();

    // do your stuff

    frameTime = SDL_GetTicks() - frameStart;
    spareTime = DELAY_TIME - frameTime;
    if (spareTime > 0) {
        SDL_Delay((unsigned int)spareTime);
    }
}

```

---
Tags: sdl, game-loop, linux
---


# Question
Title: Why does my vertex shader produce no output until I add some arbitrary value to the position attribute?
I want to draw a textured quad but there is nothing drawn and the setup should be right. This is my vertex shader:

```
#version 330

in vec2 position;
in vec2 texel;

out vec2 texCoord;

void main() {
    texCoord = texel;
    gl_Position = vec4(position, 0.0, 1.0);
}

```

This code is producing no output on screen. Now comes the crazy stuff. If I add the following,

```
#version 330

in vec2 position;
in vec2 texel;
in vec2 foo;

out vec2 texCoord;

void main() {
    texCoord = texel;
    gl_Position = vec4(position + foo, 0.0, 1.0);
}

```

everything is as it should be.

I am pretty sure that my setup is correct. I have checked the values of the vertex attributes by passing them as texCoord instead of the uv coordinates, and assigning them to my fragment color output in the fragment shader. In both cases this produces the expected color gradient. The extra uninitialized attribute foo must be zero, because its rendered as the vertex color.

So the thing is, nothing is drawn unless I add an vertex attribute to position. It doesn't matter if I add texel or the mysterious, uninitialized vertex attribute. The output is the same.

**update:**

```
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), sizeof(glm::vec2);

```

This is my vertex struct:

```
struct Vertex {
    glm::vec3 pos;
    glm::vec2 tex;
    glm::vec3 normal;
    Vertex(const glm::vec3& _pos,const glm::vec2& _tex,const glm::vec3& _normal):
    pos(_pos),tex(_tex),normal(_normal){}
    Vertex(const Vertex&)=default;
    Vertex& operator=(const Vertex&)=default;
};

```

The buffer is correct. I have mapped the vertex buffer and put it on the standard output. All numbers are correct.

# Answer
Your shader, vertex structure, and `glVertexAttribPointer` calls *do not* agree. This tends to cause unusual behavior because you're mapping unexpected values to the GPU pipeline.

Your vertex structure says you have a 3-vector for position, a 2-vector for for texture coordinates, and a 3-vector for the normal (a total of eight floats per vertex).

Your `glVertexAttribPointer` calls say that attribute 0 is nonexistant (which means it defaults to a four-component float that is tightly-packed; this is obviously very wrong in your case). It also says that attribute 1 is a 2-vector (okay) and that attribute 2 is a 2-vector (but your structure has a 3-vector). I'm unclear what exactly the result of saying attribute 0 is tightly-packed but the other two aren't is, in this case, but almost certainly it's going to lead you to getting totally bogus values in the shader by the time it gets run.

Your shader takes 2-vectors for everything, which agrees with neither your `Vertex` structure *or* what you've mapped to the pipeline via `glVertexAttribPointer`. Even if you ignore the problems you have with your attribute mapping, this would smear the values of your vertex buffer into various mismatched components of your shader inputs depending on how far along in the stream you were reading (because the stride of a vertex defined in the shader is six floats and the size of one in the buffer is eight).

You should make all three of those agree. If you choose to do so based on the `Vertex` structure, that might mean:

```
// in your shader:
in vec3 position;
in vec2 texel;
in vec3 normal;

// in your C++ code:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(glm::vec3));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(glm::vec3) + sizeof(vec2));

```
> 2 votes

---
Tags: opengl, sprites, glsl
---


# Question
Title: How to detect collision between two directed object?
I'm currently writing a game which is like Battle City game. But right now I'm facing a trouble involved to checking collision between two objects. This is the code that I wrote:

```
//-------------------------------------------------------------------------------------------
//  check collision between a tank and another object
//
bool GameController::checkTankMeetsObject(Tank tank, GameObject ob)
{
    int obX = ob.getCoord().getX();
    int obY = ob.getCoord().getY();

    // calculate area of obstacle: bottom left (X1, Y1), top right (X2, Y2)
    int obX1 = obX - SQUARESIZE / 2;
    int obX2 = obX + SQUARESIZE / 2;
    int obY1 = obY - SQUARESIZE / 2;
    int obY2 = obY + SQUARESIZE / 2;

    int tankX = tank.getCoord().getX();
    int tankY = tank.getCoord().getY();

    switch (tank.getDir())
    {
    case UP:
        if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
            (tankY + SQUARESIZE / 2 > obY1 && tankY + SQUARESIZE / 2 < obY2))
            return true;
        break;

    case DOWN:
        if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
            (tankY - SQUARESIZE / 2 > obY1 && tankY - SQUARESIZE / 2 < obY2))
            return true;
        break;

    case LEFT:
        if ((tankX - SQUARESIZE / 2 < obX2 && tankX - SQUARESIZE / 2 > obX1) &&
            (tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))
            return true;
        break;

    case RIGHT:
        if ((tankX + SQUARESIZE / 2 < obX2 && tankX + SQUARESIZE / 2 > obX1) &&
            (tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))
            return true;
        break;
    }

    return false;
}

```

This code does well with normal circumstance, but in special ones like which I describe below, it doesn't work.

The white squares are obstacles and the grey square is the tank. Current direction of the tank is RIGHT. In this situation, I can not move the tank RIGHT or LEFT, only direction I can go is DOWN. Is there any solution to optimize my code?

# Answer
> 1 votes
Give your tank a Property that Tracks where its Bounds are. Give all other objects a Bounds as well. Check against the two rectangles to see if they are binding.

```
Rectangle rect1 = new Rectangle(x,y,width,height);
Rectangle rect2 = new Rectangle(x,y,width,height);

```

x and y would be your sprites location in the world (Vector2.X and Vector2.Y) Width and Height would be the width and height of the sprites rectangle

```
//Trap movement before you allow them to bind

GameTime gameTime = this.GameTime;

//Set a velocity based on gametime passed
Vector2 velocity = (150,0);
Vector2 velocityup = (0,150);

//lets say rect1 is your tank
//lets also assume for now that we are moving up x=x y--
//rect1.x += (float)(gameTime.EllapsedGameTime.MilleSeconds * velocity);
rect1.y -= (float)(gameTime.EllapsedGameTime.MilleSeconds * velocityup);

//rect1 now is the position at which our tank would be in a non collision scenario
//so we will check to see if that position would indeed collide with something

if (rect1.Intersects(rect2){

    //we collide
    //dont allow the tank to move in this direction

}

```

I think the problem you are having is that your measurement of movement is not fine enough, and that you allow the movement first, and then check to prevent it, whereas in this manner you first check, then move.

By using Vector 2's and gametime, we know exactly where our object are, and can trap for the finest of movements. Let me know if you still have some issues here, I know this explanation wasn't the best, but I am new as well so apologies ahead of time man.

# Answer
> 0 votes
Your answer to the collision problem is true/false. Instead you can differentiate between no collision, penetration of the object and touching the object. Then only disallow movement in the case of penetration, but allow touching.

I'd also suggest you move the collision code out of your tank and GameObject. Tanks and GameObjects both really just contain a collection of collision shapes. Your collision code doesn't care about anything but the shapes (perhaps also their old position, rotation, movement direction and speed).

You don't want to write new collision code every time you add a new kind of actor. This is basically composition versus inheritance at work.

---
Tags: c++, game-loop
---


# Question
Title: How can I create a stretchy, breakable pizza cheese material?
I want to create realistic pizza and allow user interact with it.

What I want:

What I created:

I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle".

How can I make the cheese stretch and break when the user moves a piece?

# Answer
> 28 votes
## The Simple Way

Add a quad which connects adjacent slices to each other. Texture this with a nice, melted cheese texture, complete with holes. As the slice is moved away the quad will naturally be stretched and thus stretch and skew the texture.

This should look reasonable, although there will be no break. What to do here is make that texture an animated one. Iterate through the animation based on the quads area (or just the distance between the slices) instead of time. As it gets pulled further away more holes will appear due to the animation progressing.

Eventually when a distance threshold is hit, split the quad into two, programatically shrink the two quads in the direction of their attached slices to shrink them a bit and keep the animation playing which shows the snapping. Freeze the animation at the end.

For a bit more dynamics, you could attach the quad to the two slices using a joint in a physics engine.

## The Hard Way

Use a soft-body physics engine or write one. Define a cloth section between the slices and texture it with cheese. Allow the physics engine to model the dynamics of the material stretching and snapping.

This is a far more intensive, but more generally applicable method. It may also be very uncontrollable but could be an overall more compelling effect.

# Answer
> 2 votes
@originalDaemon's answers are good! I think there is a middle way that *may* get better result than the first approach and will take a reasonable amount of effort (perhaps unlike "The Hard Way" approach).

What I suggest is too actually model the cheese "web", it looks a lot like stalactites to me. Model a few pieces of stretchy cheese. Randomly position them on the edges of the triangle of deliciousness and scale them to 0 on `y-axis` and when the triangle is removed from its compadres, slow scale them on y-axis back to the needed size.

You may need to choose another axis instead of `y` if you plan to pull the triangle slightly away. Either way, I feel that although a flat texture would be a lot easier and cost-effective, modeling the cheese could turn out more realistic for close-up although a texture might work too. If you do choose a texture, maybe use more than one layer to get a more realistic feel. Also don't forget to add a little steam perhaps to emphasize the hotness of the pizza in the shot.

Another thing I noticed is that it appears the pepperoni is only a texture right now. I would definite consider modeling it or adding some detail in that area to the existing model. You could makes it slide down with the stretchy cheese for extra realism.

# Answer
> 2 votes
**Using a preset animation:**

So create preset animation in a 3D modelling software like Maya/Blender which has features like soft bodies and cloth that can do a good job simulating the pizza tearing. Export both the pizza texture AND the model animation to Unity (probably as a set of .obj models or some such).

The model animation will represent the cheese being stretched and torn using many many triangles, which you can load as a set of tri-meshes into Unity. They are collection of many mesh states, each representing the cheese pizza at different positions of stretching. Based on where the user positions the pizza slice, you'll jump to that 'mesh state' and display those triangles.

There're a few problems of-course. The user interaction is a bit restricted. If cheese is already torn a bit, you can't go back to 'untorn' state for that area of cheese. If the preset animation removes slice 1 and then 2, the user will be forced to remove the slices in that order. The size of data exported can become pretty big, based on how granular the mesh is and how long the tearing animation lasts.

But it can look very realistic, if the model artist does a good job when creating the preset animation. And you don't have to implement a soft-body simulator.

**Using Unity:**

But in-case you're interested Unity does implement its own Skinned cloth and Interactive cloth components. The interactive cloth supports tearing. But support for them are restricted to only a few platforms, last I checked.

**Using you:**

In the end, you can always implement your own soft-body simulator. Here's a sample research paper that's pretty popular. It is a lot of fun :). Good luck.

---
Tags: unity, 3d, physics, blender, soft-body-dynamics
---


# Question
Title: Trigger an event when a game object touches a non-solid game object
For a 2d game, I are currently making an AI and I want it to jump when it touches a invisible cube, which isn't solid, how do I do this?

# Answer
* **Invisible**: Don't add any components that render to the screen, i.e. mesh renderer, sprite renderer, line renderer, etc.
* **Collidable**: Add a physics collider to the object and set the bounds how you like.
* **Non-solid**: Make the collider a trigger. Triggers will trigger a collision event, but won't have a collision response, essentially making them non-solid objects.

Add your trigger code to the `OnTriggerEnter` method in your script. This method is called when the trigger is first touched by another game object's collider.
> 1 votes

---
Tags: 2d, unity, physics
---


title: Sending POST data with WWW in Unity C#

text:
# Question
Title: Sending POST data with WWW in Unity C#
I would like to use Unity's WWW class to send a an HTTP request with POST data. So in my server, my PHP script can do something like

```
$number = $_POST["NUMBER"];

```

According to http://docs.unity3d.com/ScriptReference/WWW-ctor.html, I can provide a byte array in the constructor to represent such data.

I'm a bit puzzled - suppose I want to send a mapping from "NUMBER" to `200` \- how would I create a byte array compatible with my PHP script in Unity C#?

# Answer
> 2 votes
Actually using the overloaded construct that take a WWWForm as second parameter, WWW class is automatically considered as an http post request.

Your code can be something like:

```
WWWForm form = new WWWForm();
form.AddField( "NUMBER", aNumber );

WWW postRequest = new WWW( server_url, form );

```

---
Tags: c#, unity, php, http
---


# Question
Title: Explaining vector math for a pendulum camera
I came across a code that I guess is doing a pendulum camera, that's the class name. I would like to know the math behind that. I would like also to know how to decipher those stuff in game math, what are your recommendations ? I already own the book 3D Math for computer graphics by lengyel, but those stuff are not explained there.

```
        Vector3 r = transform.right;
        Vector3 u = transform.up;
        Vector3 v = transform.forward;

        Vector3 dir = v + u * Mathf.Sin(Time.deltaTime * 0.01f)  + r * Mathf.Sin(Time.deltaTime *0.01f + 0.1f) * -0.1f;
        dir.Normalize();

        Quaternion rotation = Quaternion.identity;
        rotation.SetLookRotation(dir, Vector3.up);
        transform.rotation = rotation;

```

# Answer
> 4 votes
The three component vectors `right`, `up`, and `forward` probably point along the axes `x`, `y`, and `z` relative to the camera. So by adding these vectors together you can compose any other vector. It works the same as if you built a vector by specifying its three elements individually, except that you are adding three vectors which each have one non-zero element. Normlizing that sum guarantees that the total length of the sum is a vector of length 1.

If `Time.deltatime` is the time since last update then, except for small variations, `dir` will be not vary from frame to frame. It's essentially taking the sine and cosine of constant values, which yields a constant camera direction. If that time value were accumulated rather than constant, then this would yield a circular motion of the camera. On the x-y plane, the `x` and `y` coordinates could be specified by taking the sine and cosine of a single angle. Your code sample appears to be doing that, using `Time.deltatime` as its angle (but I think it's doing it wrongly, as it's essentially constant each frame).

This picture is loosely related, please ignore the complex part; I was just trying to find an animation of the unit circle.

# Answer
> 1 votes
He's trying to oscillate between `V` and `V+U*0.01+R*0.1`, I think. If you want to visualize, it is trying to do something like the picture below:

The arrow at the top represents the path `DIR` will take as time proceeds and it will go back to `V` when the `sin` value becomes zero. The summation, just adds the 'perturb' effect to the `DIR` vector, so that it doesn't always end up as `V`.

---
Tags: unity, mathematics, vector, quaternion
---


title: Using SVN with Libgdx

text:
# Question
Title: Using SVN with Libgdx
I decided to give LibGDX a try and am planning to use SVN for my code repository. I created my LibGDX project via the Gradle build as outlined in the book "Learning LibGDX Game Development". I'm not quite sure how to add the project to my repository. I have tried to upload the root folder (Project below) into svn, which does contain all the sub-project, but when I check out my workspace only contains the Project folder.

Below is the structure of the project in Eclipse after the gradle build.

1. Project
2. Project-android
3. Project-core
4. Project-desktop
5. Project-html
6. Project-ios

After checking out from svn

1. Project

Has anyone used SVN with LibGDX, if yes can you please guide on how to add a project to repo and checkout correctly?

# Answer
I figured it out, hope this helps someone someday :)

1. Using the normal LibGDX approach, create a project using File -\> Import -\> Gradle (gradle build).
2. Highlight all of the project folders and right click -\> team -\> share project
3. Note: SVN does not support adding multiple folders at once, make sure to click 'Share Project' option.
4. Enter repo URL: (I just clicked Next)
5. Enter folder name: (I used 'Use project name as folder name')
6. Click finish
7. Repeat for each project folder

Disclaimer: I'm not sure if this is the best way to do this but it accomplished what I am trying to do.
> 4 votes

---
Tags: libgdx
---


# Question
Title: How can I use an unsigned int as a GLSL attribute for OpenGL ES 2
I'm having trouble finding conclusive information on this, but it seems like I can't pass integer attributes to GLSL for OpenGL ES or that if I do they'll be converted to float. I need a value between the range \[0-65535\] for each vertex. If I pass it as a float and then convert it back, I'm concerned that the value will have changed (if the precision is low enough and can't suitably represent values at the higher magnitudes).

Its also confusing trying to figure out what precision for floats the OpenGL ES 2 standard requires. It seems like the minimum requirement is 16-bit (ie some implementations will use 16-bit floats for highp variables). In this case, it would seem like the floating point number wouldn't be able to store enough information for 0-65535 since that's what a 16-bit unsigned int holds.

So, formally, how can I specify a vertex attribute that will let me precisely represent the values 0-65535 in OpenGL ES 2.

# Answer
> 5 votes
Programming in GLESSL is a bit different than programming for a normal CPU.

Since you're using OpenGLES 2, I will assume you are using GLESSL 1.0. So I will be pulling quotes from its documentation.

In general, GLESSL offers you a variety of types as programming aids, with some guarantees regarding their behavior, but leaves the actual low level implementation details to the manufacturer of a specific GPU.

GLESSL is not a low level programming language (like C), and as such, talking about bit representations in GLESSL is mostly meaningless.

According to section 4.5.1 of the documentation:

> The vertex language must provide an integer precision of at least 16 bits, plus a sign bit.

That means that for the vertex shader, you can safely use values from -65536 to 65536 with a `highp int`, something which is repeated in table 2 of section 4.5.2.

This may sound strange if you're accustomed to thinking of 16 bit `int`s being able to represent values between -32768 and 35767. GLESSL does not specify how `int`s are to be represented internally, just that they **must** provide enough precision for numbers between -65536 and 65536, which should be enough for your purposes.

In fact, as section 4.1.3 implies, `int`s are meant to be programming aids, and there is no guarantee that the underlying representation must be a hardware integer. In most cases, all operations will be performed on hardware floats (probably 32-bit, even for `lowp`), but GPUs are free to implement them any way they like, even as textual representations in Swedish using EBCDIC.

In practical terms, in the vertex shader, you can use `int` (`highp` is implied, as per section 10.3), and you are guaranteed to be able to store values from -65536 to 65536. Also, you can use `float` and have at least 16 bits of precision (plus one bit sign) for any given exponenent within range, which means that you can also use `float` for your purposes. This is also clarified in section 4.5.2:

> a `highp int` can be represented by a `highp float`.

I would recommend you take `float`s, and pass `float`s from your program, since it is very likely that any given GPU uses `float`s to represent `int`s. If you pass `int`s, it is very likely that a costly conversion will take place.

Also, there is `glGetShaderPrecisionFormat` if you want to know the exact precision of a given type in a given GPU. I would rather rely on the guarantees given by the standard.

As far as I know, precision qualifiers are more about bandwidth than actual calculations. Mobile GPUs are very limited in terms of bandwidth, and specifying that you can live with `lowp` on a particular `varying` variable, may allow the GPU to perform better packing strategies and give you better performance than if you specify you require `highp`.

# Answer
> 3 votes
I'm answering based on my OpenGL non-ES knowledge, which I hope works on ES as well.

It sounds like you want to use `GLushort` in your C code, referred to as `GL_UNSIGNED_SHORT` when passing the data to OpenGL in C, and then use type `int` or `uint` in GLSL.

One gotcha is to use the function `VertexAttribIPointer` instead of `VertexAttribPointer` when sending the data to OpenGL; the difference is that you want to include the letter `I` (for integer) before the word `Pointer`.

Based on this list of GLSL data types, I don't think GLSL explicitly has a 16-bit integer type, but it has 32-bit types that should work fine.

See also:

---
Tags: opengl-es2
---


title: Point to coordinate function

text:
# Question
Title: Point to coordinate function
I am working on a game in which I need an enemy ship to point towards the player.

Here is the equation I came up with:

> angle = sin-1(abs(y1 \- y2)/√(x1 \- x2)2-(y1 \- y2)2)

This essentially takes the inverse sine of the opposite divided by the hypotenuse. Unfortunately, this algorithm does not work. **Any ideas as to what I need to change?** *Note, the angle is a radian value.*

# Answer
> 1 votes
atan2(y1-y2, x1-x2)
or maybe atan2(-(y1-y2), x1-x2), depending on the coordinate system.

---
Tags: algorithm, angles, trigonometry
---


title: Detecting mouse clicks in Unity UI Beta

text:
# Question
Title: Detecting mouse clicks in Unity UI Beta
I want my game script to detect mouse clicks everywhere on my screen, *except* one corner where I have a pair of buttons to control the sound and will be handled separately. To help identify this corner, I've created a `soundPanel` object with the `Rect Transform` component (available in the Unity 4 Beta 17+) and have sized/positioned it appropriately in the editor in my UI layer.

In my game's script, I have passed in this corner object, and tried using it in the following way:

```
bool tap = (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
           && !soundPanel.rect.Contains(Input.mousePosition);

```

Clicking in the soundPanel still triggers a tap. I figured this is because the mouse position and `soundPanel.Rect` are not in the same coordinate space. Since the documentation on the new Unity Beta UI is a bit lacking / hard to find, I tried converting the mouse coordinates to everything I could:

```
if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
{
    if (soundPanel.rect.Contains(Input.mousePosition)) { print("Raw"); }
    if (soundPanel.rect.Contains(camera.ScreenToViewportPoint(Input.mousePosition))) { print("ScreenToViewportPoint"); }
    if (soundPanel.rect.Contains(camera.ScreenToWorldPoint(Input.mousePosition))) { print("ScreenToWorldPoint"); }
    if (soundPanel.rect.Contains(camera.ViewportToScreenPoint(Input.mousePosition))) { print("ViewportToScreenPoint"); }
    if (soundPanel.rect.Contains(camera.ViewportToWorldPoint(Input.mousePosition))) { print("ViewportToWorldPoint"); }
    if (soundPanel.rect.Contains(camera.WorldToScreenPoint(Input.mousePosition))) { print("WorldToScreenPoint"); }
    if (soundPanel.rect.Contains(camera.WorldToViewportPoint(Input.mousePosition))) { print("WorldToViewportPoint"); }
    print("-------------------");
}

```

When I click with the above code, "ScreenToViewportPoint" and "ScreenToWorldPoint" print no matter where I click, and no others trigger. I suspect I need to transform the soundPanel somehow.

Here is the Hierarchy, Scene, and Inspector. The selected rect is the soundPanel, and it is in the bottom-right of the UI Canvas:

# Answer
The easiest way I found to do this was as follows:

1. Make sure to configure your canvas to use screen space based on the camera. Drag and drop your camera into the render camera property
2. Detect if the rectangle contains the mouse coordinates using `RectTransformUtility.RectangleContainsScreenPoint()` method. Pass in your rectTransform object, the current mouse position (takes screen coordinates so raw Input.mousePosition works fine), and the main camera object.
3. To keep the UI position in sync with the camera, update the canvas position with a line similar to the following somewhere where it will execute after the camera position has been updated:

`canvas.transform.position = new Vector3(camera.transform.position.x, camera.transform.position.y, canvas.transform.position.z);`
> 3 votes

# Answer
I figured out how to detect pixel coordinates on a `RectTransform` by using the `transform` property to get the center of of the rect in pixel coordinates, then use `sizeDelta` to get the width and height, make a rect from that, then test it against the mouse coordinates.

```
Vector2 topLeft = (Vector2)soundPanel.transform.position - (soundPanel.sizeDelta / 2f);
Rect soundRect = new Rect(topLeft.x, topLeft.y, soundPanel.sizeDelta.x, soundPanel.sizeDelta.y);

bool tap = (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
           && !soundRect.Contains(Input.mousePosition);

```

I will say, it's not perfect. Something is still slightly off, but it's close enough for now.
> 1 votes

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


title: Texture R8_FLOAT format?

text:
# Question
Title: Texture R8_FLOAT format?
I'm working on SAO (http://graphics.cs.williams.edu/papers/SAOHPG12/) and I want to store my ambient obscurance term (a value between 0.0 and 1.0) in a texture.

When I did shadowmapping, I created my depth-texture as `DXGI_FORMAT_R32_TYPELESS` and the shader resoure view as `DXGI_FORMAT_R32_FLOAT`, however with this I want a `DXGI_FORMAT_R8_TYPELESS` format and a `FLOAT` equivalent, yet there appears to be none according to the docs (http://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx)

1) What texture/srv/rtv format should I use if I want to store/read/write 8-bit float values?

2) Does the format used really matter? Does directx do any behind-the-scenes alterations to the texture data? Is a `DXGI_FORMAT_R8_UNORM` treated differently from a `DXGI_FORMAT_R8_SNORM` for example?

# Answer
> 1 votes
The smallest single float supported by DirectX 11.x is `DXGI_FORMAT_R16_FLOAT` which requires Feature Level 10.0 or better hardware. The smallest single float supported by Feature Level 9.x is `DXGI_FORMAT_R32_FLOAT`.

If you can require Feature Level 10.0+ or better hardware, a better choice might be to use `DXGI_FORMAT_R11G11B10_FLOAT` or `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` if you can live with the limitations of those formats.

---
Tags: directx, directx11
---


# Question
Title: How can I improve the performance of handling many objects to draw in XNA?
I have a 2D engine that uses XNA 4.0. I have an issue with handling many objects. In my engine, I only draw visible sprites, and ignore sprites outside of the current viewport. It works, so far. I also use a `RenderTarget` to minimize the amount of sprite batch being called, to draw the base.

I also need to draw buildable objects, and the worst case is that there is a list with 10,000 - 20,000 objects. I need to iterate through them, to find the visible buildable objects, as well. This really affects my frame rate, especially when the viewport changes.

I could decrease the zoom level, to minimize the amount of base tiles, but the list of objects keeps the same. Using smaller texture sizes could help, but then I´m also losing detail.

How could I improve the performance?

# Answer
1) You don't need to calculate the visible objects in a single frame, you may use a bit bigger viewport, and calcultate only 500 objects per frame, if you have 20000 objects and your framerate is 50fps, in 40 frames you will have the right list, and it will take 0.8 secs

2) if your objects are not very complex or are static, sometimes is faster to put them in a vertexbuffer and draw all. letting to the gpu discard the no visible triangles... maybe you can use instancing if you use many repeated objects

3) you can use spatial division algorithms like quadtrees to discard sprites in spaces that are not visible

4) if you are using background tiles stored in an array is easy to calculate the visible array tile ofsets... and you can hook the dynamic sprites by its center to your background tiles, so when you render the background tile you know there are other sprites to render.
> 1 votes

# Answer
I'd highly suggest you look into implementing a Quadtree.

This would allow you to run a query to fetch all the objects in your viewport, as opposed to checking every single entity before a draw.

Have a look at the following sample query code:

```
List<Entity> entitiesOnScreen;
entitiesOnScreen = QuadTree.GetObjects(Viewport.Rectangle);

foreach (Entity entity in entitiesOnScreen)
    entity.Draw();

```

As you can see, this greatly simplifies your drawing calls. You ask the Quadtree for a list of objects contained in a Rectangle, which it quickly provides for you.

Then it is just a matter of looping through this list to draw what is on screen.
> 1 votes

# Answer
You would likely have to switch over to the 3D (lower level) rendering and then use instancing which offloads most of the work to the GPU.
> 0 votes

---
Tags: xna, 2d
---


# Question
Title: Where to put graphic representation of game entity?
I am working on simple 3D version of Snake game. I created classes like `snake` and `grid` so far. My concern is, putting all render logic (draws cubes - to show snake, and lines to show the grid) in above class could obscure the "pure" logic which should be divided from "view" layer.

So my question is, how to handle the whole render layer, separately from entity objects?

My current idea is to add object of "renderer" to each class which will encapsulate whole canvas work inside. There will be also `master-renderer` always looking for renderer inside all entities.

PS. I use JavaScript and Three.js

# Answer
That said, there is no golden rule for that kind of thing, but it will mainly affect your architecture.

I would suggest you to take a look at the component pattern (which is used by some game engines such as Unity). This pattern will allow you to to "attach" component on game entity. In your case you will have, for example, a `SnakeController` component in charge of the snake movement, a `SnakeDisplay` component in charge of displaying it on screen... etc etc.

Every component will be in charge of its own stuff. So, combined with other you will have a complete and clean logic.
> 2 votes

---
Tags: architecture, design-patterns
---


title: HDR and Alpha Blending

text:
# Question
Title: HDR and Alpha Blending
I've been reading a lot about HDR techniques and came across Alpha Blending compatibility. Searched even more and found this snippet from the Ogre Forums:

> With source alpha blending, it sometimes looks ok provided the range differences aren't too high, but most other blend modes fail completely, particularly add. You really have to do your own separate composition in another fragment shader targetting a second texture and pulling the 'background' values in so you can do accurate blending, rather than render the transparent effects into the same original surface.

Why is alpha blending an issue when it comes to rendering HDR (values above 1.0) in 16FP FrameBuffers?

# Answer
The source post says it all.

http://www.ogre3d.org/forums/viewtopic.php?f=5&t=41811

> Blending in *fake HDR* is tough, because the frame buffer blend cannot cater for **the *exponent* you're storing in the *alpha channel***

Fake HDR, exponent, alpha channel. It only matters for a specific HDR format where, as mentioned above, ..

> "Fake" HDR, where the alpha channel is used as a scalar/exponent value to simulate high dynamic range

So alpha blending is not the issue. The issue is that a color surface is used for unintended purposes and only in that case, alpha blending fails.
> 2 votes

---
Tags: 3d, graphics, graphics-programming
---


title: Why is it bad to hard-code content?

text:
# Question
Title: Why is it bad to hard-code content?
I know most games store dialogue text in files, but I've also seen a few text-based games actually program the content (map, choices, possible player commands, story text) into the game code.

I can think of a few reasons, but what is the major reason why even text games keep everything in files outside the program?

The implementation details differ little between holding content in something like the popular XML format, parsing it, then rendering maps/displaying text based on the variables created from XML file, and simply forgoing the XML file entirely. They both end up with strings which output to the screen. Isn't the difference just notation?

Some games even hold the graphics (ASCII art?) inside the code. I know this isn't right, and I can guess a few reasons why it is bad, but don't know the major reason why either.

It is very popular to have most of the content outside the program. Even *Dwarf Fortress* doesn't use actual ASCII characters, but images of ASCII characters loaded into memory.

I primarily ask because it is a bit of a PITA to create, parse, and work with XML files. You know... compared to the lazy alternative of just making every unique dungeon (content) its own class.

# Answer
> 85 votes
There are several reasons for that. I'm just gonna touch on a few:

1. It makes your source code a mess. If you have a lot of dialog (trees), a huge part of your codebase is just text that has nothing to do with your actual game code.
2. You'd need to recompile every time you change so much as a single character.
3. The dialog itself is hard to navigate. I imagine trying to implement a whole dialog tree, let alone several, completely inside your source will result in a nested mess of spaghetti and nested `if`s, `switch`es and so on. Which then results in code that is prone to errors, hard to read and harder to debug.
4. If you want to enable people to mod or expand your game, that's far easier if they don't have to deal with the source code to change something.
5. The above point is even more important if you work in a team. You don't want your writer to have to mess with the code just to enter a piece of dialog.
6. Parsing XML or other standard file formats is pretty easy to do if you use existing libraries, so the cost of implementing it that way is very low while giving you lots of advantages and avoiding the problems mentioned above and lots more.
7. As @MiloPrice pointed out below, it's also far easier to localize the game if your text is in external files. You can add a language by adding a file, your team can take care of translation without having to touch the source (which is especially important if you let people translate who are not supposed to see all of your code - think freelancers, people from the community that don't belong to your team etc).

# Answer
> 30 votes
Putting game content data in code means that to see any potential change or iteration of that game content data, you have to recompile the game itself. This is bad for two reasons:

* Many languages that games are written in have long compile times. C++ is particular can be very bad in this respect, and C++ is a very common language for large commercial games. It is less of an issue with languages like C# and Java, but still not as fast as being able to store game data in external files that can be hot-reloaded while the game is actually running to see changes.
* Many games are developed by teams which often consist of non-technical developers (designers and artists) producing content. Not only do non-technical people not want to have to recompile the game, or deal with "cumbersome programmer tools," to iterate on their content, it may be desirable to minimize source code exposure to only the programmers (because the fewer people who have access to source code, the fewer people who can leak it -- accidentally or not).

I think you're overestimating the complexity of loading data from text or XML files. Most of the time you should use a library to do this, which makes the process of parsing the XML/JSON/whatever much easier. Yes, there is a bit of up-front cost to writing a level loading system that is data-driven but it will generally save you a *lot* of time in the long run versus tons of unique classes to represent each level.

Smaller or simpler games may not have as much to gain from the longer-term investment of a data-driven approach, so unless the developers are using existing frameworks/engines that support it it may be more efficient for them to simply encode the data in the game code.

There are of course a host of reasons why any given game may choose to put their data in external files (or not); it's not feasible to list them all. At some level they will usually all boil down to the additional iteration speed or flexibility that not-having-to-rebuild-the-game can provide.

# Answer
> 7 votes
As always, as always, it depends. But first, I would like to argue that hard coding is not bad by itself.

I have hard coded content, specifically dialog text, in some simple games, and the world didn't end. We programmers love abstracting things, but remember that each layer of abstraction you make will make your program more complex and more difficult to understand.

If your game is simple enough so you can hardcode some content in it, I would certainly consider it for the sake of simplicity.

This, however, does not really scale too much. Certainly the most common reason for putting content in outside resources is to simplify teamwork, as one person or team can focus on writing the game, while another one can focus on creating and polishing the content.

However, drawing the line between program and content is not always really trivial. One could say that textures are 100% content; but what about procedurally generated textures? Dialog text could be considered 100% content; but what about when the dialog changes depending on your previous actions? Other elements that one may consider to be 100% part of the program, like scripts or shaders, could also be considered part of the content of the game. Should they be hardcoded? should they be loaded as an external resource?

Remember though, that each type of content you support in your game must have a loading and interpreting code related to it, so generally, if in doubt, I'd recommend hard coding content, and only taking it out to an external resource when you really need that flexibility (not when you think you -may- need it, but when you actually do)

Finally, one advantage of storing data in resource files is that you can load them only when you need them (therefore possibly speeding up game load times), and unload them when you don't need them anymore (therefore allowing you to have more content than can fit in memory). (Nitpickers' corner: resource DLLs could arguably be considered to be external resources)

# Answer
> 3 votes
I think it is too easy to be the 'wither-than-white' guy and recommend warmly using an external text resource file.

Why? Because there's a choice here that's about balancing each solution's cost/issues/advantages.

When using an external file... Well, I guess the other answers explain the benefits well enough. But what about the costs? You have to define a valid formalism, build a interpreter, agree on a file format, and worse... build another application -an editor-. Which is a 0.00% issue if you're a member of a 50 coder team building a large project. But if you're alone: you're stalled.

Again, I don't under-estimate the huge flexibility benefits of an external resource: data-driven programming seems to me the way to go for video-games. But let's not forget the cost.

On the other hand, having the text inside the code allow for quick prototyping, so it should be preferred in a first time. Then my advice would be, as the project mature, to analyse the kind of data required to modelize the dialogs (mood/history-state/...). Then at some point you decide of some classes/rules/file format and go for the real thing, allowing other people to edit/decoupling the code from the content and so forth. OR for a game with simple dialogs (Mario...) you just consider the cost too high, and you keep the few strings/behavior hard-coded.
Your call.

(Remark about localisation: it's just a hash table away, so it's an independent and easily solvable issue.)

# Answer
> 3 votes
A big reason for storing in text files is reusability. Creating a text game framework that reads your maps, dialog, and other resources from a text file allow you to reuse your framework for other games. Going beyond text games this is how big budget titles like Call of Duty release a new game every year.

Another reason is portability. You can use the same files for web, pc, Mac, Android, etc. All you need to do is mock up your framework for these different platforms, and the bulk of the game data is untouched.

When going beyond text based games having a script and data stored in files will decrease recompile times and allow you to create an interface for manipulating the data easier.

# Answer
> 3 votes
For the sake of making changes faster, it speeds up development on larger productions by tons.

You don't need to teach everyone to learn how to go in and edit source to make simple changes. By dragging it out of the actual code, more people get the chance to fool around with, it's easier to find out what options you can play around with and the whole process of finetuning various parts of your game takes much less time. Even Q&A can help with that.

# Answer
> 3 votes
I can't believe noone mentioned this yet, but a big reason is to make localization A LOT easier. If you need to support English, French, German, Spanish, Portuguese, Italian, Russian, Chinese and whatever other language you're aiming at, hardcoded requires you to have separate code-behind for every language. It also means that if you need to remove certain content (read: censorship), you need to change your code itself to avoid it, instead of saying "just replace this anal probing minigame with this passive-aggressive banner that graphically explains what's going on". It's also rather unfriendly for consumers, since it is likely they'll need to restart the game to change the language, since you need to load other libraries. Finally, that separate code-behind means that you need to apply every single bugfix to every single one of your language codebases, resulting in potential for language-specific bugs.

On the other hand, if you're using external resources, supporting different languages just means loading a different resource file. This can easily be done while the game is running. it means that you can have a single codebase, vastly simplifying development. And it also means that you can easily add after-release support for other languages. Finally, it means that you can let the user opt out of installing certain languages (a feature which doesn't happen all that often in games, but one which is still possible) to save disk space and bandwidth.

# Answer
> 3 votes
I think a key phrase is separation of concerns.

If your code doesn't include the text than the code get's less complex. The programmer writing the code doesn't have to think about the specific text and can focus on the code.

He doesn't have to think about localization. The person doing the localization doesn't have to worry about the code.

# Answer
> 2 votes
I guess **licensing** can also be a reason not to include content in the code.

For example,

* your code might be FLOSS, but you don’t want to license your content at all (maybe you want to publish your game code so that others can use it for creating similar games with different content)
* your code might be FLOSS, but you want to use a Creative Commons license for your content (as software licenses don’t work great for content and vice-versa)
* your code might be proprietary, but you are reusing free content
* your code might be proprietary, but you want to publish your own content under a free/libre license

---
Tags: architecture, databases, text-based, content-generation, dialogue-tree
---


title: Tiling 2D textures in random order

text:
# Question
Title: Tiling 2D textures in random order
I am wondering what the best way to make a random set of 2D textures. Currently I have tried the follow code but I am aware that when this comes to collisions that would be an issue. Therefore I would really appreciate a different method of achieving this.

```
Random random = new Random();
        for (int i = 0; i < 10; i++)
        {
            GenPos = new Vector2((800 + (Length * Stone.Width)), (500 - (i * Stone.Height)));

            int number = random.Next(1, 3);

            if (i == 9)
            {
                if (Length < 31)
                {
                    i = 0;
                    Length++;
                }

            }
            else if (number == 1)
            {
                spriteBatch.Draw(Stone, GenPos, Color.White);
            }
            else if (number > 1)
            {
                spriteBatch.Draw(Grass, GenPos, Color.White);
            }

        }

```

This code works except for two critical things, the collision detection method dose not work as the GenPos changes throughout the code and that the Stone and Grass flashes. Also note that the grass is just a place holder for a future texture of Iron\_Ore. I am wondering what the best method for achieving this would be because I need it to be able to detect collisions using a similar detection method to:

```
public Boolean StonePlayerCollision()
    {
        if (playerPosition.Y >= (StonePosition.Y + Stone.Height) && playerPosition.Y <= StonePosition.Y ))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

```

If you are to suggest a new method, which would be much better than maintaining this messy system please note that the Tiled area will need to be in the view matrix method as seen below:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
            SamplerState.LinearWrap, null, null, null, camera.ViewMatrix);

```

I hope that someone will be able to suggest the best / most efficient way of making a randomly tiled textures that can be detected by collisions. Thank You.

# Answer
> 0 votes
Here is my suggestion : Create a Class for your Tile, you could have a seperate class for each type of tile (stone/tree/grass) or you could pass in a case to the Tile class that is handled from within the Tile Class which would determine its Tile Type. Regardless of what you do, you need to set up a Bounds property for each one of your tiles. The Bounds Property is just the rectangle at which you are drawing your Tile at.

```
//TheTileClass

public int TileType;
public int TileRow;
public int TileColumn;
public int TileHeight;
public int TileWidth;
public Texture2D theTile;
public Rectangle Bounds;

public Class Tile {
    public void New(int tileType, int Row, int Column, int tileWidth, int tileHeight){
    TileType = tileType;
    TileRow = Row;
    TileColumn = Column;
    TileHeight = tileHeight;
    TileWidth = tileWidth;
    Bounds = new Rectangle((int)(Column * tileWidth), (int)(Row * tileHeight), tileWidth, tileHeight);
}

public void Draw{
    spriteBatch.Begin();
    Rectangle destinationRectangle = new Rectangle(Column * TileWidth, Row * TileHeight, TileWidth, TileHeight);

    switch(TileType){

    //Stone
    case 1:
        theTile = GlobalVariables.StoneImage;
        break;
    //Tree
    case 2:
        theTile = GlobalVariables.TreeImage;
        break;
}

    spriteBatch.Draw(theTile, destinationRectangle, Color.White);
    spriteBatch.End();
}

}

//In your Game Class

//Instanciate TileSet Object at the top of your code where you set all your variables

public List<Tile> tileSet;
public int nbrOfColumns;
public int nbrOfRows;
public int TileHeight 160;
public int TileWidht = 160;
public Random rng = new Random();

//In LoadContent
GlobalVariables.treeImage = Content.Load<Texture2D>("treeImg");
GlobalVariables.stoneImage = Content.Load<Texture2D>("stoneImg");

//In your Update of your Game Class

if (tileSet.count == 0){

for (intlc = 0; intlc < nbrOfRows; intlc++){
    for (intlc1 = 0; intlc < nbrOfColumns; intlc1++){
        Tile theTile = new Tile(rng.next(1,10), intlc, intlc1, TileWidth, TileHeight);
        tileSet.Add(theTile);
    }
}
}

Public static class GlobalVariables{
    public static Texture2D treeImage;
    public static Texture2D stoneImage;
}

//In your game's Draw Class
foreach(Tile theTile in tileSet){
    theTile.Draw();
}

//For Collision you need to check agaisnt two rectangles
//The character sprites rectangle, and the stone's rectangle

public Rectangle Bounds;
public class Hero{

public void New{
//set the bounds here like in the tile class
}

public void Update{
//update the bounds here
}
}

```

//Back in your game class' Update

use the logic from this link to check for collision, and the prevent movement if the characters projected position will intersect with the tile that has a type of Stone or tree : How to detect collision between two directed object?

```
foreach (Tile theTile in tileSet){
  if (theTile.TileType == 1 || theTile.TileType == 2){
      if (Hero.Bounds.Intersects(thetile.Bounds){
       //set some boolean that will indicate that the character is moving to an invalid location
       blnCantMove = true;
       break;
    }
}
}

```

---
Tags: c#, tilemap, platformer, random
---


# Question
Title: How can I avoid having many singletons in my game architecture?
I use cocos2d-x game engine for creating games. The engine already uses many singletons. If someone used it, then they should be familiar with some of them:

```
Director
SimpleAudioEngine
SpriteFrameCache
TextureCache
EventDispatcher (was)
ArmatureDataManager
FileUtils
UserDefault

```

and many more with overall about 16 classes. You can find a similar list on this page: Singleton objects in Cocos2d-html5 v3.0 But when I want to write I game I need much more singletons:

```
PlayerData (score, lives, ...)
PlayerProgress (passed levels, stars)
LevelData (parameters per levels and level packs)
SocialConnection (Facebook and Twitter login, share, friend list, ...)
GameData (you may obtain some data from server to configure the game)
IAP (for in purchases)
Ads (for showing ads)
Analytics (for collecting some analytics)
EntityComponentSystemManager (mananges entity creation and manipulation)
Box2dManager (manages the physics world)
.....

```

Why I think they should be singletons? Because I will need them in very different places in my game, and shared access would be very handy. In other words, I don't what to create them somewhere and pass pointers down to my all architecture as it will be very difficult. Also these are kind of things I need only one. In any case I will need several, I can use a Multiton pattern too. But the worst thing is that Singleton is the most heavily criticized pattern because of:

```
 - bad testability
 - no inheritance available
 - no lifetime control
 - no explicit dependency chain
 - global access (the same as global variables, actually)
 - ....

```

You can find some thoughts here: https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons and https://stackoverflow.com/questions/4074154/when-should-the-singleton-pattern-not-be-used-besides-the-obvious

So, I think, I am doing something wrong. I think my code smells. :) I wounder how more experienced game developers solve this architectural problem? I want to check, maybe it is still normal in game development to have **more than 30 singletons**, considered the ones that are already in game engine.

I have thought to use a Singleton-Facade which will have instances of all these classes I need, but each of them would not be singletons already. This will eliminate a lots of problems, and I would have only one singleton which would be the Facade itself. But in this case I will have another design problem. The Facade will become a GOD OBJECT. I think this **smells too**. So I can't find a good design solution for this situation. Please advice.

# Answer
> 13 votes
Reading all these answers, comments and articles pointed out, especially these two brilliant articles,

eventually, I have come to the following conclusion, which is kind of an answer to my own question. The best approach is not to be lazy and pass dependencies directly. This is explicit, testable, there is no global access, can indicate wrong design if you have to pass delegates very deep and in many places and so on. But in programming one size does not fit all. Thus, there are still cases that it is not handy to pass them directly. For example in case we create a game framework (a code template which will be re-used as a base code to develop different kinds of games), and include there lots of services. Here we don't know how deep each service can be passed, and how many places it will be necessary. It dependents on a particular game. So what do we do in this kind of cases? We use Service Locator design pattern instead of Singleton, which is actually the same Singleton, with the following very important improvements:

1. You don't program to the implementations but to the interfaces. This is very essential in terms of OOP principals. At runtime you can change or even disable the service using Null Object pattern. This is not only important in terms of flexibility, but it directly helps in testing. You can disable, mock, also you can use Decorator pattern, to add some logging and other functionality as well. This is very important property, which Singleton does not have.
2. Another huge advantage is that you can control the lifetime of the object. In Singleton you only control the time the object will be spawned by Lazy Initialization pattern. But once the object is spawned, it will live until the end of the program. But in some cases you would like to change the service. Or even shut it down. Especially in gaming this flexibility is very important.
3. It combines/wraps several Singletons into one compact API. I think you may also use some Facade like Service Locators, which for a single operation might use several services at once.
4. You may argue that we still have the global access which is the main design problem with the Singleton. I agree, but we will need this pattern only and only if we want some global access. **We should not complain about global access, if we think that direct dependency injection is not handy for our situation, and we need a global access.** But even for this problem, an improvement is available (see the second article above). You can make all the services private, and you can inherit from Service Locator class all the classes you think they should use the services. This can significantly narrow the access. And please consider that in case of Singleton you cannot use inheritance because of the private constructor.

Also we should consider that this pattern was used in Unity, LibGDX, XNA. This is not an advantage, but this is kind of a proof of the usability of the pattern. Consider that these engines were developed by lots of smart developers a long time and during the evolution phases of the engine they still didn't find any better solution.

In conclusion, I think Service Locator can be very useful for the scenarios described in my question, but still should be avoided if it is possible. As a rule of thumb - use it if you have to.

EDIT: After a year of work and using direct DI and having problems with huge constructors and lots of delegations, I have done more research and have found a good article that talks about pros and cons about DI and Service Locator methods. Citing this article (http://www.martinfowler.com/articles/injection.html) by Martin Fowler that explains when actually Service locators are bad:

> So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.

But anyways, if you want to us DI first time, you should read this http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/ article (pointed out by @megadan), by paying very careful attention to the Law of Demeter (LoD) or principle of least knowledge.

# Answer
> 42 votes
I initialize my services in my main application class and then pass them as pointers to whatever needs to use them either through the constructors or functions. This is useful for two reasons.

One, the order of initialization and cleanup is simple and clear. There is no way to accidentally initialize one service somewhere else like you can with a singleton.

Two, it's clear who depends on what. I can easily see what classes need what services just from the class declaration.

You may think it's annoying to pass all these objects around, but if the system is designed well, it's really not bad at all and makes things much clearer (for me anyway).

# Answer
> 19 votes
I won't discuss about the evilness behind singletons because Internet can do that better than me.

In my games I use the Service Locator pattern to avoid having tons of Singletons/Managers.

The concept is pretty simple. You only have one Singleton that acts like the only interface to reach what you used to use as Singleton. Instead of having several Singleton you now have only one.

Calls like :

```
FlyingToasterManager.GetInstance().Toast();
SmokeAlarmManager.GetInstance().Start();

```

Looks like this, using the Service Locator pattern:

```
SvcLocator.FlyingToaster.Toast();
SvcLocator.SmokeAlarm.Start();

```

As you can see every Singleton is contained in the Service Locator.

To have a more detailed explanation I suggest you to read this page about how to use the Locator Pattern.

\[**EDIT**\] : as pointed in comments, the site gameprogrammingpatterns.com also contains a very interesting section on Singleton.

I hope it helps.

# Answer
> 3 votes
It isn't uncommon for parts of a code base to be considered cornerstone objects or a foundation class, but that doesn't justify it's life cycle to be dictated as a Singleton.

Programmers often rely on the Singleton pattern as a means of convenience and pure laziness rather than taking the alternate approach and being a tad more verbose and imposing object relationships between one another in an explicit manor.

So ask yourself which is easier to maintain.

If you're like me, I prefer to be able to open a header file and briefly skim over constructor arguments and public methods to see what dependencies an object requires rather than having to inspect hundreds of lines of code in an implementation file.

If you had made an object a Singleton and later realize you need to be capable of supporting multiple instances of said object, imagine the sweeping changes needed if this class was something you used pretty heavily throughout your code base. The better alternative is to make dependencies explicit, even if the object is only allocated once and if the need arises to support multiple instances, you can safely do so without such concerns.

As others have pointed out, use of the Singleton pattern also obfuscates coupling that often signifies poor design and high cohesion between modules. Such cohesion is usually undesirable and leads to brittle code that can be hard to maintain.

# Answer
> 1 votes
Singleton is a famous pattern, but it's good to know the purposes it serves, and its pros and cons.

It really makes sense if there is *no relationship* at all.
If you can handle your component with a totally different object *(no strong dependency)* and expect having the same behavior, the singleton may be a good choice.

On the other hand, if you need a **small functionality**, only used at certain times, you should prefer *passing references*.

As you mentioned, singletons have no lifetime control. But the advantage is they have a lazy initialization.
If you don't call that singleton in your application lifetime, it will not be instantiated. But I doubt you build singletons and not use them.

You must see a singleton like a **service** instead of a *component*.

Singletons works, they never broke any application. But their lacks *(the four you've given)* are reasons you won't make one.

# Answer
> 1 votes
> The engine already uses many singletons. If someone used it, then they should be familiar with some of them:

Unfamiliarity isn't the reason why singletons need to be avoided.

There are many good reasons why Singleton is necessary or unavoidable. Game frameworks often uses singletons because it is an unavoidable consequence of of having just a single stateful hardware. It makes no sense to ever want to control these hardwares with multiple instances of their respective handlers. The graphic surface is an external stateful hardware and accidentally initializing a second copy of the graphic subsystem is nothing short of disastrous, as now the two graphic subsystem will be fighting each other over who gets to draw and when, overwriting each other uncontrollably. Likewise with event queue system, they will be fighting over who gets the mouse events in nondeterministic fashion. When dealing with a stateful external hardware in which there is only one of them, singleton is unavoidable to prevent conflicts.

Another place where Singleton is sensible is with Cache managers. Caches are a special case. They should not really be considered a Singleton, even when they use all the same techniques as Singletons to stay alive and live forever. Caching services are transparent service, they aren't supposed to alter the behaviour of the program, so if you replace the cache service with a null cache, the program should still work, except that it only runs slower. The main reason why cache managers are exception to singleton though is because it doesn't make sense to shut down a cache service prior to shutting down the application itself because that will also discard the cached objects, which defeats the point of having it as a singleton.

Those are good reasons why these services are singletons. However, none of the good reasons to have singletons apply to the classes you have listed.

> Because I will need them in very different places in my game, and shared access would be very handy.

Those aren't reasons for singletons. Those are reasons for globals. It is also a sign of poor design if you need to pass a lot of things around various systems. Having to pass things around indicates high coupling which can be prevented by good OO design.

Just from looking at the list of classes in your post that you think need to be Singletons, I can say that half of them really shouldn't be singletons and the other half seems like they shouldn't even be there in the first place. That you need to pass objects around seems to be due to the lack of proper encapsulation rather than actual good use cases for singletons.

Let's look at your classes bit by bit:

---

```
PlayerData (score, lives, ...)
LevelData (parameters per levels and level packs)
GameData (you may obtain some data from server to configure the game)

```

Just from the classes names, I would say that these classes smells like Anemic Domain Model antipattern. Anemic objects usually results in a lot of data that need to be passed around which increases coupling and makes the rest of the code cumbersome. Also, anemic class hides the fact that you are probably still thinking procedurally rather than using object orientation to encapsulate details.

---

```
IAP (for in purchases)
Ads (for showing ads)

```

Why do these classes need to be singletons? It seems to me that these should be short-lived classes, which should be brought up when they are needed and deconstructed when the user finishes the purchase or when the ads no longer need to be shown.

---

```
EntityComponentSystemManager (mananges entity creation and manipulation)

```

In other words, a constructor and a service layer? Why is this class with no clear boundaries nor purpose even there in the first place?

---

```
PlayerProgress (passed levels, stars)

```

Why is the player progress separate from the Player class? The Player class should know how to keep track of its own progress, if you want to implement progress tracking in a different class than the Player class for separation of responsibility, then PlayerProgress should be behind Player.

---

```
Box2dManager (manages the physics world)

```

I can't really comment any further on this one without knowing what this class actually does, but one thing is clear is that this class is poorly named.

---

```
Analytics (for collecting some analytics)
SocialConnection (Facebook and Twitter login, share, friend list, ...)

```

This seem to be the only classes where Singleton may be reasonable, because the social connection objects are not actually your objects. The social connections are just a shadow of external objects that lives in a remote service. In other word, this is a kind of cache. Just make sure you clearly separate the caching part with the service part of the external service, because the latter part shouldn't need to be a singleton.

One way you can avoid passing instances of these classes around is by using message passing. Rather than making a direct call to instances of these classes, instead you send a message addressed to the Analytic and SocialConnection service asynchronously, and these services are subscribed to receive these messages and act on the message. Since the event queue is already a singleton, by trampolining the call, you avoid the need to pass an actual instance when communicating with a singleton.

# Answer
> -1 votes
Singletons to me are ALWAYS bad.

In my architecture I created a GameServices collection that the game class manages. I can search add to and remove from this collection as required.

By saying something is in global scope you are basically saying "this hting is god and has no master" in the examples you provide above I would say most of those are either helper classes or GameServices in which case the game would be responsible for them.

But that's just my design in my engine, your situation may be different.

Putting it more directly ... The only real singleton is the game as it owns every part of the code.

This is answer is based on the subjective nature of the question and is based purely on my opinion, it may not be correct for all developers out there.

Edit: As requested ...

Ok this is from my head as I don't have my code in front of me at the moment but essentially at the root of any game is the Game class which is truely a singleton ... it has to be!

So I added the following ...

```
class Game
{
   IList<GameService> Services;

   public T GetService<T>() where T : GameService
   {
       return Services.FirstOrDefatult(s => s is T);
   }
}

```

Now I also have a system class (static) that contains all my singletons from the entire program (contains very little, game and config options and thats about it) ...

```
public static class Sys
{
    // only the main game assembly can set this (done by the game ctor)
    // anything can get
    public static Game Game { get; internal set; }
}

```

And usage ...

From anywhere I can do something like

```
var tService = Sys.Game.getService<T>();
tService.Something();

```

This approach means that my game "Owns" stuff that would typically be considered a "singleton" and I can extend the base GameService class however I want. I have interfaces like IUpdateable that my game checks for and calls in to any services that implement it as needed for specific situations.

I also have services that inherit / extend other services for more specific scene scenarios.

For example ...

I have a Physics service that handles my physics simulations but depending on the scene physics simulation may need some slightly different behaviour.

# Answer
> -1 votes
An essential ingredient of singleton-elimination which opponents of singleton often fail to consider is adding extra logic to deal with the vastly more complicated state that objects encapsulate when singletons give way to instance values. Indeed, even *defining* the state of an object after replacing a singleton with an instance variable can be difficult, but programmers who replace singletons with instance variables should be prepared to deal with it.

Compare, for example, Java's `HashMap` with .NET's `Dictionary`. Both are quite similar, but they have a key difference: Java's `HashMap` is hard-coded to use `equals` and `hashCode` (it effectively uses a singleton comparator) while .NET's `Dictionary` can accept an instance of `IEqualityComparer<T>` as a constructor parameter. The run-time cost of keeping the `IEqualityComparer` is minimal, but the complexity that it introduces is not.

Because each `Dictionary` instance encapsulates an `IEqualityComparer`, its state is not just a mapping between the keys it actually contains and their associated values, but instead a mapping between *the equivalence sets defined by the keys and the comparator* and their associated values. If two instances `d1` and `d2` of `Dictionary` hold references to the same `IEqualityComparer`, it will be possible to produce a new instance `d3` such that for any `x`, `d3.ContainsKey(x)` will equal `d1.ContainsKey(x) || d2.ContainsKey(x)`. If, however, `d1` and `d2` may hold references to different arbitrary equality comparers, there will in general be no way to merge them so as to ensure that condition holds.

Adding instance variables in an effort to eliminate singletons, but failing to properly account for the possible new states that could be implied by those instance variables can create code which ends up being more brittle than it would have been with a singleton. If every object instance has a separate field, but things will malfunction badly unless they all identify the same object instance, then all the new fields have bought is an increased number of ways things can go wrong.

---
Tags: game-design, architecture
---


# Question
Title: How to design a drag and drop inventory system with transition from icons to game objects?
I’m trying to write a simple 2D game in Unity with an inventory where the user can drag and drop different objects on the screen.

I need the inventory to contain icons which on drag will become different game objects.

I’m struggling in positioning the game object after clicking the icon and using its drag-and-drop functionality (a script component which i attached to it).

I would really appreciate some guidelines or opinions about the design because I feel I’m doing things wrong.. What do you think?

# Answer
\[**EDIT**\]

As your question, now clearer seems to be more about design and not so much a technical question I change my answer a bit.

Your first attempt was the right one. Your sprite contains a drag&drop component. But it's necessary that it also contains the prefab it will instantiate once dropped in the game world. The main design is, from an inventory item perspective:

1. I know what prefab I represent
2. When player drop me on the scene I get the Mouse position and Instantiate the prefab I represent

You can add a 3rd step if you want the item sprite to its initial position in the inventory (but the inventory item will have to save its initial position before drag&drop begins).

\[**Original answer**\]

Let me rephrase your question as I understand it.

So you have an inventory (somewhere on the screen) full of draggable sprites/objects and you want to instantiate a prefab when the player drop it somewhere on the screen. As you seem to have drag/drop behaviour working, the real problem is about instantiating/activating things at the right place on screen.

If that's correct, I'd say the first technique you tried was a good one. (note that the second one, using prefabs, would totally work but it's not as "clean and easy" in my humble opinion).

Let say that the inventory is composed of sprites. When you drop something from your inventory you actually need two important informations: the drop position and the object to instantite.

The position is actually given by the mouse position. As it's a 2D game you're working on you just have to convert the mouse position, given in screen space, in a world space position. It's pretty easy using the Camera.ScreenToWorldPoint method.

Something like :

```
Vector2 world_position = Camera.main.ScreenToWorldPoint(Input.mousePosition) as Vector2;
// using Vector2 instead of Vector3 is not mandatory even in a 2D game, but I prefer.

```

So the trick here is to somehow add a property to the sprites of inventory. Simply add a component (on every inventory object), let's call it `InventoryItem`, which has the prefab you need to instantiate in a `public Transform` field.

Something like :

```
public class InventoryItem : Monobehaviour
{
   public Transform item_prefab;
   private void Start()
   {
      if ( item_prefab == null )
      {
          Debug.LogError("Item prefab is not valid.");
      }
   }
}

```

Now, when player drop an inventory item, it's easy to know what prefab to Instantiate and where to instantiate it.

```
public void OnItemDrop(GameObject item)
{
   // Get world position
   Vector2 item_world_position = Camera.main.ScreenToWorldPoint(Input.mousePosition) as Vector2;
   // Get the prefab to instantiate
   Transform item_prefab = item.GetComponent<InventoryItem>().item_prefab;

   // Instantiate it to world position
   Instantiate(item_prefab, item_world_position, new Quaternion());

   // You can do this if you want your item sprite to disappear
   // Destroy(item);
}

```

Note that this code is untested... but it *might* work :)

I hope it helps.
> 3 votes

# Answer
I made my inventory work with an "Item" class that ties actual game objects to their icon, description, etc. - the inventory only deals with "Items" while using an item (placing it, for example, in the game world) would consume one and then create the game object.

I know that's a bit simplistic of an answer, but I felt like sharing my two cents.
> 0 votes

---
Tags: 2d, unity, gui, inventory
---


# Question
Title: Do OpenGL buffers overflow to CPU memory?
This is a question about OpenGL buffers and memory. My game world is mid-sized, one contiguous space, unchanging, and only partially visible from any position.

Will modern OpenGL overflow buffers into CPU memory?

And if so, can I just allocate buffers (vertex and texture) for all of it, and adjust my draw calls to skip non-visible areas, and let OpenGL pull buffers into GPU as needed, hopefully minimizing thrashing? (Or does OpenGL just fail on the allocate after a while?)

EDIT: The above was ambiguous. But maybe both variations are interesting.

1. Could I just allocate one huge vertex buffer and a few giant textures, and hope that OpenGL moves parts of it in and out of the GPU as needed, and maybe enough early depth-testing lets it skip some of the texture drawing...
2. Could I have a handful, or maybe a lot, of "sensibly-sized" vertex and texture buffers, but only glDrawXxx() some of them on each frame? In that case, would OpenGL move them up and down from the GPU, maybe in a least-recently-used sort of way?

# Answer
No. If you request a buffer store (via `glBufferData`) larger than the implementation can satisfy, you'll get a `GL_OUT_OF_MEMORY` error. Buffers may be temporarily (or permanently) backed by CPU memory depending on their state, but a overly-large buffer store will never overflow out of GPU memory into CPU memory.

To handle the large volume of data you're describing, you'll want to page the relevant data for your world into the GPU buffer as it becomes needed (visible / near visible), leaving the rest resident in RAM (or on disk, if that's an option).

---

In response to your edit:

The first option isn't particularly viable unless all of each resource fits in GPU RAM. Otherwise you'll get out-of-memory resources trying to allocate space once you fill it up. If they do all fit, you don't need to worry about paging at all, obviously.

The second option is basically how you need to accomplish your goal: allocate smaller buffers of data and swap the contents of that data as needed. You can achieve some level of that automatically depending on how you choose to allow OpenGL to back your resources (with or without system memory), but you may also end up needing to do it yourself for optimal performance.
> 6 votes

---
Tags: opengl, memory
---


title: Tower Defence game scoring system

text:
# Question
Title: Tower Defence game scoring system
I am in the process of developing my first game on android mobile platform, it’s a tower defence game and I am currently busy designing the scoring system.

At the end of the stage when the user has defeated all the waves of enemies I want to take his score and somehow calculate a rating out of 3 Stars.

What will the best way be to calculate a score?
When should I increment the score during gameplay for example when an enemy dies?
And how do I calculate if the score is worth 1-3 Stars at the end of the stage?

Basically I want help or any ideas on how the formula should look like and how to calculate if the user scored a 1.. 2... or 3 Stars.

My variables in game :

Every enemy has a value: Example **$5**

The stage has a number of life’s before you are defeated: Example **20**

Each stage starts with money that you buy your towers with: Example **$120**

Each towers costs money: Example **$30** A stage can consist of 1 or more waves of enemies.

Any help or ideas would be appreciated as I am new to game development….

# Answer
> 3 votes
Are you randomly creating waves, or would they be set. If the enemy waves were set, I would suggest figuring out what enemies are worth what points, and if there is a diffuculty, figure out what the modifier in points would be. Once you have your set waves with enemies of set points, total up the points, and make each star be an even portion of the total. So lets say you have one wave of an enemy type of mage, and the enemy type of mage is worth 100 points. Lets also assume for now that this singular wave spawns 20 mages. That would mean the perfect score would be 100(the point value of a mage) * 20 (the number of mages) resulting in a perfect score of 2000. If a level as 4 stars, each star would be achieved after 500 points (2000, the perfect score) divided by (4, the number of stars). So if the user ends up with 1200 points, they would have two of four stars.

# Answer
> 1 votes
I like shroeder answer. It's very logical.

There could be a lot more to the scoring system as well.

When should you score? I would score when you kill a enemy from the wave. You could even fill the stars as they reach the score needed to fill X% of the star. It would be a good way for them to see before all of the bonuses are added at the end (if any) how they are doing on the level.

Perhaps there are some points to be had if the user has money left over at the end of the level. Those points would skew the score and allow a little bit of reward to be had for using skill and not just brute force damage. Money spent on upgrades to the tower could add to the score as well, showing the user that knowing how to play the game has rewards.

Also if certain criteria was met during the game (think achievements) those could add to the score, making a 3 star average higher than the total score for killing everything.

In reality, it's what you want your game to be. Make sure three stars are achievable in the lower levels with some ease, but harder to obtain in later levels. A level that makes it difficult to get 3 stars adds a lot more replay value to your game.

---
Tags: game-design, game-mechanics, andengine
---


# Question
Title: Destroy GameObject as an Array of Transform instantiated destroying the whole array
I am trying to destroy a GameObject with the Destroy() method, but when I call it the whole array is destroyed, not just that element.

```
//Instantiating the prefabs
public Transform[] blue;

foreach (Vector3 vec in xyid)
    {
        //vec.z is used as the object id
        Instantiate(blue[vec.z], new Vector3(vec.x, vec.y), Quaternion.identity);
    }

```

This is another script, I put this on every prefab

```
void Update () {

    if (Input.GetMouseButtonDown(0))
    {
        Destroy(gameObject);
    }

}

```

# Answer
OK, found the answer, BTW its a 2D game solution, forgot to tell

```
if (Input.GetMouseButtonDown(0))
    {

        RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
        if (hit.collider != null)
        {
            Destroy(hit.collider.gameObject);
        }
    }

```

Source: http://answers.unity3d.com/questions/651513/raycast-click-object-and-destroy-it-java2d.html
> 0 votes

# Answer
That's because every object has a script attached that's listening for a mouse down event. Each one checks to see if the mouse is down, and if it is, destroys itself.

It's not clear how you want to select which object to destroy, but there are a few options:

* Use colliders on the objects you want to destroy, and inside the `OnMouseDown` method, put your destroy code. This will only activate if the left mouse button is pressed while the cursor touches the collider.
* Pull the destroy code out of the object itself and put it in the same script where you generated the objects. Then you can destroy one at a time, be it each object in the array one click at a time, or by some other means you decide in that code.
> 2 votes

---
Tags: c#, unity
---