# Question
Title: Organising data of a turn-based strategy
I'm intermediate in Java but novice in everything which is on the server-side. I've set myself a task to rewrite an old game, so learning Java is more fun. It is a space turn-based strategy. The original was called Stars! (I heard that Master of Orion is somewhat similar). Basically players assign their orders to ships and planets and then submit a turn to server, where a new turn is generated.

I suppose, I will have a lot of objects (ships, fleets, planets and so on), each of them will have some properties (XY position, orders, HP etc.). When generating a turn, the server will have to cycle through all the objects and perform tasks with each one (move a ship, unload a cargo for instance).

The question is: How should I organize entities, ships for example, so it is easy to process them. Should I store them in a database? Perhaps there is some sort of a best practice for tasks like this?

If I assume, that ships will be stored in a database. Then, each player will send a file with orders to the server. The server will put everything into a database. When all the players have submitted their turns, the server will cycle through everything in the database and generate a turn. Will this be a good way to do this?

# Answer
> 0 votes
Since in order to take his turn the player needs to know the outcome of other players actions, one way to solve this is a message consumer/producer pattern.

First, you need to define a queue structure with objects sharing a common functionality; this can be as simple as just List of Unit objects where Unit is a class providing an unique identifier for each unit.

A thread on the server would cycle through the list looking for the next unit and querying a database (or in memory) for the last message provided for that unit, and wait if none is found. This is the first part, the message consumer.

The second part is the message producer, where each player would somehow put a new message for a given unit via whatever interface you define. If it's a turn based game it makes sense that only a message per unit should go there (so if there's a second message the first one gets overwritten). Ideally the interface would prevent the player from adding a message unless it's his turn (whose turn it is is an attribute of the consumer, the unit after the last one that acted)

---
Tags: java, architecture, turn-based-strategy
---


title: Quaternion Rotate / Un-Rotate Error

text:
# Question
Title: Quaternion Rotate / Un-Rotate Error
I'm trying to un-rotate a quaternion, aligning it with the axis, and then rotate it back to where it was originally. But with every iteration it seems to lose precision and just after 20 iterations the rotation disappears. Here is an example, which is a simplification of my code:

```
Quaternion rotation = Quaternion.Euler (0f, 90f, 0f);
Debug.Log ("Before: " + rotation.ToString ("F7") + " / Euler: " +
  rotation.eulerAngles.ToString());

int iterations = 1;
for (int i = 0; i < iterations; i++) {
    var currentRotation = rotation;
    rotation = Quaternion.Inverse (currentRotation) * rotation;
    rotation = currentRotation * rotation;
}

Debug.Log ("After:  " + rotation.ToString ("F7") + " / Euler: " +
  rotation.eulerAngles.ToString());

```

With 1 iteration the output is:

```
Before: (0.0000000, 0.7071068, 0.0000000, 0.7071068) / Euler: (0.0, 90.0, 0.0)
After:  (0.0000000, 0.7071067, 0.0000000, 0.7071067) / Euler: (0.0, 90.0, 0.0)

```

With 5 iterations:

```
Before: (0.0000000, 0.7071068, 0.0000000, 0.7071068) / Euler: (0.0, 90.0, 0.0)
After:  (0.0000000, 0.7071019, 0.0000000, 0.7071019) / Euler: (0.0, 90.0, 0.0)

```

With 10 iterations:

```
Before: (0.0000000, 0.7071068, 0.0000000, 0.7071068) / Euler: (0.0, 90.0, 0.0)
After:  (0.0000000, 0.7059279, 0.0000000, 0.7059279) / Euler: (0.0, 90.0, 0.0)

```

With 15 iterations:

```
Before: (0.0000000, 0.7071068, 0.0000000, 0.7071068) / Euler: (0.0, 90.0, 0.0)
After:  (0.0000000, 0.4714038, 0.0000000, 0.4714038) / Euler: (0.0, 90.0, 0.0)

```

And finally with 19 iterations

```
Before: (0.0000000, 0.7071068, 0.0000000, 0.7071068) / Euler: (0.0, 90.0, 0.0)
After:  (0.0000000, 0.0000000, 0.0000000, 0.0000000) / Euler: (0.0, 0.0, 0.0)

```

At the 19th iteration the euler angles becomes zero, and at previous iterations altough the euler angles are still correct, if I rotate a vector with the quaternion its magnitude is changed.

I hope you can help me and sorry for my bad english!

# Answer
This is a late response, but I figured this question illustrates a common problem that many people are likely to run into and that deserves an answer.

