# Question
Title: Retrieving components from game objects (entities)
Using C# and XNA 4, I've made the decision to go for an entity-component based design for my game after reading such posts as this and this, but I'm now struggling to find how to retrieve components once they've been added to an entity.

Some articles I've read say that when a component is created, register it with the system that will act upon it, using a messaging system. A drawback I see here is that if a system needs 2 components to act (say CollideComponent and PositionComponent) then this gets complicated (and I can't figure how it would work).

The other possibility, and the one that I'm currently pursuing, is to have a system ask whether an entity has a particular component when it needs it. However I've not seen any code examples, only theory on the net, so I've been trying to muddle it together. Some code here might explain how far I've got :

First a `System`:

```
public class RenderingSystem : IGameSystem
{
  public void PerformAction(IQueryable<IGameObject> gameObjects)
  {
    foreach (var gameObject in gameObjects)
    {
      RenderableGameComponent renderableGameComponent = gameObject.GetComponent<RenderableGameComponent>(ComponentType.Renderable);
      if (renderableGameComponent != null)
      {
        this.spriteBatch.Draw(renderableGameComponent.Texture, renderableGameComponent.DrawablePosition, Color.White);
      }
    }
  }
}

```

Now the actual `GameObject`:

```
public class GameObject : IGameObject
{
    private List<IGameComponent> gameComponents;
    private ComponentType componentTypes;

    public void AddComponent(IGameComponent component)
    {
        this.gameComponents.Add(component);
        this.componentTypes = this.componentTypes | component.ComponentType;
    }

    public T GetComponent<T>(ComponentType componentType)
    {
        return (T)this.gameComponents.FirstOrDefault(gc => gc.ComponentType == componentType);
    }
}

```

And finally the `Component` and `ComponentType` enumeration :

```
public class RenderableGameComponent : IGameComponent
{
    public Texture2D Texture { get; set; }

    public Vector2 DrawablePosition { get; set; }

    public ComponentType ComponentType
    {
        get { return ComponentType.Renderable; }
    }
}

[Flags]
public enum ComponentType
{
    Renderable = 1,
    Updateable = 2,
    Position = 4,
}

```

Now as you might be able to see, I'm trying to use bitwise operations on the `ComponentType` enumeration that every `Component` of each `GameObject` has. The reason being I thought this would be a much cleaner approach when trying to get the required `Component` out of the `GameObject` when asked by a `System` (also refer to link 1 above).

I'm trying to get away from passing in a type, and doing an iteration over all the `Component`s of a `GameObject`. eg:

```
foreach (var component in this.GameComponents)
{
  if (component.GetType() == requestedType) { return component; }
}

```

This is because when there are a few hundred bullets on the screen and a `CollidableSystem` is created, it will massively slow the game down checking every type. I've had experience with this when creating a previous game, but admittedly, that was using an inheritance based design system.

It worries me that for each `System` that is created, it will have to iterate over every `GameObject` every tick asking the same question every time, "Do you have the component I am looking for ?" and still doing a lot of casting and null checks.

Now my question is this. I want to know whether there is a de facto design pattern for getting `Component`s from `GameObject`s that don't require null checks or casting ? Someway a `System` will say "Give me this component, I know that you have it" and not bother wasting time asking those `GameObject`s that don't have the `Component`. Tell, don't ask.

# Answer
Systems maintain a list of the entities they're interested in.

Systems are just created *once* when the game is initialized. If you're creating systems with entities already in play, you're doing it wrong :).

All the systems your game will use are to be created before any entities are created. When a new entity is created, each system will check to see if it's interested in that entity for processing. This is where your bitwise check comes into play, very fast. When an entities components change, each system should check that entity again to see if it's still interested in processing it. See an example of this check in the Artemis Framework code with the `check(Entity e)` function.

Now, when each system processes, it just iterates over the list of entities it has stored.

Retrieving components is done with nested hash maps. The first layer is a map of maps indexed by the component ID, likely the long used for bitwise identification would work well here. The second layer is a map of components indexed by the entity ID. This would look something like the following in tree format:

```
-Renderable (1)
  |-- Entity 1 (1)
       |-- Instance of Renderable
  |-- Entity 2 (2)
       |-- Instance of Renderable
-Updateable (2)
  |-- Entity 1 (1)
       |-- Instance of Updateable
-Position (4)
  |-- Entity 1 (1)
       |-- Instance of Position
  |-- Entity 2 (2)
       |-- Instance of Position

```

Where Entity 1 is an entity with Renderable, Updateable and Position components and Entity 2 is an entity with Renderable and Position components.

These hash maps have constant access times and are very easy to navigate.

So when processing entities you can easily retrieve a component with something like the following (similar to the Artemis method):

```
Component getComponent(Entity e, ComponentType type) {
       HashMap<Long, Component> components = componentsByType.get(type.getLongID());
       if(components != null) {
            return components.get(e.getID());
       }
       return null;
 }

```

There's still a null check, but you can get rid of that if you fill all your `componentsByType` maps with empty maps for each component. Enabling you to shorten the look up to:

```
 Component getComponent(Entity e, ComponentType type) {
       return componentsByType.get(type.getLongID()).get(e.getID());
 }

```

It's still possible this will return null if the entity doesn't have that component type. It's up to you if you want to check for that, but if the system added the entity based on its components, that component should be there, so it's up to you if you want to take that risk.
> 3 votes

# Answer
When I was thinking in the optimal way of getting components belonging to a specific entity I encounter the following main concern:

Speed: constant time vs lookup.

Now, this is game programming, if you game does not perform fast you have to address that somehow.

My first attempt was to store components in a dictionary, the dictionary ordered components by type id, the type id was a 64 bit unsigned integer and it was obtained for each component by calculating hash of its class name string. The problem is that the getComponent method of the Entity class involved a look up, probably binary search, but still not optimal when comparing to constant time. Then to achieve constant time access to components, I did as Richard Lord suggests in his blog post about entity systems, I created nodes inside systems that permit access to components through static typing, no lookup. With this method I only called the getComponent method of the Entity when adding each entity to systems, to check if required component were there, and if they were then I created the node. The node is an structure/class made of pointers to components. I only did this for critical systems such as collision detection or rendering, not for AI for example, because AI may accept multiple components sets, and take different code paths depending of presence or state of components, so AI still used getComponent a lot.

Later, I found this and this. Good optimizations, because if you can access components fast and in constant time, you don't need nodes at all. With the corresponding speed and memory benefits.

Actually what I do is to store components in a vector. Each component has an unique index, not a type id like before. The assignation of index values for each type is sequential. I won't enter in details on how I achieved this, for now you can go with an enum (similar to what you are already doing).

I have two versions of getComponent function, one check for inexistent components (used by systems that can act in a variety of entities even if not all have the same component set, like AI), the other, the fast one, allow memory violation if you try to access an inexistent component. System that access components this way, have an interface to get notified when an entity changes its component set (removal or addition of components) and then recheck the entity and if it has no more the required components by that system the entity get removed from the system, but these systems never check for components during game loop, because that would make them run slow.

With my suggestion of use a vector and not a dictionary, you may run in cases where an entity only has lets say the Position component that has an index value of 0, and the CharacterStatus component that has and index value of 64 (actually less but let use a high number to illustrate this situation), as we are using a vector to store components ordered by index, then this mean that you end with a vector with 65 items, and item 1 to 63 are null pointers. To minimize this impact you will try to assign high index values to less used components. I have do some calculation (considering only the size of the entities internal vector) of the memory cost of the worst of cases (this is when you have all entities containing the last component, the one with the higher index value) and the number of entities that I can create is still in the tens of thousands and estimated memory used by entities is still acceptable comparing to the benefit of accessing components in constant time.

You have to get rid of the dictionary because access to its items involves a look up. You have to make retrieval of components constant time, or use nodes as Richard Lord shows in his post.

Note: I'm using C++, not C#, but all I have said is language agnostic. For example, I used std::map as dictionary in my first attempt. But you get the idea. In C# you can use List from System.Collections.Generic instead of std::vector, it will allow you to access components references in constant time.

Finally: The first link from entity systems wiki suggests to store components in vectors, one for each component type. I think that this is not friendly to C#, because this

```
List<ComponentClassName>

```

would mean a sequential list of references to ComponentClassName and whatever you do you get a reference, then do that in C# don't have sense, something similar as what I'm doing is better for C# (each entity have a vector of pointers, well references in your case, to components, static casts are still needed). In C++ you can do std::vector and that would be different than std::vector (with the * at the end) so the method suggested in the wiki may still have some sense in C++, maybe it requires even less memory than what I'm doing.

You still may prefer the wiki suggested method as you stated that you are concerned about doing casts constantly. With one vector (List) per component type, and the entity being only an integer, you don't need casts at all. Something like:

```
Vector3 displacement = position_list[entity_index] - previous_position_list[entity_index];

```

Assuming the "laziest" of implementations where you expose the lists to the systems.
> 2 votes

# Answer
I had the same concern, what I did was to have a **Dictionary**, each key is a **ComponentType**, and the value is a list of **GameObjects** with components of that type.

```
Dictionary<ComponentType, List<GameObject>>

```

That way most of your software design remains unchanged, the system asks to the dictionary only what he need, no unnecessary iterations and no null checks.

The other way I wanted to answer your question is well explained by Ryan Maloney in his comment.
> 0 votes

