# Question
Title: Implementing a Menu System and Buttons (Waiting in a whle loop)
I have a menu system with four screens and six buttons. I have created a button class and it works great. I even have events for the buttons working. The problem is that I have to run the events inside the game loop. This causes me to wait on a menu screen. Is there a way with SDL and c++ to wait until an even fires aside from setting a variable on button click and waiting in a while loop?

# Answer
> 2 votes
SDL allows you to wait for an event with... SDL\_WaitEvent. (That's one of the first results if you search for "SDL wait event".) However, it's not exactly clear what your problem is, since running inside a while loop is the standard procedure for games. So it's also not clear that SDL\_WaitEvent is the solution to your issue.

When implementing a GUI in a game the usual method is to have the main loop collect the events, and then you send the events to the GUI to be handled. So for example, you might wait for a `SDL_MOUSEBUTTONDOWN` event, collect the click position from the event, and then pass that to each button in turn to see if the click was on that button - and if so, execute the associated code. You wouldn't generally need to wait at all - the event is read by the main game loop and then handed off to the GUI for potential processing.

---
Tags: c++, sdl
---


# Question
Title: Should each Entity have its own update and render methods?
First, the questions:

1. Should each Entity (which are classes like Character, Tree, Enemy) have its own update() and render() methods?
2. If that's the case, then should I use Interfaces like "Renderable" and "Updatable"?

I ask you this because most of the tutorials I followed "told" me to include all Input Handling and Updates inside the Game's main update() method, and all the Rendering inside the Game's main render() method.

I know these tutorials are very simple but even a few more complex ones still had all the Entities' actions inside the same block of code, which made me doubt the ideas I previously had (separating updates and renders per each object).

To clarify, I feel like I should have something like this:

```
update() {
    HandleTheUserInput();
    for each active Entity in the game right now {
        entity.update();
    }
}

```

Then, the same thing for rendering (except the input part). Am I following the right path here or should I rethink the current architecture ideas I have? Thank you.

# Answer
My opinion is that an entity should have its own Update method, but not its own Render method.

The entity contains most of the information necessary to update itself. It may require a bit of information about the context, such as the world, other entities nearby, etc., but most of the information is contained within the entity. Therefore it is the natural place to put the updating logic.

The entity usually does not have most of the information necessary to render itself, however. Rendering details for an entity might depend on the viewer's distance from the entity, the viewer's settings, whether the program is running in client mode or server mode, etc. Therefore it usually makes sense for an external rendering object to query the entity for whatever information it needs to render it.

In general, your game logic should not know about your presentation logic, because presentation is usually irrelevant to the underlying gameplay. However, the reverse is not true, because the presentation needs to know about the game state in order to render it. This is consistent with the Model View Controller paradigm, where the entity handles the model and the renderer handles the view.
> 8 votes

# Answer
If your game consists of a few entity types, this approach will most likely suffice without little problems; however as the game's entity toolbox grows and more logic is needed to make various game entities, you'll find that inheritance trees are not ideal for entities. In such a situation, you'd want to favor composition rather than inheritance.

In a composition-focused game entity system, entities hold a list of features called components that comprise their overall functionality. You may have a TransformComponent that holds the position and orientation of an entity. You may have a RenderComponent that holds mesh information about how to render an entity to the screen. You may have a PhysicsComponent that holds rigid body information about how the entity will react to collisions in the game world.

```
class IComponent {
public:
virtual void Update(elapsedTimeMS) = 0;
};

class Entity {
private:
   std::vector<IComponent*> mComponents;
/* other stuff */
};

```

At initial glance, you may think now to update entities, you would write something like:

```
foreach(EntityList::value_type& entity, mEntities) {
  foreach(ComponentList::value_type& component, entity->GetComponents()) {
    component->Update(elapsedTimeMS);
  }
}

```

This may work until dependencies exist between entities, such as a character holding a weapon or dependencies exist between components such as updating position before drawing the render component.

The way I approach that problem is to use systems to update like components across all entities rather than the update approach above. As a side note, this also will prove helpful when you consider supporting multiple thread updates as the system approach can easily be morphed into a ParallelFor() update.

```
void UpdateRenderablePosition::Update(long elapsedTimeMS)
{
  // map<entityId,vector<IComponent*>> of entity/components
  //
  EntityComponentMap entities =
    mEntityManager.GetEntitiesWithComponents<PositionComponent,RenderableComponent>();
  EntityComponentMap::iterator i = entities.begin();
  EntityComponentMap::const_iterator iend = entities.end();
  for(; i != iend; ++i) {
    PositionComponent* position = reinterpret_cast<PositionComponent*>(i->second[0]);
    RenderableComponent* renderable = reinterpret_cast<RenderableComponent*>(i->second[1]);
    renderable->SetPosition(position->GetPosition());
    renderable->SetOrientation(position->GetOrientation());
  }
}

void RenderSystem::Update(long elapsedTimeMS)
{
  ComponentList& components = mEntitySystem.GetComponents<RenderableComponent>();
  foreach(ComponentList::value_type& component, components)
  {
    SceneNode* node = component->GetSceneNode();
    node->SetPosition(component->GetPosition());
    node->SetOrientation(component->GetOrientation());
  }
  mRenderer->RenderFrame();
}

```

While the code is meant to illustrate an example, the two systems have update methods which are called during the game loop. Each update method performs certain transformations to the components. These system updates are strategically ordered in the game loop based upon dependencies introduced by game logic.

The benefit to such an approach is that its highly modular. One can introduce a new component and matching subsystem without affecting the behavior of the rest of the game entity's behaviors. Additionally, it allows an entity to truly be composed of any feature-set you wish without the need to place that within the confines of inheritance. And finally, you can control how you update entities and manage their dependencies much cleaner than you would within inheritance.

The code presented is merely a means to illustrate alternatives. Look up entity component design and even data-driven design if you want to dig deeper into the subject.
> 3 votes

# Answer
What you want to do is exactly what **XNA** does, as you can see in this diagram from DigitalRune, they have a **GameComponent**, a **DrawableGameComponent**, and yes, **IUpdateable** and **IDrawable** Interfaces.

And just as you have pointed it may work like this:

```
Every 1/60 seconds {
    for every (IGameComponent) component on componentsList {
        //Input system:
        HandleTheUserInput();
        //Update System:
        if(component is intance of IUpdateable) component.Update(...)
        //Draw System:
        if(component is intance of IDrawable) component.Draw(...)
    }
}

```

This is based on entity/component/system architecture, XNA is very malleable so you can do whatever you want with it, but this question is not about XNA, so you can see an IGameComponent as an Entity, and the way to check which entity fits on what system may be asking the entity to implements a certain Interface.

If the complexity of the code grows to much, you can extract the systems functionalities to their own classes.

Following the entity/component/system as you have pointed you can encapsulate the code outside the main Game Class and inside the Entities and Systems classes.

Some tips:

* If a set of functionality of an entity needs to access various others entities then you should consider to put that code outside the entity and inside of a system, because the system is supposed to have access to those others entities; while the entity not.
* Check if an entity is instance of something may be slow in some languages, so instead you can have a flag of bits to handle this, other way may be to have different lists, one for each system, and then you classify each entity only once.
> 2 votes

# Answer
I'm going to assume all your entities are subclasses of an Entity class.

Entity has the following properties:

* **states** \- a hashtable of animations/images with associated string names
* **activeState** \- name of the entity's current state
* **children** \- a hashtable of other entities, whose position is relative to this entity
* **position** \- x and y position. I don't like Slick's Vectors class, so I wrote my own and use that for all coordinates

Besides getters and setters, it has the following behaviors:

* **render** \- draws the entity at its position, then loops through all children, calling their render methods
* **update** \- calls callback method "onUpdate" and then calls the update method on all children
* **onUpdate** \- empty callback method designed to be overridden by children

With this system, you can set up a certain kind of entity by creating a subclass and setting it up in the constructor (attaching states and children). You can also update in the onUpdate() method.
> 0 votes

---
Tags: java, entity-system, slick
---


# Question
Title: Composite 3-D and 2-D using Anamorphic Projection?
I'm working on a game which takes place on a two dimensional grid similar to the fluid background grid in Geometry Wars. It is implemented as a procedurally drawn spring system which may have force applied to the intersection points resulting in a primitive fluid dynamic simulation.

Let's say I want to elevate the grid into three-space. One way would be to upgrade the whole world to 3-d. Then I could render the grid to a texture and map it onto a plane which could be placed in three dimensions. What I am more interested in, however, is how I might 'fake' it by simulating perspective using 2-D. For example, its easy to vary the horizontal grid spacing based on the cell's row in the grid. By squeezing it at the top I can create a visually convincing vanishing point, but the physics and interaction with the grid is not right.

I'd like to be able to layer the 2-D grid over a separate 3-D layer such that they appear to be one. Have y'all seen the impressive demonstrations of anamorphic projection recently featured on YouTube?

Intrigued, I found another tutorial video which shows how to draw anamorphically using pencil and paper.

Anyone have an idea of how to approach the problem of creating an anamorphic projection space in 2-D that would line up with a given perspective projection as that of a typical 3-D Camera?

I envision that this would manifest as an array of weightings applied to each point in the 2-dimensional grid which I could use to modulate the physics forces that drive the grid, creating a more realistic spring system than is possible with a simple faked perspective.

# Answer
> 1 votes
`screen space position (x, y) = world position (x, y) / z`

...The basis of perspective projection, I think this would be your starting point, assuming a pinhole camera (camera with infinitesimally small aperture) in both instances. Divide-by-z is what gives the impression of depth. You would need to match your divide by z in both projections, in order to match perspectives... and matching the viewing position goes without saying. Hence this is all going to be a lot easier if the viewpoint doesn't change... which, from what you've said, sounds like it's the case.

---
Tags: xna, projection
---


# Question
Title: TextureRegions and TextureAtlases in AndEngine
This is my first android game, sorry if my code is bad, any advice will help. I am trying to find ways to improve performance on a game of mine, I'm using AndEngine GLES2. I have a basic question about how to actually load sprites.

I have 6 player sprites that actually use the same jpg as it's image, the way I've been loading them is like this:

```
private void loadLinebackers(String imageResource, int i) {
    this.playersTextureAtlas[i] = new BitmapTextureAtlas(this.getTextureManager(), 32, 32, TextureOptions.BILINEAR);
    this.playersTextureRegion[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.playersTextureAtlas[i], this, imageResource, 0, 0);
    this.playersTextureAtlas[i].load();
}

private void loadWideReceivers(String imageResource, int i) {
    this.wrsTextureAtlas[i] = new BitmapTextureAtlas(this.getTextureManager(), 32, 32, TextureOptions.BILINEAR);
    this.wrsTextureRegion[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.wrsTextureAtlas[i], this, imageResource, 0, 0);
    this.wrsTextureAtlas[i].load();
}

```

Do I have to create an atlas and a region for every player that I have? Or can I somehow use the same resource?

All the players are viewable simultaneously within the camera. I run these load\* functions via a for loop, passing in i each time.

Each set of players is performing different actions (SequenceModifiers) and I make the Sprite arrays like this:

```
private void makeLinebackers(Scene scene, float posX, float posY, int i, int spaceBetween) {
    this.olineman[i] = new Sprite(posX + (spaceBetween * i), posY, this.playersTextureRegion[i], this.getVertexBufferObjectManager());
    this.olinemenPhysicsHandler[i] = new PhysicsHandler(this.olineman[i]);
    this.olineman[i].registerUpdateHandler(this.olinemenPhysicsHandler[i]);
    scene.attachChild(this.olineman[i]);
}

private void makeWideReceivers(Scene scene, float posX, float posY, int i, int spaceBetween) {
    this.wideReceivers[i] = new Sprite(posX + (spaceBetween * i), posY, this.wrsTextureRegion[i], this.getVertexBufferObjectManager());
    this.wrsPhysicsHandler[i] = new PhysicsHandler(this.wideReceivers[i]);
    this.wideReceivers[i].registerUpdateHandler(this.wrsPhysicsHandler[i]);
    scene.attachChild(this.wideReceivers[i]);
}

```

I made each of these 2 different arrays, because generally each player from each array are doing similar animations and actions. For example, I make all the wide-receivers "run" at once.

# Answer
> 1 votes
If every player uses the same frames, create an instance of each *unique* graphic in texture memory, just as you suggest. That's all you need. When OpenGL renders textures to screen, all it's doing is reading those bytes from texture memory and copying them onto the default framebuffer (screen) after interpolation, perspective projection or whatever else is applicable in the render pipeline. So why copy from more than one source, if you can just copy from one, right?

(I don't know AndEngine so you'll have to figure out the basic *how*, but I'm sure it's fairly straightforward since this is how all GPU rendering works: AndEngine will be built accordingly.)

---
Tags: java, andengine
---


title: Labeling Areas on a map

text:
# Question
Title: Labeling Areas on a map
I've been wondering how you would go about labeling an area on a 2D tile map. What I'd like to do is associate tiles with an area i.e Forest Area, Desert Area, etc.

Keep in mind this is an idea, so far I've been thinking that one way to go about this is to have each area store tile positions as the pivot points and you need at least four of these pivot points before it is a valid area. This way would allow for some of the granularity I would like as my first idea was to just associate every tile with an area id, which is pretty inefficient time-wise, though the task would have been alleviated somewhat with a map editor that I am going to build (i.e. just paint a tile with an area color/number).

What are your ideas on this?

Also, the map, areas, and etc will be stored in an sql database FYI.

# Answer
> 1 votes
I've done something similar to this using an abstract concept of `Area`. An `Area` is just basically collection of `Tile`s, calculated at run time, but will allow you to work with that collection much easier. An `Area` made up of a collection of individual `Tile`s will also allow you to have irregular (not just square) areas of forests and deserts.

Using this concept, you can also join up `Area`s if say for example, a tree grows between two adjacent forests. Your code can then determine whether it joins two areas, and if so, combine them into one.

The `Area` would not be persisted into a database, but calculated at run time. The `Tile`s themselves are the actual data that would be stored (and created in your map editor). The `Area` would just make working with a large collection of tiles easier. A `Tile` knows nothing about the `Area` it is contained within. All game logic would then deal with the concept of `Area` rather than `Tile`. This should be much faster as there are usually a lot less `Area`s than `Tile`s.

In your game, you might want to know what `Area` your player is in, and assign associated values to the size of that `Area`. For example if your player is in a large forest (`Area.GetSize()` returns the actual number of `Tile`s), then the chance of encountering a more lethal enemy might increase. Likewise, entering a small desert might drain the players endurance less.

In order to work out the areas to begin with, you would need to iterate over every tile in your map when you load the map. If that `Tile` was not next to an `Area` of the same type, create a new `Area` and add that `Tile` to it. If the `Tile` is next to an similar `Area`, just add that `Tile` to it.

If a `Tile` is adjacent to more than one `Area` of the same type, combine all `Tile`s contained in all of those `Area`s into one `Area`.

Then if you are simulating a growing / changing world and a new forest does sprout, just use the same method as above to see whether that `Tile` is adjacent to an `Area` and act accordingly.

# Answer
> 0 votes
Not sure if associating each tile to its type should be a major concern in terms of execution speed. You'll only be doing this when the game loads, not on every frame. Regarding how I'd do it:

I would define simple rectangle structures in case there are none defined in your environment:

```
structure Rect has components:
    XPosition : integer
    YPosition : integer
    Width : integer
    Height : integer

```

and extend this to:

```
structure AreaTypeRect has components:
      <components from Rect>
      AreaType[] : symbol

```

And store them in a SQL (since you're using it) table. Map each rectangle to the level it belongs to with a foreign key.

Basically, the rectangle with XPosition = 5, YPosition = 5, Width = 10, Height = 10 means the tiles in the rectangle defined by the points (5, 5), (5, 15), (15, 5), (15, 15). Why did I define AreaType as array? You may define it as a single value-type if you absolutely won't need terrain type blending. But you might reach some nice effects with multiple types per tile. For example, you could mark a particular tile to be of the type Grass and then add the type Water to it. This could result in a Grass tile with some Water stains on it, as if it rained a lot.

I might be overthinking this though. Perhaps a single AreaType per tile is enough for your needs. AreaType can be any kind of symbol, but you must tell your game how to interpret it. I would go with integers and map them like this:

```
(integer AreaTypeID, Texture TileSprite)

```

or with colors, as you mentioned you'll be using in the editor (blending colors from multiple terrain types is even easier):

```
(integer AreaTypeID, Color TileColor)

```

e.g.

```
(0, GrassTile)
(1, WoodTile)

```

You can do this mapping in a SQL table, if you do store things such as textures in the SQL database. I'd store artwork on the hard drive though.

# Answer
> 0 votes
Just add another column (of type string) to your 'tiles' table to allow you to enter values such as 'The valley of uncanny'?

---
Tags: 2d, rpg, tilemap, sql
---


# Question
Title: What are the pros and cons of HLSL vs GLSL vs cg?
What are the pros / cons of the three?

# Answer
> 46 votes
coderanger is right about HLSL targeting DirectX, GLSL targeting OpenGL and CG being available with both interfaces.

However there are other things to consider (learned on the OGRE forum) :

* CG will not allow you to use the latest features of GLSL (I'm not sure about HLSL). It's a middle ground so you'll not be able to fully exploit the GLSL features, only the common one until Shader Model 3.0 (AFAI understood).
* CG is made by NVidia that optimize it for it's card but don't seem to do lot of work for ATI cards... some people report that there might be problems with ATI cards using CG.
* OpenGL seem to be a bit slower than DirectX on Windows platforms. That's really relative to what you're doing and the reason for this find it's source in the drivers implementations but it's good to know before you choose the API and the associated shader language. However, OpenGL is the only one interface available on all (win/mac/unix/some consoles) platforms. So knowing that, using exclusively GLSL might be the better choice for a non-Microsft-centric-cross-platform game.
* NVidia drivers on Linux seem to be more stable than ATI drivers, making CG more interesting if you need to be sure it works nicely on linux (that's all reported informations, you'll have to check for details)

So, if you're not using the lastest shader features, CG seem a good choice. GLSL seem a beter one if you're going full OpenGL. HLSL if you're going exclusively on Microsoft platforms.

Now first developping in HLSL for windows to use DirectX and then convert to GLSL for linux and mac could be the better solution to be sure of performance and have the larger set of shader features available. It might however be a lot of work (didn't do it myself so I cannot tell). OGRE graphics engine (and other engines) allow to use any API (DirectX or OpenGL or others) so it helps, but there is still shader code to convert if you go this way.

That's all the information I gathered while choosing my shader language (I've not made my decision yet).

---

Update: Valve did a conversion of one of their game to OpenGL and found no way to make the DirectX version faster than the OGL one. So keep in mind that the state of driver implementation, API quality, etc., all that change too much each year for you to totally rely on raw performance as an argument to choose one or the other. With this in mind, choose OpenGL/GLSL to simplify your life when working (or having plans or hopes to work) with other platforms than Windows, use DirectX/HLSL if you really want to use only Microsoft platforms and focus and maybe have some good API faster than OpenGL (this is reversing now, so don't count on it); use CG if you want to provide both possibilities to the user, but if you have the work force (and tools) to do it, using both GLSL and HLSL might be a viable solution too.

---

Update (2012): It is important to note that CG has been discontinued, and is no longer supported or actively worked on by Nvidia. Nvidia recommends that all users switch to a combination of GLSL and HLSL, or a newer library such as nvFX (on github). This is because it was too difficult to maintain feature-compatibility between GLSL and HLSL.

# Answer
> 15 votes
I can only talk about CG vs HLSL because those are the 2 I have used so far.

Cg is *not* the same as HLSL.

In Cg, NVIDIA did an excellent job in creating a very clean shader syntax. Its very similar to HLSL.

**But**, tie-together with D3D9/D3D11 (init code, shader compilation code) is ***much cleaner*** on HLSL than Cg. -1 Cg. Cg has a nasty bit of start up code that you don't even need to have for HLSL over D3D.

In Cg, you have to "cgGetNamedParameter" for *every* `uniform` shader variable you want to set/modify. And you have to maintain a `CGparameter` reference in your code for that variable

```
// C++ code to interact with Cg shader variable (shader language independent)
CGparameter mvp = cgGetNamedParameter( vs, "modelViewProj" );
CG::getLastError("Getting modelViewProj parameter");  // check for errors
cgSetMatrixParameterdr( mvp, &modelViewProj._11 ) ;   // setting the matrix values

```

In HLSL, this ends up being much cleaner - just one line, and you don't have to maintain that `CGparameter` variable.

```
// D3D9 C++ code to interact with HLSL shader variable
DX_CHECK( id3dxEffect->SetMatrix("modelViewProj", &mvp._11 ), "Set matrix" ) ;

```

In the above, `DX_CHECK` is just a simple function that checks the HRESULT that gets returned from the `SetMatrix` call. *The above code is d3d9*. D3D10 and 11, are of course, a lot more painful (since there isn't an ID3DX11Effect object).

Before I started using HLSL, I used to look at this code and actually *get jealous*.

Although NVIDIA did their best to make a common interface for Cg between OpenGL/D3D, practically speaking its *not* that way, and you have `cgGL*`, `cgD3D9`, `cgD3D10`, `cgD3D11` function groups to contend with. So that whole *works for OpenGL **and** D3D!!* claim only goes so far. You still have to wrap everything up into OpenGL/D3D `#ifdef` type groups to make it work on different platforms. -2 Cg.

Further I have recently had a bad experience with Cg/ATI cards, which I'm *pretty sure* isn't my bad. (Someone else try it out?). I think it may be true that NVIDIA doesn't completely test ATI cards, as Klaim claims. Or that ATI doesn't test on Cg. One way or the other, there's a mismatch there and some sort of conflict of interests. -3 Cg.

All in all I preferred Cg. Its *shader code* syntax and naming is clean, sweet, and tidy. Its too bad its got these other problems.

# Answer
> 11 votes
My very basic understanding is that HLSL is only for DirectX and GLSL is only for OpenGL. Cg is basically the same language as HLSL, but can be used with either DirectX or OpenGL (though via different runtime code).

# Answer
> 9 votes
Another crucial difference between HLSL and GLSL (I don't know CG so I can't speak for it) is that with HLSL Microsoft provide the shader compiler as part of the D3D runtime whereas with GLSL your hardware vendor provides it as part of their driver.

This has advantages and disadvantages on both sides.

With the GLSL method the vendor can tune the compiler to the capabilities of their hardware. They know their own hardware best, they know what to do and what not to do. On the other hand the disadvantage is that - in a world where there are multiple hardware vendors - you have a situationwhere there can be inconsistencies between shader compilers, and the vendor also has complete free reign to screw up.

With the HLSL method Microsoft control the compiler. Everyone is on a consistent tech base, and if a shader compiles successfully in one place then it can be reasonably supposed to compile everywhere. The same shader will produce the same compiled output irrespective of vendor (all other things being equal of course). On the other hand the HLSL compiler has to be a "works consistently on everything" thing, so it's not able to pull any special vendor-specific tricks to get the last few drops of juice out of the tank.

If this comes across as though I have a preference for the HLSL view of the world it's because I do. I've been bitten badly before by wildly inconsistent behaviour on different platforms, and in one case even ended up having to roll a load of GLSL back to ARB ASM just to get a baseline that worked. NVIDIA's GLSL compiler can be viewed as particularly notorious here - it will even accept HLSL syntax and keywords, meaning that if you're not careful you can end up producing shaders that will only work on NVIDIA and nothing else. It is a jungle out there.

# Answer
> 1 votes
You might want to look into the RTSS (Run Time Shader System) that comes with Ogre as well. It is fairly new, but you basically write shaders in code rather than external files. I have not implemented it yet, but definitely plan to use this when the time comes.

Here is a huge series of tutorials on the Ogre wiki as well for writing shaders. http://www.ogre3d.org/tikiwiki/JaJDoo+Shader+Guide

As for your original question, like Praetor said, its not really a matter of pros/cons, it is a matter of what rendering system you want are going to use. Since using DX/OpenGL with Ogre is just a matter of loading the plugin, you will most likely want to use .cg format.

# Answer
> 1 votes
I have been using both, I started with glsl and moved to hlsl only because the project demands it. Given the choice, it's glsl all the way. glsl feels very slick and hlsl feels like it came out off an engineer's hobby bench.

---
Tags: shaders, glsl, hlsl, cg
---


# Question
Title: Is using Sprites the most recommended way for doing 2d animations with Directx?
I am working on a game engine of my own and I was using Vertex buffers to create triangles and then draw textures on them. Now I want to extend it so I can do simple 2d animations using "sprite sheets". I'm not sure how to accomplish this by using vertex buffers, since those are "hard coded" and I can't figure out an easy way to draw "portions" of the sprite sheet using them. I've been searching online and most tutorials use DirectX Sprite functions to do it so my question is, is it possible to achieve this by using vertex buffers or should I go and use sprites? The only thing that is stopping me from using sprites is the fact that some graphics stuff I have already relies on vertex buffers.

# Answer
If you use Dynamic Vertex Buffers in DirectX you can write to existing vertex buffers changing only one or even several attributes. You could simply overwrite the UV coordinates of vertices in the buffer of every sprite every few frames to make animations work. I think this will perform wonderful because that information needs to get to the GPU anyway and updating vertex buffers is usually very fast.

That said using the built in sprite functions might be easier but underneath a sprite is just 2 triangles and the sprite functions might even use vertex buffers underneath so if you've written a lot of code already that you don't wish to change I would recommend trying this.

(small note: creating a vertex buffer for *every* 'sprite' is not a good idea though, you should implement some form of sprite batching for sprites with the same texture that are on screen)
> 3 votes

---
Tags: directx, animation, sprites
---


# Question
Title: Multiplayer game sdk for ios and android
I am working on a multiplayer game supporting Android and IOS.

For IOS Game-Center seems promising. But its IOS only.

OpenFeint could be a option, but now GREE has stopped supporting it.

Is there any other multi-platform SDK which I can use for both IOS and Android?

---------EDIT------

I could not find any good service which provides their own server and SDK for both IOS and android. So finally I chose to go with my own server on AWS-EC2 + python tornado + Websocket. If anyone want to know more plz contact...

# Answer
> 3 votes
Multiplayer SDK? you don't need an SDK.

Multiplayer works over network, all you need to run a multiplayer game is a discovery service to allow players to start playing together.

* This can be setup on a LAN using a zeroconf protocol
* Over the web by using a small web service.

Once the players are interconnected you start sending your data across nodes.

# Answer
> 0 votes
Well you could look into open feint's competitors such as scoreloop, AGON, plus+, etc. Theres many different options available online, some doing more than others. Perhaps you could elaborate on what you want so I or someone else could make a suggestion.

---
Tags: android, game-design, ios, multiplayer
---


title: How is 'mass' handled in video games?

text:
# Question
Title: How is 'mass' handled in video games?
Mass is one of the basic scalar quantities, which is required in most rigid body physics calculations.

In a game, does every moving object have mass defined in the code, or is it allotted by the rendered objects size? Size should not be the only solution, though, since density also comes into play.

For example how does the physics engine handle mass in the Frostbite engine used in *"Battlefield 3"*?

# Answer
> 1 votes
Might as well make this an answer.

---

From my experience, mass is either:

a) A global value that applies to all spatial objects equally (or no mass scalar at all).

or...

b) An individual scalar value (e.g., pounds, kilograms) directly associated with each individual object. This approach obviously doesn't scale well.

or...

c) Defined by a base "type" (e.g., wood, rock, water, flesh, weightless...) with a scalar value associated with the type. That value could be used on its own or it could be used in conjunction with the size of the object to determine the final scalar, depending on the accuracy required.

Not sure about the Frostbite engine but I would assume it uses something similar to c).

# Answer
> 4 votes
Physically, mass is not directly related to volume. OK, technically mass is related to volume, but based on another property: *density*. My point is that you could only apply a volume-based mass if the object has a specific density. Which is ultimately little more than just selecting the mass by selecting a density. Though if you have breakable things, having a density is useful as it allows you to compute the mass of the broken object(s).

In general, the masses of objects that are physically modeled are usually chosen in a videogame based on the actual *results* of the physics simulation, not realistic physical properties. Game developers pick what looks good and behaves well, not what is necessarily "correct" in any real-world context.

# Answer
> 0 votes
there is probably diffrent ways to solve this, and depending on how important that is for your game, you could end up adding a scalar value to each entity saying it´s specifik mass that gets calulated at loading time.

Another aproach is what Djentleman said, to define stuff like wood, rock, metal and water and from there define the mass.

I dont think any one here knows the frostbite engine well enugh to say how they handle it, and if they are, they are probably not allowed to tell you how it´s working.

---
Tags: physics
---


title: Casual gamer age distribution

text:
# Question
Title: Casual gamer age distribution
What is the age histogram of people who play casual mobile games like Cut The Rope, Angry Birds and so on?

# Answer
Here is a source, i do not know if it can be trusted but it looks legit. http://www.statista.com/statistics/246577/age-distribution-of-mobile-gamers/

To put the answer right here the largest group of mobile gamers have an age of 25 to 34 and represent 27% of the total.

2nd and 3rd are surprisingly older with 23% for 35-44 years and 18% for 45 to 54 years.

Only 16% of the ages of 18 to 24, but i am sure it would be significantly bigger if they would have count it from the age of 15.

Last but certainly not least we have the 55+ gamers representing 16%. Who would have expected that?
> 1 votes

# Answer
Tracking the references in this Forbes Article: New Report Details Demographics of Mobile Gamers Buying Virtual Goods

The MocoSpace study, as well as numerous others with similar data is available through Fact Browser.
> 1 votes

# Answer
A Flurry report shows an interesting pattern in freemium games - mostly younger people play (age groups 18-24, then 13-17), but older people pay (age groups 25-34, then 35-54).
> 1 votes

---
Tags: casual-games, demographics
---


# Question
Title: Spherical procedural terrain shader based on slope
I've created a spherical terrain object out of 6 sphere projected (normalised) planes, each plane has been heightmapped post to being normalised.

I'm looking to create a CG shader which will firstly calculate the slope of the heightmapped terrain, I understand this will need to look at the normals to calculate this can anyone elaborate on this for me? The next problem is that I want to do the slope calculations based upon the terrain "flat" rather than normalised.

Would it be best to either reverse the normalisation of the vertices during the slope calculations, or pre calculate and store the vertices slope data (on the flat plane) during the mesh generation?

This is an example of what I want to achieve with the shader:

Any suggestions would be brilliant.

Thanks, C.

---

Update in response to **opatut** answer:

I've output the current slope data based of how I "think" was suggested and these were the results:

I think my issue is that as each plane begins to curve that curve is includes as a slope which is the obvious thing to happen. I want to "flatten" out each of the 6 planes again for the slope calculations.

# Answer
> 1 votes
Why does it have to be 6 height-mapped planes? It would probably be a lot easier if you geometry-shaded a sphere and did all your calculations based on that sphere - you can easily compare the normal vector to the radius vector (basically the location of the vertex relative to the sphere center) to get your slope angle.

Also, I think it'd be easier to generate the heigh maps, or at least you could cubemap the sphere as well... Also, you will definitely get higher resolution heightmaps, since you don't have to use part of the value range (0..255) to achieve the sphere shape.

*Update due to more information from comment below:*

> Would it be best to either reverse the normalisation of the vertices during the slope calculations, or pre calculate and store the vertices slope data (on the flat plane) during the mesh generation?

Depends on what you need the slope calculations for. If you require them for your simulation (e.g. driving physics), it won't help you if you have them in the shader only. Then you will need them in the program anyway, so you can implement your calculations once and store them in the vertex data - if the mesh does not get too high-resolution, it should be fine.

But if you just want to apply the slope-based texture effect, calculating them in the shader should be fine. You should have the exact (heightmap-transformed) vertex position in the shader, so you can just take that position, calculate the radius vector from that (i.e. just normalize the vertex position since your sphere center is `0,0,0`) and calculate the angle to the normal vector. No need to transform the vertex position again.

---
Tags: shaders, terrain, heightmap
---


# Question
Title: How to handle multiple effect files in XNA
So I'm using ModelMesh and it's built in Effects parameter to draw a mesh with some shaders I'm playing with. I have a simple GUI that lets me change these parameters to my heart's desire. My question is, how do I handle shaders that have unique parameters? For example, I want a 'shiny' parameter that affects shaders with Phong-type specular components, but for an environment mapping shader such a parameter doesn't make a lot of sense. How I have it right now is that every time I call the ModelMesh's Draw() function, I set all the Effect parameters as so

```
foreach (ModelMesh m in model.Meshes)
        {

            if (isDrawBunny == true)//Slightly change the way the world matrix is calculated if using the bunny object, since it is not quite centered in object space
            {
                world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position + bunnyPositionTransform);
            }
            else //If not rendering the bunny, draw normally
            {
                world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position);
            }

            foreach (Effect e in m.Effects)
            {
                Matrix ViewProjection = camera.ViewMatrix * camera.ProjectionMatrix;
                e.Parameters["ViewProjection"].SetValue(ViewProjection);
                e.Parameters["World"].SetValue(world);
                e.Parameters["diffuseLightPosition"].SetValue(lightPositionW);
                e.Parameters["CameraPosition"].SetValue(camera.Position);
                e.Parameters["LightColor"].SetValue(lightColor);
                e.Parameters["MaterialColor"].SetValue(materialColor);
                e.Parameters["shininess"].SetValue(shininess);

                //e.Parameters
                //e.Parameters["normal"]

            }
            m.Draw();

```

Note the prescience of the example! The solutions I've thought of involve preloading all the shaders, and updating the unique parameters as needed. So my question is, is there a best practice I'm missing here? Is there a way to pull the parameters a given Effect needs from that Effect?

Thank you all for your time!

# Answer
> 1 votes
It's possible that in code, you could create a structure that holds the ShaderVariable name and then the ShaderVariable value. You'll most likely need a specific overload or function to set the value, seeing as `EffectParameter.SetValue( ... )` only has certain overloads (or you could write a `SetValue` on the structure that takes a generic object and just does some runtime type determination, but that *could* be slow).

You could store a list of all these external `UniqueEffectParameters` with the `Model` it's used on or with the `Effect` it's used with. In the end, you'd end up just using another variable along with your `UniqueEffectParameter`:

```
foreach (UniqueEffectParameter u in UniqueParameterList) {
    u.SetValue(effect);
}

```

In order to keep this working without having to have a switch statement or runtime type-checking, `SetValue` could be a virtual function that you overload with specific classes, say:

```
public class Vector3EffectParameter : UniqueEffectParameter {
    public Vector3 Value;

    public override void SetValue ( Effect effect ) {
        effect.Parameters[Name].SetValue(Value);
    }
}

```

The base class would contain just a string `Name` and an `public virtual void SetValue` for you to override and use as you like. I hope this makes sense. Good luck!

# Answer
> 1 votes
You could do something like this:

1. At startup, you run though all the Effects and save the parameters name that they expose
2. Create a class that let the user associate a parameter name (String) with a resource (Textures, matrix ...) (for example, he can say that the string "ColorMap" is associated with the texture Diffuse123)
3. When you draw the model, you ask for this class to lookup and see if the current effect has any of this exposed properties globally setted by the user and if it has you just update the related effect parameter, for example, if the current shader has a parameter called "ColorMap", the above class will recover the texture previously added and will """inject""" it in the effect.

In XNA, every Effect have an EffectParameterCollection, that contains lots of EffectParameter that have a Name and methods to set and get their values. Take a look at it.

Lots of engine like Hieroglyph 3 (Directx 11) has some way of handling global effect parameters.

# Answer
> 0 votes
```
foreach(var parameter in e.Parameters)
{
    Debug.WriteLine(parameter.Name);
}

```

---
Tags: xna, shaders
---


# Question
Title: making a game in 2D(C++). SDL or openGL? Or, why not both?
I'm trying to make a platform game in 2D and I want to know what tool should I use to make it happen. I understand that I can use SDL with openGL. However, if I want to make a solid 2D platform game, should I use SDL? Or, openGL?

# Answer
> 8 votes
If you want a lot of fancy effects and sprites on the screen at once, use OpenGL because it supports shaders and is hardware accelerated. If your game is simple and doesn't need a lot of effects or sprites, stick with SDL, especially if it's your first game. SDL isn't hardware accelerated, but it's much easier to use. SDL2 *does* have hardware acceleration, which also has a very easy API (`SDL_Renderer`s and `SDL_Texture`s).

Note that if you are going to use OpenGL, you can actually use SDL for everything but graphics at the same time. Other cross-platform windowing libraries that support OpenGL include:

* FreeGLUT - a free implementation of GLUT, which is older and well-documented
* GLFW - similar to FreeGLUT, but more modern **(I use this one)**
* SFML - this one is a bit more heavyweight, but it's also object-oriented

# Answer
> 3 votes
OpenGL is for rendering polygons on the screen and SDL provides low level access to hardware like joysticks and mice. SDL also provides access to the video frame buffer.

I would suggest you use SDL for hardware stuff and OpenGL for drawing and stay away from the video frame buffer. It's easy enough to create an orthographic projection and position the camera so it's always pointing down at your scene. If you don't want to use polygons you can always use a textured quad as a sprite. This gives you all the power of OpenGL(rotate, while maintaining your 2d platform game feel.

You might also take a look at love2d.org

---
Tags: opengl, c++, software-engineering, sdl
---


# Question
Title: How do I get an instance of KX_PolygonMaterial in Blender?
I've got a question concerning using Python in Blender's Game Engine.

Before I start I want to state that I'm trying to change the color of an object in Blender's game engine. To do this, I'm attempting to find a way to update the texture of the object (I basically want two or three states, red, (yellow), green).

What I'm doing right now is:

```
scene = GameLogic.getCurrentScene();
pingMeter = scene.objects['Ping Meter'];
mesh = pingMeter.meshes;
materials = mesh[0].materials;
material = materials[0];

```

However, when I do `print(material.__class__.__name__)` it outputs `KX_BlenderMaterial`. Shouldn't I be getting `KX_PolygonMaterial` if I'm running the Blender Game Engine? Is there anyway to change color or texture with `KX_BlenderMaterial` because I can't find anything in the documentation. Can I get an instance of `KX_PolygonMaterial` out of the code above?

...or should I just take a different approach all together?

Thanks!

**EDIT**: I'm using Blender 2.65 which uses Python 3 in case anyone is wondering.

# Answer
> 0 votes
I determined a way to change the color of an object's material in Python with Blender 2.65. Before my approach above I simply tried something like:

```
scene = GameLogic.getCurrentScene();
pingMeter = scene.objects['Ping Meter'];
red = mathutils.Vector((1.0, 0.0, 0.0, 1.0));
pingMeter.color = red;

```

However, this produced no change to the color of the material (should've turned red, and the object was properly lit as well). I found that there has to be an option checked under the materials menu of the object which is `Object Color`. After checking this box the ping meter successfully change to red in the game.

Additionally, another method I attempted was to get the mesh of the object, get the material of the mesh, and change each vertex color of it. This did not work either, however I speculate that if the `Vertex Color Paint` option is checked in the materials menu that it would. I have not tested this though.

---
Tags: textures, python, blender
---


# Question
Title: Fastest way to render lines with AA, varying thickness in DirectX
So I'm doing some DirectX development, using SharpDX under .NET to be exact (but DirectX/C++ API solutions are applicable). I'm looking for the fastest way to render lines in an orthogonal projection (e.g. simulating 2D line drawing for scientific apps) using DirectX.

A screenshot of the sorts of plots I'm trying to render follows:

It's not uncommon for these sorts of plots to have lines with millions of segments, of variable thickness, with or without antialiasing per-line (or full screen AA on/off). I need to update the vertices for the lines very frequently (e.g. 20 times/second) and offload as much to the GPU as possible.

So far I have tried:

1. Software rendering, e.g. GDI+ actually not bad performance but obviously is heavy on the CPU
2. Direct2D API - slower than GDI, especially with Antialiasing on
3. Direct3D10 using this method to emulate AA using vertex colours and tessellation on the CPU side. Also slow (I profiled it and 80% of time is spent computing vertex positions)

For the 3rd method I'm using Vertex Buffers to send a triangle strip to the GPU and updating every 200ms with new vertices. I'm getting a refresh rate of around 5FPS for 100,000 line segments. I need millions ideally!

Now I'm thinking that the fastest way would be to do the tessellation on the GPU, e.g. in a Geometry Shader. I could send the vertices as a line-list or pack in a texture and unpack in a Geometry Shader to create the quads. Or, just send raw points to a pixel shader and implement Bresenham Line drawing entirely in a pixel shader. My HLSL is rusty, shader model 2 from 2006 so I don't know about the crazy stuff modern GPUs can do.

So the question is: \- has anyone done this before, and do you have any suggestions to try? \- Do you have any suggestions to improve performance with rapidly updating geometry (e.g. new vertex list every 20ms)?

**UPDATE 21st Jan**

I have since implemented method (3) above using Geometry shaders using LineStrip and Dynamic Vertex Buffers. Now I'm getting 100FPS at 100k points and 10FPS at 1,000,000 points. This is a huge improvement but now I'm fill-rate and compute limited, so I got thinking about other techniques/ideas.

* What about Hardware Instancing of a Line Segment geometry?
* What about Sprite Batch?
* What about other (Pixel shader) oriented methods?
* Can I efficiently cull on the GPU or CPU?

Your comments & suggestions much appreciated!

# Answer
> 15 votes
If you are going to render `Y = f(X)` graphs only, then I suggest trying the following method.

The curve data is passed as **texture data**, making it persistent, and allowing for partial updates through `glTexSubImage2D` for instance. If you need scrolling you could even implement a circular buffer and only update a few values per frame. Each curve is rendered as a **fullscreen quad** and all the work is done by the pixel shader.

The one-component texture contents could look like this:

```
+----+----+----+----+
| 12 | 10 |  5 | .. | values for curve #1
+----+----+----+----+
| 55 | 83 | 87 | .. | values for curve #2
+----+----+----+----+

```

The work of the pixel shader is as follows:

* find the X coordinate of the current fragment in the dataset space
* take eg. the 4 closest data points that have data; for instance if the X value is `41.3` it would choose `40`, `41`, `42` and `43`.
* query the texture for the 4 Y values (make sure the sampler does no interpolation of any kind)
* convert the `X,Y` pairs to screen space
* compute the distance from current fragment to each of the **three segments** and **four points**
* use the distance as an alpha value for the current fragment

You may wish to substitute 4 with larger values depending on the potential zoom level.

I have written a very quick and dirty GLSL shader implementing this feature. I may add the HLSL version later, but you should be able to convert it without too much effort. The result can be seen below, with different line sizes and data densities:

One clear advantage is that the amount of data transferred is very low, and the number of drawcalls is only one.

# Answer
> 5 votes
There was a GPU Gems chapter on rendering antialiased lines: Fast Prefiltered Lines. The basic idea is to render each line segment as a quad and calculate, at each pixel, a Gaussian function of the pixel center's distance from the line segment.

This does mean drawing each line segment in the graph as a separate quad, but in D3D11 you could certainly use a geometry shader and/or instancing to generate the quads, reducing the amount of data to be transferred to the GPU to just the data points themselves. I'd probably set up the data points as a StructuredBuffer to be read by the vertex / geometry shader, then do a draw call specifying the number of segments to be drawn. There wouldn't be any actual vertex buffers; the vertex shader would just use SV\_VertexID or SV\_InstanceID to determine which data points to look at.

---
Tags: 2d, directx, shaders
---


# Question
Title: Persistent Data for Multiplayer, Browser-Based Games
What is generally used to store persistent data in online games - browser games/facebook apps, in particular?

I have used MySQL in web development before - but I've read that it's not very scalable, especially if many transactions are happening constantly (which is what will happen inside of a game).

I'm writing the back end in Node.js using Heroku, so it would be really nice if there were a Node package to go with it.

Any insight would be much appreciated.

# Answer
> 2 votes
You can find one nodejs mysql pack here https://github.com/sidorares/nodejs-mysql-native To scale you can use shards, partitioning, replication (with read only instance), try adding some cache layer like memcached ... (not game specific - there is an article from facebook showing how they scaled mysql) The database choice heavily depends on your data modeling. If you need to scale at high rates, consider using some kind of nosql database (in games, some key value based db like redis can help you a lot - it also integrates nicely with nodejs http://redis.io/clients)

# Answer
> 0 votes
If you want to persist the data with the user you can use localStorage. It's pretty simple to use

```
windows.localStorage['myvar'] = 'some data';

```

There are two downsides tho.

1. Almost all browsers limit you to 5m of data
2. You can only store strings which means you will need to stringify any objects you want to store.

# Answer
> 0 votes
Well, the load of the DataBase depends a lot of what kind of game you want to develop, in some cases MySQL or Postgres will do, but assuming the worst case MongoDB is a very good solution, plays nice with Node.js, scales horizontally, and has useful features for VideoGames as geospatial indexes.

Take a look at the use cases.

PD: I have seen blogs posts about Heroku + Node.js + MongoDB.

---
Tags: browser-based-games, databases, online, data, node.js
---


title: Camera Calculation

text:
# Question
Title: Camera Calculation
For my game I don't able to decide what camera resolution I have to use ?

Normally I use 1024x600 landscape resolution of camera for my game and create single graphics for my game.

But I found that my chosen resolution was not perfect enough, in some device it shows black bar that does not render by the game engine.

So what I have to do for camera that support all type of android device that I am not able to decide. If I have to create multiple graphics that also suggest me about that option also. What resolution I have to choose so that It runs on all type of android devices and from graphics designer I have to create which resolution graphics?

Thanks guys for your help because I got a lot from you.

EDIT : I like to mention that my current development platform is AndEngine.

# Answer
> 3 votes
You need to ask for the device's resolution, and then, set the viewport to fit it. I assume that you are using Cocos2d X, they call it Multi Resolution, hope this helps.

---

**Edit:** This post from Jesús bosch may give extra information about the topic.

---
Tags: sprites, andengine, cocos2d-x, viewport
---


# Question
Title: Is a "game engine" a necessity for making a game?
What's up with the terminology confusion anyways? Some have claimed DirectX SDK to be a game engine itself.

According to Wikipedia a game engine is a system for making games. But along what lines do what draw between the two concepts, such as "making or using an engine to make a game", and just "writing the code that the specific game will be executed upon". This is a hassle to break down. People enforce the idea of an "engine" to run games on or with, or written around, but a direct executable series of code that implements user I/O, graphics of some sort, and conditional logic, AI and animations, you have yourself a game.

Does this imply that every game is an "engine", or that a game has the potential to run as part of an engine? Confusing terminology.

# Answer
> 10 votes
There is no standard, canonical definition of the term "game engine." The Wikipedia article on the subject is reasonable, but isn't authoritative and you'll still find a lot of developers who disagree over various details. Consequently, you end up with a lot of slightly different (but generally similar) definitions in use and that's often what leads to the "terminology confusion." This is *especially* a problem when you get non-technical people (like video game journalists) using the term, because they often have a very poor understanding of what actual game development is like and tend to perpetuate half-truths and myths.

A "game engine" isn't required to make a game. A game is just a piece of software, and you can write software using a variety of tools. We tend to call some of those tools "engines" (you'll find that *most* developers agree that an "engine" of some sort is aimed at providing reusable building blocks).

But you don't need to use every tool at your disposal to build a product, and indeed you seemed to have demonstrated this already by building games "directly."

# Answer
> 2 votes
Well, the problem as I see it is that people use the term too loosely, inasmuch as they refuse to specify what kind of "GAME ENGINE" they're referring to.

It's not that "Game Engines" aren't full-fledged things, which handle all aspects of the game...
...or that they can be.

The problem is that a Physics Engine is an engine which is self-contained, and will accept inputs of things to do work on, and will output the equivalent in work, after the engine transforms the input.

So is a Lighting Engine.

So is a Graphics Engine.

So is a Sound Engine.

All of these things meet the qualifications of being an "engine", as a lexicologist might consider it, in the abstract sense, and all of these engines are game engines, in that they are all engines predominantly written to be used in games.

The extra layer of frustration comes in when you consider that you can have an overarching game-management engine, which wraps ALL of the other engines, as plug-ins, or as bolt-ons.

This is something which doesn't really happen often, in the real world, except when thinking more of fully-autonomous corporate subsidiaries...
Dell bought Alienware -- Alienware is still allowed to do its own thing, in a modular and self-contained way, but the self-contained entity known as Dell has wholly-encapsulated it (with a few "API" Alienware-branded touchpoints left exposed).

So now, most of the functionality of Alienware is still held by Alienware, still self-contained, still a revenue-engine...
...but it's owned and operated in a loosely-coupled fashion by Dell, who, themselves, are their own revenue-engine.

OpenGL isn't really an engine, because there's nothing particularly self-contained about it.
There are no well-defined inputs and outputs.
Consider it like Calculus -- something goes in, you know what's coming out.

A graphics engine might be one where the resource-management engine hands the graphics engine the textures, and the physics engine hands the graphics engine the transformed polygons, and then the graphics engine will make all of the magic happen, and can be loosely coupled through bolt-on/plug-in interfaces to work with OpenGL or OpenGL ES2.0 or DirectX or Canvas/JS or Flash/AS3 or a software renderer, based on switches, but without other graphics work happening externally.

Is it an engine? Sure. You've got well-defined inputs and outputs, you've got known quantities/properties for input (fuel) and you have expected results.

Wrapped inside of a game-engine, is a specific engine still an engine? Yes.

Do fans/journalists/etc get the distinction between Rage being an overarching game-engine, Havok being a physics engine and Euphoria being an AI+physics "natural and procedural animation" engine?

Not remotely.

Is it still an engine?
Yep.

Also: "game engines" aren't a requirement at all.
Pong is totally doable as a bunch of procedurally-called lines in Notepad.exe

But as complexity of game-code, as well as complexity of visual and state-managing (RPGs) expectations rose, engines made life better, whether they were physics engines, graphics engines, lighting engines, sound engines, combat engines, stat engines or just flat-out engine-configuring/running engines...

---
Tags: terminology
---


title: Why can't my .exe find my .fx file?

text:
# Question
Title: Why can't my .exe find my .fx file?
I'm having a problem with my .fx file in my D3D 11 application.

I can run the application just fine from Visual Studio, but when I run the .exe it fails when trying to load the .fx file.

I've checked the file name in the code and tried all sorts of paths but I can't figure this out, why is this happening?

# Answer
This is likely due to a difference in the working directory for your program when run from Visual Studio versus launched "normally." Visual Studio sets the working directory for a process it launches. When you launch the executable normally, the working directory is the directory containing the executable itself.

Since relative paths begin at the working directory, this changes where you end up effectively looking for data files. Consider the following typical directory structure:

```
X/Projects/Game
  Game.sln
  Game.vcproj   <-- your project file
  Source/
  Assets/
    Shader.fx   <-- your shader
  bin/
    Debug/
    Release/
      Game.exe  <-- your compiled executable

```

You probably refer to your shader file in code via the relative path `"Assets/Shader.fx"` (or similar, adjusted for your actual directory structure).

Visual Studio uses the *project directory* as the working directory by default for C++ projects when launching your process. In the case of the above structure, that is the path `X/Projects/Game` and consequently your relative path reference to the shader is `X/Projects/Game/Assets/Shader.fx`. This path exists, so everything runs normally when launched from the IDE.

But if you double-click the compiled `Game.exe` from `explorer.exe` your working directory is `X/Projects/Game/bin/Debug` and consequently your relative path reference becomes `X/Projects/Game/bin/Debug/Assets/Shader.fx`. That path *doesn't* exist, and until it does, your game won't run properly.

The solution is to ensure that the shader and other assets get copied to the output directory of the executable (maintaining their directory structure, if applicable). One way to do this is via custom build steps in your project, for example by launching a batch file to copy the relevant files or using a direct invocation of something like robocopy. Visual Studio has a fairly robust set of macros that can be used to make construction of this build step easier, so you could do something like:

```
robocopy $(ProjectDir)/Assets $(TargetDir) /S

```
> 3 votes

---
Tags: shaders, directx11
---


# Question
Title: Story dialogues: user controlled or script driven?
I'm currently working on the animations that present the story.

Right now my animations are scripted. They allow me to dictate the pace of the scene. My dialogue bubbles expire on a simple "time per char" system or scripted time where needed.

I was wondering that maybe i should let the user control the flow with a click for each major frame. This gives him the time he needs to read and process the dialogue.

But that breaks the flow. For example: when i want to create agitation, dialogues are really fast, barely readable etc.. Important stuff on the other hand is slow.

So my question is, what would your approach and why? Generally speaking. What do users prefer in these cases?

Platform is phones, scenes are presented in the same env as game engine, with characters only walking and talking.

# Answer
> 3 votes
I believe the correct answer to be 100% ***both***.

Based on how you've implemented it, you're going to want to do one or more of a few things:

First, I think it's a big deal that you present your game artistically and in a meaningful way.
I would never argue with that requirement. If the best way to do that, at various points of the story is through text, then do it exactly that way.

At the same time, never prevent a user from speeding through your presentation, either.
If somebody is so excited by your gameplay that they'd rather burn through the cutscenes and read a synopsis or read it on a second playthrough, because they just want to go back to being awesome, then you should let them do *that*, as well.

Depending on the game, I'm totally both. I'll still watch every cutscene in Anachronox or every talking head in Fallout 1...
...but how annoying is it when you just want to auto-skip the 5-minute cutscenes in Max Payne 3, to get back to mowing down half of Brazil?

So the solution might be to do something like this:

1. Set different *paces* (rather than speeds) for your text-display.
2. Have user-selected "speeds", which operate like a multiplier (slow\_rate = slow\_pace * speed)
3. When starting a cutscene, allow for users to hold the text box to speed up delivery...
Or allow them to tap the box to dump that full card worth of text into the box...
Allow them to tap again to skip to the next box...
Consider allowing a swap between auto and manual (and sped-auto, by holding)...
Give them an option to outright skip over the cutscene, and teleport them to the next section

Really, there are a lot of things that you can do, here.

Perhaps your cutscenes might appear "out of sync" if you line up animations with key moments in the text...

That's okay, if you teleport forward in the scene, as well as on the cards, or play everything at double-speed if people are trying to fast-forward the text... ...or selectively choose which animations appear in fast-forward or not...
...or just ignore it altogether (as long as player-state is perfect when the game starts again).

Players who are actively trying to speed-read, or are actively trying to skip the cutscenes and get back to gameplay aren't going to be upset that you didn't find a way to convey ALL of the animation and voiceovers, et cetera, in the 500ms that they were willing to wait, before playing again.

The point is more that you should try to appease both, if possible, and do so without stepping on your art, unless they're asking to skip it.

# Answer
> 2 votes
I know that I personally always prefer to have complete control over the flow of dialogue, except in real-time situations. I get annoyed when a game prevents me from reading at my own pace. One major plus for me is when games have a setting that changes the default speed at which text is displayed on the screen.

One possible approach to your specific situation would be to implement manga iconography (or something similar) to convey emotion, while allowing the user to control the flow of dialogue himself. Admittedly, whether or not this is feasible depends on the style of your game.

---
Tags: game-design, storyboard
---


# Question
Title: Distortion of color space in UDK (material editor)
## Question

Using UDK's material editor, I wish to use a texture as a two-dimensional array of values for mathematical computations (basically, the color components of each pixel in the texture alter the behavior of some transformations applied to another texture).

I want to retain rather precise color values for my mathematical operations to keep their meaning, but in my experiments I noticed a heavy distortion of the color space: **dark colors are darker than they should be, and light colors are lighter than they should**.

## Additional information

This effect is best shown by the following material, which takes a simple linear gradient texture, and applies a rounding operation on the colors:

If the colors were correctly preserved, the preview on the left should have 10 bands of equal length (a black band, a 10% gray band, a 20% gray band etc. with each band being 10% of the width of the image), however the black band is huge, the next (10% gray) one rather large, and the bands get smaller and smaller as they get lighter.

In this example, I take the red channel of the image, but taking the other channels gives similar results: The red and blue channels are identical, and the distortion is slightly different with the green channel, and taking the combination of these logically produces small bands of purple and green between any two bands.

I guess this is a compression issue with the original texure, but I don't know which parameters I should change so the colors are preserved when I use the texture in the material editor.

Above is the texture I used, created with The Gimp. The colors are correct, it is a linear gradient: the color of the pixels in column 0 is (0,0,0), the pixels in the column 255 are (255,255,255) and I manually checked at many points in the image that the pixels in the column x are (x,x,x)).

