title: OpenGL assets and new OpenGL context

text:
# Question
Title: OpenGL assets and new OpenGL context
So I have a bunch of meshes, materials, etc and then all of a sudden the window needs to be torn down and then recreated (such as switching on fullscreen with GLFW) which means I will get a new OpenGL context and my old OpenGL data is invalid.

What is the best way to reload all my OpenGL assets - do I save all the mesh and material data in system RAM (which is quite a waste isn't it? if you do not recreate the window during the game, it does absolutely nothing for alot of RAM) -OR- do you map the filepaths to all assets, and then re-read from disk when you reload them? (could lead to alot of file i/o)

Or is there a better alternative? What is the best-practice here?

# Answer
The best practice is to create the new window first, sharing the resources with the old window's context, and then destroy the old window.

~~However, it doesn't seem like GLFW (even v3.0) supports resource sharing yet. For now, you may have to retain the data in RAM and then just recreate the OpenGL objects in the new window's context.~~

To accomplish this in GLFW, you pass an existing `GLFWwindow *` object to `glfwCreateWindow()`. (Thanks @tecu for the clarification!)
> 0 votes

---
Tags: c++, opengl, assets, asset-management
---


# Question
Title: LWJGL - If I use VBOs what can I do about separate textures?
So basically this is my problem: I am creating a game that needs a texture for each object. Now I would use a sprite sheet but the textures are different sizes. I am using VBOs and I need to some how bind the correct textures when calling drawElements. Now I don't know what to do because I don't want to separate each class to its own VBO because that will just make it like 100+ VBO per level which isn't so efficient (or maybe it is?) Note this is a 2D game but I still want to make it efficient.

Maybe there is some thing I can do with shaders? I am using shaders...

**So that is my question: What Do I Do?**

*Things I came up with:*

* Separate the classes to different VBOs (Easy but I am not sure if very efficient)
* Use sprite sheets but have a really really big cellsize then just draw big quads with transparent backgrounds.. (Seems like a stupid idea :P)

Thats it.. So I hope you have ideas!

***EDIT:*** I read some where its possible to have an attribute of which texture to use and pass it in as an element and then the fragment shaders use it.. If this is true I'd love if some one could describe it in more detail and add some examples.. (Also if you need to customize the fragment shader please tell me how because I dont know how to write shaders)

# Answer
Based on my experience, you should go on with your VBO per class solution. I don't know whats your target platform, but any computer should be able to handle a couple thousand VBOs without problem, especially as you are talking about a 2D game, which is less likely to have many vertices. It depends on the usage and target platform tough.

But as a general rule, never optimize something that you haven't profiled to be a bottleneck, avoid premature optimization.
> 3 votes

# Answer
You say that you can't use a sprite sheet because the textures are different sizes. That doesn't really matter. You can use something called a texture atlas, where different sprite images are put together in a non-uniform manner. I've never used the technique myself, but here is a tool I found to put together a texture atlas.

Since you probably have too many sprites to fit on a single texture atlas, you should group together sprites that will show up with each other more commonly. You will still need to use multiple VBOs, one for each texture atlas, but it is more efficient than using one draw call per individual sprite.
> 2 votes

---
Tags: opengl, textures, shaders, lwjgl, vbo
---


title: Gamepad thumbsticks active range

text:
# Question
Title: Gamepad thumbsticks active range
for my current project I use gamepad. I was successfull in hooking it up in C# through SlimDX. Everything works fine, only problem is that thumbsticks don't fully use the active range.

If I move stick all the way to left on X axis, I get maximum value half-way through. Then the driver clips the values returned.

I understand, why this happens. The driver operates in square area, but the stick in circle.

The red square marks values I get from driver. The blue area represents actuall physical range of sticks and the green one is what I want to get from the gamepad. I get these readings in calibration utility and in my program too.

My question is: is this normal behaviour for gamepads? Do I have to buy better one? Currently I'm using really cheap one - Genius MaxFire Grandias 12, as I don't want to invest much into this.

# Answer
> 4 votes
To answer this you need to think of the simple idea of what a controller *needs* to be capable of doing and why.

* It needs to report on an axis - X and Y - to allow game devs to use raw direction values **AND** scaled direction values - typically lets say this would be a raw range of -141 to 141 and a scaled direction value of -100 to 100
* It needs to have physical movement of an analogue nature to allow values more than -1 to 1, very few games would benefit from a stick being Digital - bar fighting games. This allows devs to make characters walk slow (x\<30) normal (30
* It often needs circular boundaries to make moving from one angle to another smooth. Making movement of the stick smoother from corner to corner allows players more control whilst not sacrificing accuracy

Now looking at your diagram is actually all we need to do to show why using the red square is the best convention and why having the dead zone arcs at north east south west positions of that square are necessary. I'll use my best PhotoShop skills to show you.

If I have a game which my speed is linear in **each** direction based on the raw individual values from the stick for both x and y (let the range on the red square x and y be -100 to 100) then I have this situation:

Bob is wearing a magic hat that allows him to float in any direction and at a constant x and y speed (because his hat has thrusters on the north and south sides as well as on the east and west sides) meaning he can move 100 units/s in both north and east directions at once.

This is brilliant! Our controller square input allows us to do this and more importantly should Bobs hat magically only have one thruster that can go a maximum of 100 units a second well that's okay. We can then give him a direction using inverse tan:

```
θ = tan-1 ( 100 / 100 ) = 45°

```

And it can only go 100 units a second so we simply clamp the speed after putting Pythagoras' awesome theorem on that x and y:

```
int pythagThatSpeed (x,y) {return sqrt((x^2) + (y^2));}
speed = clamp(100,pythagThatSpeed(x,y);

```

Meanwhile in circular input land we have this layout:

Now Bobs first hat with 4 thrusters cannot reach its maximum speed at the NorthEast angle! What happened? Well as we have restricted our range of input to a circle we are not allowing x reaching 100 at the same time as y reaching 100.

In the picture above you can see that bob has to move at 70 units x and 70 units y per meaning he cannot reach his max speed of 141. Even if we were to use Bobs second space ship that can only use one thruster then it has a value of 99 units speed NorthEast (using appropriate integer rounding) meaning his max speed isn't even accurate with his second magical hat.

Well with the circular input we would have to change the way a pad reports to a computer in order to do this without a lot more maths than a simple Pythagoras theory and tan-1(x,y) function. Using the scaled directional values reported by the controller instead of the raw values means we don't restrict our selves with dead zones like we see in the green square of your diagram.

If you were to use the blue circle values resulting from using raw values from the controller you could use polar coordinates instead, giving us the angle and the magnitude of input. However as it stands if you were to restrict yourselves to a circular input you would have to add in extra clamp functions to your x and y inputs from the controller to make it a range of -70 to 70 in order to do what we did with Bobs first magic hat taking us right back to this:

Which looks awfully familiar.

And this is why we have square inputs on controllers that clip "half way" and raw inputs. We use the scaled ones to give ourselves a more flexible set of x and y values in development.

---
Tags: c#, directx, gamepad, directinput
---


title: SFML RenderWindow Unhandled Exception

text:
# Question
Title: SFML RenderWindow Unhandled Exception
So I've been following an SFML tutorial but unfortunately, it doesn't seem to be working. The tutorial shows a RenderWindow as a global variable and then accesses it like this:

```
LevelState.h:

struct LevelStateAssets
{
sf::Texture img_background;
sf::Texture img_player;
sf::Texture img_enemy;
};

extern LevelStateAssets ls_Assets;

class LevelState : public StateBase
{
public:
    LevelState();
    void Input(sf::Event event);
    void Update(void);
    void Render(void);

private:
    sf::Sprite spr_background;
};

LevelState.cpp:

LevelStateAssets ls_Assets;

LevelState::LevelState()
{
ls_Assets.img_background.loadFromFile("res/images/background.png");
ls_Assets.img_player.loadFromFile("res/images/player.png");
ls_Assets.img_enemy.loadFromFile("res/images/enemy.png");

spr_background.setTexture(ls_Assets.img_background);
spr_background.setPosition(0, 0);
}
/* More unnecessary code in the middle */

void LevelState::Render(void)
{
window.draw(spr_background);
}

```

But when I do this, I get an error that says: "Unhandled exception at 0x774F3632 (ntdll.dll) in SFMLTutorial.exe: 0xC0000005: Access violation writing location 0x00000004"

If you could help me that would be great! Thanks for your time! :)

# Answer
> 3 votes
Never make your sf::RenderWindow global.

The SFML developer stated that global RenderWindow can cause issues:

> Don't declare your RenderWindow in global scope, something happens in its constructor and some internal objects of SFML might not be initialized at this point.

---
Tags: c++, sfml
---


# Question
Title: Does the gender of a game's protagonist affect sales?
Most protagonists of games are male. I imagine the conventional wisdom is that this is because

1. We live in a patriarchal society, especially when it comes to game development, and
2. The target demographic is predominantly male.

I once heard that for fiction, females are more able to empathise with a male character, than males are with a female character. So the great imbalance in gender in fiction is *not necessarily* due to patriarchy, but that it just makes sense from a financial point of view. I'm not sure if I subscribe to that, but it is interesting.

And there was a time when gaming *was* for super hardcore nerdy males, but now almost everybody has a games machine, and it is not a stigma to like games as it once was, I don't know if it is such a male domain any more.

So leaving aside any question of whether we *should* try to reduce gender stereotypes, my question is, does having a female protagonist actually affect sales, in particular, for small indie games? Are there any experiments, statistics or research relating to this question? What is the actual demographic breakdown of gamers these days?

I realise this is an inflammatory subject, so I will stress here that I am not looking for opinions:

## I am looking for hard facts and data.

# Answer
I don't think you can **prove** that "having a female protagonist actually affect sales, in particular, for small indie games?" And I don't think the **sex** of the lead character will deter people from buying games. Allow me to explain.

The article where an investor said he would not invest in a game with a female lead "You can't have a female character in games. It has to be a male character, simple as that.". The guy was a **sexist** person with a sexist attitude making great assumptions about buyer attitudes. **Read the comments below the article for a response to that**.

So that's one isolated instance of *somebody* saying something sexist like that. Of course, they didn't say who it was, whether he was big time or small time, or whether at all he knew the market he was trying to sell to.

So anyway, without a carefully controlled study/social experiment (each *same* game quality, exact same *fun* level, only thing changed: lead male becomes female), it's not really possible to tell *if there is an effect or not*. But I urge you to think about this rationally and not let sexist attitudes of a couple of people dominate your thinking. Have **you** ever avoided a game title because the lead was female? I personally have not. Have your friends? **Has anybody you know?** Why would the market respond negatively to a female lead then?

Now consider the following notable games with female protagonists, leads, or main characters (by no means complete):

* Final Fantasy 6 (Terra). Terra was the only magic user in a world where magic had all but disappeared (and was forbidden). The majority of the story **centers** around her, particularly the early parts of the game.
* Portal. A "maze-shooter" with a female lead character who you see in mirrors at the beginning of the game.
* Mario Bros 2 : Had princess toadstool, who was arguably the best for beginners to use (since she could float for 5s)
* Warcraft 3 - The Night Elves are a matriarchal society. 2 of the heroes for the race are female including Maiev and Tyranda
* Tomb Raider featured Lara Croft.

There are a lot more games listed here featuring female protagonists.

So in short, **I don't believe having a female role prevents the game from selling**. I think how well the game is made, how fun it is, etc, dominate the scales in terms of people liking the game. The isolated sexist people who say things like "It won't sell because the lead is female" are simply speculating and projecting their sexist views on the entire market.
> 8 votes

# Answer
### Old Opinions

A game recently came out called Remember Me. The sad thing about this game is that for most people it flew under the radar. Why? The studio, Dontnod, attempted to get funding and support from multiple investors but couldn't so they weren't able to advertise. Investors did not one to sink money into the game for one major reason, the lead was female. There was a scene where the character's past is explored and she kisses a man, which the investors thought that the male population wouldn't want to see.

Whether or not they were right is not the point, Dontnod couldn't get support due to the lack of faith by the investors, so when it came time to sell their product it flopped due to a rather small and under budget advertising department.

### The Honest Truth

So then where does this leave us, is making a female lead wrong? Is there a large male gamer population than female? Let's look at the Sales, Demographic, and Usage Data provided by the Entertainment Software Association. On page 5 it shows that 47% of all gamers are female. What does this mean?

Knowing who all of Dontnod's investors were is impossible but it is a safe assumption that they were male, or just overly cautious about the male consumers. Could the game have done better with more investments, maybe; was it a female lead that caused it to crash, no.

### Strong Female Leads

There are several examples of female leads in games that did great: Konoko from Bungie's Oni, Lara Croft from Square Enix's Tomb Raider, and Samus Aran from Nintendo's Metroid.

### Conclusion

I would post more links to show what I mean, but I can't due to the posting limitations, to make a long post simple:

The gaming industry catered towards males for the past twenty years, but as this newest generation began to grow up with technology, the internet, and video games, the gender gap began to close. Sure there are still people out there who will argue against it, but having a female lead shouldn't affect your game much, so long as the character is interesting.

### Personally

Personal opinion I would never even second guess adding a female to a cast or even making her the lead. If it works with what you are going with than do it, as well as the fact that if more leads are given to female character's than eventually the amount of female leads will be similar to that of males.
> 1 votes

# Answer
Game development is also about creating something that **gives a "feeling" to the user.** You have to set a tone to the game and by setting the tone you can speak to the public outside. Todd Howard has talked about this and I find him inspiring.

I personally think that data as you want is not reliable because, even if available, it does not preclude the fact that you might find an idea for a game that will attract female users and male user with the same ratio because the range of devices that support video game has increased and they have a wider reach (see Nintendo Wii and Smartphones).

For me the focus should be about story telling. Any good story if well implemented is potentially successfull and hence any gender "choice" could be potentially valid as you could find an idea that breaks into an unknown market :).