# Answer
Just complementing what Ryan Maloney told. I worked on the port of the amazing Artemis Entity system (Java Version: http://gamadu.com/artemis/ and our C# version http://thelinuxlich.github.com/artemis\_CSharp/).

Systems are "somehow "conected with Components, when you create a system you specify the types of components that it process and at runtime only the entities that has those components types are send to the System for processing. When you remove or add a Component of an entity (we call that the entity was refreshed), the interested systems are notified (their method onChange will be called).

I really recomend you to take a look at the source code https://github.com/thelinuxlich/artemis\_CSharp

Most of the problems you are talking about were "solved" there =P

There is also a basic demo game using it here https://github.com/thelinuxlich/starwarrior\_CSharp
> 0 votes

---
Tags: xna, c#, architecture, component-based, design-patterns
---


# Question
Title: Can Google Translate's audio files be used in a game?
For my game, I need text-to-speech. Since it's Android, I decided to settle for MP3s, since the range of words spoken is few.

For my prototype, I'm using Google Translate to generate the audio since it has awesome pronounciation across multiple languages.

But can I use it in production? What if I sell my game for $1 on the app store?

All I can find on SE is that the API may be LGPL, and that the licensing page mentions the API is only available for academic research -- nothing more. My usage is a bit different; I'm actually capturing the audio bits and using those instead.

I'm curious to know the license for this; I can't find anything with my Google-fu.

# Answer
> 6 votes
The only way to get answers for questions of specific use of a specific product is to consult the owner. You should write an email to google's legal team, or to the google tranlsate mailing list.

Anything other than this is pure speculation and is likely to cause you harm.

# Answer
> 3 votes
First, you are absolutely right to be concerned.

They haven't been clear about their license

Licensing fees for *usage* of proprietary voice recordings, even for just 5-10 wave files of prerecorded TTS can be inane. For example, AT&T's TTS (marketed by Wizzard) charges $5,500 (no, that isn't an extra zero) for *any* distribution or reuse of it's prerecorded voices.

This SO thread has several links to other open source voices, which you may want to use.

# Answer
> 1 votes
Google does have a payment system in place to use "Google translate" in programming projects.

Look here: https://code.google.com/apis/console/b/0/

Create a project, then near the bottom it should say Google translate. it's about 20$ for 1M chars

Billing link: http://code.google.com/apis/language/translate/v2/pricing.html

---
Tags: legal
---


title: Transmit map vs Transmit seed

text:
# Question
Title: Transmit map vs Transmit seed
Given a map created with procedural generation algorithms, should the server transmit the seed used to generate this map (so client must contain the same algorithm) or maybe send all the information?.

I'm inclined to send the seed, i have in mind generating big maps. Right now, i have one seed to generate multiples seeds, and each one is used to generate a chunk, so this last seed would be transmited to each client everytime someone needs information about a new chunk.

# Answer
This would work just fine for the initial generation of the maps. If the generation algorithm is using a deterministic approach for generating the chunks, you will get the same chunk every time. This means you can't create any random generators on the clients them selves unless you're using the seed from the server as the seed for the random generator.

This can be demonstrated in Minecraft with the world generation seeds shared among its users. If someone finds a map they like, they can share the world generation seed with others and Minecraft will generate the exact same map.

Obviously you'll need to send the clients any changes that are made after the initial generation. Since those could not be predicted by the generation algorithms. In that case it would be far better to transmit the map instead. You can try to only submit the changes, but it may more complex and could be more time consuming to find what has changed and send the changes than to just send the entire map.
> 2 votes

---
Tags: multiplayer, maps, procedural-generation
---


# Question
Title: How can I transform a point from world space to object space?
If I have an object space described by transformation matrix that should be applied to object to transform it to world space, what I have to do to transform point (world space) to that object space.

I guess it's more of a math question, but I believe gamedevs are more familiar with terminology.

# Answer
> 11 votes
If you have a matrix that transforms from object to world space, the inverse of that matrix will transform a world space value to object space.

# Answer
> 6 votes
You need to keep around the components of how you built your `world` matrix to begin with.

Say your world matrix is for a spinning coin. So, it has `rotate`, `scale`, then `translate` in that order.

Let's assume you're using row-major matrices. You'd form your forward transformation matrix as:

```
matrix = rotate(30,60,90) * Scale(5) * Translate ( 5, 0, 0 )

```

Form the backwards (inverse) transformation as just the opposite operations, in the opposite order.

```
inv_matrix = Translate( -5, 0, 0 ) * Scale( 1.0/5.0 ) * TRANSPOSE( rotate(30,60,90) )

```

So note a few things:

* inverse of rotation matrix ("unrotate") is just its transpose. (this is a **special** property of rotation matrices only and doesn't apply to other matrix types)
* inverse of scale matrix (unscale) is 1/scale
* inverse of translation matrix is applying -translate

---
Tags: mathematics, graphics, matrix, geometry
---


title: Getting an images rgb value at click

text:
# Question
Title: Getting an images rgb value at click
I'm not sure if this is at all possible, but maybe it will spark up an interesting conversation. (Sidenote: working on a small game in Löve).

I'm making an archery shooting kind of game, and I was thinking it might be cool to have critical and regular hits based on where the user shoot the arrow at the enemy. Example, if I have a troll image, and the user clicks the head of the troll, it will count as a critical hit.

Checking to see if the user clicked on the top part of the image vs the bottom, isn't the tricky part. The hard bit will be to check if the user clicked on apart of the image, instead of blank space in the png...

So, main question: Is it possible to get the rgb value of where an image has been clicked, to determine if they hit or missed the target.

Also, if this is at all possible, is there anyone familiar with Löve that can confirm it is doable?

Edit: I'm realizing now it's not the rgb value I want to look for, it is whether or not the clicked pixel has transparency. If it is 100% transparent that means the user missed the image.

# Answer
> 4 votes
You can get specific information about the image clicked by accessing the `ImageData` associated with the `Image` you're drawing. Specifically the `getPixel` function. When you detect a click, find which image is being clicked on. Then you need to get the `ImageData` you created for that image. Finally, convert the click coordinates to image local coordinates and pass them into the `getPixel(x, y)` function. You'd likely want to test the alpha component to see if it's below whatever threshold you define as "not part of the image".

---
Tags: image, love2d
---


title: Billboard text is upside down

text:
# Question
Title: Billboard text is upside down
First thing, I am not a seasoned game developer. I am using game development as a conduit to learn programming.

I am attempting to put the player names above the player's head's. I am using a variation of Shawn Hargreaves solution;

```
            basicEffect.World = Matrix.CreateConstrainedBillboard(textPosition, textPosition - cameraFront, Vector3.Down, null, null);
            basicEffect.View = view;
            basicEffect.Projection = projection;

            const string message = "hello, world!";
            Vector2 textOrigin = spriteFont.MeasureString(message) / 2;
            const float textSize = 0.25f;
            spriteBatch.Begin(0, null, null, DepthStencilState.DepthRead, RasterizerState.CullNone, basicEffect);
            spriteBatch.DrawString(spriteFont, message, Vector2.Zero, Color.White, 0, textOrigin, textSize, 0, 0);
            spriteBatch.End();

```

My game is space based, so I needed the text to rotate on all 3 axes, so I implemented the following;

```
        foreach (PlayerShip objPlayerShip in objPlayers)
        {
            Vector3 objTextPosition = objPlayerShip.objShipVector + new Vector3(0, 3, 0);
            Vector3 objCameraFront = objManager.objCamera.objCameraPostion;

            objBasicEffect.World = Matrix.CreateBillboard(objTextPosition, objCameraFront, objManager.objCamera.objCameraUp, null);
            objBasicEffect.View = objManager.objCamera.objViewMatrix;
            objBasicEffect.Projection = objManager.objCamera.objProjectionMatrix;

            string strText = objPlayerShip.strGUID.ToString();
            Vector2 objTextOrgin = objCourierNew.MeasureString(strText) / 2;

            spriteBatch.Begin(0, null, null, DepthStencilState.Default, RasterizerState.CullNone, objBasicEffect);
            spriteBatch.DrawString(objCourierNew, strText, Vector2.Zero, Color.Green, 0, objTextOrgin, 0.09f, SpriteEffects.None, 0.0f);
            spriteBatch.End();

        }

```

It seems to be working, but the text is upside down. How would I flip the text right side up? I know I have to change something in objBasicEffect.World. I try to tweak it, but I just make things worse...

Any help would be appreciated. Linuxx

# Answer
> 1 votes
As it appears my text was both upside down, and backwards. I solved this with;

```
spriteBatch.DrawString(objCourierNew, strText, Vector2.Zero, Color.Green, 0, objTextOrgin, 0.09f, SpriteEffects.FlipHorizontally | SpriteEffects.FlipVertically, 0.0f);

```

I feel really stupid it was so basic... :-/

Then again, I did learn how to combine enum's!

Thanks for your help Adam.

p.s. I couldn't answer my own question until 8 hours had passed. I'm a new user...

Linuxx

---
Tags: xna
---


# Question
Title: Can't run Nvidia PracticalPSM sample in debug mode
I want to add PSM (Prespective shadow map) to my engine but I have problems with that. I think the problem is somewhere in my math code so I want debug Nvidia PracticalPSM sample and compare the math result in the sample and in my engine so maybe I could find the bug

When I want to compile the sample with VS2005 I get some linker error with DXUT functions maybe it is due to that the static lib DXUT.lib that included is compiled with VS2003 and dose not work probably with VS2005 then I added DXUT source codes from SDK 9.5 to the solution and the sample compiles this time.

When I hit F5 to run the sample it complains about nv\_nvb.dll but only release version of nv\_nvb.dll is included in the sample and I copied that to debug folder when the program starts it crashes in NVBscene9.cpp line 283.

I don't know why it crashes here.

you can download the sample code from here

# Answer
I have the same problem.
To fix the DXUT linking errors, for all the functions in DXUT.h that were listed in the error logged, I replaced in their prototype `const WCHAR*` or `LPSTR` by `const unsigned short*`, because this is the type that I found in the DXUT.lib library when running Microsoft dumpbin.exe on it.

However after this stage, I am like you stuck at the `nv_nvb.dll is missing` problem.
It seems that that this is a library used to load `.nvb` files, which I guess is an effect or model file created by NVidia.

If you have 3ds Max installed on your PC, maybe you can try to add the NVidia plug-in described on this page, it might contain the .dll (I don't have 3ds Max so I could not give it a try).

Good luck !

Alternately, if you run a 32 bits version of Windows you might be able to install the 9.52 version of NVidia SDK (I couldn't because I work on a 64 bits machine).
> -1 votes

---
Tags: shadows, shadow-mapping, nvidia
---


title: Texture will not rotate with gluSphere

text:
# Question
Title: Texture will not rotate with gluSphere
I have a **gluSphere** generated in my display that is rotating, but having a problem with the texture rotating with the sphere as well. So in a nutshell, no matter how the sphere rotates, the texture around the sphere remains in the same position regardless.

How am able to update the texture along with the sphere so that it rotates?

```
private static Texture testTex;
...

// This method is called in init()
public void sphereTexture(GL2 gl)
{
    InputStream iStream = null;

    try
    {
        iStream = getClass().getResourceAsStream("cratepng.png");
        TextureData data = TextureIO.newTextureData(iStream, false, null);
        testTex = TextureIO.newTexture(data);
        testTex.getImageTexCoords();
        testTex.setTexParameteri(GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
        testTex.setTexParameteri(GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);
        iStream.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        System.exit(1);
    }
    // Set material properties
    gl.glEnable(GL2.GL_TEXTURE_GEN_S);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT);
    gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

    gl.glEnable(GL2.GL_TEXTURE_GEN_T);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT);
    gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);

    testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S);
    testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T);
}

// Draw Sphere (FILL, LINE, POINT) method called in display()
public void draw(GL2 gl, GLU glu)
{

    gl.glTranslatef(1f, 0.0f, -20.0f);
    gl.glRotatef(angleSphere, 1f, 0.0f, 0.0f); //90

    GLUquadric sphere = glu.gluNewQuadric();
    glu.gluQuadricDrawStyle(sphere, GLU.GLU_LINE);
    glu.gluQuadricTexture(sphere, true);
    glu.gluQuadricNormals(sphere, GLU.GLU_SMOOTH);
    glu.gluQuadricOrientation(sphere, GLU.GLU_OUTSIDE);

    testTex.enable(); // enable texture
    testTex.bind(); // bind texture

    glu.gluSphere(sphere, radius, slices, stacks);

    testTex.disable();
    glu.gluDeleteQuadric(sphere);
    angleSphere += speed;
    //System.out.println(angleSphere);

}

```

# Answer
> 1 votes
After posting your glEnables I see that you are enabling sphere mapping with glEnable(GL\_TEXTURE\_GEN\_S) and glEnable(GL\_TEXTURE\_GEN\_T) and generate texture coordinates. You shouldn't need to do this since this is done by glu (see here).

Nonetheless, what looks more suspicious is your use of GL\_NORMAL\_MAP in the glTexGeni function. In the openGL reference page there is no description of how the texture coordinates are calculated using this parameter. You should either remove these two texture generation blocks or try a different parameter in the glTexGeni i.e. GL\_OBJECT\_LINEAR.

---
Tags: java, textures, jogl
---


# Question
Title: How to make some monsters appear more dangerous than others?
My game is an open-world co-op MMO with retro graphics, permadeath and no leveling system.

The problem I'm facing, is the fact that I don't know how to make some monsters appear harder than others. Since nothing has a level, and characters can only get stronger by acquiring better items, it's difficult for me to "warn" players that a monster is difficult for them.

Fortunately, the whole world is designed by hand and we know which areas should be more difficult than others. So this means, **I as developer knows which monsters are stronger than others**.

**But new players won't!** I don't want them to get frustrated by walking into the wrong monsters reserved for higher players.

So then, **how can I make monsters appear more dangerous than others?**

Some things I thought of:

* **increasing the size of the monsters:** This could work but it's not a valid rule for everything. For instance, the end-boss has small minions which are also powerful.
* **use of particles:** I remember from playing WoW some monsters who were stronger excessively used particles to make them appear more powerful:
* **dividing the world into danger levels:** Here I would add a danger level or something to the HUD that displays whether the player is in a safe zone or somewhere dangerous. It would change and display a notice whenever the player moves to a different danger level. Do-able although I have no clue how to portray it on the HUD.

# Answer
> 28 votes
I think not knowing the monsters strength immediately is a great idea. New areas would be much more threatening and the player can't just overpower his or hers character and run away from everything that's bigger than him or her.

Of course the player needs some hints:

* Bright colors are generally a sign of danger e.g. poisonous mushrooms or frogs
* Dangerous characters could act more sophisticated; use sword or other kinds of weapons; ride or use other less dangerous monsters; have their own house/shelter/tent..
* You could find books which describe some monsters and tell you what attacks they might use or even some basic strategies on how to kill them

As long as the game is balanced and fair i think new player won't get that frustrated by dying. In the end it's part of the game.

# Answer
> 28 votes
As someone already posted, nature gives hints:

* Bright colors, look at poisonous snakes and frogs
* The lair of the monster, if you run into a troll encampment on the forest, you will find the remains of other adventurers, pools of blood, none piles, etc. the more powerful the monster, the more hints you can give. You can also use environment in a way in which the more dangerous the monster, the more dangerous the area appears to the player, very creepy part of the forest, swamp, dark cave, fog, etc.
* Sound and light are your friends, use them to give hints to the players.
* There is a relationship between the power of the monster and the food chain, the more powerful, the more things nature gives them to help this purpose (claws, spikes, etc). Try to take a look at the game Spore from EA.

# Answer
> 17 votes
Some ideas:

1. You could make something like a small crystal (like in Sims) or such (a bar, name of the mob) which would appear above all monsters with different colors

for example:

* gray - insane
    * pink - extremely hard
    * red - hard
    * yellow - a bit hard
    * green - normal
    * blue - a bit easy
    * light blue - easy
    * white - extremely easy
2. This is not really a sure method but when the player is close to a powerful mob some kind of scary music might start playing.
3. At the beginning of the game you might also insert some type of guide which would help players in knowing the dangers in the world.
4. In general, for bosses it is best to use the big-size technique.

# Answer
> 8 votes
While you might not have explicit levels, you can probably come up with labels that give a warning. This could be done manually when the creature is created or automatically by calculating the sum of HP, attack bonuses or however else you gauge difficulty.

For example, if the monster is targeted and it's name appears in the UI, it would be pretty obvious that "Common Goblin" is a lot easier opponent than "Goblin Bodyguard" or "Goblin Lord" even if they share the same graphics.

It would be best if this is combined with the previous answers. A name combined with color, size, music or effect cues.

# Answer
> 5 votes
Well, it all depends on what kind of enemies you are trying to make stronger.

If you are making variants of enemies that are stronger (Like an elite or champion enemy that is based off of another weaker enemy), you could always add deadlier appearances. Lets say you have a slime. The ultra version of it could have red eyes and have spikes sticking out of it. But then the elite version would have white eyes, horns, and be glowing white.

Characteristics like red eyes, glowing a color, spikes, horns, greater size, and having weaker enemies around it could help distinguish dangerous enemies from their stronger counter parts. Those characteristics can also work for enemies that are stronger but do not have a weaker counterpart.

Different sounds can also help separate stronger enemies from weaker enemies. While battling a weak enemy, a small song could be played. But when you engage a stronger one, the music goes dark and gives a sense of fear and urgency.

Terrain can also help. Darkened or stormy skies show danger, as do barren or deserted lands. You would put weaker enemies in happier territory, like a grass field or a forest. But you would put the stronger enemies in a darkened isolated cliff side, or a fiery volcano. Ambience can tell apart the weak areas from the strong ones. Birds tweeting or a small breeze could mean weak, but screams and moans would tell a player that the area could cause death, or potentially have strong enemies.

Even the location of the enemy could tell them apart. If you have enemies that are guarding treasure, make the stronger ones guard a more elaborate chest than the weak ones. If the strong enemies are near weaker enemies, put more weak enemies, and less strong ones. That gives a sense of leadership, showing that the strong one(s) are ruling over the weaker ones.

Equipment details can also decide strong and weak. More detailed and/or bigger weapons can show strength. Blood stains can show that the weapon has killed before, or that blood has splashed on his armor.

# Answer
> 4 votes
This goes into the concept of character development and design which can go very deeply. There are many ways to alter the hostility of an enemy, it is all relative to the resources you have at your disposal to make it happen.

Here are some ideas that will help you:

**Choice of color:** This can affect how a player perceived an enemy and in which order do the player encounter them. For instance, if a Green Blob is the first encounter for the player, the player will know that the Green Blob is the weaker enemy to fight. As the game progress, if you introduce a Red Blob, the player will be more attentive to what the Red Blob can do.

**Body Gesture:** What is the enemy doing in their idle state. Is it actively roaming? or is it just stationary? It is fast moving or is it slow? The way a monster moves can emit an aura of danger.

**Uniqueness:** Position a monster that is out of context is a good way to let the player know something is not right. If you have a group of Green Blob and suddenly you see a Bear, the player will know something is off.

**Sound:** What types of sound it is emitting? It is a cute oink or is it an aggressive ROAR!

Of course, there is more to it than just those. Things such as Environment Context, Facial Expression, Dress Code, and Size. Other things that indirectly notify a player the enemy is dangerous could be different display of health bar, change of music, etc.

I hope this helps :)

# Answer
> 3 votes
You can borrow ideas from nature! Horns and spikes, big angry eye spots, and many other such cues make things look more menacing. You might also try giving higher-level things tendrils, glowy red eyes, and so on.

Heck, using eye color as an indicator of relative strength might work pretty well too - when you're level 10, that level 5 slime has baby-blue eyes, but if you're level 1 it has glowing red eyes with a bloom coming off of it.

# Answer
> 3 votes
You could give a character an 'awareness' property, modifiable via some in-game equipment/collectible.

Behavior description:

* Every character has a default awareness of the enemy they are fighting. Once you attack an enemy, a partial ring appears under them. The color indicates relative difficulty and the completeness of the ring indicates health. At this level, the awareness ring only appears after an attack has begun.
* Interested players can obtain equipment/collectibles to increase their awareness, allowing them to view the awareness ring of enemies before they engage them in combat. Factors such as enemy proximity and environment (lighting, e.g. dark cave level) could be modifiers to the players effective awareness, as well.
* The above could be tweaked, for example in response to a 'blindness' curse, which might disable any awareness indicator for the curse's duration.

This element would set a tone for the gameplay. Players that like the feel can stick with it. Players that don't can pursue the awareness upgrades.

# Answer
> 2 votes
Consider how Halo: CE does things with the Elite enemies. There are several different colors of elite armor that one encounters, and as far as I can tell, the color is the only visible difference between them. So how does the player know what the hierarchy of colors is? Rarity! Blue elites are the first color encountered, and they are by far the most common. Next are red elites, which are less common, and finally yellow elites are the rarest and most difficult (and they usually have giant glowing energy swords, which is another hint). There are other colors too, especially in the sequels, but you get the idea.

So, sometimes simple visual distinctiveness combined with the frequency and context of encounters is enough to distinguish. For example, I believe that for the first 2 and a half missions of Halo: CE, there are *only* blue elites. So the first time the player encounters any other color, the natural response is to proceed with caution until the player knows how the new color is different from the blue elites. Basically, the important thing is that when the player encounters a new "level" of monster, it mostly just needs to look and behave obviously different from what the player has seen before. Once the player realizes it is new, wise players will approach with caution until they understand the new abilities and behaviors of the new monster.

# Answer
> 1 votes
WoW uses level color to make monsters appear more dangerous than others.

For example a monster far below your level has a gray level, monsters slightly lower level than you are green, monsters on your same level are yellow and monsters on higher level than you are orange then red.

# Answer
> 1 votes
If your goal is to highlight some special qualities of the monsters, you may also make them flash or change their colours, or make them moving in a different way, or changing their dimentions at certain rhythm.

# Answer
> 0 votes
I think in enemy design, form follows function. I would suggest that you consider what makes each enemy more or less of a challenge and, given that part of your goal is to efficiently communicate this information to your players, to also consider some existing enemy modeling paradigms:

* Is the enemy a sentinel who can take tons of damage? Make it large.
* Is it capable of a specific type of damage? Color accordingly.
* Is it particularly agile? Perhaps model a smaller character.

Also, in addition to what Fluffy and Shadows wrote about eye color, I think you may be able to add character to the appearance of your enemies by altering eye shape and size.

# Answer
> 0 votes
What about some kind of simulation of fear (tunnel vision, heartbeat sounds etc.)? Approaching enemies that would easily kill the player would trigger this.

---
Tags: graphics, difficulty
---


# Question
Title: OpenGL ES 2.0 texture distortion on large geometry
OpenGL ES 2.0 has serious precision issues with texture sampling - I've seen topics with a similar problem, but I haven't seen a real solution to this *"distorted OpenGL ES 2.0 texture"* problem yet.

This is not related to the texture's image format or OpenGL color buffers, it seems like it's a precision error. I don't know what specifically causes the precision to fail - it doesn't seem like it's just the size of geometry that causes this distortion, because simply scaling vertex position passed to the vertex shader does not solve the issue.

---

Here are some examples of the texture distortion:

* Distorted Texture (on OpenGL ES 2.0):
* What the texture normally looks like (also on OpenGL ES 2.0):

The texture issue is limited to small scale geometry on OpenGL ES 2.0, otherwise, the texture sampling appears normal, but the grainy effect gradually worsens the further the vertex data is from the origin of XYZ(0,0,0)

These texture issues do not occur on desktop OpenGL (works fine under Windows XP, Windows 7, and Mac OS X)

I've only seen the problem occur on Android, iPhone, or WebGL(which is similar to OpenGL ES 2.0)

---

**All textures are power of 2** but the problem still occurs

* **Scaling the vertex data** \- The values of a vertex's X Y Z location are in the range of: -65536 to +65536 floating point

+ I realized this was large, so I tried dividing the vertex positions by 1024 to shrink the geometry and hopefully get more accurate floating-point precision, but this didn't fix or lessen the texture distortion issue
* **Scaling the modelview** or scaling the projection matrix does not help
* **Changing texture filtering** options does not help

+ Disabling mipmapping, or using GL\_NEAREST/GL\_LINEAR does nothing
    + Enabling/disabling anisotropic does nothing
    + The banding effect still occurs even when using GL\_CLAMP
* **Dividing the texture coords passed to the vertex shader** and then multiplying them back to the correct values in the fragment shader, also does not work
* **precision highp sampler2D, highp float, highp int** \- in the fragment or the vertex shader didn't change anything (lowp/mediump did not work either)

I'm thinking this problem has to have been solved at one point - Seeing that OpenGL ES 2.0 -based games have been able to render large-scale, highly detailed geometry

# Answer
> 4 votes
What you're seeing is floating point accuracy, or lack thereof.

Even highp is specified as **16 bit** in OpenGL ES according to the spec (pdf link). To make things worse, denormals/subnormals are not required (these are used to improve accuracy near zero, but require special handling and, to save silicon space, are often not implemented).

Note that's the minimum spec, and implementations may be more accurate. You can get more information about the accuracy of your specific implementation by calling glGetShaderPrecisionFormat().

To solve the problem, try not to use huge numbers with tiny changes.

---
Tags: android, iphone, textures, rendering, opengl-es2
---


title: Play .mp4 videos using Irrlicht

text:
# Question
Title: Play .mp4 videos using Irrlicht
In the game I'm making, I'll sometimes need to play videos of the .mp4 format. Does Irrlicht support .mp4 playback? And if so, can anyone recommend a good tutorial on doing so?

# Answer
Short answer: no.

Slightly longer answer: you can use irrlicht to display video (for instance by updating a texture you're displaying), but you have to handle the decoding in some other way. Based on a quick googling, ffmpeg seems a popular answer.

Here is a thread at irrlicht forums asking exactly the same thing you asked here.

Personally, I'd suggest using some other format than mp4 due to licensing issues, such as xiph theora (cool guys, horrible project names).
> 2 votes

---
Tags: irrlicht
---


# Question
Title: Is there a sound library for C to generate sound samples from code?
I'm working on an engine for a retro-style game in C. I'm looking for a sound library that would produce chip sounds from code...I want to make my own simple chiptune tracker for the engine to create music. Does such a thing exist?

I'd also be interested in a library to use .nsf files in my project.

I'm using Linux for development.

# Answer
Probably not a correct answer but here is a library of various audio engines

(Scroll down to the second segment for audio libraries)

At least 9 out of 12 engines go with C. Most of them also support tracker files. Which is not so different than nsf ( I assume these are NES music files ) files.
> 3 votes

# Answer
Sure you can, it's just not trivial to get it sounding "nice".

I don't know how to do it in Linux, but if you can play a PCM buffer, all you have to do is fill it with whatever you want.

So supposing your buffer is set to play in monaural, signed 16-bit samples, at 44100 samples per second, creating a pure (sinusoidal) A4 sound (440 Hz) is as simple as

```
int16_t buffer[44100];
float frequency = 440.0f;
float sampling_ratio = 44100.0f;
float amplitude = 0.5f;
float t;
for (int i = 0; i < 44100; i++)
{
    float theta = ((float)i / sampling_ratio) * PI;
    buffer[i] = (int16_t)(sin(theta * frequency) * 32767.0f * amplitude);
}

```

However, this sound is probably very dull for your interests, so you have to do some more complicated things. In general, there are two types of sound synthesis: Additive and Subtractive. There are many others, but these two are probably the most simple ones. Today I'll just talk about additive synthesis.

For additive synthesis, you do the same thing as I did just up there, but instead of just using one frequency at one amplitude, you add several waves together. This is just like pressing several keys on a piano at the same time. So you modify your code to look something like this:

```
void add_sine_wave(int16_t* buffer, int buffer_length, float frequency, float sampling_ratio, float amplitude)
{
    for (int i = 0; i < buffer_length; i++)
    {
        float theta = ((float)i / sampling_ratio) * M_PI;
        // make sure to correct for overflows and underflows
        buffer[i] += (int16_t)(sin(theta * frequency) * 32767.0f * amplitude);
    }
}

```

and then use it like this:

```
int16_t buffer[44100];
memset(buffer, 0, sizeof(buffer));
// Create an A Major chord
add_sine_wave(buffer, 44100, 440.0f, 44100.0f, 0.5f);
add_sine_wave(buffer, 44100, 554.37f, 44100.0f, 0.5f);
add_sine_wave(buffer, 44100, 659.26f, 44100.0f, 0.5f);

```

By the way, I'm getting my frequencies from here (I'm using equal temperament, but there are lots of other tunings available).

Notice that so far I've only been using sine waves, but old synthesizers also support square, triangular and saw waves as well, each with its own interesting sound properties. Implementing these is pretty straightforward.

Other things you can do to increase the variety of sounds you can create are:

1. Amplitude modulation: Changing the amplitude of the wave throughout the buffer
2. Frequency modulation: Changing the frequency of the wave throughout the buffer
3. Reverb: Repeating a sample by changing its shape and position in the buffer. Itself a very complex topic.
4. Enveloping: Changing the amplitude of a sample to give it more life

The point here is that the techniques themselves are not very difficult, so you don't really need a library to abstract them for you. It's using them to create interesting sounds what is difficult.

One final note. When experimenting with sound like this, it may be really useful to save your data to WAV files, and then visualizing them in some software like Audacity. That way you can see what you're doing more clearly.
> 17 votes

# Answer
For chiptune sound effects, there's one definite answer: sfxr.

It's a standalone application that you can use to generate samples, but the source code is also available should you want to integrate it to your code.
> 4 votes

# Answer
I can personally recommend Blargg's audio libraries. Something that may be of particular interest to you is his Blip\_Buffer.

Blargg's site has several "retro" audio synthesizers, and I am actively using his Game\_Music\_Emu to play NSF files in a Mega Man clone I am writing.

Many of the libraries are written in C++ but some provide a C interface as well.
> 3 votes

---
Tags: c, sound, music, linux
---


# Question
Title: How can I render primitives to pixel coordinates?
I'll emphasize that I am *very* new to graphics programming. I've been using XNA up until now and I've been looking for a way to build simple 2D functionality with textured quads. I'm *sort of* starting to get how the whole process works, but the idea of positioning things from 0 to 1 doesn't seem quite right for what I'm doing. Is this the *only* way to do it? I've learned that I'm supposed to be rendering quads to an orthogonal projection, but I guess my problem is exactly how to implement that the correct way.

I totally acknowledge that my problems are a result of not understanding the technology, but all of the tutorials I can find tend to gloss over a lot of the details. Is there a simple way to set up an orthogonal projection in d3d11, and is there a simple way to convert the coordinates so I can specify it in pixels (like the XNA spritebatch)? I'm hoping that seeing the answer to this will help me get a more solid grasp on a lot of the areas where I'm confused in general with graphics programming.

# Answer
> 1 votes
I don't know exactly how its done in DirectX as I've only ever worked with OpenGL, but presumably you just transform all your objects' location vectors by a scaling matrix made from the reciprocal of your viewport's current resolution.

For example, in fullscreen 1080p you would scale all x coordinates by 1/1920, and y's by 1/1080. That way you can specify all locations in pixels.

(UPDATE: Actually, having just tried this out, for pixel perfect it should be HALF the viewport size, so 1080p would mean scaling by x=1/960, y=1/540, I forgot that device coordinates go from -1.0 to 1.0, resulting in a width of 2.0 not 1.0. Yeah I know, obvious in hindsight huh?)

You just have to remember to keep those scale factors up-to-date with your viewport if it get's resized, and if I recall correctly, XNA's 2D origin was in the top left, while in this case it would always be the middle of the screen, though that's fix-able too, just translate down and right by half the resolution in each direction after scaling. (Update: this translation should still be correct)

Edit: Also, when working in 2D don't bother with complex orthogonal projection matrices, scaling with your resolution does the same thing and at least you know what's going on.

---
Tags: 3d, directx11
---


# Question
Title: How to achieve persistence of objects between game states?
What are the possible ways of sharing different objects between game states?

Lets say a game has a couple of states (a menu state and a game state for example), at first the engine calls the menu state's load function which loads menu textures, music et cetera.

After returning from the load function the engine enters a loop which calls update and render over and over. At this point the menu state makes a TCP connection to a IP (joining a lobby for a 1v1?) which simply creates a object of a connection class and then signals the engine to switch to the game state, the menu state then unloads all the stuff it loaded up.

Now the engine calls game state's load function, the game state loads models, textures et cetera and then enters the update-render loop.

The question now is, how will the game state know about the connection class object that the menu state created? How do the states share objects between themselves? And not only connections, different object types too, even templates maybe, imagine a template class called container which can hold anything such as textures, models, integers, strings, settings under the form of strings that are shared between the menu state and game state such as what game save the player chose when in menu state, or the difficulty...

There are two questions that look like this one but neither of them answered my question:

# Answer
You're probably overthinking it. The only things owned by the game state should be things specific to that game state alone. Everything else should exist outside the game state and persists throughout. Usually, whatever owns the game state should also own those items, but it could be any object really. If the game state needs access, pass it in as an argument.

My object hierarchy often looks somewhat like this:

```
Application
+- Current State
   +- World (if it's a gameplay state)
      +- Characters
      +- Objects
+- Application Settings
+- Graphics/GUI
+- Audio
+- Networking
+- Resource Managers (unless they're part of specific subsystems)

```

How does the Current State know about the Audio? I pass in a reference, either when I create the state or when I update the state. Same for everything else.
> 6 votes

# Answer
There is a book called Head first Design patterns that discusses the various scenarios and designs for the types of situations you are describing. It's worth a look, I think you will find it useful.

Head First Design Patterns on amazon.co.uk
> 0 votes

---
Tags: architecture, state
---


# Question
Title: How should I go about randomizing levels in a "runner" game?
I'm working on a runner type of game (basically it's a never ending run through hordes of enemies and platforms and whatnot). 2d platformer view.

Should I random a bit of map every now and then? Few screens or 30 screens? And what about platforms and ground to make the whole thing "doable". Can I find any resources on that subject?

# Answer
If you look at the way something like Jetpack joyride works, it has sections within each level that are pre-prepared, for example formations of groups of coins. There are a finite number of configurations that are added randomly in random positions. The enemies and bonus pickups are spawned in the same way. This is probably the simplest method and you could tune the probabilities as the game progresses to increase the difficulty. Playtesting should dictate the best settings.
> 1 votes

---
Tags: game-design, algorithm, level-design
---


# Question
Title: Turn based card game multiplayer: http polling or TCP
I am working on card games for mobile devices. For multiplayer I will be communicating through a central server. For the purpose I sorted out three options:

1. HTTP polling
2. TCP
3. Websocket (client libraries are not good, so will not use it)

HTTP polling is simple, but I fear it will introduce much more delay and too many HTTP calls. TCP introduces other complications.

So my question is: Is HTTP polling appropriate for a card game? Will the HTTP overhead be too much? How much interval should I keep for polling?

Can you give a sample game based on HTTP polling?

# Answer
When you can use TCP sockets, you should use them. Everything else you mentioned are just protocols on top of TCP anyway which add boilerplate which is unlikely to add anything in your particular use-case. I don't know what "other complications" you are referring to, but when you have problems, we at stackoverflow.com will certainly be able to help you.

When you want to make your application HTML-based (best option for true portability), you can't use pure TCP sockets. But there is socket.io, which is able to pick the most socket-like transport mechanism available to the browser and use it through a common interface.
> 2 votes

---
Tags: networking, polling
---


title: Trying to make a python map editor

text:
# Question
Title: Trying to make a python map editor
The program is supposed to read the pixel color values from an image, and use that data as a map for where to place objects in a game world.

Getting the color values was easy enough:

```
import numpy
from PIL import Image

img = Image.open("colors.png")
data = numpy.array(img)

```

The color value should be used to choose a type of object, and the data\[ \] index values translated as coordinates to choose where on a surface the object is placed. It's not clear to me how to go about implementing this, I'm still trying to learn python.

I need help with understanding how to structure a system which goes through all the values of the data\[ \] array, and creates a map based off of those values. For example, data\[0,0\] is a red pixel, therefore make an instance of object\_type\_1 and place it in the top left corner of the screen surface, data\[0,1\] is a blue pixel, make an instance of object\_type\_2 and place it 20 pixels to the right of the first object.

# Answer
> 1 votes
The general process here is simply something like this:

```
for row_number in rows:
  for column_number in columns:
    value = data[column,row]
    if value == 1:
      obj = ObjectType1()
    elif value == 2:
      obj = ObjectType2()
    else value == 3:
      obj = ObjectType3()
    obj.x_position = column * 20
    obj.y_position = row * 20

```

I have assumed objects are 20 units in width because your question implied it.

This gives the objects a position, but it does not place them on the screen - how to draw objects depends on the graphics library you choose to use. But the process there will look a bit like this:

```
for object in all_objects:
    screen.draw(object.graphic, object.position_x, object.position_y)

```

---
Tags: python, pygame
---


title: Cocos2D-X on Steam and iOS App Store

text:
# Question
Title: Cocos2D-X on Steam and iOS App Store
With Cocos2D-X can I really submit my games to Steam and iOS App Store? It's commercial quality? Do you have some samples of games built on Cocos2D-X that is on sales in Steam?

Thanks.

# Answer
I dont think steam will bother in what you use for engine, as long as your product are stable, correct and worthy. if they find your game filld with bugs and crashes, they are probably not going to release it. Just take a look at What happend with warZ. they did use a pretty well known engine, but the game was filled with bugs and had promises it dident held up, that ended in steam removing the game. So if you dont to it like that i dont see any problem using Cocos2d. Better send them a mail and ask them.
> 1 votes

# Answer
Regarding Steam: These two threads ask the same question but have not generated any conclusive answers.

http://www.cocos2d-x.org/boards/6/topics/2880

http://www.cocos2d-iphone.org/forum/topic/12044

The Steam FAQ makes no mention that any particular frameworks are disallowed. In fact the SteamWorks API is C++.

Regarding the iOS App Store: There are apps for sale that use cocos2d-x, here is just one:

http://www.cocos2d-x.org/boards/21/topics/6812
> 0 votes

---
Tags: ios, cocos2d-x, pc, appstore, steam
---


# Question
Title: How to determine that nodes in Grid Graph are unreachable before applying pathfinding?
I would like to determine accessibility of nodes before applying pathfinding algorithm to Grid Graph.

I have a surface with nodes overlayed on it and I would like to somehow determine that nodes inside yellow region are unreachable from outside of it (from behind the wall).

# Answer
> 9 votes
1. Choose a walkable node.
2. Flood-fill it. Any square not filled is not reachable from the chosen square.
3. Repeat the above with another unfilled walkable node to find another separated region.

If you do this completely, you will have a list of connected regions of the map (a *partition* of it into *connected components*).

If your map is static, you only need to do this once. Otherwise, it's still not hard: If a node becomes unwalkable, rerun just on the component containing it and you may find you have two components. If a node becomes walkable, then if if it has immediate neighbors from two different components, combine them.

---
Tags: unity, ai, path-finding
---


# Question
Title: Simulate movement towards the screen in a 2D world
I need to create the illusion of someone kicking a ball to the screen. For that, I have a initial position of the ball (about the middle of the screen), and I put the sprite of the ball scaled at 0.2 of his original size. Then, I generate a random position on the screen, and move the ball sprite to it, and at the same time, I increment the scale of the ball, until I reach 1, the real size.

At this point, the ball "hit" the screen. All this works great, but the scale of the ball is not coordinated with the movement of the ball, and, because of it, I must always wait until the scale reaches zero, after the ball is arrived to his destination, or, I must wait until the ball reach his destination, after the ball is already scaled to 1.

The question is, how must I calculate the resize factor of the ball, so it gets to 1 at the same time that the ball reach the desirable coordinates in the screen? The speed of the ball is a random number between a given range, and, of course, I'm using only 2D sprites.

# Answer
The ball needs to travel a certain distance to reach the coordinates where it "hits" the screen. Find this distance and calculate how long the ball will take to reach it given its randomly chosen speed. Now you have a time. Use that time to calculate the scale/second change you will apply to the ball.

Roughly:

```
Ball = (BallOnScreenX, BallOnScreenY, BallDepthIntoScreen);
Target = (TargetX, TargetY, 0);
a = Ball.x - Target.x;
b = Ball.y - Target.y;
c = Ball.z - Target.z;
Distance = sqrt((a*a)+(b*b)+(c*c));
DeltaPerMS = GetBallSpeed();
BallMoveTimeMS =  Distance/DeltaPerMS;
ScaleDelta = 1.0 - 0.2;
ScalePerMS = ScaleDelta/BallMoveTimeMS;

```

Essentially you are moving the ball in `x` and `y` on screen and simulating the movement in the `z` direction by changing the scale.
> 9 votes

# Answer
This is probably done best by emulating 3D. The following is 3D maths cut down to the bare minimum needed for your case. In the following I presume that you define an `[initial scale]` and a `[final scale]` for the ball according to how large/close you want it to appear, along with start and end coordinates, and the `[time]` it should take. You should also define a `[gravity]` constant.

### Scale

The `[ball scale]` should be proportionate to `1/[distance to screen]`, where `[distance to screen]` should decrease linearly with time, it must not reach 0, but should rather decrease to the point where the ball has the desired size.

It doesn't matter what unit the distance is measured in, so the easiest this to do is simply to declare the `[initial distance]` to be equal to `1/[initial scale]` and `[final distance] = 1/[final scale]`

### Position

The ball should also move across the screen in the same non-linear fashion that it scales, so when you have calculated `[ball scale]` you can use that to get the position as well, it would simply be

```
[position] = [start position] + ([end position] - [start position]) *
             ([ball scale]-[initial scale]) / ([final scale]-[initial scale])

```

### Gravity

This makes the ball seem to move through the air in a straight line, real balls tend not to do that because of gravity, save for very speedy shots it would look weird if the ball's path doesn't bend downwards. First we need parabola that goes through 0 at the initial and final distance to screen:

```
[height] = ([distance to screen]-[initial distance]) *
           ([final distance]-[distance to screen])

```

Then this parabola should be scaled to the desired level of gravity and to give greater height to slow balls:

```
[height] = [height] * [gravity] * [time]^2

```

Finally the visual representation of this height should be scaled like the ball:

```
[visual height] = [height] * [ball scale]

```

The \[visual height\] should then be added to the vertical part of the screen position. Depending on time and gravity scale this may make the ball go off screen for part of the shot.

Don't hesitate to ask if something isn't clear.
> 3 votes

---
Tags: xna, c#, movement
---


# Question
Title: How to make a character in a Box2D world jump faster?
I have a question about using Box2D to simulate a physics-platformer. I manage to make the character move to the right and left, and jumping as well. However, jumping seems extremely slow when compared to most tile-based platformers.

Is there a way to speed up the jumping and falling of the player? I of course know from my basic physics lessons that 'heavier' objects don't fall faster in the real world, but is there a way to simulate this in Box2D?

# Answer
> 6 votes
You're likely simulating some kind of upward force greater than gravity to make the physics object "jump". Increasing the amount of force will allow the character to reach a higher velocity quickly. Likewise, increasing the force of gravity on the player will make them fall faster.

You can either increase gravity for the entire world, or apply an additional constant force to the player to simulate increased gravity.

Make sure you also increase the jump force when you increase gravity to allow the jump force to overcome the increase in gravity.

---
Tags: physics, box2d, platformer
---


# Question
Title: What is the appropriate way to implement collision in 2D worlds?
If I want to create a 2D game map which features areas traversable by a player through standard up/down/left/right inputs, and then have areas that are NOT traversable... perhaps just a bush, or a sign post, or a rock.

What is the appropriate agent to enforce these rules?

It seems like the trendy thing is to ship off these responsibilities to Box2D, but that seems wrong to me. Is there a technique with lower overhead to produce the same effect? Is it as simple as inventorying and enumerating through every rock and making sure the player can or cannot walk to the space they are trying to walk to? That's how I am doing it now.

# Answer
> 7 votes
There are multiple different solutions, each with their good and bad points. Three ways:

1. Using a dedicated physics engine, such as indeed Box2d. This is very helpful when you want to do all kinds of crazy calculations with your objects. However, when you don't really need the physics-part of the engine, it is often better to write your own simple collision engine.

Pros: easy to implement.

Cons: slow, can behave unpredictable at times.
2. Using Bounding-boxes. This is in fact what you are using now. Store for each collidable object in your scene a box (or another shape, but a box is the easiest) and then check when the player moves if he/she will intersect with these boxes. If they will, then prevent the movement from happening.

Pros: easy to implement as well.

Cons: With a big amount of objects, calculating becomes extremely slow.

Also worth noting: This system is more or less the same as part of what happens internally in Box2d.
3. Using a Tile-based system. Divide the map you have in a square grid(can easily be conceptualized using a two-dimensional array). Before the game starts, fill in each of the grid's tiles that intersects with the position of one or multiple of your solid objects.

Pros: relatively fast. Does not get slower when using more objects in your map.

Cons: Less precise than the above(unless you use a pixel-size grid). Possibly more memory-intensive than the above.

---
Tags: 2d, physics, maps
---


title: Why is chunk size often a power of two?

text:
# Question
Title: Why is chunk size often a power of two?
There are many Minecraft clones out there and I am working on my own implementation. A principle of terrain rendering is tiling the whole world in fixed size chunks to reduce the effort of localized changes.

In Minecraft the chunk size is 16 x 16 x 256 as far as I now. And in clones I also always saw chunk sizes of a power of the number 2.

Is there any reason for that, maybe performance or memory related? I know that powers of 2 play a special role in binary computers but what has that to do with the chunk size?

# Answer
This would depend on the game and the indexing structure used for the chunks. Though, at such a high level, it's not too likely it has much to do with memory or a specific performance enhancement. More than likely it's an arbitrary decision for sizing chunks in a predictable way. It allows for some counting and indexing tricks using bit shifting that wouldn't be possible with numbers that aren't a power of two.

For example, counting in powers of two is as easy as shifting a bit in binary:

```
Dec =  Bin
1   =  000001
2   =  000010
4   =  000100
8   =  001000
16  =  010000
32  =  100000

```

Where these shortcuts will be used will depend on the developer and what problem they're trying to solve.

If you're making a decision for what size to make the chunks, and it doesn't matter in any other aspects, you may as well use something that is familiar and has benefits you're used to using.
> 27 votes

# Answer
First, multiplying by powers of two is much cheaper than multiplying by an arbitrary number, since you can do it by bit shifting. Most of the time the compiler can do this for you, so whenever you write "\* 16" in your code, the compiler actually does a shift by four, and you don't need to worry about it - you just need to give the compiler the opportunity by designing your data structures this way.

Second, since cache lines, memory busses and other information highways in your computer also tend to be designed to use powers of two, you may get a better performance overall this way.

Third, we old geeks just are used to playing around with powers of two, so it's a habit.

(Fourth, other old geeks who design your hardware and your compilers also like powers of two, so this is not going to change any time soon).
> 15 votes

# Answer
The real answer is just this: On a binary computer, powers of two are nice round numbers.

When a normal person needs to pick an arbitrary number for some purpose, they typically choose nice round numbers in the number system they're comfortable with, base 10. So they'll pick 10, 100, 1000, etc. Because they're simple and easy and don't require much thought and the precise value wasn't really important to them, they were just aiming at a general scale of magnitude.

As programmers, when we need to pick an arbitrary number for some purpose, we typically choose nice round numbers in the number system computers use, base 2. So we'll pick 2, 4, 8, etc. Because they're simple and easy and don't require much thought and the precise value wasn't really important to us, we were just aiming at a general scale of magnitude.

It's really not any more complicated than that. They're just nice round numbers.
> 9 votes

# Answer
One reason not mentioned in other answers is that if needed, powers of two numbers can always be halved without rounding problems. This is probably not a reason in Minecraft clones, but is in some other cases such as in textures with mipmaps.
> 6 votes

# Answer
Another potential reason would be that it would allow you to encode info about each chunk in a 3D texture. If your target hardware supported 3D textures but didn't have fully robust and general non-power-of-two texture support (which I admit you'd want to be shooting fairly low for) then making your chunk sizes powers of two is not just ideal - it's essential.
> 2 votes