Above are the properties for this texture. Nothing special here, just the defaults. Specifically, the `Adjust Brightness Curve` and `Adjust RGB Curve` properties are set to `1.0` (by default), which seems correct since they are the power to which the HSV and RGB curves must be elevated. The distortion I observed looks a lot like if the values were raised to a given power.

# Answer
According to UDN, the `SRGB` setting in the texture's properties has to be turned **off** (false) for normal maps and other textures that need exact values.
> 2 votes

---
Tags: textures, udk, compression, materials
---


# Question
Title: What is the best way to check lists of objects that collide
I am making a top down shooter in XNA. I have a player, a list of enemies, a list of world objects like crates, trash cans, etc. and the map which has walls. Is there a better way to check for collisions than,

for (all enemies) for (all world objects) check for collision between enemies and world objects for (all players bullets) for (all enemies) check for collisions between players bullets and enemies and so forth.

What I mean is, I have a few lists of a bunch of objects and they all need to be checked for collisions. What is the most resourceful way to do this? Thanks for your help in advance.

# Answer
That all comes down to how your game is organized, currently.

BUUUT, there are some quick wins to be had with various organization systems (if you're talking about dealing with many elements, rather than, say a PONG number of collisions to test against).

For example, a quick win might be to use quadtrees/octrees to do your sorting.

Think of it like this: You know that the enemies in the top-left aren't going to be colliding with the walls in the bottom-right.

So why not do some work ahead of time, to cut those checks out?

Depending on the language you're using and the hoops you might have to jump through to have multidimensional lists which contain lists, all of which also contain your items...

...I've got a list of enemies which span the whole screen.
Instead, I'll make a list, which contains ***4*** lists -- each of those lists is going to represent a quadrant of the screen (NE, NW, SE, SW).
Then, I'm going to stuff the position data of each entity into one of those buckets.

Right off the bat, I've shaved a TON of superfluous collision checks.
As objects move over the bounding lines, I should take them out of one bucket and put them in the appropriate new bucket.

If there are still areas where there are lots of collisions going on, you can use recursion to break one of THOSE buckets up into 4 smaller buckets (so breaking NE into NE:NE, NE:NW, NE:SE, NE:SW), and within that quadrant, assigning all of the objects into the quadrants of the quadrant. If one object is too big to fit inside of the smaller bucket, or is now crossing over the lines, then leave it in the parent bucket, and check that one exception object against all of the objects in the smaller buckets (beats checking all of them, though).

You can recursively do this until you hit a threshold which you set for yourself (eg: "no more than 5 levels deep, but until you hit that depth, no more than 5 collisions to check per quadrant").

That said, if you DON'T have lots of collisions to check for, then this kind of optimization can actually slow things down.
For instance, you wouldn't want to do this for, say, Super Mario Bros III, because there just isn't enough stuff going on to warrant the maintenance of the quadtree.

But quadtrees and octrees are used in many, many games - even higher-end 3D games. Octrees are similar, except they also deal with height (or depth -- whichever axis you're not using in a quadtree in your game). So instead of breaking a square into 4 quadrants, you're breaking a cube into 8 octants.

Hope that helped.
> 4 votes

# Answer
There are many ways to optimize your idea (it's a exponential complexity algorithm).

I think, for a 2D game, a good way to implement a collision detection system is using Quadtrees. It is simple, and easy to implement, and in the long run can be parallelizable.

I'm not going to extend in this subject, but will leave links to others SE questions about this spatial data structure ;)

https://stackoverflow.com/questions/4981866/quadtree-for-2d-collision-detection

Data Structure (or algorithm) for fast distance-based entity lookups
> 0 votes

# Answer
A Smart way is to store your object in a Spatial Structure like an octree (3D) or quad tree for 2D. (there are lots of others, the choice depends on the usage)

Those types of structures make the lookup complexity very smaller (queries like "what object is close to me" will be faster (not n\*n like brutal force approach) ).

Try using a Physics Engine that handles this for you.
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Compile-time checking for component-based, data-driven games
This is not a specific question, but rather someone who is looking for opinions about a typical design problem. In a component based data-driven games, I've often seen something similar to the following when accessing attributes:

```
int* health = mOwner->get< int >( HEALTH_ATTRIBUTE );

if (health)
    *health -= 10;

```

Or, alternatively:

```
if (mOwner->hasAttribute( HEALTH_ATTRIBUTE ))
{
    int health = mOwner->get< int >( HEALTH_ATTRIBUTE );
    mOwner->set( HEALTH_ATTRIBUTE, health - 10 );
}

```

Where `mOwner` is a pointer to the parent game object. In this example, assume that the game object stores a map of attributes which are downcasted to the correct type at runtime.

There are some problems with this approach. Mainly, it is prone to bugs since it requires the programmer to know the the type of the attribute they are after. If I was working on a small team or by myself, this wouldn't be an issue. However for my requirements, this is undesired.

The only way to have compile-time checks is to create a helper function for each attribute that returns the proper type, so our code would then look like:

```
int* health = Attributes::getHealth( mOwner );

```

Where `Attributes` is declared as a namespace. Because the type is known at compile time, this gives us several advantages. In addition to the compile-time check, we gain the flexibility to easily declare certain attributes as constant, or that can't be modified outside the game object, etc. Of course, the downside is that it becomes necessary to manually create a new function for each and every attribute in the game.

Thoughts? Opinions?

***EDIT:***

After thinking it through a little more, I realized there is a way to define the function once using templates to avoid code duplication. For example:

```
template <typename Type, int ID>
class Attribute
{
public:
    typedef Type type;

    static int getID()
    {
        return ID;
    }

    static type getData( const GameObject* obj )
    {
        return obj->getAttribute < type >( ID );
    }

};

```

And then for each attribute we have in our game,

```
typedef Attribute< std::string, MODEL_NAME > ModelName;
typedef Attribute< Vector3, POSITION > Position;
typedef Attribute< int, HEALTH > Health;

/// ... and so on ...

```

And when we want to access an attribute:

```
int health = Health::getData( mOwner );

```

Or alternatively, if we want to:

```
Health::type health = Health::getData( mOwner );

```

If we don't know the health attribute exists or not:

```
int* health = Health::getData( mOwner );

if (health)
   // ....

```

I think this approach gives a lot of flexibility while still maintaining type safety.

# Answer
> 1 votes
The level of abstraction that is done here is one that I often consider too far when it comes to a component based system. It is also one that seems more and more predominant in general software development. To me both of the examples you have given have gone too far in that there is a generic interface for accessing any type of attribute from a given object. This is not useful as the default interface and leads to the situations you have described.

My components contain data as well as logic and are focused on handling a single area. Since we are using health I will just continue with that. At the root of a inheritence tree I will have an IComponent object that gives you the very basic interface to the object that all components must complete. This gives typedef/load/save capabilities of all components. From there I would then have an ICmpHealth interface that would provide typed accessors to the data values that you would expect to deal with when looking at the health of an object. It is this interface that gives you the specific data types like int ICmpHealth::GetCurrentHealth() or ICmpHealth::GetMaxHealth().

Now when dealing with a data oriented design these are actually static accessors for me as they are acting on contiguous data blocks with offsets.. But in a general system this would replace the calls above to getting a specific attribute to getting a component interface object so something like

```
ICmpHealth * cmpHealth = mOwner->GetComponent(HEALTH);
if (!cmpHealth)
    throw new Exception("Expected Component for Object not available");
int health = cmpHealth->GetCurrentHealth()
cmpHealth->SetCurrentHealth()

```

So this looks like just a 'we moved the problem around' sort of answer but I want to point out what you get for this. You already have to be aware of the types of components you are using in order to use them. Same could be said about needing to know the Attributes but the scale is much smaller as the components should contain multiple attributes. What this also gives you type check safety when setting any of the attributes for a component as you are now using a specific API in order to do so and are getting compiler type validation for accessing them.

Hope this helps.

---
Tags: c++, component-based, data-driven
---


# Question
Title: Where to find more documentation on Ogre3D?
I sucessfully managed to compile Ogre with MSVC2010 and I could dabble with the tutorials.

However, is there a website I am missing where there would be more ressources / infos?

The documention of the lib itself is very scarce and their wiki pages contain very few content, which is mostly outdated. For instance I'm trying to understand how the paging terrain manager works but I wasn't even able to find a single code snippet of a basic example, I don't even know which classes manage this effect.

So what's the best way to learn how to use Ogre? Are there some ressources outside of the main website?

Thanks

# Answer
> 1 votes
We have a very active community in the forums as well as the IRC chat. You also mentioned the wiki yourself, which often is a good entry point.

Apart from that, some other not-yet mentioned places to look:

Plus, don't forget our growing list of samples which should provide exactly what you asked for: a condensed, basic example of a certain feature. In your case the following two should be relevant:

* Sample\_Terrain
* Sample\_EndlessWorld

---
Tags: ogre
---


title: Tween Animation Cannot Start

text:
# Question
Title: Tween Animation Cannot Start
Do you have any reasons why my tween code didn't run or work? I already add the tween engine onto the library folder under LibGDX project folder and "Order and Export" it under **Java Build Path** at the *Properties* menu. My first two classes ran correctly and workly but my third class didn't work. Here's the sequence:

1. First class is the first screen. Fade animation works on the company's logo.
2. Second class is the second screen. Fade animation for the loading screen works.
3. Third class is the third screen. After the second screen, now calls for the third screen. Animation stopped or won't run since I want the black screen to fade out at the start when the menu is here.

Can you check if I did right? Look carefully by comment lines for explanation.

```
    //-----[ Animation Setup ]-----
    Tween.registerAccessor(Sprite.class, new Tween_Animation()); // --> Tween_Animation.java
    Tween_Manager = new TweenManager(); // --> I initialized it the TweenManager and seems okay.
    cb_start = new TweenCallback() // --> I'll use this when I choose START and the menu will fade in black.
    {

        @Override
        public void onEvent(int arg0, BaseTween<?> arg1)
        {
            goTo();
        }

    };

    Tween // --> This is where I focused the problem.
    .to(black_Sprite, Tween_Animation.ALPHA, 3f)
    .target(1)
    .ease(TweenEquations.easeInQuad)
    .repeatYoyo(200, 2.5f) // --> I set the repeat for 200 times when I noticed that the animation won't work!
    .start(Tween_Manager);

```

# Answer
I solved it! I forgot to add this code at the **render()** method:

```
Tween_Manager.update(delta); // --> Set update to enable animation changes.

```
> 2 votes

# Answer
I've had issues with the Tween library and I usually find I have to eliminate variables and until it works and then add them back in.

Some things to try:

Did the animation work before you added repeatYoyo?

Did you mean to set the Alpha to 3? Usually this ranges from 0 to 1.

Did you try it without any easing?

Good Luck!
> 1 votes

---
Tags: java, libgdx, tweening
---


# Question
Title: How to make background to stage in kineticjs
```
   var stage = new Kinetic.Stage({
    container: 'container',
    width: 490,
    height: 300,
  });
  var layer = new Kinetic.Layer();

```

I want to make a default image to a stage to be the background of the stage. i'm using kineticjs .

# Answer
> 2 votes
There are two ways to do this: 1. Assign a background image to the `div` container using CSS. 2. Create a background layer and add an image that takes up the whole layer.

An example of (2) might be:

```
var background = new Kinetic.Layer();
var bgImage = new Kinetic.Image(...);

layer.add(bgImage);
stage.add(background);

```

---
Tags: javascript, html5
---


# Question
Title: Android Game, Blurring effect while moving camera
I have posted this issue on stackoverflow, but unfortunately nobody couldn't find solution, maybe someone here know this.

I'm developing Side Scroll 2D Game, using AND ENGINE

https://i.stack.imgur.com/58Q1U.png

I'm using their SVG extension (I'm using vector graphic)

But I discovered strange and ugly effect, while moving my player (while camera is chasing player exactly, means while camera is changing its position)

Images of my sprites looks just different, they are like blurred or there is effect like those images would be moving (not changing their possition, just jittery effect, really hard to explain and call this effect properly) Hopefully this image may explain it a bit:

https://i.stack.imgur.com/z02UL.jpg

Its more or less, how does it look in the game, where:

a) "FIRST" image is showing square, while player is moving (CAMERA isn't) image looks as it should

b) "SECOND" the same image, but with this strange effect "which looks like image moving/blurring during camera moving \[chasing player\])

Friend of mine told me that it might be hardware problem:

"the blurring that you notice is actually a hardware problem. Some phones "smooth" the content on the screen to give a nicer feel to applications. I don't know if it's the screen or the graphics processor, but it doesn't occur on my wife's Samsung Captivate. It happens on my Atrix and Xoom though. It's really noticable on the Xoom due to the large screen size."

But seems there is way to prevent it, since I have tested many similar games, where camera is chasing player, and I could not notice such effect.

**Is there a way to turn this off in code?**

---

I'm grateful for previous answers, unfortunately, still problem exist.

Till now, I have tried:

* casting (int) on setCenter method which is being executed on updateChaseEntity
* testing game using PNG images, instead of SVG extension and vector graphic
* different TextureOptions
* hardwareAcceleration

If someone have different idea, what may cause this strange effect, I would be really grateful for help - thank you.

# Answer
> 1 votes
It could be the refresh rate not being in sync with the screen's refresh rate.

First thing to test is to take a screenshot while the camera is moving and see if the blur appears on the resulting image.

If not then it definitely is a problem with the hardware and you might have to try to sync the drawing cycles with your hardware (I have no knowledge of how to achieve this in android).

Does the blur appear on the emulator as well?

# Answer
> 0 votes
I had a few issues with the performance of actually moving a camera, and switched to a SmoothCamera which increased performance, and looks so much better.

Hope this helps:

http://code.google.com/p/andengine/source/browse/src/org/anddev/andengine/engine/camera/SmoothCamera.java?r=ce34423c75330560d7bb4d4a00d20e9b9a18175a

Update: This may not be the most recent version of this code, but SmoothCamera is available in GLES 2 also. Just switch "Camera" to "SmoothCamera", I believe it takes some different parameters upon configuration, (like MAX\_VELOCITY, etc).

---
Tags: 2d, java, android, andengine
---


# Question
Title: Game loop, how to check for conditions once, do something, then not do it again
For example, I have a Game class and it keeps an `int` that tracks the player's lives. I have a conditional

```
if ( mLives < 1 ) {
    // Do some work.
}

```

However this condition keeps firing and the work is done repeatedly. For example, I want to set a timer to exit the game in 5 seconds. Currently, it will keep setting it to 5 seconds every frame and the game never ends.

This is just one example, and I have the same problem in several areas of my game. I want to check for some condition and then do something once and only once, and then not check or do the code in the if-statement again. Some possible solutions that come to mind are having a `bool` for each condition and set the `bool` when the condition fires. However in practice this gets very messy handling lots of `bools`, since they have to be stored as class fields, or statically within the method itself.

What is the proper solution to this (not for my example, but for the problem domain)? How would you do this in a game?

# Answer
> 13 votes
I think that you can solve this problem simply by exerting more careful control over your possible code paths. For example, in the case where you're checking if the number of the player's lives has dropped below one, why not check only when the player loses a life, instead of every frame?

```
void subtractPlayerLife() {
    // Generic life losing stuff, such as mLives -= 1
    if (mLives < 1) {
        // Do specific stuff.
    }
}

```

This, in turn, assumes that `subtractPlayerLife` would only be called on specific occasions, which would perhaps result from conditions that you *must* check every frame (collisions, perhaps).

By carefully controlling how your code executes, you can avoid messy solutions like static booleans and also cut down bit-by-bit on how much code is executed in a single frame.

If there's something that just seems impossible to refactor, and you really need to only check once, then state (like an `enum`) or static booleans are the way to go. To avoid declaring the statics yourself, you can use the following trick:

```
#define ONE_TIME_IF(condition, statement) \
    static bool once##__LINE__##__FILE__; \
    if(!once##__LINE__##__FILE__ && condition) \
    { \
        once##__LINE__##__FILE__ = true; \
        statement \
    }

```

which would make the following code:

```
while (true) {
    ONE_TIME_IF(1 > 0,
        printf("something\n");
        printf("something else\n");
    )
}

```

print `something` and `something else` only once. It doesn't yield the best looking code, but it works. I'm also pretty sure there are ways to improve it, perhaps by better ensuring unique variable names. This `#define` will only work once during the runtime though. There is no way to reset it, and there is no way to save it.

Despite the trick, I strongly recommend better controlling your code flow first, and using this `#define` as a last resort, or for debug purposes only.

# Answer
> 5 votes
This sounds like the classic case of using the state pattern. In one state you check your condition for lives \< 1. If that condition becomes true, you transition to a delay state. This delay state waits the duration specified and then transitions to your exit state.

In the most trivial approach:

```
switch(mCurrentState) {
  case LIVES_GREATER_THAN_0:
    if(lives < 1) mCurrentState = LIVES_LESS_THAN_1;
    break;
  case LIVES_LESS_THAN_1:
    timer.expires(5000); // expire in 5 seconds
    mCurrentState = TIMER_WAIT;
    break;
  case TIMER_WAIT:
    if(timer.expired()) mCurrentState = EXIT;
    break;
  case EXIT:
    mQuit = true;
    break;
}

```

You could consider using a State class along with a StateManager/StateMachine to handle the changing/pushing/transition between states rather than a switch statement.

You can make your state management solution as sophisticated as you want, including multiple active states, a single active parent state with many active child states using some hierarchy, etc. Use what makes sense to you for now of course, but I truly think a state pattern solution will make your code much more reusable and easier to maintain and follow.

# Answer
> 1 votes
If you're worried about performance, the performance of checking multiple times is not usually significant; ditto for having bool conditions.

If you're interested in something else, you can use something similar to the null design pattern to solve this problem.

In this case, lets assume you want to call a method `foo` if the player has no lives left. You would implement this as two classes, one which calls `foo`, and one which does nothing. Lets call them `DoNothing` and `CallFoo` like so:

```
class SomeLevel {
  int numLives = 3;
  FooClass behaviour = new DoNothing();
  ...
  void tick() {
    if (numLives < 1) {
      behaviour = new CallFoo();
    }

    behaviour.execute();
  }
}

```

This is a bit of a "raw" example; the key points are:

* Keep track of some instance of `FooClass` which can be `DoNothing` or `CallFoo`. It can be a base class, abstract class, or interface.
* Always call the `execute` method of that class.
* By default, the class does nothing (`DoNothing` instance).
* When lives run out, the instance is swapped for an instance that actually does something (`CallFoo` instance).

This is essentially like a mix of strategy and null patterns.

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


# Question
Title: How can I remove enemies from my ArrayList after they have died?
> **Possible Duplicate:**
> How do I best remove an entity from my game loop when it is dead?

Right now, I have an ArrayList like this:

```
List<Enemy> enemies = new ArrayList<Enemy>();

```

When an enemy dies, how can I remove it? Should I use a different type of list, array, or set?

# Answer
> 5 votes
Please, don't use a set, you don't need it. There's a simple trick that can help improve @Jake-Woods' answer.

From my experience, if you keep a lot of enemies (or other entities) in an array, you don't really care about the order in the array. The trick is, it's possible to remove an object from an array with a small and constant amount of operations (O(1)), if you allow for the order to change. The algorithm is as follows:

* Iterate over the entities in your array
    + If you find an item that needs to be removed
        - Swap it with the last element
        - Remove the last element from the array

It's quite easy to write, but takes some work to understand that this works properly for corner cases (like removing the last element from the array). Here's a code sample from my project:

```
   public void update(int dt) {
            for (int i = 0; i < entities.size(); /* conditional incr */){
                    Entity entity = entities.get(i);
                    entity.update(dt);

                    if (entity.isToBeDestroyed()){
                            int lastEntity = entities.size()-1;
                            entities.set(i, entities.get(lastEntity));
                            entities.remove(lastEntity);
                    } else {
                            i++;
                    }
            }
    }

```

This particular variant uses update and remove in a single loop, but depending on your context you might want to split those into separate loops (so that entities don't disappear during the update phase).

# Answer
> 11 votes
The java List interface provides two methods for removing objects, one taking an instance of the object and one taking an index. You can see all the methods on the list interface here

Regardless of what list implementation you use all lists will have those methods. The difference is in the speed of certain operations. The JavaDocs for list implementations provide a good overview of the performance tradeoffs: ArrayList, LinkedList

To remove an element from any list it depends on if you're iterating or not. If you want to remove an element from a list while you're looping over the list you need an iterator:

```
List<MyObject> objects = getMyObjects();
Iterator<MyObject> iterator = objects.iterator();
while(iterator.hasNext()) {
    MyObject current = iterator.next();

    if(enemyIsKilled) {
        iterator.remove(); // Removes the current object.
    }
}

```

If you're not iterating and you just want to remove the enemy outside the loop, then we can just use the list.remove method:

```
List<MyObject> objects = getMyObjects();
MyObject instance = objects.get(2); // Get the 3rd object, could be any MyObject instance in the list
objects.remove(instance);

```

The choice of what collection to use depends on two things: What collection makes logical sense to use and what collection has the best performance for my application.

The answer to these two questions is the age old "it depends". The choice between a list and a set is a choice between duplicate and non-duplicate elements and sometimes between ordered and unordered elements. The choice between an ArrayList and LinkedList is a tradeoff where ArrayLists are faster to iterate over but LinkedLists are faster to remove from/insert to.

When you're just starting out you don't know where your performance bottlenecks are going to be. My advice would be to use List everywhere and just pick either ArrayList or LinkedList as the underlying type. If later on in development you notice the game is going slow you should **use a profiler** to determine if traversal or removal is the problem, if it is then you can look at changing the underlying list type that you use.

Remember: The golden rule is **don't optimize prematurely**

# Answer
> 2 votes
First off do you need to actually 'remove' them? Another alternative would be to set a flag on them to 'dead' or 'disabled' or something, anything that sees that (such as your rendering function) will just skip over them.

If that is a good idea or not will depend on the usage of your program.

If you have a limited number of guys spawned at the start of the level then it works fairly well. It can also make things like reloading saves much faster (you just unset the disabled flag and reset their other attribues). But it does have some runtime costs as you will still be looping over all the dead guys (although you would be doing the full load at the beginning anyway).

If you are continuously spawning and killing of waves of bad guys then that's not a great solution. In that case you need a data structure that is quick to insert and delete. An array is not a good choice as the entire memory must be copied each time. You want a linked list instead. Linked lists have a little bit of overhead compared to an array as each item points to the next one, it's also harder to access a specific element in the array as you have to iterate over each one, but generally it's good enough to not worry about for real world applications. You could always combine the LinkedList with a Array you use for indexing.

Games often try and reduce the allocation of memory at runtime as much as possible. Games are generally fairly predictable. You know there will be a finite number of bad guys, the only unknowns are plays input (maybe there is a way for the player to cause bad guys to spawn), in that case they will guess a fairly good maximum and add a saftey factor and provide a fallback runtime way to increase the size (or just put some limits in place since otherwise the player could spawn so much they run out of memory).

You can create new guys at runtime using what is called a Pool. Basically they allocate the guys in advance and pull out a new one when it's needeed.

---
Tags: java
---