However... **so far mine is a subjective answer and I wanted to provide you with also some links to published research on this matter so you can have some hard core data and facts to analyze and come up with your own conclusions**:

In short:

There is evidence that the demographic of game players are also feemale teenegares (cit ) and if you want to make your player FEEL something you will have to think what YOUR GAME wants to TELL. If it is a story about a FAIRY then the characters will be mostly female, if it is a story about a solider of the 2nd World War then the character could be MALE (but you could have a FEMALE character as supporting character for specific missions - eg. one character is the solider and needs to do certain missions the othe is a nurse and needs to do other missions -save people- and the overall mission score is combined in a co-op multiplayer experience). **Again there is no definite and final answer on this. Fantasy is the beauty and power of video games** (I have no data to prove this :-)).

My conclusion is that is UP TO US to create something groundbreaking that will attract both female and male gender and that ANY research in this field is limited as videogames are increasing their users reach day by day (see what is happening with the Nintendo Wii, families and older people play... it kind of made consoles cool also for eldery people which is an achievement to me and suggests that gaming can be for everyone + see what is happening with smartphone games where you see people playing on smartphones everwhere and with any gender, thing that was not seen with portable consoles).
> 1 votes

# Answer
Although it does, it isn't the most defining trait. What defines characters is how they act, look, talk, move. The gender has an effect of each one of these traits, but to what extent it depends entirely on the designer.

An example of a female character with almost entirely male characteristics is Byonetta. She is basically a female Dante and she is female in order to appeal more to the teenager audiance.

Take Elizabeth from the newest Bioshock for an amazing example for a character who has great depth and is female. Even though she isn't the main character, she is a more developed character than Booker.

Tl;dr: Yes it does, though not alone. When the gender is combined with looks, talk acting it can help appeal to a certain audance therefore increasing sales.

Edit: Let's add another pawn on the table. In order to have a main character, you must have some sort of naritive, if you have some sort of naritive, then it is expected for the player to bond with the character. It would appear that male gamers (which are the majority of single player gamers) have harder time bonding with female characters? Maybe... On the other hand we have Portal, which has huge sucsess and guess what, has a female protagonist. There are a lot of factors. I want to point your attention to two things. One of them is this quote:

> In terms of pure sales numbers, in the first three months of availability, games with only a male hero sold around 25 percent better than games with an optional female hero. Games with exclusively male heroes sold around 75 percent better than games with only female heroes.

And the other is this link: http://penny-arcade.com/report/article/games-with-female-heroes-dont-sell-because-publishers-dont-support-them

These guys have done an amazing job and I don't want to rip-off their hard work, so just read the article. I think it gives a lot of good points to think on.
> -2 votes

---
Tags: character, sales, demographics
---


# Question
Title: How can I escape my field delimiter in my game's packet data?
For my game I decided to not encrypt my packet's payload. Instead I'm just going to check everything on the server to make sure the packet is legitimate.

As I'm not doing any encryption, my packet's raw payload looks like this:

```
PacketID|Arg1|Arg2|Arg3[|Arg4...]

```

Now I want to encode those arguments, so if I have a `|` in for example a chat message, I can still handle my packet. How can I achieve this?

# Answer
> 2 votes
There are any number of ways to do this. You could, for example, treat `||` as being a literal `|` and not your field separator. If your current process for decoding your packet involves first splitting it on single `|` tokens, you'll probably want to either

* change the split so it uses a regular expression with a negative lookahead to avoid the `||` or
* process the packet data linearly instead of pre-emptively splitting it.

That said, I would suggest instead that you don't transmit ASCII data as your packet payloads, but instead serialize them to an efficient binary representation (this is not the same as *encrypting* them). You'll have far fewer character-escape issues this way, because the structure of your chat packet (for example) will be something like four bytes to indicate a message length, followed by *n* bytes of character data that you know is the entire message.

(You can, of course, use the length-prefixing technique in an ASCII-format payload as well, as suggested by Byte56 in his answer.)