---
Tags: performance, data-structure, minecraft-modding, memory
---


title: Code structure in Android 2D game

text:
# Question
Title: Code structure in Android 2D game
Well I've finnaly decided to start Android game dev, and my first project will be simple 2d canvas based game. I have some experience in game developing with C# and XNA, and I'm a bit confused now. Back in XNA we have Game class with Initialize, Update and Draw methods.

In Android I have to extend SurfaceView class, run draw and update in their own thread, and receive touch input from user.

I'm looking for a proper way to structure my code.

Some of my questions are :

* How to deal with Activities (Should I run everything in one activity, or split whole game in 2 or more) ?
* Where should I run game loop ?
* Where to put Draw and Update methods ?
* How to respond to touch events ?

Hope I came to the right place for answers...

# Answer
> 2 votes
A minimal Breakout game, demonstrating the use of Activities, touch event handling, and draw/update with GLSurfaceView can be found here.

---
Tags: android, architecture, multithreading
---


title: Texture prefetching in GLSL

text:
# Question
Title: Texture prefetching in GLSL
I have a fragment shader which needs lots of semi-random access to 32x32 texture patch. Fortunately, the patch is constant for each poly, so there should be no issue storing the whole thing to the texture cache.

So my question is, is there any way in GLSL to prefetch texture patches? Normally, I would be fine letting the FS load the texture naturally, but with the nondeterministic access pattern, I'm afraid that could be producing a ton of unnecessary thrashing while it sorts itself out.