Quaternion rotation uses half the angle you want to rotate by. Since you (in this example case) are rotating by `90` degrees, the quaternion needs to calculate the sine and cosine of `45` degrees, both of which are `sqrt(2)/2.0 = 0.7071...`. Since this is irrational you are guaranteed to get some round-off error, as well as for any value other than 0 or 180 degrees, or some integer multiple of them. (see Niven's Theorem).

Calculating the inverse is even worse, since this requires division by the squared norm of the 4 components, and even though the norm of a unit quaternion is supposed to be `1`, the round-off error from the sines and cosines used internally to calculate the quaternion components often make it not be `1`, but just "close to" `1`. This usually gets worse with repeated inversions.

So losing precision is generally unavoidable if you're using limited precision numbers like `float` or `double`. However, there is still hope. One strategy to help prevent the repeated inversions getting worse and worse is to re-normalize the quaternion after each inversion (or after a few of them if you can tolerate more error).

```
public static class QuaternionExtensions
{
    public static Quaternion Normalize(this Quaternion q)
    {
        Quaternion result;
        float sq = q.x * q.x;
        sq += q.y * q.y;
        sq += q.z * q.z;
        sq += q.w * q.w;
        //detect badness
        assert(sq > 0.1f);
        float inv = 1.0f / sqrt(sq);
        result.x = q.x * inv;
        result.y = q.y * inv;
        result.z = q.z * inv;
        result.w = q.w * inv;
        return result;
    }
}

```

which I borrowed from the Physics for Games article Quaternions: How.

This keeps the precision loss from growing out of control. See also this StackOverflow question.

So your final code should look something like this:

```
Quaternion rotation = Quaternion.Euler (0f, 90f, 0f);
Debug.Log ("Before: " + rotation.ToString ("F7") + " / Euler: " +
    rotation.eulerAngles.ToString());

int iterations = 1;
for (int i = 0; i < iterations; i++) {
    var currentRotation = rotation;
    rotation = Quaternion.Inverse (currentRotation) * rotation;
    rotation = Quaternion.Normalize (currentRotation * rotation);
}

Debug.Log ("After:  " + rotation.ToString ("F7") + " / Euler: " +
    rotation.eulerAngles.ToString());

```

but I haven't actually tested this.
> 5 votes

# Answer
Seeing your code, I think it would be better to store the two rotations and switch between them

```
Rotation firstRotation; // Stores the initial value
Rotation rotationAmount; // Stores the rotation tick per loop
bool isRotated = false; // False is the current rotation is the initial value, true if it's the new one
int iterations = 20;
for (int i = 0; i < iterations; i++) {
    if (!isRotated) {
        transform.rotation = transform.rotation * rotationAmount;
        isRotated = true;
    } else {
        transform.rotation = firstRotation;
        isRotated = false;
    }
}

```

Also you may want to provide some context as to why you are doing the same rotation 20 times in the same for loop (which effectively shouldn't do anything) what is your objective?
> -1 votes

---
Tags: unity, rotation, quaternion
---


title: How to draw small sprite bigger?

text:
# Question
Title: How to draw small sprite bigger?
I have created an image with the resolution of 25px(width)\*34px(height) (*I know it's unusual, however it doesn't bother me now*). The problem is that when I try to display it by creating a bitmap, it becomes really really small on my Galaxy S4. It should look a little pixelated, kinda like a flappy bird sprite. I checked those sprites as well and they are even smaller in comparison to mine however it is displayed much bigger than my sprite on the screen. I want to know if I can make it look larger without scaling it. Is there a way to make my sprite look bigger?

```
@Override
protected void onDraw(Canvas canvas) {
    Log.i(TAG, "onDraw called");
    BitmapFactory.Options op = new BitmapFactory.Options();
    op.inPreferredConfig = Bitmap.Config.ALPHA_8;
    bm.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    bm = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.giraffe_default,op));
    canvas.drawBitmap(bm,getWidth()/2,getHeight()/2,null);  //get from res, set coords to 10,10
}

```

This is my onDraw method where I draw my canvas and bitmap. As I said, my image appears to be so small, I can barely see it.

# Answer
Draw the bitmap using a `Matrix`.

```
Matrix matrix;
matrix.reset();
matrix.postScale(2.0f, 2.0f);
matrix.postTranslate(getWidth()/2.0f, getHeight()/2.0f);
canvas.drawBitmap(bm, matrix, null);

```

EDIT: you probably should tell it where to draw too. My bad.

EDIT2: In response to you blurry comment, you can try turning off anti-aliasing, and bitmap filtering.

```
Paint paint = new Paint();
paint.setAntiAlias(false);
paint.setFilterBitmap(false);

canvas.drawBitmap(bm, matrix, paint);

```

If that doesn't give you the results you are after you can create the larger image by using blocks of color (i.e. 3x3, or 10x10) to represent each pixel of the original image. Also, consider searching this site, there have been similar or related questions already asked and answered.

Angry Birds Scaling
> 2 votes

---
Tags: android, sprites, html-canvas
---


# Question
Title: Physics-perfect (or somewhere near) 3d sound engine
I'm new to game programming, although I have some years of experience in console/web development. My problem is not so much that I can't find what I'm looking for, it's just that I don't have the terminology to actually perform a successful search.

I am looking for a physics engine which has great focus on sounds. In fact, I do not care at all for anything else. What I mean is better explained by an example:

Suppose a 1st person type game. You are facing North, and someone somewhere around you throws a flute at you (nevermind the absurdity of the situation). The flute spins while it is on its way, making sounds through its holes. There is a wind of say, 5 knots South.

I imagine a physics engine will be capable of calculating the trajectory of the flute, as well as the direction it takes after it hits. What I want is for the physics engine to calculate the precise sounds it will make, from any listener's perspective.

Does any such engine exists? If there are several, which one would be best for the example above?

# Answer
> 10 votes
You are asking the wrong question. You're making the mistake many new game programmers make. Games are ***not*** perfect simulations, they aren't even close. Games simulate just enough to be fun/interesting. Everything else is faked.

Case in point:
World of Goo: simulates mass, tensile strength, and elasticity. The rest is faked because it doesn't add the feel of the game. For instance it doesn't simulate gravity. All objects accelerate down with constant force. Boyancy is faked. Ballons pull up with a constant force and goo balls under water experience a constant upward force as well. This all works great for the game. It would however break down if you tried to make a space elevator using World of Goo's physics engine.

Lets imagine a near perfect physics based sound engine. What about environmental effects? Is the flute in a cave or in a field. Does the engine provide a predefined set of environments(how many?) or does it figure it out by calculating the actual physical topography(yeah right)? Does the player have directional ears (ala human) or just ear holes (ala dolphin or alien) or multidirectional like an animal? Is the air hot? How humid is it. This list can quickly get out of control.

Now assume for a moment such true physics sound engine existed. Would you really want to use it to make a game? How long would it take you to define the sound of flute flying through the air. How many parameter do you have to get just right (100's?).

What you should have asked is:
*How can I simulate the sound a flute when it flies past the player?*

OpenAL can do what you want.

* Directional listener
* Directional sound sources
* source velocities and doppler effects.

I would suggest having a repeating sound effect of a spinning flute. Input the player position and the flute's position/velocity. Skip the directional stuff for now.
You could record the sound that comes from each end of a flute as the air flows by and have the flute use two sound sources. But I doubt it would be worth the effort unless the whole game mechanic revolved around thrown and spinning flutes.

# Answer
> 8 votes
You want physical modeling? Try the Synthesis Toolkit:

https://ccrma.stanford.edu/software/stk/classstk\_1\_1Flute.html.

You'll have to write the glue code which sets the wind speed / amplitude yourself.

What you're asking for hasn't really been invented yet. We're getting close though- check this out, I saw it the other day:

http://www.physorg.com/news198351307.html

# Answer
> 4 votes
I doubt you'll find a physics-audio engine. What is more likely is to use any physics engine you like (such as Bullet) and use OpenAL for sound. Calculate the position of the flute, and use that as the position of the Source.

# Answer
> 4 votes
Phya is a "physical sampling" based collision audio synthesis library which can be driven by a game physics engine. (Bullet was used in the examples)

http://www.zenprobe.com/phya/

Not sure what the latest is, the last site update is over year ago now.

It is not so much geared to modeling resonance of air in a volume, but could perhaps be a good example of how to drive real-time audio synthesis from physics.

I think this does not need to be an impossibly cpu-expensive undertaking, The problem stated is entirely deterministic and should be achievable on modern hardware. (at least to a level suitable for an entertainment/learning product.)

The question to answer is how fully do you need to simulate, and how much can you fake? For audio just having some kind of realtime modulation of sound in a reasonably convincing manner gets you a lot without having to model acoustic vibrations down to the molecule.

Maybe this helps. Good question, btw.

-j

# Answer
> 3 votes
Actually doing an accurate simulation of the physics involved here would be substantially more complex (and computationally expensive) than a run-of-the-mill physics system like Havok or Bullet. A traditional physics system is optimized for rigid bodies and soft bodies, both of which are limited in their mesh complexity for speed reasons.

Sound, on the other hand, is a propagation of waves through air, and the frequencies generated by something like your example are dependent on tons and tons of properties. What material it made of? What mathematical model should we use for air particles interacting with that material? If it's a tube shape, what are the dimensions of the tube? (This determines the resonant frequency.) Etc., etc.

On top of all of this, you've got to run a pretty sophisticated particle simulation to model the air, as well as extracting particle motions waves which are essentially the sound waves hitting your eardrums. And let's not even mention the eardrums, because the resonance of the waves in your ear canal affects what you hear, too.

All in all, this is way too much simulation for a current game to perform, especially if you have any hope of an interactive frame rate. As deft\_code noted, games are rarely accurate simulations, but rather gloriously faked ones. The best way to approach this would probably be to start with a large sound sample set and start running things through a DSP until you've got a grasp of how you can impact the effect of those sounds. DSPs are definitely fast enough for real-time games, and if the sound would be a big component then it makes sense to devote a decent chunk of your frame time to sound processing.

**tl;dr: Accurate simulation is probably out the question for many years to come. Great games fake it. With a large enough sample set and enough DSP tweaking you can probably fake it, too.**

# Answer
> 2 votes
Check our approach.

http://dsp.agh.edu.pl/en:research:rayav

Developed library utilizes beamtracing to provide user with realistic audio auralization. All audio effects are computed based on the actual geometry of a given game level as well as its acoustic properties (acoustic materials, air attenuation). The sound changes dynamically along with movement of the game character and sound sources. Sound path creation algorithm supports phenomena like specular reflections, diffuse reflections and edge diffraction, whilst audio processing supports signal filtering (modelling air dumping, reflection/diffraction impact and so on), Doppler effect modelling and spatial effects. Finally directional sound is implemented using HRTF per each soundpath.

# Answer
> 0 votes
I realize this is an old question, but things have been progressing in the last couple of years, and what you are describing is becoming more and more feasible, computationally.

Tools like Synthesis Toolkit are used to answer the following sort of question: "My physics engine told me that the flute is vibrating in such-and-such manner. What note does that produce?"

There is another major question that must be answered, though: "What does this note sound like from the listener's position?"

It is a common misconception that audio APIs like OpenAL take care of this. In fact, all they do is what is called **positional audio**. They do not model **sound propagation:** the interactions between the sound waves and the environment. Sound propagation involves answering questions like:

* Is this room large enough for there to be noticeable reverb?
* Or does the furniture in the room absorb most of the sound?
* When standing outdoors, should I hear echoes from a distant hill? A nearby building?
* Does the sound dissipate over long distances?
* Is the sound source occluded (hidden) from the listener?
* If so, are there alternate routes that sound waves can use to reach the listener? Perhaps from under a closed door, around a hallway corner, or through a vent?

Phonon is an audio-physics engine that answers these questions. (Full disclosure: I am involved in developing Phonon.) With Phonon, the user needs to specify a very *small set of parameters* (absorption and scattering coefficients). Phonon then performs *just enough* computation to be able to convincingly recreate sound propagation effects for the listener.

Phonon is currently available as a plugin for Unity. Apart from PC and mobile, Phonon can also run on VR platforms like Oculus Rift, and it makes a noticeable difference there too.

Hope this helps!

# Answer
> 0 votes
When reading your question, I can translate it two ways.

1. **Is there an engine that can create sounds based on physical simulations? Such as air blowing across a reed, or a hammer striking a string?**

In gaming? not that I've heard of.

2. **Is there an engine that plays pre-existing sounds but modifies them based on physical information such as distance from microphone to simulate a "surround sound experience"?**

Yes! they are called "3D sound engines" a well-known one is OpenAL.

---
Tags: audio
---


title: Where does game logic belong?

text:
# Question
Title: Where does game logic belong?
I've always had a hard time wrapping my head around the 'high levels' of game logic and where/how large components, such as collision detection/physics, rendering, and user input, interact with one another. What I'm asking is how you deal with these higher level interactions.

Here is what I am doing:

```
interface Stage() { //or a "scene" as many call it. Manages the logic for Actors
   init()
   update() //update this stage
   render() //render this stage
}

StageManager() implements Stage { //a stage that manages stages :)
   var stages = array<Stage>
   init() //create a MainStage & other stages that may be used in this specific game
   update() //logic for checking which stage should be active
   render() //tell the active stage to render
   getActiveStage()
}

MainStage() implements Stage {
   var mainCharacter
   var actors = array<GameObject>
   var ...
   init()   //create the player, game world, other initialization stuff
   update() //collision detection, check mainCharacter state, etc
   render() //render all the Actors on this stage
   handleMouseClick()
   handleKeyBoardEvent()
}

Main() { //created on game start
   var manager = new StageManager()
   updateGameState() {
      manager.update()
      loop
   }

   renderState() {
      manager.render()
      loop
   }

```

My main gripe with this is that the StageManager and all other Stages will become enormous and unwieldy as the game scales over time. Off the top of my head, some components can be delegated out such as a Stage uses a PhysicsManager, but there would still be all the keyboard events and what not.

I was thinking of making individual Actors listen to events and giving them an update() method, thus encapsulating what an Actor should do at any given point. However, I would run into complications when an Actor needed game-state information (game time, a "power-up" Actor needing the player's speed) and I would no longer have Stages as Actors are now managing themselves.

# Answer
This is a somewhat broad topic as the problem is not how to fix something but more akin to planning ahead to use the "best" structure and avoid potential problems in the future. And thus, depending on your requirements and complexity you are aiming for this may be entirely a non issue.

That being said, I have a 2 suggestions: Composition over inheritance and Occam's Razor. You can read about composition over inheritance and Occam's Razor just means pick the easiest method that works. Looking at your code, to me, it seems like it has many unnecessary indirections. I would just have a stage object that contains a init() method and a list of actors. Then each of my actors would know how to update() itself and render() itself in addition to knowing which stage it belongs to.

Then the mainloop would be something like

```
- handleUserInput()
- for (actor in stage.actors) actor.update();

- stage.render();
- for (actor in stage.actors) actor.render();

```
> 0 votes

# Answer
An effective but complex method would create states for every object. These states would be along the lines of Active, InActive,and Remove.

```
Active = Update/Render Alongside all other 'objects' with this state.
InActive = Don't Render or Update at all, this must be activated before anything happens with it.
Remove = This means for whatever reason, the object needs to be removed from the Array before/after it's next loop.

```

You can create more states as needed. Using states can improve the time it takes to both render and update each object, as some inactive won't be updated, and even maybe removed.

To solve something like the power-up issue. Give all events the necessary parameters for what has activated them; Inside the power-up file

```
onHit() // No information Given

```

Should look like

```
onHit(Object i) // i equals whatever hit the powerup

```
> 0 votes

---
Tags: game-design, javascript, logic
---


title: Name generation

text:
# Question
Title: Name generation
I'm making a game (or planning to, at least) and to do that, I need a way to automatically generate names for the NPC "bosses" (long explanation and irrelevant here). Something like this is a good example of what I mean.

I have an idea that I can just build a database of names by nationality, maybe first/last pairs, and assign them randomly, with an ignored names list so I don't get something like Homer Simpson and get sued or something.

The problem with that is that I'd need to build up a massive database of names for that to work. It would either take forever or cost money, unless someone has a list of names available for free already.

I have another idea where I make random pairs of vowels and consonants, flip a few, and add them together, but a quick program that does that generated names like these:

> * Seermeecpa
> * Cime
> * Ofmiahwumafi
> * Gozidi
> * Effawided

(For anyone interested in the code, you can see it here)

These are... kind of a mouthful. Well, except "Gozidi" -- that one could work. Still, the success rate is clearly not very good.

Is there anything I could do to make the names sound nicer (see below), or should I start making that list? Can I somehow mimic the way humans decide if a name is decent or not, with at least some accuracy? I'd much prefer something like this to a lookup in a big list.

What I mean by "nicer" is that, instead of random combinations of characters (which it is, to be fair), things that sound like actual names. They can be from any culture (or sound like they are), real or imaginary, anything at all, so long as your stereotypical dumb, monolingual American like me can say 'em without too much trouble.

If you need extra clarification, go ahead and ask. I'm not really sure what to put here.

Addendum: So far as I can tell, there really aren't tags that fit this question all that well. If anyone who's been here longer can recommend some, that'd be awesome.

# Answer
> 14 votes
Most name generators work via some variation of Markov Chain, which are fairly remarkable (re*markov*le?) constructs that have many uses in games, as well as other domains.

The basic approach does invoke a list of some kind. These do not need to be fairly huge. The purpose of this list is merely to inform the algorithm what syllables are likely to be paired together for a given category of name.

This allows you to put together different lists for e.g. male names, female names, family names, or names for different cultures/regions/species.

The time you'll spend tweaking an algorithm that randomly assembles made-up syllables into a pleasing fashion is likely going to be more than you'd spend just generating a list of names that you think sound good and fit a common theme.

There *are* many lists of names available. Download the latest US census database for modern day names easily separated by age, gender, and ethnicity, or grab lists of old Norse names or the like. These are all quite easy to find via Google; that last link was literally my first hit for "list of norse names."

# Answer
> 3 votes
Most names in languages follow a series of patterns. For example Russian or Greek names may have five or ten different prefixes, thus if you find a name ending with *-ov* you may suspect its Russian because it kinda fits the pattern.

If you want real names (or real like) I think you should start building your list (which shouldn't be so long) because analyzing real names of some languages, finding their pattern, and creating an algorithm to produce such names is not worth the effort in my opinion.

If you want random names that could be a name in some language, you could build a small list of rules to follow (like a subset of the above). Already, what you are doing is that: you made a rule about vowels and consonants. You could add a few more like surnames should end in these 10 syllables or some consonants can be followed only by vowels like 'q' followed only by 'u' and some others can be followed by other consonants like 's' followed by 't' or 'k'. Again, this is more to create some words that can be actually pronounced and feel a bit real than creating actual names.

Something that may be relevant is the way "Papers, Please" generates names. http://papersplease.wikia.com/wiki/List\_of\_names

# Answer
> 0 votes
I think the easiest way to do this is to use an existing random name generator or an existing list of random names that meet your requirements. Then store it somewhere as a list. When you need a random name, just pick from the existing list at random.

---
Tags: procedural-generation, npc
---


# Question
Title: How do I create a simple clickable button?
I've tried to attach this function to the play button.

```
public void Play () {
    Application.LoadLevel("Scene1");
}

```

I've created an empty **Game Object** and attached my script to it. But when I go to the `OnClick()` method in the Play button and try to select my `Play()` method can't find it, there is only a bunch of useless functions that do nothing to help me load the level.

And apparently most tutorials and forum posts suggest doing it this way, but it doesn't work for me.

Other posts say that you can assign the `OnClick()`-method in your script and show how to assign the function, but no one remembered to mention how to get the button object to which I could assign the function.

I'm new to unity and this problem is getting very frustrating. I'm using the free version of Unity for now.

# Answer
> 2 votes
**I am assumming you are trying to make a GameObject that, when clicked, will load another level. If so, continue on with this answer. If not, explain what you want in the comments below or in your question.**
**Note: In this case, I am going to use the OnMouseButton() method, since it would suit your needs perfectly**

---

# Steps

### Step One: Preparation

I would make a Game Object that would act as the button
*This includes:*

* A 3D Model with a Collider (Cube)
* A 2D Sprite with a 2D Collider (Sprite)
* *An OnGUI Element:* **Note, OnGUI is redundant and most would recomend the next option**
* Unity 4.6 GUI Object

**In this case, I will make an empty cube**

### Step Two: Coding

Now, create a new script or use an existing script for controlling the play button. In this case, I will make a script called PlayButton, but the following code will work on an existing script
```
using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {
    void Start() {

    }

    void Update() {

    }
}

```

Now, what we are going to use is the method **OnMouseDown()**, which will run when the cursor clicks the game object. Also, we do not need the **Start()** and **Update()** methods, so we will remove them from the script.

```
using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {
    void OnMouseDown() {
    }
}

```

From here we can do one of two things. We can directly load the next level inside this block of code, or we could call another block of code that would load the next level. I will do both for example sake. In the first example, we will add the code **Application.LoadLevel("Scene1")**, which will simply load the level **Scene1**

```
using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {
    void OnMouseDown() {
        Application.LoadLevel("Scene1");
    }
}

```

And that's it! Skip to the next step if that is all you want. If you would rather call a separate method that loads the next level, look down a bit further before moving to the next step.

Now, I am going to make a method, called **Play()**, that will load the next level. This code will be activated when I click on the Game Object that holds this code. The **OnMouseDown()** method will simply trigger the **Play()** method, rather than actually loading the level itself.

```
using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {
    void OnMouseDown() {
        Play();
    }
    void Play() {
        Application.LoadLevel("Scene1");
    }
}

```

### Step Three: End

All you need to do now is to attach the script onto a Game Object that you would like to be the play button, in this case it will be Red Cube. Then Click the Play Button to activate the game and see if it works out.

# REMEMBER:

Make sure that you added the scene to the Build Settings, or else it will not work out properly. Search on Google to find out how to do that if you are not familiar with it.
---

# References/More Info

Unity Script Reference: OnMouseDown()

# Answer
> 0 votes
What @Ahkam said is right `100%` attach the Script to the gameobject you created and add a `BoxCollider` component to it ,then do the following in the script

```
using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {
void OnMouseDown() {
    Application.LoadLevel("Scene1");
 }
}

```

Adding a BoxCollider component is Mandatory here for triggering the mouse event

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


# Question
Title: How to programmatically disable sprite renderer and mesh renderer in Unity3D?
In my game, I have an empty `GameObject` that has a sprite and a `TextMesh` as child. I want to access the child (sprite and the text mesh) and turn off the sprite renderer and mesh renderer of the sprite and the text mesh programmatically and be able to then turn it back on, but I don't know how. Some help and/or sample code would be much appreciated. Thanks.

# Answer
> 5 votes
You can use 'GetComponent' to access these things. Then, you can edit enable or disable the sprite and mesh renderers.

```
gameObject.GetComponent<TextMesh>().renderer.enabled = false;

```

This example will disable the renderer on the TextMesh. Assuming you have a SpriteRenderer on your GameObject (which you refer to as 'Sprite'), to disable that you would use the following code:

```
gameObject.GetComponent<SpriteRenderer>().enabled = false;

```

If it is not a SpriteRenderer you can still use the GetComponent method to get the component of your choice and manipulate this component to your likings.

---
Tags: unity, unityscript
---


# Question
Title: Unity engine vs JS engine for browser game
I'm trying to do a browser based game and I don't want to create my own game engine, no sense in recreating the wheel. Should I use Unity as my game engine? Or should I focus on a more Javascript based engine like Impact since it will be a browser game?

# Answer
Unity3D is a good candidate with WebGL support coming soon in version 5. S,o no plugin in the browser is required. You also can program it in JavaScript.

Info about it here
> 2 votes

---
Tags: game-design
---


# Question
Title: Libgdx screen keeping text on screen from main Game class
In my libGDX app I have some text running on the main Game class, and when I switch to a different screen the text is still there? Can anyone explain this please. Also in my main class it is changing screens to a splash screen then to the screen I mentioned earlier. But the splash screen doesn't have the text on the top.

# Answer
Gdx.gl.glClear : as **.glClear** suggests, this function clears the screen before drawing the next frame. It depends where do you instantiate your font object (as you're using libgdx I guess you use BitmapFont to create your font object).

An approach could be **to instantiate it in the main class** (the one that extends Game), and whenever you want to draw it on the screen, you call it in the render() method.

Assuming you're using **BitmapFont** to draw your text :

**MainClass**

```
private BitmapFont font;
private SomeScreen someScreen;

    @Override
    public void create () {
        font = new BitmapFont (path);
        someScreen = new SomeScreen (this);
        (...)
        setScreen(someScreen);
    }

    public void drawText (String text) {
      font.draw (spritebatch, text, x, y);
    }

```

**SomeScreen**

```
 public class SomeScreen implements Screen {

    // create reference to the main class
    MainClass main;

   // the contructor
   public SomeScreen (MainClass main) {
   this.main = main;
   }

   @Override
   public void render(float delta) {
    // clean the screen
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    spritebatch.begin();
    main.drawText("your text here");
    spritebatch.end();
    }

}

```

**It can be also drawn during the main life-cycle :**

**MainClass**

```
  (...)
    @Override
    public void render () {
     super.render(); // it draws whatever is in the render() method of the current screen
     font.drawText ("your text here"); // and then you draw your text (actually it doesn't make much sense)
    }
  (...)

```
> 1 votes

# Answer
Try adding `Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);` to your render function, as still clears the buffer, and alloys the new screen to load.
> -1 votes

---
Tags: libgdx, screen-management
---


title: Libgdx Actions interpolation Fadeout

text:
# Question
Title: Libgdx Actions interpolation Fadeout
In `libGDX` there is a simple fade `Interpolation` that speeds up towards the end of the action animation. But what I am looking for is the reversed of it, it needs to start fast and slow down near the end. Is there a `Interpolation` function for that or how can I create this effect myself?

Currently i'm directly just initiating the action from the actor.

```
actor.addAction(Actions.moveTo(currentTouch.x - actor.getWidth() / 2,
 currentTouch.y - actor.getHeight() / 2,
 .2f,
 Interpolation.fade));

```

# Answer
> 3 votes
I use `Interpolation.bounceIn.apply(current_position, target_position, smoothness)` to achieve this effect. Take a look at this.

**Edit** I found the answer on their site

```
MoveToAction action = Actions.action(MoveToAction.class);
action.setPosition(x, y);
action.setDuration(duration);
action.setInterpolation(Interpolation.bounceOut);
actor.addAction(action);

```

***(I haven't tested it !!)***

Take a look at the full tutorial here

---
Tags: java, android, libgdx, interpolation
---


# Question
Title: How do I access the "Ascii Start Offset" property of a Font at runtime?
When I create a "Custom Font" in Unity 4.6.1, I get this:

"Ascii Start Offset" indicates which character is first in the font. I've set it to 48 (the zero character) by hand, and my custom font works fine just for numbers.

But I'm creating these fonts at runtime as a build step. I access "Character Rects" through `Font.characterInfo` in code:

```
font.characterInfo = infoList.ToArray();

```

So the names don't necessarily align. But I can't figure out how to change "Ascii Start Offset" at runtime; none of the available members of Font class seem to be related. Is this possible?

# Answer
"Ascii Start Offset" is a Unity internal field. It is not available in any of the Managed(C#) DLL's, so you can not use reflection to get to it. The "Ascii Start Offset" field is named `m_AsciiStartOffset` in Unity's internal representation of the `Font` class.

Since the "Ascii Start Offset" is shown in the inspector, I knew it had to be available using a Custom Editor. All of the properties shown, are available to the custom editor via `Editor.serializedObject`. I figured this out using a reflection tool and diving into what Unity does behind the scenes when drawing fields. There was, of course, more churn before I figured it out.

Luckily there is `Editor.CreateEditor` so you can make your own custom editor on the fly. Normally Custom Editors are made with a decorator (you can see an example below the horizontal break).

You can't use this snippet in game runtime, but it works just fine anywhere else in a editor script.

```
public void SetAsciiStartOffset(Font font, int asciiStartOffset)
{
    Editor editor = Editor.CreateEditor(font);

    SerializedProperty startOffsetProperty = editor.serializedObject.FindProperty("m_AsciiStartOffset");
    startOffsetProperty.intValue = asciiStartOffset;

    // Save off all of the values to Unity's internal structure
    editor.serializedObject.ApplyModifiedProperties();
}

```

---

Here is a full Unity Editor Window script that uses the snippet above to change "Ascii Start Offset". *The `XML->Font` code is by Almo(question asker).*

## GitHub Gist: `GenerateCustomFontWindow.cs`

You can access the editor window by going to `Window -> Generate Custom Font`:

---

This following script will loop through all the properties/fields shown in the Unity Inspector and print out the Display name, actual internal name, and its type. It is just to show how I found the variable name, knowing it is shown in the inspector.

```
using UnityEngine;
using UnityEditor;

// Custom Editor of Font: http://docs.unity3d.com/ScriptReference/Font.html
[CustomEditor(typeof(Font))]
public class CustomFontEditorPropertyLogger : Editor {

    // This will loop through all the properties/fields shown in the Unity Inspector
    // and print out the Display name, actual internal name, and its type
    public override void OnInspectorGUI()
    {
        GUILayout.Label("Woah, Custom Font Inspector Script!");

        // Basically From `UnityEditor.FontInspector` which is an internal method
        UnityEngine.Object[] objArray = base.targets;
        for (int i = 0; i < (int)objArray.Length; i++)
        {
            if (objArray[i].hideFlags == HideFlags.NotEditable)
            {
                return;
            }
        }
        //base.DrawDefaultInspector();

        // You can find individual properties if you know their internal name via `FindProperty`
        //this.serializedObject.FindProperty("m_AsciiStartOffset");

        // This is essentially what `base.DrawDefaultInspector();` (commented out above) does
        // From `UnityEditor.Editor.DrawDefaultInspector()`
        SerializedProperty propertyIterator = this.serializedObject.GetIterator();
        for (bool i = true; propertyIterator.NextVisible(i); i = false)
        {
            Debug.Log(propertyIterator.displayName + ": " + propertyIterator.name + " of type: " + propertyIterator.type);

            EditorGUILayout.PropertyField(propertyIterator, true, new GUILayoutOption[0]);
        }
    }
}

```
> 5 votes

---
Tags: unity
---


# Question
Title: Implementing Client-Server Delta Compression (with Protobufs)
I am writing a 2D real-time RPG in C# and I am trying to implement client-server communication using protocol buffers. I am trying to figure out how to implement delta compression to reduce message sizes.

I have read the protobuf "optional" fields take up no extra space on the wire when they are not set (obviously they still do in local memory though), so if I can just programmatically determine my deltas efficiently I would be in better shape.

Here's the problem. I can think of a few ways, but none seem to be ideal. I was wondering if someone could point me in the right direction.

1. Try to keep a dirty bit array for EACH message-able class that gets cleared when a message is sent and marked when a variable changes. Then to send a message you just send the members that match the Boolean fields. This has LOW maintainability, but probably decent performance.
2. Every message-able class keeps a "pastMessage" member that gets updated saved when a message is sent. Then just serialize your current state and diff the two messages. This would probably have LOW performance and almost DOUBLE memory overhead for the game types..
3. Create a new message every time a message was sent and "fill-in-as-you-go." This would provide a better performance than the above, but still would essentially double my memory overhead on my server.

Any other ideas?

# Answer
> 3 votes
Start with whatever's easiest to get your stuff up and working. It sounds like you have a good grasp of potential improvements and tradeoffs, so, go for "easy and works" first, and improve if needed. Do profiling of time & space. Might even, just to start, send un-delta'd messages, if it is feasible.

Choice 1 is pretty good, by the way, and there may be ways to lower the maintenance burden, with c# property tricks. Or at least to enforce a test suite that will alert you if you add a field that doesn't have the Boolean-on-change nature correctly implemented, by reflecting over members or similar...

---
Tags: networking, client-server, compression
---


# Question
Title: How can I implement procedural humanoid generation like MakeHuman?
Some applications allow you to generate a human mesh by simply adjusting parameters. The results are broad and convincing: you can get from a thin asian girl to a muscular african man by just adjusting those. MakeHuman, for example, exposes the following UI:

What is the technique and what are the formulas used to implement that kind of procedural humanoid generation? Is there any published study/resource with the required information?

# Answer
So you start off with a base mesh. Maybe a few. It might be split up into multiple portions (eg, the shoulder mesh, the neck mesh, the head mesh.) Each section might have a variety of "options" (eg. elf, male, female, etc.), alternatives that can be swapped out into the same position. You can think of it much like a seamless texture. As long as all the edges line up exactly, you can do whatever you want in the middle.

Vertex merging/vertex welding/removing duplicate vertices/whatever else it's called, is merging all those parts into one solid mesh/humanoid. You have all those meshes, defined by vertices, whoms edges line up just right so that you don't see any lines between them. What that means is that both part-mesh `a` and part-mesh `b` both need to have vertex(s) at `p` to have a seamless edge. When combining it so you can see it as a whole, you remove the duplicate, so there's only one `p` instead of one `p` for mesh `a`, and one for mesh `b`. If that makes any sense.

You can google around for a better explanation.

Shape keys, as explained on Blender Cookie: https://www.youtube.com/watch?v=gDZcmAWL2jA

Programmatically, there are several approaches to this. The simplest is to have a base-mesh, and then accompanying data that has "offsets". You then apply a percentage of that offset to the base-mesh, and it transforms it by that amount. combine multiple offsets, and you can end up with some pretty complicated results. The hardest part is moderation of these different offsets, to prevent unwanted deformities.

So now you have a mesh that gets distorted in all kinds of funny ways. To make it ready for use, you just need to animate it. Give it a skeletal structure. Really, that's just some extra data you tag into your base-mesh.

Aside from that, programmatically, you need moderation. You need to have, coded in, what keys go together, what parts of the mesh go together when, what shape-keys can and can't work with each-other and, if they can, how much they can both be applied before you start having problems. I'll also add onto that, different sets of shape-keys (male shape-key, female shape-key, lizard shape-key, etc.)

If you aim for a make-human like feature, the hardest part (I expect), would be the sheer amount of data for the shape-keys + base-meshes + animations. To get to something anywhere close to make-humans level requires sheer data. Particularly on the shape-key part.
> 2 votes

---
Tags: animation, models, procedural-generation, 3d-meshes
---


# Question
Title: how to sync two players to start at the same time for a head-to-head networking game?
I am developing a game similar to "Street Fighter" and two players can fight each other via Internet.

The networking model is "lockstep" by trying to sync user controller status for each frame.

When a game starts, the basic sequences are:

1. Random matching
2. Game Start
3. Player A sends out a message to B every 30ms, and vice versa.

The question is, in step 2, "Game Start", these two players must start at the same time "physically".

I am thinking to negotiate a timestamp (based on UTC) for two players to start the game right upon it. However, I am suspecting the timestamp might be device dependent. Maybe it's possible for a device to report a timestamp that is 10 seconds or 100 seconds behind the other player.

Therefore, I am wondering what's the best solution for this kind of situation when implementing a networking game like this (no server involved)?

# Answer
Even if there's no host or server, one of the players needs to be in control, be the "host".

Assume there's host A and any number of players B (in your case just 1). A pings B and records the average delay. When the game is about to start, A sends to B that it needs to start within N msec (delay value obtained above) after that message arrives.

Now when the game is running A and B each keep their lock-step timers running (30msec in your case). As the time goes, network lag and timers may fluctuate, so you need to adjust to network delay changes and timers imperfections (yes, some clocks can run at minor but noticeably different rates), so each now and then A sends to B request to adjust number of ticks planned ahead (so there's more or less lag, but no stuttering) and by delaying or catching up time between ticks if needed.

No UTC or any local times involved.
> 4 votes

---
Tags: networking, multiplayer
---


# Question
Title: How can I copy an asset folder programatically depending upon a constant?
I have a Unity project in which I have 200 games and some 350 scenes. Now I want to make separate builds for each game. All my assets are present in `Assets/IgnoredAssets/ABC` folder. To include these assets in my current build the assets of the current game (say ABC) needs to be in `Assets/Resources/ABC`.

I want Unity to take these `Assets/IgnoredAssets/ABC` files and copy them to `Assets/Resources` before making build depending upon a constant defined in some file.

I want a kind of automation so that when I mention in my constant file `string gameName="ABC";` it automatically picks its assets, paste them in `Resources` and builds for me.

How can I do this?

# Answer
First of, you should have separate projects for individual games and not all games in one project.

You can just move the assets around if you know what the current select game is. First, move the current game back.

```
AssetDatabase.MoveAsset("Assets/Resources/<filenanme>", "Assets/Resources/<currentgame>/<filename>");

```

Now, move the next game into the asset folder.

```
AssetDatabase.MoveAsset("Assets/IgnoredAssest/<newgame>/<filenanme>", "Assets/Resources/<filename>");

```
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How do you filter entities in an Entitiy Component System?
I am currently writing my own ECS in C++ and I am using `std::bitset`.

I register a component at compile time and give it an ID.

```
Position has ID 1
Direction has ID 2
..

vector<bitset<numberOfComponents>>

```

And so on. The problem with this approach is the more components I register the bigger my bitset for every entity will get.

If I overshoot my goal a bit and say that I will have 1000 components and 5000 entities.

A std::bitset\<1000\> is 128 bytes big of my machine and for 5000 entities that is 640kbytes of overhead. To be fair that is actually not that big considering that many machines have 8 gigs of ram.

But I am wondering how you guys are doing it? How do you filter your entities? Are you also using something like a component mask?

Update based on congusbongus answer:

```
vector<DrawComponent> c1;
vector<MoveComponent> c2;

vector<Entity> draw = {1, 2, 8, 42,128}
vector<Entity> move = {8,128};

```

I assume that is how you think it works right? Two questions:

1.) How do you make `vector<Entity> draw = {1, 2, 8, 42,128}` contiguous in memory? If the id is just the index into a vector there will be a lot of "holes".

2.) Because there is no filter, how do you then associate entities together? If you have system `System<Draw,Move>`, you need the Draw and Move component and because of

```
vector<Entity> draw = {1, 2, 8, 42,128}
vector<Entity> move = {8,128};

```

if you just iterate over both of them it doesn't work. because `move[0] = 8`, and `draw[0] = 1`.

I mean if you draw something you actually need the draw and move component because u need to draw at a specific position.

# Answer
> 9 votes
In a "pure" ECS, your entities consist of just a unique ID, which shared among its components. For example you may have these entities:

* Entity ID 123, it is *drawn* and *moved*
* Entity ID 234, which is only *drawn*

Thus you'll have the following component collections:

* Drawn components: \<123, 234\>
* Moved components: \<123\>

There is no need to filter in this scheme; you might have a rendering system that draws all the "drawn" components, and a physics system that moves all the "moved" components.

# Answer
> 4 votes
I suppose that you're really asking now, post-edit, how you can use the entity ID's as indices into your component vectors without there being gaps in the component vectors. The simple answer is that you can't. You really want an associative container for your components, like an std::map or std::unordered\_map, but barring that, if you insist on storing your components contiguously, you just need to let your components know what entities they are associated with:

```
// use as a base class for your components
class Component{
    Entity ent_id;
}

```

Then, in your "`System<DrawComponent, MoveComponent>`", you loop through EITHER your vector of DrawComponents or your vector of MoveComponents, and use the ent\_id from those components to find the corresponding component from the other component vector that you're not looping through by using something like std::upper\_bound.

An alternative to a Component base class containing the Entity ID would be to use an associative vector class, like Łukasz Czerwiński's AssocVector or Loki's. These guarantee memory contiguity while allowing you to retrieve your components by a key.

# Answer
> 2 votes
## 1. component types

I am using component bit mask as well and the mask size is only 64 now, maybe too small, but I don't think it would grow to 1000 in any case, that's too much for the types of components.

The point of ECS is that you can create unlimited types of "entity" with provided components, so with N types of components you can have a maximum of (CN1 + CN2 + ... + CNN) types of entities, and that's really many.

The entity has a component bit mask to identify which types of component it has. Like `bitset<64> componentTypes`, and the value could be `1100...` which indicates the entity contains type `0` and `1` of components.

## 2. contiguous memory

I think the contiguous memory is focused on components not on entities, i.e.

```
vector<DrawComponent> c1;
vector<MoveComponent> c2;

```

should be contiguous, and that's guaranteed by `vector`.

The entity ID is not the index of component `vector`, if you want to get certain component of your entity, you have to find it sequentially in the `vector`, so I keep the component vector sorted by entity id.

## 3. system

`System<Draw,Move>` wants to filter all entities who have at least `Draw` and `Move` component, so the system itself should have a mask (`bitset`) (same size as entity's bit mask) as well.

The system also has a list of entity (or entity id) which records the filtered entites. (in your case, that's the `vector<Entity> draw`)(so this list should belong to a system)

When an entity add a component, the entity updates its component bit mask, and then try to match the masks with all systems; when a match occurs, that system register the entity onto its list, then the filtering is done.

On the next system's update, the system check the list, get the first entity id, then get the components from `c1`, `c2` by this id, update those components, then move to the next entity id and repeat.

---
Tags: architecture, entity-system, entity-component
---


# Question
Title: Saving Scores on iOS and Android Devices using MonoGame
Quick question, what is the best way to save a game score in a mobile device (iOS and Android) using MonoGame (example would be a Flappy Bird score).

You can also list ways and approaches of saving scores in mobile devices and discuss the pros and cons of each one.

Just like in Android using Java, there are options like using SQLite, Shared Preferences, external and internal storage.

# Answer
> Quick question. What is the best way to save a game score in a mobile device (iOS and Android) using Monogame (example game Flappy Bird score)?

Well there is only 1 way to do it with MonoGame and that is using the IsolatedStorageFile class. All the other approaches you mentioned do not use MonoGame and if you are looking for any Mono solution you should specify so.

**Getting an instance of the class. This works the same in MonoGame as it does for XNA.**

```
#if WINDOWS
    IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForDomain();
#else
    IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
#endif

```

**How to read data from a file.**

```
protected override void OnExiting(object sender, System.EventArgs args)
{
    // Save the game state (in this case, the typed text).
    IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();

    // open isolated storage, and write the savefile.
    IsolatedStorageFileStream fs = null;
    fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Create);
    if (fs != null)
    {
        // just overwrite the existing info for this example.
        fs.WriteByte(gameState); // a single byte
        if ((typedText != null) && (typedText.Length > 0))
        {
            fs.Write(System.Text.Encoding.UTF8.GetBytes(typedText), 0, typedText.Length);
        }
        fs.Close();
    }

    base.OnExiting(sender, args);
}

```

**How to write to a file.**

```
protected override void Initialize()
{
    gameState = 0;

    IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();

    // open isolated storage, and write the savefile.
    if(savegameStorage.FileExists(SAVEFILENAME))
    {
        IsolatedStorageFileStream fs = null;
        try
        {
            fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Open);
        }
        catch (IsolatedStorageException e)
        {
            // The file couldn't be opened, even though it's there.
            // You can use this knowledge to display an error message
            // for the user (beyond the scope of this example).
        }

        if (fs != null)
        {
            // Reload the last state of the game.  This consists of the UI mode
            // and any text that was typed on the keyboard input screen.
            byte[] saveBytes = new byte[256];
            int count = fs.Read(saveBytes, 0, 256);
            if (count > 0)
            {
                // the first byte is the mode, the rest is the string.
                gameState = saveBytes[0];
                if (count > 1)
                {
                    typedText = System.Text.Encoding.UTF8.GetString(saveBytes, 1, count - 1);
                }
                fs.Close();
            }
        }
    }

    base.Initialize();
}

```
> 1 votes

# Answer
I'm using xamarin on windows If you want to keep it simple this worked for me for reading 1 number:

```
IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForDomain();
    int high_score;
if (savegameStorage.FileExists("high_score.txt"))
        {
            IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream ("high_score.txt", FileMode.OpenOrCreate,FileAccess.Read);
            using (StreamReader sr = new StreamReader (isoStream))
            {
                high_score = int.Parse (sr.ReadLine ());
            }
        }
        else
            high_score = 0;
    }

```

And this for saving , when you die:

```
if (player1.score > high_score)
                {
                    IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream ("high_score.txt", FileMode.OpenOrCreate,FileAccess.Write);
                    using (StreamWriter sw = new StreamWriter(isoStream))
                    {
                        sw.Flush ();
                        sw.WriteLine (player1.score.ToString ());
                    }

```
> 0 votes

---
Tags: monogame, mobile, storage, scoring, xamarin
---


# Question
Title: Why it’s recommended to keep global variable initialization and the objects’ constructors very simple (C++)?
Considering game-development?

I have this question in a gamedev quiz and I wonder what to answer.

Any clues?

# Answer
> 1 votes
Main problem with global variables in C++ that compilers don't guarantee initialization order. Let's you have 2 global variables with constructors:

```
global_A g_a;
...
global_B g_b;

...

global_A::global_A()
{
    this->test = 5; // test is int
}

...

global_B::global_B()
{
    printf( "%d", g_a.test );
}

```

If initialization order of `g_a` and `g_b` is undefined, then sometimes you can get situation when constructor of `g_b` would be called before `g_a` and variable `g_a.test` would be undefined. The worst thing - sometimes it works well.

Note, if global variables in same source file then you may be sure that order will be same as global variables are defined. But using global variables with dependencies is bad practice because other people who will work with this code may not know about dependency between global variables and got troubles if move one of global variable to other file.

# Answer
> 0 votes
Global's initialization happens before `main()` gets called and the UI setup stuff happens if that takes too long then the game window may take a long time to show up.

Common rule in UX (user experience) is to react to user input as fast as possible even if the result is not yet available.

This is a common setup for games as they will show a semi-static screen for some time as they load all the needed assets before showing the main menu.

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


title: Slick2D Graphics Misaligned

text:
# Question
Title: Slick2D Graphics Misaligned
I'm working through a game in Slick2D and am now focusing on a lot of the graphical end. It's going pretty well other than a couple of issues with alignment. An image illustrating both of these issues here: Firstly, the background. I have 2 Entity objects containing coordinates, velocity, and an image for the background. Both contain the same image (1600x600). For the first, `x=0` and for the second, `x=1600`. They both move to the left at a speed of 1 pixel per frame. No matter if I make the offset smaller (like 1580), I am still left with a gap showing the background colour. I've put the two images together in photoshop and they blend together, so it's not an issue with the image. Here is some relevant code:

```
//in init block
Entity bg1 = new Entity("background",1600,600);
        bg1.setXVelocity(BACKGROUND_VELOCITY);
        Entity bg2 = new Entity("background",1600,600); //a second one is needed for endless background
        bg2.setXVelocity(BACKGROUND_VELOCITY);
        bg2.setX(1600);
        backgroundList = new ArrayList<Entity>();
        backgroundList.add(bg1);
        backgroundList.add(bg2);
...
//in update loop, running every frame
for (Entity bg : backgroundList){
    bg.update();
    if (bg.getX() < -1*bg.getSpriteWidth()){
        bg.setX(1600);
    }
}

```

In other words, what I expect my code to do is have both images move left one pixel each until the left image reaches -1600 (`-1*bg.getSpriteWidth()`), at which point the right image will be at 0, and with a width of 1600 the first image would be moved to 1600. This is, at least, how I expect my code to work. `bg.update()` calls a method which adjusts the position based on the velocity given, so it will move x backward by 1 each time for both backgrounds.

Secondly, the misaligned walls. As you can see in the image, the walls on the right are perfectly aligned. They move left together at the same velocity in the same way as above. For some reason, however, as the walls pass the mid-way mark (where the fish is), the upper wall's velocity slows for a slight second which misaligns it with the lower wall (though the velocity returns after and they stay that constant distance apart). I actually have found the code causing this (when commented out it stops), but I cannot see why it would do such a thing. The values still remain correct, but the graphical output is distorted.

```
for (int i = 0; i < wallList.size(); i++) {
    Wall wall = wallList.get(i);
    wall.update();
    if (wall.getX() < -1 * wall.getImageWidth()) {
        wallList.remove(i);
    }
}
...
if (wallList.get(wallList.size() - 1).getX() < WIDTH - DISTANCE_BETWEEN_WALLS) {
    createWalls();
}

...
private void createWalls() {
    Wall w1 = new Wall();
    Wall w2 = new Wall();
    int yPos = rand.nextInt(400) + 50 - w1.getImageHeight();
    w1.setLocation(WIDTH, yPos);
    w1.setXVelocity(WALL_VELOCITY);
    w1.setVisible(true);
    w2.setLocation(WIDTH, yPos + 11 * player.getImageHeight() / 3 + w2.getImageHeight());
    w2.setXVelocity(WALL_VELOCITY);
    w2.setVisible(true);
    wallList.add(w1);
    wallList.add(w2);
}

```

It's the `wallList.remove(i);` line that is causing this offset to happen. When I remove the line, the walls stay aligned as intended. Any ideas? Are these just imperfections of Slick2D? Perhaps there is a better way for me to do these things?

# Answer
```
for (int i = 0; i < wallList.size(); i++) {
    Wall wall = wallList.get(i);
    wall.update();
    if (wall.getX() < -1 * wall.getImageWidth()) {
        wallList.remove(i);
    }
}

```

If you remove a wall then the next wall at index i but you skip it.

Decrement i after the remove or use an iterator based loop:

```
for (Iterator<Wall> i = wallList.iterator(); i.hasNext(); ) {
    Wall wall = i.next();
    wall.update();
    if (wall.getX() < -1 * wall.getImageWidth()) {
        i.remove();
    }
}

```
> 0 votes

---
Tags: java, graphics, lwjgl, slick
---


# Question
Title: How to change animation view in Unity3D?
How can I change the animation view in Unity3D? I have only some "dot", but I want to view some curve! How do I change this?

What I have:

And what I want:

(image from the documentation of Unity3D)

# Answer
The "dot" view is called a "Dopesheet"

From the Unity animation curves docs, "Click the Curves button at the bottom left of the window to change to the Curve view."

You can see the Curves button just beside the bottom scroll bar in this image from the Unity Dopesheet docs:
> 0 votes

---
Tags: unity, curves
---


# Question
Title: In 2D, how do I efficiently find the nearest object to a point?
I have a sizable game engine and I'd like a feature for finding the nearest of a list of points.

I could simply use the Pythagorean theorem to find each distance and choose the minimum one, but that requires iterating through all of them.

I also have a collision system, where essentially I turn objects into smaller objects on a smaller grid (kind of like a minimap) and only if objects exist in the same gridspace do I check for collisions. I could do that, only make the grid spacing larger to check for closeness. (Rather than checking every single object.) However, that would take additional setup in my base class and clutter up the already cluttered object. Is it worth it?

Is there something efficient and accurate I could use to detect which object is closest, based on a list of points and sizes?

# Answer
> 41 votes
The problem with a quad/octree in nearest-neighbor searches is that the closest object may be sitting right across the division between nodes. For collisions, this is okay, because if it's not in the node, we don't care about it. But consider this 2D example with a quadtree:

Here, even though the black item and green item are in the same node, the black item is closest to the blue item. ultifinitus' answer can only guarantee the nearest-neighbor only every item in your tree is placed in the smallest possible node that could contain it, or in a unique node - this leads to more inefficient quadtrees. (Note that there are many different ways to implement a structure which could be called a quad/octree - more strict implementations may work better in this application.)

A better option would be a kd-tree. Kd-trees have a very efficient nearest-neighbor search algorithm you can implement, and can contain any number of dimensions (hence "k" dimensions.)

A great and informative animation from Wikipedia:

The biggest problem with using kd-trees, if I recall correctly, is that they are more difficult to insert/remove items from while maintaining balance. Therefore, I would recommend using one kd-tree for static objects such as houses and trees which is highly balanced, and another which contains players and vehicles, which needs balancing regularly. Find the nearest static object and the nearest mobile object, and compare those two.

Lastly, kd-trees are relatively simple to implement, and I'm sure you can find a multitude of C++ libraries with them. From what I remember, R-trees are much more complicated, and probably overkill if all you need is a simple nearest-neighbor search.

# Answer
> 19 votes
`sqrt()` is monotonic, or order-preserving, for non-negative arguments so:

```
sqrt(x) < sqrt(y) iff x < y

```

And vice versa.

So if you only want to compare two distances but are not interested in their actual values you can just cut out the `sqrt()`-step from your Pythagoras-stuff:

```
pseudoDistanceB = (A.x - B.x)² + (A.y - B.y)²
pseudoDistanceC = (A.x - C.x)² + (A.y - C.y)²
if (pseudoDistanceB < pseudoDistanceC)
{
    A is closest to B!
}
else
{
    A is closest to C!
}

```

It's not as efficient as the oct-tree thing, but it's easier to implement and does bump up the speed at least a little bit

# Answer
> 11 votes
You have to do spatial partitioning, in this case you make an efficient data structure (usually an octree). In this case each object is inside one or more spaces (cubes) And if you know in which spaces you are you can look up O(1) which spaces are your neighbors.

In this case the nearest object can be found by first iterating over all objects in your own space looking to which one is the closest there. If there is no-one there you can check your first neighbors, if no-one is there you can check their neighbors, etc...

This way you can easily find the nearest object without having to iterate through all objects in your world. As usual this speed gain does require a bit of bookkeeping, but it's really useful for all kinds of stuff so if you have a big world it's definitely worth implementing spatial partitioning and an octree.

As usual, see also the wikipedia article: http://en.wikipedia.org/wiki/Octree

# Answer
> 1 votes
Maybe try organizing your spatial data in an RTree, which is kind of like a btree for stuff in space and allows queries like "nearest N neighbors" etc... http://en.wikipedia.org/wiki/Rtree

# Answer
> 0 votes
Here is my java implementation to get the closest one from a quadTree. It deals with the problem dlras2 is describing:

I think the operation is really efficient. It is based on the distance to a quad to avoid searching in quads further way then the current closest.

```
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

public T getClosest(float x, float y) {

    Closest closest = new Closest();
    getClosest(x, y, closest);

    return closest.item;
}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

protected void getClosest(float x, float y, Closest closestInfo) {

    if (hasQuads) {

        // we have no starting point yet
        // so get one
        if (closestInfo.item == null) {
            // check all 4 cause there could be a empty one
            for (int i = 0; i < 4; i++) {
                quads[i].getClosest(x, y, closestInfo);
                if (closestInfo.item != null) {
                    // now we have a starting point
                    getClosest(x, y, closestInfo);
                    return;
                }

            }
        }
        else {

            // we have a item set as closest
            // we should check if this quad is
            // closer then the current closest distance
            // let's start with the closest from index

            int closestIndex = getIndex(x, y);

            float d = quads[closestIndex].bounds.distToPointSQ(x, y);

            if (d < closestInfo.dist) {
                quads[closestIndex].getClosest(x, y, closestInfo);
            }

            // check the others
            for (int i = 0; i < 4; i++) {
                if (i == closestIndex) continue;

                d = quads[i].bounds.distToPointSQ(x, y);

                if (d < closestInfo.dist) {
                    quads[i].getClosest(x, y, closestInfo);
                }

            }

        }

    }
    else {

        for (int i = 0; i < items.size(); i++) {

            T item = items.get(i);

            float dist = distSQ(x, y, getXY.x(item), getXY.y(item));

            if (dist < closestInfo.dist) {
                closestInfo.dist = dist;
                closestInfo.item = item;
                closestInfo.tree = this;
            }

        }
    }

}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

class Closest {

    QuadTree<T> tree;
    T item;
    float dist = Float.MAX_VALUE;

}

```

---
Tags: c++, 2d, algorithm, vector, picking
---


# Question
Title: How can I build Minecraft-style light propagation without recursive functions?
This question is more about expanding on an answer posted for an old but similar question.

Part of the answer says this:

> You simply fill the sunlight from the top to the bottom, every layer is gathering light from neighbor voxels in the previous layer with attenuation. Very fast - single pass, no lists, no data structures, no recursion.

I actually am having an easier time understanding how you would flood fill light for point lights. But doing so for sunlight, in one pass with no recursions, I still can't understand how it is done step by step.

Specific questions I would like to know about this:

Do you compare lighting of neighbor voxels only to the 4 cardinal directions, or do you check the up and down neighbors too?

If you don't store data structures for the lighting algorithm, how do you check for voxels that are already visited?

If there was a diagram explaining a step by step process of a single-pass light propagation that would be helpful. It seems like it would be easier on performance than casting several rays from each voxel to see if it hits light.

# Answer
I can't think of a way to do it wherein you don't revisit nodes...and this is because of the pseudo-radiosity created by the light propagation. In essence, you could have a node closer to one "light source" than another, but lit by both. If you only visit it once, you might wind up with the incorrect lighting value. *However*, this is only if you are allowing light to "wrap around" corners and such.

But you can indeed perform the propagation without using recursive functions.

In such a case, I did the following:

1. Create a light 'mask' starting at the top, full light value for empty voxels, 0 for solid ones
2. As you push down from the top, set the lighting values of empty voxels according to the mask
3. If a solid voxel is encountered, set the value of the mask at that position to 0
4. For empty voxels encountered at the edges of the mask, set those to max light value - 1 and add them to the queue
5. Repeat 2, 3 and 4 until the bottom is reached.

After setting the initial lighting values, you then:

1. Pop the top off the queue
2. Check it's neighbors (Top, Bottom, Left, Right, Front, Back) light values
3. Set neighbors with light values LESS THAN the current value - 1 to the current value - 1 and add them to the queue
4. Repeat until queue is empty

This resulted in an average light calculation time of 200ms (on a mid-range desktop) for a 256x256x128 voxel map using Google Chrome. Using a queue also eliminates the overhead of a function call (do **not** underestimate the overhead of function calls).

I will try to migrate my example code over to this answer, but for now you can see it in action here. *Requires a browser that allows passing of arraybuffers from web workers.*
> 2 votes

# Answer
The assumption is that like Minecraft, you are only doing lighting that runs perpendicular to sea level, i.e. straight up/down as if the sun is always at midday... you only increase the relative contrast between sunlit and shadowed voxels from dawn to midday, and reduce it from midday to dusk. But the raycast angle is always directly downward, no matter the time of day.

> Do you compare lighting of neighbor voxels only to the 4 cardinal directions, or do you check the up and down neighbors too?

Down (or up) are all that's required. All you are doing is casting rays vertically from top to bottom of the voxel space. Vertical attenuation is only needed once you've cast below the ground level (however you care to define that), i.e. into a hole in the terrain, such that you can still see the sky by looking straight up but are now below ground. Horizontal propagation / attenuation might only be needed to soften shadow edges beneath overhangs, floating islands and so on, where sunlight is otherwise blocked and may only infiltrate in by ambient lighting from sunlit, horizontal neighbours.

> If you don't store data structures for the lighting algorithm, how do you check for voxels that are already visited?

You don't have to: It's a while loop running on each voxel column from sky to ground (or vice versa), i.e. till the sun-ray hits a solid voxel. Just like any loop, of course you will only run once over each element - whatever's past, is past. You don't need to check for what is already visited. If you are storing your voxels as columns like Minecraft does, then of course this is made even simpler because you can rapidly see where ground ends and sky begins. RLE compression allows for even fewer iterations.
> 2 votes

---
Tags: lighting, voxels
---


# Question
Title: How can I manage the deceleration of units so that they arrive on-target?
When I first started trying to set up my air units' movement in my RTS game, I thought it was going to be easy with simple Euler method linear acceleration. This was far from the case as the ship would have to slow to a halt on exactly the target destination, as well as properly compensate after a sharp turn.

How would I decelerate my unit exactly onto the target destination and properly compensate for changed destinations while still factoring in the current velocity in a 2D simulation (Positions and velocity stored in 2D vectors)?

StarCraft 2 does this well, and I'd like to arrive at a similar effect. I want something like shown here. Acceleration can be seen at 0:20. Turning and maintaining momentum can be seen at 1:25. Deceleration can be seen at 1:55. (Find these times in recent comments of the video).

Note: I'm using a lockstep model and frame rate can be either 5 or 10 per second depending on players' computer abilities.

# Answer
I found the answer thanks to this essay Daniel posted. It's something like this (from page 10):

```
closing_distance = max_speed * 2;
desired_velocity = normalize (position - target) * max_speed
if (distance < closing_distance)
    desired_velocity *= (distance / closing_distance);
steering = desired_velocity - velocity
ApplyForce(steering)

```
> 2 votes

---
Tags: physics, rts
---


# Question
Title: Entity Component Architecture and Scripting without using threads
I am working on a small game engine for practicing purpose and also for putting some of my ideas into action. What I have so far is a couple of systems for rendering, sound etc. The next step is to put all these things together. I already looked into entity component systems, in particular the following article: http://www.gamedev.net/page/resources/\_/technical/game-programming/implementing-component-entity-systems-r3382

I think that this approach would suit my needs to a certain level, but I also would like to implement the game logic itself inside scripts. I came up with a slightly different approach:

The rendering, sound, physics, input and simulation systems perform actions on the data, which is basically a level object and a list of entities (for technical reasons I have to distinguish between entities and level geometry). The particular systems only perform actions on those entities which match their criteria (e.g. the physics system only handles entities with a bounding volume). In my approach the systems do not directly implement behavior. Instead they are either creating output (rendering, sound) or input (physics, input). The simulation system manages the scripts which may be assigned to entities. The script of an entity consists of two parts, first the initialization code which is executed when the entity is added to the scene, and second the code which is executed once per frame (or less, depending on whether the code contains a wait-statement). Additionally every entity may implement event handlers which are called whenever the input or physics system throws an event (e.g. a CollisionEvent, KeyDownEvent etc.). Entity scripts may define parameters, which can be modified inside the level editor.

My question is, whether this architecture has some severe weaknesses. Since I want to avoid threading, my scripts will be scheduled by the simulation system, which lead me to the restriction that an entity script is called once per frame (which means that loops should be avoided, since basically everything already is inside a big loop). Is this reasonable or is there any better way?

# Answer
> 1 votes
## Input/Output

What's the idea in collecting input and outputs? Do you filter it somehow? Sort? That may be costly to do so for every frame. And disadvantage for it would be to have implement every system in two/three places:

1. sorting/filtering inputs
2. sorting/filtering outputs
3. reading inputs and generating outputs (the system itself)

Implementation is scattered.

But I could misunderstand you. So the *second* thing I could think of is a hope to always have input/output. Systems are made to change state of entity components so it's all about modifying data. I'm not sure whether it would be easy for you to implement such output as DataChangeOutput (depends on programming language) but it would cost the CPU anyway.

## Events

I'm not sure where do you handle your events. But seeing this statement

> every entity may implement event handlers which are called whenever the input or physics system throws an event

looks dangerous. I believe that system should handle events in proper moment. Having events the way you described may lead into some incosistences due to order of call. It's best to collect events and handle them in proper time in the system queue. That way I don't see a reason of entities handling events.

## Input, output - objects

This doesn't seem as a hard point but did you consider to implement Object Pools? Garbage collector may kill your performance very quickly in such architecture.

## Scripts and parameters

Parameters in scripts - I feel that's approach taken from Unity3D. Some people believe it's good but the thing is that it's not `ECS` at all. Parameters are data and data should be put into Components (the `C` part). Parameters not fitting into components should be put somewhere else in my opinion, especially if those are static parameters.

But still, having a Script component is a pretty straightforward approach and still puts into ECS.

## Custom implementation?

I know that's you may dislike it but I suggest you to try some ECS frameworks before implementing your own. It's a hard work and when you modify the whole ideas to your current likes, you may be in a place in the future when you have many incosistences. It's best to try already made things first to know how does it taste.

If you're asking for frameworks: artemis-odb or Ash. I prefer the first one but it's Java.

# Answer
> 0 votes
In one word: eventloop.

In more than one word:

event loops allow you to have a complex runtime behaviour with multiple "simultaneous" events, timers, signals and much more without the use of more than one thread.

They are used among other things in microcontrollers.

The open-source GUI library called Qt5 is based on eventloops. In fact, I am pondering why not more games use Qt5 for that very reason (and the fact that it has excellent high-performance, industry tested, cross-platform support for OpenGL/OpenGL-ES, networking, threads, input, media playback, ....

# Answer
> 0 votes
Why not invert the relationship with the simulation system and allow it to be a hookable option in your entity design?

For example, you have a `LogicComponent` that essentially allows you to associate a specific script (or even a list of scripts) to a given entity. During the initialization of your logic component, it runs an init method from your script and during various update phases, calls the appropriate script function.

Additionally, other components in your framework could have a place where you can either place scripting code snippets that are to be executed for various conditions or allow your components to reference other scripts that can be fired at specific points. These scripts can be inspected during load and appropriate handlers linked to the event loop based on some set API.

For example, your `PhysicsComponent` may allow you to associate a script that has an event handler for collision. Inside this handler which gets called when a collision is detected, you can implement whatever custom behavior is needed.

While you are arriving at a similar place as your proposed design, the beauty here is that you've now decoupled your script logic into smaller snippets enabling you to reuse as well as modify and affect larger volumes of entities across the board when a change is needed.

# Answer
> 0 votes
I use coroutines. Coroutines are just functions which, instead of `returning` and exiting, `yield` while maintaining their state. For example, here is a python coroutine which counts up from 1 to N:

```
def count(num):
   for i in range(1, num):
       print i
       yield RUNNING

   yield SUCCESS

```

Now, to put a coroutine into your game loop, you simply have to do something like this:

```
def tickCoroutines():
    for routine in coroutines:
        status = routine.next()

```

I've also had a lot of success at combining coroutines with behavior trees. Coroutines give you several advantages over simple `tick` or `update` functions:

* Allow you to loop without blocking
* Allow you to store local state and garuntee it will still be there when you come back
* Allow you to run several of them in parallel
* Allow you to cancel, resume, or restart depending on the return value

They also have advantages over threads:

* Generally lighter-weight
* Require no locking
* Deterministic update order

However, depending on your language, implementing a coroutine might be slightly more difficult. Python supports coroutines through generators. C# and C++ support them through iterators. Other languages might require some glue to get it to work.

---
Tags: architecture, entity-system, scripting, entity-component
---


# Question
Title: Why does Resources.Load cause a CastException in this case?
I am doing this:

```
string fontName = "freespin_big";

TextAsset xml = Resources.Load<TextAsset>(fontName);
Texture2D image = Resources.Load<Texture2D>(fontName);

Font font = Resources.Load<Font>(fontName);
if (font == null)
{
    font = new Font();
    AssetDatabase.CreateAsset(font, "Assets/Resources/" + fontName);
}

```

In Resources, we have freespin\_big.png and freespin\_big.xml. I am planning to import the png and xml and create a font. So I check if the font object is there, if not create it.

But I get this error if the font does not exist yet:

> InvalidCastException: Cannot cast from source type to destination type.

If I try to do this:

```
Font font = Resources.Load<Font>("blorg");

```

Where no files are named "blorg", I get null as I expect.

Shouldn't Resources.Load return null if it finds no *fonts* with the right name?

# Answer
> 1 votes
`Font font = Resources.Load("fontname",typeof(Font)) as Font;`

Using this form, instead of the form with in it, works.

---
Tags: unity
---


# Question
Title: Do I really need a render() method in the game loop if the view subscribes to the models?
For a game that I'm working on, we've followed the MVC paradigm. However, in classic MVC, the view subscribes to the model and when the model updates it informs the view. We've implemented this as an Observer pattern so the model doesn't really have a direct link to the view, to reduce coupling.

Now, given such a configuration, is the call to `render` in the game loop really necessary?

That is,

```
while(true){
 update(); //mostly called via user interaction
 render(); //necessary if called by model?
}

```

The game loop is more like:

```
while (game_is_running){
 getUserInput();//This updates models which in turn asks views to render the changes.
}

```

Is there really an advantage to having render in the game loop? Is it acceptable to have the models inform the view to render themselves? What's the preferred way to go about this?

# Answer
> 4 votes
It's not *necessary*, in the sense that you can make it work. But your approach is somewhat... awkward.

In your approach, the pre-render and post-render work (such as clearing the appropriate render targets, and then presenting the final frame the screen) has to be done before and after `getUserInput()`:

```
while (game_is_running){
  prepareForRender();
  getUserInput();
  completeRender()
}

```

After all, that work has to happen at *some* point and your only other approach here is to track whether or not you've started it yet and then make the views that *happen* to be the first and last to draw make the appropriate calls. This is ugly.

So ultimately in this approach you have one giant conflated frame that includes both input processing, logic updates, and render commands in an unstructured order. This is both hard to follow, hard to profile, and potentially extremely problematic as the complexity of your rendering increases (for example, if you don't have an order-independent transparency implementation you have to sort transparent things back-to-front and make sure they render in that order to get correct transparency; how is that bulk operation done in response to individual model updates?).

It also raises some serious questions about the viability of the approach under concurrency scenarios.

I wouldn't advise this approach at all. If you really want to adhere that closely to the MVC pattern, I'd make the "rendering" that your views do in response to model updates simply be the preparation of any bookkeeping that needs to eventually be consumed by the renderer when you later call `render()`. Things like making sure any visually-impacting properties that changes (like a unit going to a "critical health" state) are reflected in the data the renderer will eventually consume (like the "tint" color for that particular unit's shader).

# Answer
> 1 votes
Lets call everything that *happens* inside a game an event for the duration of this answer. The events that occur in a game are not "observing" the game model. They happen every x frames.

Rendering for instance happens every frame and the view doesn't need to care if the model changed or not since the previous frame. It normally will render every frame. This is not a utility type thing where you possibly don't need to render if no changes happened. This is a game, a resource hungry piece of software that uses every bit of power the computer can offer normally.

The model doesn't need to wait for input to change. The model is constantly changing because time is passing by. It could be creatures moving around or simply a clock that is ticking down.

The reason the thought process is wrong when using Observers to render a game is that rendering happens each and every frame. The game model is updated every frame. You check for input every frame. Games respond because input changes the state of the game but they continue to tick and take action when no input is given.

You need to think about the tasks the game may need to do:

```
 // Input
 1. Accept input from the users' peripherals.

 // Model state changes
 2. Comprehend the input and convert it into game commands or state changes.
 3. Compute movement, collisions, physics.
 4. AI.

 // Output
 5. Play sounds.
 6. Rendering.

 // Networking
 7. Communicate with the server or peers.

```

The models are important but all the processes will likely need to be handled every frame. If so then why trigger them with an observer? Why connect them conceptually to input? Why mix all the different types on manipulations that are done on the model with one another?

---
Tags: architecture, rendering, game-loop, design-patterns
---