Alternatively, if you're going to use ASCII payload data for diagnostics and visibility, choose a format that is already known so you can leverage existing specifications for character escapes (or even better, existing 3rd party libraries). I really don't recommend ASCII transports for data that goes across the public internet, but if you are transmitting only in a more controlled environment (LAN or intranet where the bandwidth issue isn't as severe, nor are the visibility concerns) it can be a reasonable approach.

# Answer
> 7 votes
When serializing data, it's best not to rely on special characters for data separation. Instead, simply let the receiver know how much they need to read to complete the data. Like:

```
PacketID [ByteLengthOfNextVariable NextVariableBytes]

```

Then the receiver knows how much of the packet to read before moving on to the next variable. Ideally, you'd have some type information in there as well, but it depends on your use case.

---
Tags: java, networking, multiplayer, packet
---


# Question
Title: How can I show information from a variety of sources in my debug menu?
I'm creating a debug menu, and I want to be able to show a lot of information (variables) on that menu. This information will come from a lot of classes (instances).

How can I show a lot of information from a lot of classes in my debug menu? How can I get access to all the variables of the instances of the classes that I need information from?

# Answer
What you want to do is homogenize the interface to that information, so that the debug menu itself need only deal with a single concrete API to get information concerning what it needs to display. Your first step, thus, is to ask yourself "what information do I need?"

At a bare minimum, I would expect a debug menu to display key-value pairs: the name of a property or field and it's corresponding value. Both can be represented as strings, because you're so far only talking about *displaying* that data. Additionally, you probably want each collection of key-value pairs for a particular object instance to be grouped with the rest of the fields for that object, so you'd want an overall container to represent the key-value pairs for a specific object. Perhaps

```
class field_debug_info {
  string name;
  string value;
};

class object_debug_info {
   string name;
   array<field_debug_info> fields;
};

```

With these types, you can construct your debug menu from a list of `object_debug_info` objects by iterating through each one, adding a section for the object and then adding sections for each field.

```
debug_menu::debug_menu (array<object_debug_info> objects) {
  foreach (object in objects) {
    // For each object, add a line with the object's name.
    add_line("{0}", object.name);

    foreach (field in object.fields) {
      // For each field of that object, add a line with the field data.
      add_line("  {0}: {1}", field.name, field.value);
    }
  }
}

```

The constructor above would let you create a `debug_menu` from a list of object debug information. Implementing `add_line` (particularly with that C#-style string formatting) is left as a task for the reader. Also note that the above is all pseudo-code.

Now that you've accomplished that (and you can test that by manually creating the debug information objects you send to that constructor to start with), you need to get the information from the classes themselves. Because you are using Java, you can use the built-in reflection features to take any `object` instance and query it for all it fields and their values. You can then transfer that data into your `object_debug_info` structures (in fact, you could eschew your own `object_debug_info` structures entirely and just use the Java reflection API's types if you wanted, and didn't need to add any additional data in the future).

The final part of the solution is to write the code that actually iterates all the live object in the game you want to inspect. There's nothing special or magical here: if you want to inspect all `character` objects in the game when you open a debug menu, have your game collect and send the list of characters to the code that opens the debug menu, and so on.
> 3 votes

---
Tags: java, objects, debugging
---


title: Why Index Particles?

text:
# Question
Title: Why Index Particles?
This is a general question, but as a specific example, I'll use the XNA Particles3D sample (http://xbox.create.msdn.com/en-US/education/catalog/sample/particle\_3d).

What is the point of the index buffer in a particle system? If the advantage is indexing repeated vertices, wouldn't only a connected mesh take advantage of these? The probability that the vertices in a particle system will be shared for extended periods of time is extremely low.

# Answer
Since each particle is a quad of 2 triangles, there are 2 vertices per particle that are shared. That's enough to consider it a savings to index them. It reduces the vertex buffer size from MaxNumParticles * 6 (if you didn't use indices) to MaxNumParticles * 4 (when using indices, like the sample does). If you set it to 1000 max particles per particle system and have a half dozen systems loaded up, it's worth saving that GPU memory. All for the expense of a relatively small amount of space that the index buffer uses.
> 4 votes

# Answer
Indexing particles can allow multiple particles to be drawn in a single draw call. Since D3D9 (which XNA is derived from) has no quad primitive type, indexing is an efficient way of concatenating multiple strips or fans. It doesn't require degenerate vertices, indices are smaller than vertices, and thousands of particles can be handled in a single draw call which greatly enhances performance.

Take these two strips for example:

They don't share vertices, and without indexing you would need to make a separate draw call per strip. Now multiply that by hundreds or thousands, and you'll get so much draw call overhead that your performance will really suffer.

However, if you add an index buffer you just need a single draw call to draw both of them. Hundreds of particles? Single draw call. Thousands? Likewise. So you get to avoid the draw call overhead of an unindexed particle system.

Another reason is that instancing is sometimes used as an efficient way of pushing vertex data to the GPU for particles. Using instancing it's possible to draw billboarded particles using only one vertex per particle, rather than the usual four, so this quarters the memory overhead.

Now, and again with D3D9 class APIs, instancing is only supported for indexed drawing. So if you want to use instancing you have no choice - you *must* index.

(Of course other solutions - such as point sprites and geometry shaders - are also possible for particles, but since the question was about indexing I'm focussed on answers that provide the rationale for that.)
> 3 votes

# Answer
I've never measured, but there may be use for index buffers in mesh particles. Though the particles don't share vertex, the meshes making up a particle might, and reducing the vertex processing of those is just as helpful (if not more so, with a large enough number of particles) than doing it for many "regular" models.
> 1 votes

---
Tags: 3d, particles, index-buffer
---


title: How are multiplayer mods created?

text:
# Question
Title: How are multiplayer mods created?
How do you make a single player game into a multiplayer one? For example: SA-MP San Andreas Multiplayer and the new Just Cause 2 Multiplayer. Before making the mod, did they need permission? How did they even know what to code without having the games source code? I have some ideas but I have no idea where to really start.

# Answer
Lets look at a high level, simple example. Say two people have a single player game called Box Game on their computer. Box Game is just a screen with a number of colored boxes. Fun game. Now someone figured out how to mod the game, the mod allows you to add new boxes to the screen *with any color you want*. Sweet.

Now someone writes a little application called Mod Controller that runs separate from the game. Mod Controller ties into Box Game's modding capabilities, and allows them to use Mod Controller to add and change the colors of whatever box they want.

Next they network Mod Controller. Now, when two people are using Mod Controller the two instances will talk to each other and share what boxes they're adding to their local system, and the other system will add the same color box to its own system.

Now, you can connect to other people, and see what color boxes they're adding, and they can see what color boxes you're adding.

Now we've gone from a single player game, to modding that game, to networking our modding controllers to a multiplayer game.

Obviously in a real example, it's a bit more complex than that. And it changes depending on the game, and what's supported in the game already. But as far as I know, a number of these types of mods use an external application for controlling the connections.

As for if they needed permission or not, that also depends on the game, and it's something you'd have to look into for the game you want to do this with.
> 6 votes

---
Tags: multiplayer
---


# Question
Title: Issues loading in AudioSource at runtime using WWW class
I am having an issue with loading in an OGG audio file to my project. Basically I want to set my game up so that players can drop audio files into a folder called Playlist in the game directory then they can listen to this music while they play.

For some reason my audio clip never becomes instantiated. I have an Audio Source in my scene with this script attached to it.

As you can see I have commented out some code for the time being as I am trying to get a simple case of only 1 audio file playing at this stage.

So my question is what exactly am I doing wrong here? I have printed out the file path and it comes out as file://B:/Users/Matt/Development/Unity Projects/Space Game/Playlist/19\_Tumbling\_Dice.ogg which is the location to my audio.

However when I print out the audioLoader.audioClip.name it comes out as blank...

```
[RequireComponent(typeof(AudioSource))]
public class MP3AudioImporter : MonoBehaviour {

    private List<string> playlist;
    private string musicDir = "B:/Users/Matt/Development/Unity Projects/Space Game/Playlist/";
    private int currIndex = 0;

    void Start()
    {
        string[] songs = Directory.GetFiles(@musicDir, "*.ogg", SearchOption.TopDirectoryOnly);
        playlist = new List<string>(songs);

        StartAudio();
    }

    void StartAudio()
    {
        WWW audioLoader = new WWW("file://" + playlist[currIndex]);

        Debug.Log(audioLoader.audioClip.name);

        audio.clip = audioLoader.audioClip;
        audio.Play();

        /*
        currIndex++;

        if (currIndex > playlist.Count)

            currIndex = 0;
        }

        Invoke("StartAudio", audio.clip.length + 0.5f);
        */
    }
}

```

# Answer
WWW is processed on separate thread, asyncronously, so its not ready yet, when the next line executes. You have to yield after www, to make sure its done. WWW class does not contain "audioClip" member, but there is "GetAudioClip()" method.

```
void IEnumerator StartAudio()
{
    WWW audioLoader = new WWW("file://" + playlist[currIndex]);
    while( !audioLoader.isDone )
        yield return null;

    Debug.Log(audioLoader.GetAudioClip().name);
    audio.clip = audioLoader.GetAudioClip();
    audio.Play();

}

```

Then you can just call this as coroutine in Start()

```
void Start()
{
    StartCoroutine(StartAudio());
}

```

To play full playlist, you would have to download and save the files to audio list. Then you you could start playing em, with coroutine, just like how the StartAudio now. You would play one song from the list and "yield WaitForSeconds (audio.length )". So something like this.

Downloading to list:

```
IEnumerator DownloadPlaylist()
{
    string[] playlist = Directory.GetFiles(@musicDir, "*.ogg", SearchOption.TopDirectoryOnly);

    foreach(string song in playlist)
    {
        WWW audioLoader = new WWW("file://" + song);

        while( !audioLoader.isDone )
            yield return null;

        audioClips.Add(audioLoader.GetAudioClip(false));
    }
}

```

Playing from list

```
IEnumerator PlayAudioList()
{
    yield return StartCoroutine("DownloadPlaylist");

    foreach(AudioClip song in audioClips)
    {
        audio.clip = song;
        audio.Play();
        yield return new WaitForSeconds(song.length);
    }
}

void Start()
{
    StartCoroutine(PlayAudiolist());
}

```

Unity WWW class Documentation
> 2 votes

---
Tags: unity, audio, assets
---


title: Heightmaps on the GPU

text:
# Question
Title: Heightmaps on the GPU
Originally I was doing all terrain calculations in a vertex shader and simple modifying the positions of the vertices from there. I would now like to use normal maps and I cannot think of any way of using these with this current method. So my question is: how can one create a heightmap (as a texture) on the gpu in a pixel shader? Thanks for any replies/suggestions.

# Answer
> 1 votes
Using the four adjacent heights to a position to compute its normal provides a nice balance between performance and accuracy. Use RGBA texture where RGB represents normal and alpha height.

```
vec3 ComputeNormals(vec3 position,sampler2D map)
{
   float left=texture(heightMap,position.xy - vec2(1.0,0.0)).w;
   float right=texture(heightMap,position.xy + vec2(1.0,0.0)).w;
   float bottom=texture(heightMap,position.xy - vec2(0.0,1.0)).w;
   float top=texture(heightMap,position.xy + vec2(0.0,1.0)).w;
   return vec3(left-right,bottom-top,2.0);
}

```

---
Tags: gpu, heightmap
---


# Question
Title: Is there a significant importance in what axis I chose in my top down 2.5D game?
I have read several posts stating what seems like a "standard" in how to chose your 2d axises in a 3d engine. It is often Y up on screen and X right on screen. However, in these examples I often see that it's a scene set up like a platformer, where the player sees the world from the side.

I'm developing a top down 2.5D (locking depth axis but keeping perspective on camera) game and I have it setup so that Z is up on the screen and X is right on the screen. To me it makes sense as Y is height in the world and thus would approach the camera. I will make use of the 3d world at certain times and I feel that it would be confusing to not have the standard axises then...

Is there something I'm not thinking about here?

# Answer
> 3 votes
No. You can choose whichever coordinate system you want. The only thing to maybe consider is what coordinate systems your tools and models are in; converting is no biggie but there's only headaches to be found in being too different.

There's a lot of opinion about coordinate. I've been witness to some rather heated debates about whether it makes "more sense" to use a left-handed coordinate system or a right-handed one, for instance. In the end, it just doesn't matter.

If the coordinate system makes sense to you and your content folks, you are good.

# Answer
> 0 votes
I would consider using the standard axis (which I believe are (x y) for a 2d plateformer and (x z) for a top-down view).

* It will be easier after to associate the Vector3 (up, forward, left) to their respective axis.
* It will also prevent you from having trouble with built in functionalities like gravity or particle effects
* and any asset you make for this game will be easily reusable in any other kind of game.

It sure can take some time to get used that your playground is defined by x and z axis, but I guaranty you will save time in the end.

---
Tags: 2d, unity, 2.5d, standards
---


title: Adding lighting pygame

text:
# Question
Title: Adding lighting pygame
I have created a day and nigh cycle in a game of mine by drawing a rectangle over the screen and having it's alpha change constantly. However, I obviously want to add some lighting to the game. Is there a way to kind of set the alpha of a particular part of a rectangle to 0 using pygame? Or is there perhaps another way of going about this whole lighting thing?

# Answer
You can edit the transparency of Surface objects pixel-by-pixel with the surfarray module. The surfarray module is dependent on Numpy.

```
# SRCALPHA flag means that blit uses source alpha blending.
# It is required for pixels_alpha().
image = pygame.Surface((width, height), pygame.SRCALPHA)

# Create a 2d array that contains per-pixel transparency values of the Surface. (0-255)
# This is a reference, so it affects original
transparency_array = pygame.surfarray.pixels_alpha(image)

```

You can then access the transparency value of each pixel and create light sources.

```
# single pixel to fully opaque
x, y = 10, 10  # position of the pixel
transparency_array[x, y] = 255

# rectangle 100*100 to fully opaque
width, height = 100, 100  # width and height of the light source
x, y = 200, 200  # x and y position of the center of the light source
transparency_array[x-width/2:x+width/2, y-width/2:y+width/2] = 255

```

Note that this example is not very efficient, at least not for moving light sources.

If you have a tile-based map you could change your transparencies on a sprite-by-sprite basis. This will be much faster, albeit a little blocky.
> 2 votes

---
Tags: lighting, pygame
---


title: Abstract Java game objects for Jython

text:
# Question
Title: Abstract Java game objects for Jython
I want to create an abstraction layer between my Jython Script objects and my Game Objects. I am not making the all of the engine in Jython. Most of my game logic is in Java. I just want to expose high level functionality. I am thinking of using these classes.

1. `Jython Object` is created using a Jython class and a Java interface that is coerced into java.
2. `Abstracted Object` and `Abstraced Map` are objects with get() functions that limit the exposure of the underlying Game Map and Game Object.
3. `Game Object` and `Game Map` are the underlying Java objects. They are wrapper classes for a component based system.
4. `Action Factory` provide functionality to `Jython Object`. My game is a turn based tactic, so any change in the game board is done by a set of generic actions (move, damage, apply buff, etc).

This is the first time I have tried to implement a scripting system. The goal is be able to design objects and abilities in Jython. Also create a modding system. I have read several places that creating an abstraction layer is a good idea. I am just not sure how to do it.

# Answer
I think you are a bit confused what an abstraction layer is.

An abstraction layer handles the communication between the game engine and the scripts. It's basically a bunch of functions which are exposed to the scripts and can be called by them and some hooks for the engine into the script engine to invoke script functions.

The abstraction layer hides the messy translation from static-typed programming language to script language and vice versa.

Jython can import and use any Java class. So you can just use any java object from Jython.

It might be worth considering what functionality should be handled by your engine and which by the scripts. Which features do you want to expose to scripting?
> 1 votes

---
Tags: java, scripting
---


# Question
Title: How do I get URL parameters from a Flash game (developed with Unity3D)?
I made a simple Flash game in C# using Unity3D. It interacts well with a web page: There is a textbox for the player to type their name and that name is used in-game.

Now I want to pass the player's name into my game as a *URL parameter*. How can I read URL parameters from within a Flash game?

# Answer
Use `Application.absoluteURL`.

http://docs.unity3d.com/Documentation/ScriptReference/Application-absoluteURL.html

If navigating to the game from another page, they can pass arguments via a `?query-string` that the server can ignore, and that you can parse via string manipulation. If you need to transition to your game without navigating to a new page, you can use an `<iframe>` and do the same.
> 2 votes

---
Tags: c#, unity, flash, web
---


# Question
Title: Isometric - precise screen coordinates to isometric
I'm trying to translate mouse coords to precise isometric coords (I can already find the tile the mouse is over, but I want it to be more precise). I've tried several different methods but I seem to keep falling short.

For drawing I use:

```
batch.draw(
    texture,
    (y * tileWidth / 2) + (x  * tileWidth / 2),
    (x  * tileHeight / 2) - (y * tileHeight / 2))

```

This is what I currently use for figuring out a tile position:

```
 float xt = x +  camPosition.x - (ScreenWidth/2) ;
 float yt = (ScreenHeight) - y + camPosition.y - (ScreenHeight/2);

 int tileY = Math.round((((xt) / tileWidth) - ((yt) / tileHeight)));
 int tileX = Math.round((((xt) / tileWidth) + ((yt) / tileHeight))- 1);

```

I'm just wondering how I could update these to allow for more precise coordinates, instead of tile only. EDIT: Following what ccxvii said below, and removing the -1 from tileX, the object follows my mouse just like I had wanted. Just going to re-examine the math and figure out if that change will result in other messes =o

# Answer
> 1 votes
I have worked with isometric games before, there is usually 'two' approaches (there are many but I've only personally worked with two). If you truly want to stick to 2D and want to work with tilemaps, which from your question appears to be the case, then I would highly suggest following a wonderful tutorial which talks about handling various aspects of isometric maps at XNA Resources. The tutorial is in XNA, but the concepts talked about in the article really helped me when I first played with it.

The second method, one I decided to go with, was to render the game in 3D (using decals for 2D sprites). This method allows you to easily cope with vertical displacement as you will simply be projecting/unprojecting your screen coordinates to 3D and using ray casting to determine where things intersect. The reason I picked this method was so that I could rotate the map easily and simulate isometric by using an orthographic camera. Finding the intersection I followed this guide on libgdx-users. (Its a bit dated but again the concepts are the same).

---
Tags: java, mathematics, libgdx, isometric, mouse
---


# Question
Title: Why do games seemingly reload the entire level when restarting a level?
Is the data really modified that much during play?

I'm assuming the longish pause between restarting a level is the entire level reloading. But it seems to me that a well implemented system should just be able to 'ping' back to the start of the level.

It's more noticeable on consoles, but its not unnoticeable on PC games.

# Answer
Well now - what a simple but interesting question to tackle.

When reloading a level there are so many factors that need to be taken into account that the answer can go many ways.

If your level state contains a large list of assets it can be more practical to start from a clean slate when reloading a level back to a save/mission state as this maintains the accurate state of the level upon reloading but doesn't take a lot of processing. However it is more efficient to reset the assets alone if there are only a few to take into account - making sure you can restart the action quickly on these smaller levels. The latter is especially so when you don't need to preserve anything in the scene or it isn't affected by your choices in game - if you didn't need dead bodies to be preserved from your first run through a village they would not need to be reloaded on your way back through that level, thus conserving processor time and save/mission state access time.

A good example to think of would be a First Person Shooter that used terrain destruction / bullet decals that had a **persistant state during that playthrough but wouldn't stay if you restarted that checkpoint or level**.

If you were to *rewind* the level instead of destroy and reload it you would have to trace each and every state changed. If you shot a hole in the wall with a rocket you would generate terrain gibs from the pieces falling off the wall, the model of the wall would change to produce the hole and you would have particle effects that had been generated to make it look pretty. To clean this up by rewinding it back to a "restartable" state you would have to:

* Remove any dynamically generated gibs for that wall (but not remove ones from the state you loaded)
* Remove the particle effect for the dust from the bullet hole
* Replace / repair the wall to get rid of the holes you created
* Reset the player ammo
* Etc...

With so many resources to trace for rewinding a level it is often less processor intensive to simply destroy the entire level and reload all the assets again in their default or mission specific states. Having to reset specific objects involves searching a list of the objects in the scene and then accessing their properties to reset them. Instead of that bullet hole in the wall being repaired by cleaning up, you don't need to *caluclate* any clean up actions, just delete the whole level from memory and reload it from scratch.

This means reloading a level is dones from one state object (a save game file or a mission script) and not needing dynamic caluclations. For consoles this is exacerbated by the loading times involved with discs. It also helps PC games as it can take into account computers that won't have the procesing power to make the loading times acceptable.

So for large content levels - Loading a single state instead of calculating and "rewinding" one:

* Is less processor intensive
* Is more efficient on lower tier machines
* Enables a mission script and save file to be used in the same manner (potentially use the same loading system to load a save state or a mission checkpoint state when restarting the level)
* **Means you have less work as a developer to reset a level** \- It is far easier to program a full reload from session data than track and rewind. This is probably the most influencial point

However, as a counter example a fighting game (great real life example being Street Fighter 4) may not need to reload all that many assets in order to restart a level. The 2 players, environment state for the level and simple level timers are mostly static and not dynamic (the players health will always respawn at 100% each round, timers reset to 90 seconds and the level has no bullet holes \[or does it!\]) and so resetting the level is a matter of putting the fighters to full health and putting the environment back to its original positions (like onlookers in some of the levels.)

So for a fighting game when doing a rematch (not going from round to round) you need to:

* Reset Health and energy to Max or defaults (always the same per character)
* Reset Timer
* Reset Character starting positions
* Reset Terrain to default state (no bullet holes to fix or reload!)

And that's the entire list essentially - meaning that a quick state reset instead of a full level reload is more feasible. This can also be shown by the loading time when you initially start the match. It takes a long time to load all the character and level models but only a few processor ticks to reset the character starting positions between matches with an already loaded model.

It's important to note that this is also a more in demand requirement of fighting games as their players tend to want to get back in the action incredibly quickly as matches can typically only last a minute - emphasising that this answer is very much dependant on the game and genre. FPS's demand more dynamic assets while Fighters demand quick repeatable action.

I hope this has shed some light on your question.
> 54 votes

# Answer
To clarify the existing answers against your question about consoles: they don't have enough memory to store both the starting state and current state for larger complex games.

A game could store the level and initial state separately so that just the state could be restreamed in, and this is very likely what many games do. Even streaming just that is going to be quite a bit slower than if it had been kept in memory, though.

The "best" current-gen console has only 512MB of memory shared between CPU data and graphics. That is tiny. One of the current headaches of console development is trying to fit in games that meet today's quality levels with such small amounts of memory. Kilobyte counting can become important, especially close to the ship date. Storing a copy of the initial state of a level is some amount of data that could be done without, allowing more memory to be used for things that make the game more interesting during play rather than simply making level reloading faster.

Ideally, the player spends more time playing the game than dying and restarting, so optimizing for a better experience during play makes more sense.

Things might change drastically with the next-gen consoles and their 8GB of memory. Or they might stay the same, with simply higher-resolution models and materials and great numbers of active in-game objects. Time will tell. Given that PC games typically target machines with 2GB of RAM and 512MB of VRAM (though many scale to much larger values), the 8GB of the new consoles is pretty luxurious as far as minimum baselines go. We'll likely see a transition to games demanding a 64-bit CPU/OS and 4-8GB of RAM with 1-2GB of VRAM in the years coming up soon. Storing multiple states in memory for fast snapshotting should be a lot easier then.
> 14 votes

# Answer
I disagree with much of Blue's answer, I do not believe there is a technical case for not resetting levels - I certainly never encountered one. Level loading is almost always slower than level resetting, in fact I find it difficult to conceive of an occasion when it wouldn't be. In most cases games could offer effectively instant level loading if the devs chose to.

The real answer is, as suggested, it's easier and quicker. Repeated loading of levels is something that a game requires anyway so repurposing this into a level restart is relatively straight forward. Resetting requires complex new pathways with a great deal of potential for new bugs and memory leaks and it requires a decent investment of developer time. In a some cases it may also push memory limits. Since games are rarely developed with a surfeit of developer time, items such as level resetting have a regrettable tendency to get dropped along the way, particularly if the game architecture isn't the best built in the first place.

While I suppose one could come up with a situation where "rewinding" was necessary for resetting, in fact most games need only store the original state, provide an effective means to reset completely to that state for retained objects and a means to flag objects to abandon on reset. Game state information also needs to be stored and restorable. This kind of information is typically relatively light on memory compared to the requirements for an entire level so doing this removes the need for slow, expensive loading of data from disk (including large items like textures and models) and substitutes it for a rapid, in-memory pass of the scene.
> 7 votes

# Answer
To allow for large levels or seamless level game play, even with limited memory (memory is always too small, the question is if you hit the limit in RAM first, or on the graphics card) there is another strategy:

Only have the part of the level in memory, that the player needs currently or will need in a few seconds. Models, textures, sound samples, ... that are probably not needed anymore are removed from memory.

Dungeon Siege comes to mind (developers once claimed, that memory management took more processing power than the actual game play), most MMORPGS do it, Shooters with an open environment have to do it, ... In these cases, the start of the level (or even a respawn point 30 seconds ago) might not be (completely) in memory anymore.

Often a fresh reload is the easiest way, the cheapest way, and perhaps the fastest way.

Edit: Here is a paper about the loading mechanisms of Dungeon Siege: The Continuous World of Dungeon Siege
> 2 votes

# Answer
With Sean and Blue's excellent answers regarding physical platform limitations and pro-con decisions, I'm going to expand a comment into a different approach:

## Why You Should Probably Just Completely Reload The Level

So you've got your loadLevel() call working perfectly, yay! You stream in a level file information, and step through building the world based on it, creating objects and loading textures and sounds as you go. Then, when it's all done - or done "enough" to let the play start, you call startPlay() and your world is revealed and your music begins to play.

Now when you are done with the level, or escape to the menu, or exit the game, you call unloadLevel() to free up all the resources and memory you've been holding onto to allow a smooth experience.

Now, what happens when you want to add a "Restart Level" feature? Well...

```
unloadLevel(currentLevel);
loadLevel(currentLevel);
startPlay();

```

And you are done! No new code, just a few simple function calls at most, and you've already written and debugged all that so now your new shiny Restart Feature is crossed off your list, and probably never to be encountered again - cruftless, non-rusting code is the best kind! Move the code into a restartCurrentLevel() function and you can fold that code away and never look at it again - maybe after making sure there is a level to restart, of course :)

But then you wonder if this isn't a waste, unloading things you are just about to reload again anyway. Well, if your levels and resources are small then the most you have to gain is a few spare seconds of load time each time "Restart" is called even on slow systems (and maybe older smartphones), so who cares? "Premature optimization", you've got better things to do with your time.

Ah, but now your levels are growing and your textures are becoming more detailed and the soundtrack got ripped in 512kbps with separate channels for every voice and musical layer (it seemed like a good idea at the time, though you can't remember why...) and something about "state-origin dependent voxel ray tracing multidimensional Fourier transform matrices" which you think is just totally made up and not a real thing, and level loading actually takes a while now and its beginning to annoy you. You've even tested with real people and they actually show a distaste for the waiting times as its worse than similar games (you aren't expecting an MMORPG capital city with 100 players to fully load in \<2 seconds, are you?), and it's a problem.

So how do you optimize? Well, if level **re**-loading is a problem, then isn't level **loading** a problem? If you think it's just reloading, why on earth are people reloading your level so much more often than they just load the level in the first place? Sounds like a game play problem, not a code-engineering problem. Who thinks its fun to reload a level over and over and over again, and just wishes it was *faster* instead of *entirely avoidable*?

**Fix the real problem first!**

But lets say your game is designed so you are supposed to restart at least occasionally, and the load time is long enough that its OK to do once and utterly unavoidable, but you don't want to have to do it again. What kind of game is this, anyway? Seems like a bit of a weird problem...maybe a high-resolution Portal-like game where its assumed you are going to mess up the puzzle repeatedly?

First of all, you have to realize that this isn't going to be trivial. You are going to have to write completely new, untested code, and it's "state-dependent" so that you might not even know what is or isn't going to be reused between level plays. Are there random elements, spawns, variable textures (do your skeletons only sometimes wear armor?), or other changing elements in your level? Are there things that vary with the player, like an outfit or customized model or colors/doors/traps?

You are going to be doing comparisons, and lots of them. You are going to be looping through level elements, comparing what will be needed versus what is loaded right now (what do you do with stuff that was loaded for the last level but not for this one - release them or hold on to prevent a future load?). If this is really a big deal for your game you are probably going to want to change your load/unload code to see if something is already loaded before loading it (making the code multipurpose but potentially introducing new bugs to previously working features, and functions that carefully release resources that aren't going to be in use in the near future). Sigh.

No matter what you do, even if your game is simple, you are going to get into obscure bugs that are based upon level/player state when a level was restarted that doesn't happen to you load the level the first time. So you get to write game updates with text like:

"Dropping a helmet on a bomb onto a tile that had a missile explode near it that was also within 200 pixels of water will no longer corrupt your game data or cause the game to crash."

## The Real Reason Most Games Don't Bother

Have you ever noticed that most people just paint or drywall over their existing walls instead of stripping down to a base layer, or lay carpet right on top of hardwood floors instead of pulling them up?

The simple fact is that it's all more work for minimal reward. Painting over your existing walls **works fine most of the time**, and the value of ripping up hardwood floors is often minimal or nonexistent.

The same is true in software, from games to multimedia Power Point Presentations - if all you do is shave a few seconds off a loading screen people spend 1% of their time looking at, then that better be incredibly trivial to do or you are getting a very poor return on your invested time.

And so most games don't bother, and I have trouble thinking of very many games where loading screens made an otherwise good game less worthwhile, except a few extreme examples; the extreme examples are where optimizing for faster level loading makes sense, and that's a tiny fractions of games that make it to the public, and probably even a smaller fractions of games that no one ever sees because they never get released.
> 2 votes

# Answer
Because it's harder to develop the opposite behavior which is all about keeping the static game data (such as textures, geology information, unaffected mobs) in memory and reloading only the dynamic data (such as player position, player stats, quest status, inventory).

Since it costs more money and time, game developers generally don't do that.
> 0 votes

---
Tags: levels, filesystem
---


# Question
Title: Most common resolution used in Android phones as of 2013
Before making an Android app, I want to know what screen resolutions I should target. I know there are resolutions of 1280x800, 1280x720 and 800x480, but I would like to know which are most common.

Are there any recent stats on the distribution of Android devices' screen resolutions?

# Answer
> 8 votes
A quick snapshot of the information on current android devices can be found here:

http://developer.android.com/about/dashboards/index.html

The site is kept up to date every 14-days based on devices which access the Google Play Store so its a pretty decent source for information.

---
Tags: android, resolution, statistics
---


# Question
Title: How would you handle different aspect ratios in a 2d platformer?
A long time ago, 4:3 was pretty much the only apect ratio you would find on a PC. Today the most common one is 16:10, but most new monitors (especially laptops) are 16:9

I'm writing a 2D platformer, and I can't decide how I should handle all the different ratios.

Here are some ideas:

1. 4:3 gets more content, widescreens are cut on top and bottom
2. 16:9 gets more content, the others are cut left and right
3. The game is in 16:9 with black horizontal bars for other ARs
4. The game is in 4:3 with black vertical bars for other ARs

# Answer
If you have no compelling reason to make your game "wide" (in which case use approach 3) or narrow (in which case use approach 4), go with a **combination of 1 and 2** (or possibly 3 and 4 if you want to hide things off-screen).

Select a compromise aspect ratio (16:10 is a good one, or even 16:11). If the user is on 16:9 give them more content to the side, and if they're on 4:3 give them more content at the top and bottom.

In any case - I find it best to implement it with something like this in your camera class:

```
float scaleToFitWidth = viewport.Width / nominalWorldSize.Width;
float scaleToFitHeight = viewport.Height / nominalWorldSize.Height;
float scale = Math.Min(scaleToFitWidth, scaleToFitHeight); // world to client

```

At which point you can simply experiment with different nominal world sizes (ie: the size of the camera in world units) and simply select the best one.
> 12 votes

# Answer
Well, as a basic bit of advice, on PC I'd say "don't assume your user wants to run full screen". And in windowed mode, pick your ideal ratio and just use that directly.

Users I think are generally accepting of black bars when presented with full screen content. So strategies 3 and 4 are acceptable, if not ideal. They have the advantage that you always know how much content you are rendering: i.e. no sneaky bugs which only occur when running in wide-screen.

If you are trying to be adaptive, and detecting the users ratio via screen resolution and showing as much content as possible, then you have to take account of high and low priority content differently. High priority content is stuff that the user absolutely has to see onscreen, if it is offscreen the game is failing. So this is things like HUD and UI elements, and the player avatar and anything they are interacting with. Low priority content is stuff that if it's onscreen then that's good, but if it is offscreen it's no big deal. E.g.:Background graphics and things that are reasonably far away from the avatar.

Assuming you have a UI/HUD which is being superimposed over the top of some 'physical' 2D world, then this is straightforward enough. Low priority items are easy, you just make sure that the 4:3 viewport is centred on the interesting things, then draw as much low priority stuff as you can to the left or right. High priority things in the 2D world (e.g. your character, enemies your character is directly fighting) should always be kept in the 4:3 viewport. I.e. don't have your game code zoom the camera in to take advantage of the extra screen real estate, because then you will have game code acting differently in widescreen vs. not. Have the game code assume that the world is being rendered in 4:3, and only let your rendering code be aware that there is actually more than that being visible.

Laying out UI/HUD elements can be approached in one of two ways:

1. Dynamic positioning: Specify all your elements relative to screen edges (i.e. not all relative to 0,0). Depending on your aspect ratio, the elements will be closer or further away from the center of the screen. Pros: Allows you to hook things to corners and have them 'just work'. Cons: Difficult to get layout working nicely in the centre, and risk of elements overlapping
2. Conservative static positioning: Lay out all your elements in 4:3, and simply offset them when running in widescreen. Pros: simple, unambiguous layout logic/coordinates. Cons: leaves visual dead space at the left and right of your UI controls, where you'll see the 2D world in the background but no UI.
> 16 votes

# Answer
Which is most appropriate for your game? If you're making Canabalt (i.e. a game which depends on horizontal speed), a wide aspect ratio with black bars (#3) on narrower aspects would be ideal for highlighting lateral movement. On the other hand, if you have a more aerial game like Super Smash Brothers, a taller screen (#2 or #4) would be best. I'd base my decision on what works best for the game.

I agree with other responders that care should be taken with regard to elements that might be visible on one display but not on another.
> 8 votes

# Answer
Castle Crashers seems to use a bit of #2 and a bit of #3 - you get black bars on a 4:3 screen, and also a very slightly smaller visible area - but you should always have a "safe area" around the edges where you don't put anything vital anyway (for screens like CRT TVs that crop the edges)
> 1 votes

# Answer
There is another option. You could frame for an intermediate ratio, and do both cropping and expanding (or bordering) on both normal resolutions.

I believe TV filming is framed in this way, such that widescreen looks ok (everyone isn't crowded into the middle of the scene), whereas cropping for 4:3 isn't quite as drastic and there's minimal panning.
> 1 votes

# Answer
Here is a blog post about handling multiple screen sizes on mobile devices, and here its second part how this approach coded in Java using libgdx. It is a bit like Andrew's answer but may help someone else.

The blog post covers three main approaches:

1. Live with black bars on top or on the sides.
2. Use a virtual viewport.
3. Use floating elements, much like you would find in a web page flexbox layout.

No. 1 is pretty self explanatory.

To illustrate no. 2, suppose you want to support three different devices with three different aspect ratios. Open the image in an image editor. For the first device, draw the largest rectangle at that device's aspect ratio that will fit inside of your image. Do the same for the second device and the third device. Your usable area, or virtual viewport, is the intersection of all three of those rectangles. Anything outside of that viewport cannot be guaranteed to be visible.

No. 3 involves placing objects on the screen similarly to how you would place elements on a web page using flexbox or floats. For example, you would place the pause button 5 pixels from the top and 5 pixels from the right. No matter what aspect ratio the device is, the pause button will always be in the upper right corner.
> 1 votes

---
Tags: 2d, aspect-ratio
---


# Question
Title: Advices on Linking Between Entity Component System in C++
After reading a few documentation about entity-component system, i decided to implement mine. So far, I have a World class which contains the entities and the system manager(systems), Entity class which contains the components as a std::map, and a few systems. I am holding entities as a std::vector in World. No problem so far. What confuses me is the iteration of entities, i can't have a crystal clear mind on that, so i still can't implement that part. Should every system hold a local list of entities which they are interested in ? Or should I just iterate through the entities in the World class and create a nested loop to iterate through systems and check if the entity has the components the system is interested in ? I mean :

```
for (entity x : listofentities) {
   for (system y : listofsystems) {
       if ((x.componentBitmask & y.bitmask) == y.bitmask)
             y.update(x, deltatime)
       }
 }

```

but I think a bitmask system will kinda block flexibility in case of embedding a scripting language. Or having local lists for each system will increase memory usage for classes. I am terribly confused.

# Answer
> 7 votes
> Having local lists for each system will increase memory usage for classes.

It's a traditional space-time tradeoff.

While iterating through all the entities and checking their signatures is straight to code, it may become inefficient as your number of systems grow - imagine a specialized system (let it be input) that looks for its probably single entity of interest amongst thousands of unrelated entities.

That said, this approach may still be good enough depending on your goals.

Although, if you're worried about speed, there are of course another solutions to consider.

> Should every system hold a local list of entities which they are interested in?

Exactly. This is a standard approach that should give you decent performance and is reasonably easy to implement. The memory overhead is negliglible in my opinion - we're talking about storing pointers.

Now how to maintain these "lists of interest" may not be that obvious. As for data container, `std::vector<entity*> targets` inside system's class is perfectly enough. Now what I do is this:

* Entity is empty on creation and does not belong to any system.
* Whenever I add a component to an entity:

+ obtain its **current bit signature**,
    + map component's size to world's pool of adequate chunk size (personally I use boost::pool) and allocate the component there
    + obtain entity's **new bit signature** (which is just "current bit signature" plus the new component)
    + iterate through all the world's systems and if there's a system whose signature **doesn't** match the entity's current signature and **does** match the new signature, it becomes obvious we should push\_back the pointer to our entity there.

    ```
        for(auto sys = owner_world.systems.begin(); sys != owner_world.systems.end(); ++sys)
                if((*sys)->components_signature.matches(new_signature) && !(*sys)->components_signature.matches(old_signature))
                        (*sys)->add(this);

    ```

Removing an entity is entirely analogous, with the only difference that we remove if a system matches with our current signature (which means that the entity was there) and doesn't match with the new signature (which means the entity should no longer be there).

Now you may be considering usage of std::list because removing from vector is O(n), not mentioning that you would have to shift big chunk of data every time you remove from the middle. Actually, you don't have to - since we don't care about processing order on this level we can just call std::remove and live with the fact that on every deletion we only have to perform O(n) search for our to-be-removed entity.

std::list would give you O(1) remove but on the other side you have a bit of additional memory overhead. Also remember that most of the time you will be processing entities and not removing them - and this surely is done faster using std::vector.

If you are very performance critical, you can consider even another data accessing pattern, but either way you maintain some kind of "lists of interest". Remember though that if you keep your Entity System API abstracted enough it shouldn't be a problem to improve systems' entity processing methods if your framerate drops because of them - so for now, choose the method that is easiest for you to code - only then profile and improve if needed.

# Answer
> 5 votes
There's an approach that is worth considering where each system owns the components associated with itself and the entities only refer to them. Basically, your (simplified) `Entity` class looks like this:

```
class Entity {
  std::map<ComponentType, Component*> components;
};

```

When you have say a `RigidBody` component attached to an `Entity`, you request it from your `Physics` system. The system creates the component and lets the entity keep a pointer to it. Your system then looks like:

```
class PhysicsSystem {
  std::vector<RigidBodyComponent> rigidBodyComponents;
};

```

Now, this might look a little counter intuitive at first but the advantage lies in the way component entity systems update their state. Often, you'll iterate through your systems and request they update the associated components

```
for(auto it = systems.begin(); it != systems.end(); ++it) {
  it->update();
}

```

The strength of having all components owned by the system in contiguous memory is that when your system iterates over every component and updates it, it basically only has to do

```
for(auto it = rigidBodyComponents.begin(); it != rigidBodyComponents.end(); ++it) {
  it->update();
}

```

It doesn't have to iterate over all entities that potentially don't have a component they need to update and it also has a **potential for very good cache performance** because the components will all be stored contiguously. This is one, if not the greatest advantage of this method. You'll often have hundreds and thousands of components at a given time, might as well try and be as performant as possible.

At that point your `World` only loops through the systems and calls `update` on them without needing to iterate entities as well. It's (imho) better design because then the responsibilities of systems are a lot clearer.

Of course, there are a myriad of such designs so you have to carefully evaluate the needs of your game and choose the most appropriate but as we can see here it's sometimes the little design details that can make a difference.

# Answer
> 1 votes
In my opinion, a good architecture is to create a components layer in the entities, and separate the management of each system in this components layer. For example, the logic system has some logic components that affects to their entity, and store the common attributes that are shared to all the components in the entity.

After that, if you want to manage the each system's objects in different points, or in a particular order, it is better to create a list of active components in each system. All the lists of pointers that you can create and manage in the systems are less than one loaded resource.

---
Tags: c++, entity-component
---


# Question
Title: Are frequent game updates a solution for preventing multiplayer cheating?
I'm creating a game on Android where the enforcement of rules can only take place on client side (I can't shift it to server side...think aimbotting but in my case I wouldn't even be able to use heuristics to detect it!).

As I've read many times, the client side is impossible to 100% protect from modification/hacking.

I am going to include protections such as ProGuard obfuscation. But also I'm going to use a formula in the code which encrypts data from the client.

Hackers/cheaters can decompile the code and locate this formula eventually.

But how long will it take for them to uncover the encryption formula? A day, a week? Actually, how long in general does it take for a game to be modded for cheating?

Can I release updates to my game so that by the time hackers release modded versions of my app to public, they become obsolete? If I did release updates, I wouldn't require updates for single player mode, but only when they tried to do multiplayer would a message display telling them they must update.

I just really want to make multiplayer fair and not scare off players because they face opponents with uber-awesome hax.

# Answer
> 4 votes
> But how long will it take for them to uncover the encryption formula? A day, a week? Actually, how long in general does it take for a game to be modded for cheating?

It varies, but could happen within hours of a hacker gaining access to the relevant data. Note that it's possible, in some cases (generally not with indie developers), for this to be before the product actually ships so a hack can be available on launch.

How long it will actually take, in practice, depends. The key factors are

* how popular your game is (less popular games are less likely to get noticed by hackers interested in them) and
* how skilled the individuals who do take notice of your game are.

> Can I release updates to my game so that by the time hackers release modded versions of my app to public, they become obsolete?

No, this is probably not viable solution for an independent developer. Unless you are significantly changing your protections with every build of the game, a skilled hacker will be able to leverage his or her previous work to easily render a new version of the game vulnerable to tinkering.

Your best bet is shift the confirmation of client-side actions to the server, or at least move verification there. If your system is purely peer-to-peer, you can use a majority-rules form of verification where every peer vets the actions of other peers. You can't trust the client code itself.

---
Tags: android, multiplayer, modding, security, hacks
---


# Question
Title: How do I play a sound just once when the cursor enters my button?
I want to play a sound when the mouse is within the bounds of a button. When I first did it, it was just a constant sound no stoppages. But I then did it through a SoundEffectInstance, which just repeats the sound over and over while the mouse is within the bounds of the button. I've gotten to play it once. However, say that I would put my mouse over the play button, it would play the sound, but if I put it over the play button again it wouldn't play. So the sound would just play once of each button. I basically just want it to play once if the cursor is over a button. Then play again if the cursor goes over another/same button.

SoundManger class

```
    static SoundEffect selected;
    static SoundEffectInstance soundEffectInstance;

    public static void Initialize(ContentManager Content)
    {
        try
        {
            selected = Content.Load<SoundEffect>("Sound Effects/SelectSound");
            soundEffectInstance = selected.CreateInstance();
        }
        catch
        {
            Debug.Write("SoundManager failed to Initialize");
        }

    }

    public static void PlaySelected()
    {
        try
        {
             soundEffectInstance.Play();
        }
        catch
        {
            Debug.Write("Selected sound failed");
        }
    }

```

Update Method for Button.cs

```
if (btnRect.Contains(mousePosition))
        {
            btnCol.R = 62;
            btnCol.G = 85;
            btnCol.B = 91;

            if (mouseState.LeftButton == ButtonState.Pressed)
             clicked = true;

             SoundManager.PlaySelected();
        }
        else
        {
            btnCol.R = 255;
            btnCol.G = 255;
            btnCol.B = 255;

            clicked = false;
        }

```

# Answer
As per @Byte56's and my comment, this is quite a simple solution even without using any xna sound manager variables. Use a property or variable in your button or whatever handles the button update to flag when the sound is played and whether that sound should be played again.

```
if (btnRect.Contains(mousePosition))
{
    btnCol.R = 62;
    btnCol.G = 85;
    btnCol.B = 91;

    //set played as true (you can create this variable yourself)
    if (!soundPlayed) {
        SoundManager.PlaySelected();
        soundPlayed = true;
    }

    if (mouseState.LeftButton == ButtonState.Pressed){
        clicked = true;
    }
}
else
{
    btnCol.R = 255;
    btnCol.G = 255;
    btnCol.B = 255;

    played = false; // reset once mouse leaves button
    clicked = false;
}

```
> 4 votes

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


# Question
Title: How can we validate subjective inputs from a client?
Let's propose for a minute where we have a game using something like the Virtuix Omni. You track feet movement. You track the speed at which they run. Now, let's suppose we want to translate this into game movement and velocity relative to the speed the player is moving. Now, suppose the game is multiplayer. How can a server validate that the input is reasonable? Most architectures described often tell us to validate the input - but in this case we truly want the player to tell us how fast they're running.

How can I we ensure sane values and not some hacked "always turbo" device?

# Answer
What you want to do is *record everything*. With that corpus data, you want to do two things:

* Implement rapid-response validation that checks the input against known boundary conditions (for example, the top speed of a human is about 45 kilometers per hour over a short stretch) and situations you've identified as potentially malicious.
* Build longer-term, slower-running reports that build up data about averages (for example, average player speeds, average clicks-per-minute, et cetera) and other statistics you can use to feed into your rapid-response verification.

The result of a verification test that concludes an action is potentially malicious should not necessarily be to ban the originator of the action. Instead you should increase a "cheat score" (which may decrease over time), such that users who hit a cheat score over a certain threshold are flagged for a more in-depth review (possibly by a human).

It's important to make these verification checks highly tunable, especially to correct situations where any long-running feedback loop has crept into the tests in a way that starts generating false positives for cheat score increases. You may also want to consider not verifying every action every player does all the time, but randomly selecting them or other distributing the processing to avoid wasting too much server CPU validating input instead of actually serving the game.

There isn't a hard-science answer to this problem, it's going to involve lots of iteration on your part and tweaking of fairly fuzzy variables. Having good metrics and good tunability is critical.
> 6 votes

# Answer
Apart from logging the data and analyze it (either directly or after somebody flags another player as potential cheater), I would try to measure "imperfection" of data. Input generated by a bot/script is most likely flawless, with almost linear acceleration, while an actual persons acceleration and stopping most likely isn't.

Maybe you can gather some reference data of people that are moving on the device and use it to compare against the incoming data. Ideally in a level that is pretty linear and with a controllable pace.. something like an introduction or tutorial level.

Another idea to measure imperfection is to do a Fourier-Transform of the incoming data. A bot will most likely create rather clearly distinguishable peaks (same frequencies), while a human will have different speeds and a "noisier" frequency domain.
> 2 votes

# Answer
The way how I see this you have 2 options:

1. Define a rule / set of rules that state what is considered "reasonable input".
2. Forget validation just accept what you're given and roll with it.

Surely the "speed the player is moving" is something you can "acquire" from all this data you are gathering or calculate in some way?

Without knowing more about your solution it's hard to be precise.
> -1 votes

---
Tags: networking, multiplayer, input
---


# Question
Title: Overlapping sibling problem in AABB tree
I'm trying to make a real-time GPU (CUDA) ray tracer, and for now I'm tracing single rays, but I've ran into a problem: the BVH. This \[PDF\]paper has been my inspiration for the theoretical part, and as you can see, the BVH is composed of Axis Aligned Bounding Boxes, however, the stackless rope-based algorithm for the ray-AABB intersection does not take into account overlapping siblings, which occur quite a lot with the AABB creation algorithm I've read about in multiple places on the Internet, which is averaging the centroid of each triangle in the current triangle list and deciding in which child to place each triangle based on the projection of the average on the axis parallel to the longest edge of the parent box.

The use of AABBs in the paper indicates that there indeed exists a method to efficiently (in terms of speed) make AABB trees without overlapping siblings. Unfortunately, I can't find such a method.

Would someone please describe a fast method for creating an AABB tree without overlapping children? I'd also appreciate it if they'd post pseudocode too.

Thank you.

# Answer
I worked around the problem by adding the triangles which vertex/vertices go over the split plane position to the other child too so they exist in both children. Of course, this affects the subsequent split positions slightly but it's not a serious problem.

One solution would be to clip the triangles which go over the split position.
> 1 votes

---
Tags: aabb, raytracing
---


title: RPG level-experience formula

text:
# Question
Title: RPG level-experience formula
I want to make an RPG game and I would like an advice on how should I create my level-experience formula. I saw this formula http://rsdo.net/rsdonline/guides/Experience%20formula.html#PHP and I created a formula myself and I want to ask you which would be better.

```
    RuneScape rates                     My rates

    Level 2 - 83 xp                     Level 2 - 35
    Level 3 - 174 xp                    Level 3 - 84
    Level 4 - 276 xp                    Level 4 - 150
    Level 5 - 388 xp                    Level 5 - 238
    Level 10 - 1,154 xp                 Level 10 - 1,087
    Level 100 - 14,391,160 xp           Level 100 - 311,017

```

As you can see at level 100 RuneScape's xp is very big and my level 100 is equal with RuneScape's Level 61. Is it better if the xp grows very fast at one point or depends on how I make my game?

# Answer
> 9 votes
You're better off trying to balance leveling as a function of time, rather than experience points, since experience points are meaningless outside the context of a particular game.

Take your example. If it takes 100 times as long to earn experience in your game, you effectively end up with 2x as long a level grind to get to level 100 compared to Runescape. This is an example of comparing apples to oranges.

Now, you seem to have a quite nice scale going on. Players usually need to level up quickly early on and then see their progress slowed down progressively.

What I would do is figure out how long you want a player to grind between every level (or perhaps group a few levels together) and tweak the XP gained in the corresponding zones of your game to match that.

So, let's say you want levels 1-10 to take 1 hour total and that killing a monster there takes an average of 1 min, the level 1-10 leveling zone of your game should have monsters that yield and average of 18 XP (`1087 XP/60 minutes ~= 18 XP/minute`).

At that point, it's really a question of how fast you want your game to feel at different stages. Many games have very long leveling grinds because that's where the content is and others have very fast leveling grinds because the endgame is the most important part.

# Answer
> 0 votes
The Runescape formula for exp needed to level up is:

> **PREVIOUS Level Xp** \+ **PREVIOUS Level Xp** * 10%

There are more formulas for leveling subskills so it instead of playing with hard to understand formulas, you could always make a system that makes the process of levelling up (less exp / hour) instead of making a higher experience bar.

> http://runescape.wikia.com/wiki/Combat\_level

The question you must ask yourself is - How much experience per hour will the player get. In Runescape you can easily/cheaply/effortlessly get 250,000 xp/h while cooking, where leveling up the Slayer skill is far more time consuming ~~ 30,000 xp/h.

The system you choose will be best if you can match the experience gained with your system, leveling up cooking with Runescape style in your system to gain level 100 will take roughly a few hours.

---
Tags: rpg, progression
---


# Question
Title: How to circle an uneven object with Camera at a fixed distance?
Unity3d. I am trying to move an object with Camera around a fixed terrain (Mountain), while staying an set distance from its edge. I have the camera set to lookAt the mountain, and I want to circle the mountain. I was thinking about sine wave for circular motion but its not an exact circle as I need to move in or out to maintain the fixed distance from the mountains edges.

It looks like I might need transform.RotateAround(..), but what about the adjusting to maintain a fixed distance from the edge of the uneven surface while maintaining the circular motion.

```
    transform.RotateAround (Vector3.zero, Vector3.up, 20 * Time.deltaTime);

```

Update: Here is my current script for circling around mountain as first person object:

function Update () { var mountain : GameObject; mountain = GameObject.Find("QuantumCold\_B"); transform.RotateAround(mountain.transform.position, Vector3.up,20 * Time.deltaTime);

}

Unfortunately there are two problems:

1) The first person object appears to be falling or maybe its the main camera, but in any even there is a game screen looks like its falling below the mountain. 2) it is the mountain that seems to be rotating. Do I need to switch the main camera to be the first person camera. Why does the mountain appear to be rotating?

# Answer
> 3 votes
After rotating the camera position, slide the camera position toward or away from the mountain by casting a ray from the camera position to the center of the mountain. Choose a ray intersect test that returns a distance value. Test that ray against all triangles (or optimize with some sort of hierarchical system) of the mountain mesh and whichever triangle you hit whose Dot(triangleNormal, ray.direction) \<= zero and has the least absolute value, use that test result to set the cam position like this:

```
cameraPosition += -ray.Direction * (distanceIwantMyCameraToBe - intersectionTestResult);

```

---
Tags: unity, unityscript
---


# Question
Title: How can I achieve strong typing with a component messaging system?
I'm looking at implementing a messaging system in my entity component system. I've deduced that I can use an event / queue for passing messages, but right now, I just use a generic object and cast out the data I want. I also considered using a dictionary. I see a lot of information on this, but they all involve a lot of casting and guessing. Is there any way to do this elegantly and keep strong typing on my messages?

# Answer
> 4 votes
Create a separate message class for each type of message (to a degree).

In your entities, make a different method for each type of message. eg.

```
class CollisionMessage;
class DamageMessage;

class Entity {
public:
  virtual void onCollision(CollisionMessage&);
  virtual void onDamage(DamageMessage&);
};

```

You can now use a form of double-dispatch to select the right version. Have a `deliver` method on your `Message` types that delivers them to the right handler:

```
class Message {
public:
  virtual void deliver(Entity& e) = 0;
};

class CollisionMessage : public Message {
public:
  virtual void deliver(Entity& e) { e.onCollision(*this); }
};

class DamageMessage : public Message {
public:
  virtual void deliver(Entity& e) { e.onDamage(*this); }
};

```

You can extend this to an observer system by registering message handlers. You can also use this to allow multiple independent messages to share the same type using a little metadata, e.g, ensuring that the `"EnvironmentDamage"` and `"GunDamage"` messages both use the `DamageMessage` type.

The use of components or ECS really doesn't change this much. With components you're just delivering to individual components instead of a main game object class. With ECS you're delivering them to systems and including a "target entity ID" as part of the message. Nice and simple.

If you're going down the ECS route and want it to actually be useful, you might consider a more heavily data-oriented approach to messaging. See the BitSquid blog on managing coupling (actually, read all their articles; they're quite fantastic, even if I don't agree with all of it).

# Answer
> 1 votes
Separate queues per data type to end casting. (I like this one better as it is simple, flexible, and allows for explicit ordering of types of operations)

```
class SpawnEntityEvent {
public:
    std::string resource;
    double x,y,z;
};
class MoveEntityEvent {
public:
    Entity* ent;
    double x,y,z;
};
class ChangeEntityPropEvent {
public:
    Entity* ent;
    std::string key;
    std::string value;
};
std::queue<SpawnEntityEvent> spawnQueue;
std::queue<MoveEntityEvent> moveQueue;
std::queue<ChangeEntityPropEvent> propQueue;

    /*** And if one needs to maintain interleaved order... ***/
std::queue<int> order;
enum {
    ENT_SPAWN,
    ENT_MOVE,
    ENT_PROP
};
void nextSpawnEvent() {
    SpawnEntityEvent& evt=spawnQueue.front();
    // spawn your entity with evt data now
    spawnQueue.pop();
}
void nextMoveEvent();
void nextPropChangeEvent();

void nextEvent() {
    switch (order.front()) {
        case ENT_SPAWN: nextSpawnEvent();break;
        case ENT_MOVE: nextMoveEvent();break;
        case ENT_PROP: nextPropChangeEvent();break;
    }
    order.pop();
}

```

Or tag structures with metadata to end guessing. (This feels a bit cumbersome to me but does allow to keep a single event queue, also creating message codes should be re-usable for networking)

```
class EntityEvent {
public:
    EntityEvent(int t) {type=t;}
    unsigned char type;
};
enum {
    ENT_SPAWN,
    ENT_MOVE,
    ENT_PROP
};
class SpawnEntityEvent : public EntityEvent {
public:
    SpawnEntityEvent() : EntityEvent(ENT_SPAWN) {};
    std::string resource;
    double x,y,z;
};
class MoveEntityEvent : public EntityEvent {
public:
    MoveEntityEvent() : EntityEvent(ENT_MOVE) {};
    Entity* ent;
    double x,y,z;
};
class ChangeEntityPropEvent : public EntityEvent {
public:
    ChangeEntityPropEvent() : EntityEvent(ENT_PROP) {};
    Entity* ent;
    std::string key;
    std::string value;
};
std::queue<EntityEvent*> eventQueue;

```

# Answer
> 0 votes
I have spent a while thinking about this issue myself and it seems that it's a static vs dynamic programming type of choice. You can't have both advantages unfortunately.

When speaking about a language like C# it comes down to a choice of where to put casting + reflection logic or alternatively whether to use dynamic objects.

The best sample of two approaches would be NServiceBus and SignalR distributed messaging frameworks:

NServiceBus (casting somewhere "above"):

```
public class PlaceOrderHandler : IHandleMessages<PlaceOrder>
{
    public void Handle(PlaceOrder message)
    {
        Console.Out.WriteLine(@"Order for ""{0}"" placed.", message.Product);
    }
}

```

SignalR (using dynamics in-place):

```
stockTickerHubProxy.On("UpdateStockPrice", stock =>
    // Context is a reference to SynchronizationContext.Current
    Context.Post(delegate
    {
        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);
    }, null)
);

```

---
Tags: component-based, entity-system, messaging
---