# Answer
> 3 votes
No, there isn't.

> while it sorts itself out

Which will, for a 32x32 texture require... 128 memory accesses. Assuming a 32-byte cache line size and GL\_RGBA8 format for the texture. It's only 4KB in size. Unless the cache is microscopic, there won't be any cache misses after it touches all of those 128 memory accesses. And if the cache is smaller than 4KB, there's no "prefetching" that can make a small cache big enough for your data.

Just let the GPU do its job.

---
Tags: textures, glsl, optimization
---


# Question
Title: Do games depend on the OS to scale resolution?
I'm having issues with my computer related with scaling when using different resolutions other than the native. So I started to wonder, in PCs, is scaling handled by the card driver or the game engine? Does it depend of what engine we are talking about? Do engines somehow bypass the scaling algorithm from the driver?

PS: I'm talking about the regular PC games that uses DirectX or OpenGL.

# Answer
A video card sends out a video signal of some resolution and update frequency.

A monitor displays images of various resolutions and update frequencies.

The logic controlling the display of images of non-native resolutions is handled in the monitor.

*Exceptions:*

Video driver software on the computer can often determine the supported resolutions of a monitor, and perform scaling by itself, to scale a video image of unsupported resolution into one which is supported by the monitor. In this case, a scaling algorithm can be applied from within the driver to convert the low-resolution video signal into native resolution, which is then sent to the monitor.

Game software can often also determine supported resolutions, and can scale its own video image from its internal resolution to one of the supported output resolutions. In this case as well, a scaling algorithm can be applied from within the game, and the driver and monitor receive a native resolution video image. (To my knowledge, this is very rarely done except on video game consoles, where many games render at a lower resolution and scale the resulting image up to fill the full display resolution. PS2 games, in particular, were notorious for rendering 512x386 images, and then scaling them up to full display size).
> 4 votes

---
Tags: graphics
---


title: Make image follow path

text:
# Question
Title: Make image follow path
I made an animated main menu introducing my game. In the menu there is snow and fog to create a more alive feel to it. Now I want to add a hawk that randomly spawns and flies across the screen in the distance.

Any idea how I'd create a "path" for it to follow? The path would be a curved line or something for the hawk to follow to simulate realistic movement. I have no idea how to design this.

As a side note, I'm writing this game in Löve2D.

# Answer
> 10 votes
Spawn the object at a random location on the side of the screen. Additionally, give it a initial direction/velocity of straight across the screen +/- random 20 degrees at whatever speed you want it to move. Finally choose a random target location on the opposite side of the screen.

Now use steering to guide the object from its initial starting position and velocity to the target position. This way you only need to choose two positions and you'll get fairly natural movement while it's moving from one side of the screen to the other.

Alternatively, you can pick your start and end positions forming a line across the screen, then use mid point displacement to alter the line to make it less straight. (I suggest a higher (H) value closer to one so your bird doesn't look like it's on drugs).

Further, you can combine the two and steer between the deformed vertices on the displaced line. Creating smooth movement that's more random than one point to the next.

Or you can take those displaced line vertices and use them to make a Bézier curve and follow it exactly.

Another alternative is to use the wander behavior defined in this GDC paper from '99. You'd want to put some constraints on that to make sure your object reaches the other side, but it could give more interesting results depending on what you're going for.

---
Tags: love2d
---


# Question
Title: Looking for a peer reviewed article that details the benefits of a physics simulation within interactive media
I'm hoping this is the correct place to ask this question as it is video game related and can be seen as a key ingredient in modern game development.

Does anyone know of a peer reviewed article that details the benefits of incorporating a physics simulation into interactive media (such as video games)?

I can find books with a few remarks in their introduction (no more than a couple of sentences) but nothing substantial.

# Answer
> 1 votes
You should check the proceedings of the relevant conferences in the area of Computer Graphics such as SIGGRAPH, SIGGRAPH Asia, SCA and I3D. They all have tracks about physically based animation and most of the papers will have an introduction / related work about physically base animation.

To make things easier, this website does actually links the most relevant papers about physically based animation in the conferences I mentioned.

You could also look for surveying papers about physics simulations in fluids and character animation, they should contain information about the benefits of this approach. Here you have two that might help you: http://www.cc.gatech.edu/~jtan34/downloads/scienceInChina.pdf and http://hal.archives-ouvertes.fr/docs/00/07/32/49/PDF/RR-3441.pdf

---
Tags: physics, simulations
---


title: Allegro 5 al_draw_text skips characters

text:
# Question
Title: Allegro 5 al_draw_text skips characters
I'm using Allegro 5.0.8 al\_draw\_text to draw text on a bitmap (backbuffer). However, I've noticed that the first character of the string is always skipped. Moreover, whenever the same character appears in the string, it is skipped again.

For example:

```
font = al_load_font(path.c_str(), 100, 0);
std::string str = "01230450678";
al_draw_text(font, color, 100, 100, 0, str.c_str());

```

Will print "12345678", skipping all occurrences of '0'

I've tried several TTF fonts, which work with other graphic software. I've noticed that this sometimes may or may not happen with the same font, depending only on the text size on screen (font size)

Edit: I've formatted the code and added the arguments I've used to load the font.

Edit2: Here is a complete code to replicate this using Allegro 5.0.8.

This code should print "0123045670890", but, instead, it renders the following image: (Note: I didn't cleared the memory because the error appears before program finishes)

```
//---------------------------------------------------------------------------

#include <string>

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_opengl.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_primitives.h>
//---------------------------------------------------------------------------

using namespace std;

//---------------------------------------------------------------------------

int main(int argc, char * argv[])
{
    al_init();
    al_install_keyboard();
    al_init_image_addon();
    al_init_primitives_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_set_new_display_flags(ALLEGRO_OPENGL);
    ALLEGRO_DISPLAY * mainWindow= al_create_display(1200, 1000);

    ALLEGRO_PATH *path = al_get_standard_path(ALLEGRO_RESOURCES_PATH);
    string file = al_path_cstr(path, '/');
    file = file + "arial.ttf";
    ALLEGRO_FONT * font = al_load_font(file.c_str(), 50, 0);

    al_set_target_bitmap(al_get_backbuffer(mainWindow));
    al_draw_filled_rectangle(0, 0, 1200, 1000, al_map_rgb(0,0,0));

    al_draw_text(font, al_map_rgb(255,0,0), 50, 50, 0, "0123045670890");

    al_save_bitmap("d:\\teste.bmp", al_get_backbuffer(mainWindow));

    al_flip_display();

    al_rest(5.0);

    return 0;
}

```

# Answer
> 4 votes
It sounds like a bug with caching glyphs. These sorts of glitches generally are only applicable to video memory, so if you switch to a memory bitmap font by calling this before loading the font you can work around the issue:

```
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);

```

You'll need to clear the flags after you load the font, or else all subsequent bitmaps will be software based as well.

However, this is not a good long term solution, as using memory bitmaps may significantly degrade performance.

While the above will probably get you up and running, you should at some point:

* Upgrade your OpenGL drivers if applicable
* Try out Allegro 5.1.X, as it may have fixes that have not yet made it to 5.0.X.

If neither of those solve the issue, then you should file a bug report, including the sample source code and details of your OS and video card.

---
Tags: allegro
---


# Question
Title: Billboards offset for character names + rotation
I am successfully using Matrix.CreateBillboard in my XNA game to print the characters name above the models. The problem I have is with the offset (to appear above the models). Currently, I am creating the location of the text using;

```
Vector3 objTextPosition = objPlayerShip.objShipVector + new Vector3(0, 3, 0);

```

This works fine if I stay within the same general lateral location. If I rotate above or below the model the text either appears on top of, or is covered by (or even below) the model. To compensate for this, I would need to create a rotation around the model (should I use a quaternion?) with the top always pointing up (with a Vector3(0, 3, 0) offset).

Am I over thinking this? Is there a simple way to achieve this?

Thanks in advance!

---

Here is the correct way (above the model)

---

Here is looking from top, down

# Answer
> 1 votes
A Vector that you can use to always cause the text to be slightly above the ship on the screen regardless of camera angle would be:

```
Vector3 objTextPosition = objPlayerShip.objShipVector + (Matrix.Invert(view).Up * 3);

```

essentially, it does what you were thinking of (transforming global UP by "some" rotation). But since the camera already using that "some" rotation , it just borrows a vector from it. (although it needs to be inverted to world space first).

---
Tags: xna
---


# Question
Title: How To show document directory save image in thumbnail in cocos2d class
I have just implemented multiple photo selection from iphone photo library and i am saving all selected photo in document directory every time as a array, now i want to show all saved images in my class from document directory as a thumbnail, i have tried some logic but my game getting crashing, My code is below. Any help will be appreciate. Thanks in advance.

```
-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value

    if( (self=[super init])) {

        CCSprite *photoalbumbg = [CCSprite spriteWithFile:@"photoalbumbg.png"];
        photoalbumbg.anchorPoint = ccp(0,0);
        [self addChild:photoalbumbg z:0];

        //Background Sound
    //    [[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"Background Music.wav" loop:YES];

        CCSprite *photoalbumframe = [CCSprite spriteWithFile:@"photoalbumframe.png"];
        photoalbumframe.position = ccp(160,240);
        [self addChild:photoalbumframe z:2];

        CCSprite *frame = [CCSprite spriteWithFile:@"Photo-Frames.png"];
        frame.position = ccp(160,270);
        [self addChild:frame z:1];

        /*_____________________________________________________________________________________*/

        CCMenuItemImage * upgradebtn = [CCMenuItemImage itemFromNormalImage:@"AlbumUpgrade.png"
                                                              selectedImage:@"AlbumUpgrade.png"

                                                                     target:self
                                                                   selector:@selector(Upgrade:)];
        CCMenu * fMenu = [CCMenu menuWithItems:upgradebtn,nil];
        fMenu.position = ccp(200,110);
        [self addChild:fMenu z:3];

        NSError *error;
        NSFileManager *fM = [NSFileManager defaultManager];
        NSString *documentsDirectory = [NSHomeDirectory()
                                        stringByAppendingPathComponent:@"Documents"];
        NSLog(@"Documents directory: %@",
              [fM contentsOfDirectoryAtPath:documentsDirectory error:&error]);

     NSArray *allfiles = [fM contentsOfDirectoryAtPath :documentsDirectory error:&error];

        directoryList = [[NSMutableArray alloc] init];

        for(NSString *file in allfiles) {
            NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
                [directoryList addObject:file];

        }

        NSLog(@"array file name value ==== %@", directoryList);

        CCSprite *temp = [CCSprite spriteWithFile:[directoryList objectAtIndex:0]];
        [temp setTextureRect:CGRectMake(160.0f, 240.0f, 50,50)];
       // temp.anchorPoint = ccp(0,0);

        [self addChild:temp z:10];
        for(UIImage *file in directoryList) {

//             NSData *pngData = [NSData dataWithContentsOfFile:file];
//        image = [UIImage imageWithData:pngData];
        NSLog(@"uiimage = %@",image);
        //  UIImage *image = [UIImage imageWithContentsOfFile:file];
        for (int i=1; i<=3; i++) {
            for (int j=1;j<=3; j++) {
                CCTexture2D *tex = [[[CCTexture2D alloc] initWithImage:file] autorelease];

                CCSprite *selectedimage = [CCSprite spriteWithTexture:tex
                                                                 rect:CGRectMake(0, 0, 67, 66)];
                selectedimage.position = ccp(100*i,350*j);
                [self addChild:selectedimage];
            }
        }
         }

    }

    return self;
}

```

# Answer
I was in same situation, after downloading image to my `Documents` directory, i have to use it in `CCSprite`. I used the function `spriteWithCGImage`, it worked for me. Here is my code,

```
    NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *logoImagePath = [NSString stringWithFormat:@"%@/%@", documentDirectory, @"image0.png"];
    UIImage *logoImage = [UIImage imageWithContentsOfFile:logoImagePath];
    // Then use spriteWithCGImage
    CCSprite *logoSprite = [CCSprite spriteWithCGImage:logoImage.CGImage key:nil];

```
> 1 votes

---
Tags: cocos2d-iphone, ios, objective-c
---


# Question
Title: How can I really master in game programming?
Game Programming is fun and interesting.

To develop games I have to learn several languages, game engines and should have sound knowledge in Math.

But what I'm really looking is how to be a **master** in **Game Programming**.

---

I have read a nice question and answer

But here, in my question I want to know **specially regarding Game Programming from the Game Programmers.**

Your suggestions would help me to be a master in game programming.

# Answer
> 6 votes
Make games.

... that's all I've got. You want to master *anything*, you practice it until you have. That's all the other great game makers have done: make lots of games. The experienced people who frequent this site? Check their credentials, you'll see they've made a lot of games.

That's it. Practice makes perfect.

# Answer
> 2 votes
Make lots of games. If you really want to focus on mastering, you need depth and breadth. This means:

* Make different types of games. Pong has totally different challenges from a 2D RPG.
* Challenge yourself. Try to solve "hard" problems or technical growth (eg. different architectures, like an entity/component system).

Also, read widely in your field. Read GameDev.SE, read game development blogs, and implement things that look cool, fun, or interesting.

---
Tags: software-engineering
---


# Question
Title: Strategy for controlling the physics of a bike
I'm new(ish) to Actionscript 3 and I was wondering what the code what would be like for controlling the bike in a game.

How would the animation of the bike work? Would I have to create a bike animation of the wheels moving and make it start and stop when the key to go forward is pressed. How would I go about it slowly stopping when the key to go forward is released?

# Answer
I think you will learn a lot using Box2d, and even if at the end you prefer to write the code yourself for a simple collision effect, you won't lost what you would have learned.

About your second question, i guess it is like a jump with the gravity : in a function called every frame (onEnterFrame), you can decrement a counter for the rotation, and slowly get closer to 0 rotation, when you release the button. With Box2d, you can do this with a "motor" i think, look at this link for more informations :

motor with box2d
> 1 votes

# Answer
To make the bike not only go forward, but also slow down, you need to apply decay when key is released.

Pseudocode:

```
var speed = 0;
var decay = 0.97;
var keyIsPressed = false;

// on key press:
keyIsPressed = true;

// on key release:
keyIsPressed = false;

// on enter frame:
if keyIsPressed:
  speed += 1;
else
  speed *= decay;

```

On every frame, if the accelerate key is held down, then the decay will slow it down and speed value will return to 0 over time.
> 0 votes

---
Tags: actionscript-3
---


title: Component-based object, traversal?

text:
# Question
Title: Component-based object, traversal?
I'm working on a small C++ component based game engine, as such...

Object `Foo` might extend `GameObject` and x number of component interfaces, like `Renderable` and/or `Physical`. So let's assume that `Foo` looks like this:

```
class Foo : public GameObject, public Renderable { ... }

```

...and `Renderable` looks like this:

```
class Renderable
{
    virtual void render(void) = 0;
}

```

So, my engine is divided into sub-systems like the `Renderer` and `AssetManager`, etc. and all of those GameObjects are stored in some kind of container, for simplicity sake lets say it's an array.

My question is simple, it's the Renderer's job to hit up all of the game objects that are Renderable and do some work on them, how then can I test or know which objects are Renderable in this component-based approach?

Or furthermore, should I be testing each object in the first place or is there a better way for the Renderer to do it's job (perhaps the `Renderable` interface should attach each `GameObject` to a list maintained by the `Renderer` upon creation)?

Thanks, -Cody

# Answer
Components should register themselves with the appropriate system. You could do this in the constructor/destructor, though I'd highly recommend some explicit OnCreate() and OnDestroy() methods or some such.

You'd have something like so:

```
void Renderable::OnCreate() {
  g_Renderer->RegisterRenderable(this);
}

void Renderable::OnDestroy() {
  g_Renderer->UnregisterRenderable(this);
}

```

Your Foo class, going with your explicit inheritance-based composition, would then just have:

```
void Foo::OnCreate() {
  GameObject::OnCreate();
  Renderable::OnCreate();
}

void Foo::OnDestroy() {
  GameObject::OnDestroy();
  Renderable::OnDestroy();
}

```

That said, I don't particularly like the inheritance-based approach you have. It destroys one of the most important parts in my opinion of the component-based design approach: data-driven design.

Instead of making a bunch of specific hard-coded classes that combine components, you can take an approach where a GameObject is just a container of Component objects. This can range from the simple literal interpretation where GameObject is a class that actually has some kind of container of Component objects to an extreme abstraction where GameObjects are just identifiers that relate Component objects together, or you can do something more reasonable in between.

Going with the simple approach, take something like so:

```
class IComponent {
public:
  virtual void OnCreate() = 0;
  virtual void OnDestroy() = 0;
};

class Renderable : public IComponent {
public:
  virtual void OnCreate() { g_Renderer->Register(this); }
  virtual void OnDestroy() { g_Renderer->Unregister(this); }
};

class GameObject {
  std::vector<IComponent*> m_Components;

public:
  ~GameObject() {
    foreach (IComponent* cmp : m_Components) {
      cmp->OnDestroy();
      delete cmp;
    }
  }

  template <typename Type>
  void AddComponent() {
    m_Components.push_back(new Type());
    m_Components.back()->OnCreate();
  }

  template <typename Type>
  Type* GetComponent() {
    foreach (IComponent* cmp : m_Components) {
      Type* typed_cmp = dynamic_cast<Type*>(cmp);
      if (typed_cmp != nullptr)
        return typed_cmp;
    }
    return nullptr;
  }
};

```

Obviously that's hardly the most efficient implementation, but it gets the point across.

With an implementation like that, you can read in a data file that describes your objects. A game designer can use your game editor (or a text editor, if you haven't put in the time to make a useful editor) to compose objects as needed, without needing to go bug a developer and wait for a new build just to get some new behavior.

Even if there's not much need for finding new crazy combinations of components (but there is, especially once you allow scripts to define new components, so that you aren't stuck with the usual component-based engine with its "five C++ components and then helter skelter in script management" brilliance), it's at least handy for a designer to be able to add or remove components at runtime. Say that you had created two classes, StaticMeshDecoration and StaticMeshCollidable, the latter of which has a PhysicsBody component. In your editor, it would be really lame if a designer had created a StaticMeshDecoration, decided it needed physics, and then had to delete the object and recreate/reconfigure it all over as a StaticMeshCollidable.

On a final unrelated note, don't have a virtual method render on Renderable. It's not the individual object's job to render things. The whole point of having a Renderer object is that it takes the *data* of the renderable objects and then intelligently and efficiently figures out how to render the scene best. You should have a handful of specific Renderable component types that individually register themselves in the appropriate data structures in your renderer as meshes with all appropriate metadata (materials, shaders, etc.).
> 4 votes

---
Tags: c++, component-based, gameobject
---