# Question
Title: How to make my installer install XNA framework and .NET 4.0
I have made a simple Monogame game. Right now I am using this installation-package maker: http://installforge.net/

Currently my installer only installs my "game". (All the output files generated by the build)

However I also want it to install the XNA framework 4.0

https://www.microsoft.com/en-us/download/details.aspx?id=20914

and the .NET Framework 4.0

http://www.microsoft.com/en-us/download/details.aspx?id=17718

How would I do that?

# Answer
Rather than using Forge as my installation package maker I decided to use Inno Installer in the end.

http://www.jrsoftware.org/isinfo.php

In Inno installer you can include the .NET installer in your bundle of files and then make a command to run the installer.
> 1 votes

# Answer
MonoGame based games do NOT require the XNA framework to run. The XNA namespaces in your MonoGame code are named as such for compatibility purposes.

In fact, the lat4est versions of MonoGame also no longer require XNA at development time.

Please download the latest MonoGame build: http://www.monogame.net/downloads/

To force an install of the .NET Framework, you have to set it as a dependency in your installer package, and you may need to download and link to the .NET 4.0 runtime installer.
> 2 votes

---
Tags: xna-4.0, monogame
---


# Question
Title: unity3d - Fire bullet using AddForce is very slow
This is a top-down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel.

```
void Fire () {

        float speed = 80;

        GameObject projectile = Instantiate (bullet, transform.position, transform.rotation) as GameObject;

        projectile.GetComponent<Rigidbody>().AddForce(transform.forward * speed);
        coolDown += Time.time;
    }

```

I also tried this but in this case the bullet always moves in a fixed direction (North) :

```
projectile.GetComponent<Rigidbody>().velocity = Vector3.forward * speed;

```

`Bullet` is an empty object and the actual bullet is it's child ( did that to overcome a rotation issue ), the problem is nomatter how high I turn up the speed the bullet travels very very slow. Both the parent and the bullet have `Rigidbody`.

# Answer
> 1 votes
`Force = Mass * Acceleration`, so in order to accelerate an object to 80 you'd have to apply a force of `80 * Mass` for one second.

If you want to instantly accelerate the object to a set speed, you should pass `ForceMode.VelocityChange` into `AddForce`. That will instantly change the object's velocity to what you want.

```
projectile.GetComponent<Rigidbody>().AddForce(transform.forward * speed, ForceMode.VelocityChange);

```

---
Tags: unity, bullet-physics
---


# Question
Title: How to play more than one background song in XNA?
The current tutorial I am using to play background songs only allows me to play one song throughout the entire game.

Link to tutorial --\> http://rbwhitaker.wikidot.com/playing-background-music

I want to have multiple songs where after one song is finished playing another random song will be selected and played.

How would I do that?

Also I would not liked to get involved in XACT.

# Answer
For checking if a song has finished playing, do this:

```
if(MediaPlayer.State != MediaState.Playing
   && MediaPlayer.PlayPosition.TotalSeconds == 0.0f){
  //start playing new song
}

```

For starting a random song, you should have a list of songs:

```
public List<Song> bgm = new List<Song>();

```

Then playing a random one could be like this (if your list is not empty):

```
MediaPlayer.Play(bgm[rand.Next(bgm.Count)]);

```

Keep in mind that selecting a random song like this will not guarantee that the same is not played multiple times one after another. You should shuffle your list of songs for that and selecting the next song each time.
> 0 votes

---
Tags: xna-4.0, sound
---


# Question
Title: OpenGL Slow Rendering Procedures . glDrawArrays
Hello i would like to present my problem here. At the moment i have a scene with about 250 trees , 100 ferns , a player model and a custom generated terrain (from height map). For the past few days i was searching about batch rendering in OpenGL which gave me some ideas about how i can render some objects (similar to batch rendering , but in my own fashion). Bellow are simple examples of my render functions which are executed each frame. I came to the conclusion that glDrawArrays takes up most ms/frame to execute(for the terrain render this line takes up about 8 ms/frame). Uploading to shaders or switching buffer bindings does affect slightly (~0.3 ms)

In Main creating Example Models can look something like (&TreeData is a reference to a object that contains model's data already bound to a certain vbo - i use 1 vbo to store all vertex data(normals,position,texcoords). So TreeData will occupy vboID 1 , FernData will occupy vboID 2 and so on. Later in the render i just rebind to the correct vbo ID and directly render.

```
vector<Model*>Trees
for(number of trees)
Trees.push_back(new Entity(&TreeData, ShdrBasic));
Trees.back()->Translate(vec3(randomX, Terrain1->getTerrainData()->getHeightOfTerrain((float)randomX, (float)randomY), randomY));

```

And the render function below which takes vector list of models and renders them all.

```
void EntityRenderer::RenderArray(vector<Model*> Models)
{
GLuint model_vertex_number = Models[0]->getModelData()->getVerticesSize() / sizeof(vec3);
if (Models[0]->getModelData()->getTransparency()) Models[0]->disableCulling();
glBindBuffer(GL_ARRAY_BUFFER, Models[0]->getModelData()->getVboID());
Models[0]->getActiveShader()->StartShader();
Models[0]->getActiveShader()->EnableVertexAttribArray();
Models[0]->ShaderStaticLoad();
for (int i = 0; i < Models.size(); i++)
{
    Models[i]->ShaderDynamicLoad();
    glDrawArrays(GL_TRIANGLES, 0, model_vertex_number);
}
Models[0]->getActiveShader()->DisableVertexAttribArray();
Models[0]->getActiveShader()->StopShader();
glBindBuffer(GL_ARRAY_BUFFER, 0);
Models[0]->enableCulling();
}

```

This simple array render function renders objects (from the same type and same data , from vector list) Shader Dynamic Load -\> contains only transformation matrices: translate scale and rotate. As for the Static Shader Load -\> contains vertex data, some uniform variables .. etc. As far as logic and sanity tells me this function should be relatively good in terms of performance since most of the operations are executed per frame rather than per object. The problems come when i try to render about 500+/- objects (trees + ferns) , i have a millisecond per frame function which tells me that it takes about 10 ms for the scene to render, if i add terrain to the picture the ms/frame goes up to 20 ms/frame. (And for a fact i know that 33~ ms/frame is about 30 fps)

Terrain Renderer Function. Terrain generated from height map. This terrain render functions takes up about 7-9 ms/frame to render

```
void TerrainRenderer::Render(Terrain* TerrainToRender)
{
glBindBuffer(GL_ARRAY_BUFFER, TerrainToRender->getTerrainData()->getVboID());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, TerrainToRender->getTerrainData()->getIboID());
TerrainToRender->getActiveShader()->StartShader();
TerrainToRender->getActiveShader()->EnableVertexAttribArray();
TerrainToRender->LoadToShader();
glDrawElements(GL_TRIANGLES, TerrainToRender->getTerrainData()->getIndicesSize()/sizeof(GLuint), GL_UNSIGNED_INT, NULL);
TerrainToRender->getActiveShader()->DisableVertexAttribArray();
TerrainToRender->getActiveShader()->StopShader();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

My Question is: Am i doing the rendering correctly , is it a problem on my side , or my PC's. I have some suspicions that my Graphics Card or/and my CPU are probably not good enough.I need to test that on other configurations. The program currently uses steady 30-33 MB of RAM during run Time. Supported OpenGL version 4.4. Drivers up to date PC Specs: CPU: AMD A8-5600K APU with GPU: AMD HD Graphics 7560D + 6500 Dual Graphics. (OFF TOPIC: some days ago i downloaded a simple 2d engine from youtube which handles batch rendering with 56k Sprites, according to the video that person is rendering those 56k sprites with ~4000 FPS, i render them with ~20-25 FPS, thats when i started to suspect my configuration)

# Answer
If anyone is interested or stumbles upon such problem. I implemented complete batch rendering. Meaning that now i can batch render objects from the same type with one draw Call. Further more i am working on implementing a LOD algorithm for the terrain and also implementing Frutrum Culling to limit maximum objects rendered per frame. This results in huge performance boost.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: How to use multiplication operation in game render delta time?
We are using **delta time** like this:

```
private static final float SPEED = 200f; // Moving pixels in one second

@Override
public void render(float delta) {
    myObject.vx += SPEED * delta;
    myObject.vy += SPEED * delta;

    myObject.move();
}

```

So I am using this update method to apply friction on my object:

```
private static final float FRICTION = 0.98f;

@Override
public void render(float delta) {
    //...

    myObject.vx *= FRICTION;
    myObject.vx *= FRICTION;

    myObject.move();
}

```

I know this is **wrong**:
`myObject.vx *= FRICTION * delta`

I want to use friction with *"multiplication operation"* not *"minus"*.

So how can I implement the ***delta time*** to my `FRICTION` variable?

# Answer
If my assumption that you want your speed to lose 2% of its value every second, then this is a perfect opportunity to use the exponential rate of decay expression, which looks like this:

`A=Pe^(rt)`

`A` is the final amount you want (so, after 1 second, `.98(vx)`) and `P` is the initial amount. `t` is just time, so since you want the velocity to only be 98% of its value from the second before you can just plug in `1` for `t`, `.98(vx)` for `A`, and `vx` for `P` and solve for `r`.

This will get you about a value of about -.0202, but you can always store something more accurate.

So what your friction application code should look like is this:

```
myObject.vx *= Math.pow(Math.E, delta * -.0202);

```

If you did not know already, decimal numbers that omit the `f` are automatically initialized as doubles. `Math.pow` also uses and returns doubles, since they are more accurate. So you may want to have your velocity measured as a `double`. This will not likely make a very noticeable difference, but if you want accurate simulations, I recommend using doubles.

I have not tested this, so please leave a comment if you notice a problem, but I do believe this is the best way to do what you want.
> 4 votes

---
Tags: movement, game-loop, timestep
---


# Question
Title: What is the line between a serious game and an application with points?
Gamification has become a buzz word lately and is being applied to everything from applications to meetings. In many cases it is being done as an afterthought and sort of game-washing.

What are the key differences between something having real game dynamics and simply being a superficial gamification layer? Where is the line between a serious game and an application with points?

# Answer
> 11 votes
I see this as a false dichotomy, a mere semantic issue. The only real difference between "game," "simulation" and "application" is the mindset of the person using it. The only reason "gamification" even entered the vocabulary is because of one TED talk and marketing (a fuzzy science to many) people do love their sound bites and justifying budgets.

Stock markets are serious business, yet people "play" the stocks.

Gambling is a game, yet people (try) to make a serious living at it.

Being a salesman is a serious job, yet they often work for "points" or "rewards" like a game.

Managers simulate planning scenarios to optimize budgets, they're minmaxing just like a gamer.

Entire national armies participate in war "games" for training.

The examples go on and on =)

# Answer
> 3 votes
Ideally, serious games are just normal games with a 'serious' topic like pollution, recycling, etc.

Serious games do quite well when the topic is to teach people how to drive a boat, how to fly a plane, etc. Note that these type of games work particularly well when the simulation is realistic (crashing and sinking for example) because the user needs to think that the simulation is realistic for them to believe they can, and actually, benefit from it.

The biggest problem in serious games at the moment is for more 'cognitive' tasks where the it is more difficult to tell whether the user has learned anything or not. Coupled with the fact that the clients don't fundamentally understand what a game is, and in what ways people can learn from it, we get these 'gamified' textbooks.

A client can start off wanting a serious game, but will also want everything he's used to; pie charts, QA's and generally things that don't go well with games at all. This is probably due to the fact that the money that is put into a serious game is considered an investment, and people will want figures to justify that investment.

This is where we end-up with this bastardized serious game that is neither one thing or another and is pretty no more useful than a text-book.

I believe that the solution is for developers to find new and innovative game mechanics that will enable them to properly test the users' knowledge and give the client this information without having to actually ask a single question.

# Answer
> 3 votes
> What are the key differences between something having real game dynamics and simply being a superficial gamification layer?

Current gamification is focused on extrinsic rewards that drive people to do otherwise unpleasant and inherently unrewarding tasks. It's like giving your dog a treat when he sits on command. Doing this never makes the task of sitting fun, but it makes it bearable enough because you know a reward is coming.

Game development is about crafting a fun and rewarding experience for the player by offering them understandable systems, and the means by which to manipulate that system towards a desired end. Fundamental to game mechanics is the concept of developing mastery over time. Then intrinsic joy of gaming comes in large degree from the reveling in the development of that mastery. You can't just bolt game mechanics onto software after the fact, they have to be integrated and designed into the user's experience.

> Where is the line between a serious game and an application with points?

Serious games are typically constructed like traditional games, with a combination of understandable systems and the means to manipulate them towards a goal. However, this software is often designed with a mindset towards delivering the player an experience which can offer some type of off-line learning. So mechanics and systems that might be streamlined away from reality in a gaming context where fun is the primary goal, may be kept in place because the software's goal extends beyond second-to-second enjoyment.

# Answer
> 2 votes
I'd suggest it comes down to 'player' motivation.

If an application uses a point system to encourage extended and more skillful interaction with the system, then it is a game.

If it just attributes points to actions/outcomes, without any sense of motivating the user/player to do better, then it is not a game.

# Answer
> 1 votes
Your question asks:

> What are the key differences between something having real game dynamics and simply being a superficial gamification layer?

When designed and implemented correctly, Gamification does include real game dynamics:

* There is a strong focus on rewards, but those rewards must fall within a balanced system.
* There must be engagement.
* There must be motivation (both intrinsic and extrinsic) there has to be levels to complete and accolades/rewards delivered upon completion.
* It should be fun, so "play" is a focal point.
* Risk factors must be vetted.
* Play challenges must be developed, and remain balanced.

The problem with gamification is that it isn't taken seriously from the outset. It is usually seen as marketing afterthought. It is often developed by marking persons with little knowledge of game dynamics and more focus on "social shares" and "badges given".

The bandwagon of "Gamification" is produced by many, but refined/balanced bby a few. The many that fail often give the few good examples of it a bad name.

You also asked:

> Where is the line between a serious game and an application with points?

You would need to define *"serious game"* in order to answer this effectively, however, I will go by an assumption you mean a AAA title from Ubisoft, Nintendo, Bioware or the like.

A serious game has level designers, programmers, story developers, character arcs, modelers, script writers, designers etc. They are focused on the dynamics of the game-play and making sure not only is the "look and feel" of the game is done well, but the inner workings of the game play dynamics are sound. A powerful weapon needs to be balanced so that it isn't a "god weapon" and a powerful enemy must be beta tested so that it isn't invincible.

Though gamification does not usually have the level of complexity in it's "design layer" there is a lot of insight and forethought put into a well designed system to maintain a fair and balanced game-play system.

The line that is drawn is in the level of complexity and planning that is invested into the gamification system.

---
Tags: game-design, gamification
---


# Question
Title: Unity Inspector Not Showing Serialized Variables Of Child
So I'm new to using Serialaiziblewtfever(I just cannot remember the correct spelling). In the Unity editor it works fine if I have something like:

```
[System.Seriliabizblewtfever]
Public class BaseClass{
    public ChildClass showvariables;
}
[System.serializable]
Public class ChildClass{
    public float nipz;
}

```

With that I can see the variables "nipz" in the inspector when I click the drop-down arrow. However, I want ChildClass to be an actual child class so I can manipulate variables inherited from the parent. So if I change it to:

```
Public class ChildClass:BaseClass

```

It stops working. It doesn't matter what class the "BaseClass" is. In the inspector it shows me "showvariables", but then has the field like how you can drag objects, transforms, etc, but no drop down list of any variables. Is there something I'm missing?

# Answer
Unity's serialization system doesn't support inheritance for custom serializable class. In order to correctly serialize fields of a polymorphic type it must be derived from `MonoBehaviour` or `ScriptableObject`.

For your example BaseClass should extend `MonoBehaviour` to make it work.

In addition, custom serialized class references won't be resolved. This means that if 2 `class A` have a field referencing the same instance of a `class B`, the 2 field will be serialized separately and so you'll end up with **2 instance** of `class B` one assigned to each field of the `class A`.
> 1 votes

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


title: Is this a good way to regulate fps?

text:
# Question
Title: Is this a good way to regulate fps?
In all of my tests I always regulate the fps by using this method.

```
const int fps = 30;
const int msPerFrame = 1000/fps; // 33 ms per frame, so it's more like 30.3030 fps
while(true)
{
  const int start = SDL_GetTicks();

  // do stuff

  const int end = SDL_GetTicks();
  const int delay = msPerFrame - ( end - start );
  if ( delay > 0 )
    SDL_Delay( delay );
  else
    std::cout <<
      "Warning, main loop took " << -delay <<
      " ms more than it was allowed." << std::endl;
}

```

At the beginning of the game while loop I set a start = SDL\_GetTicks(); then I do various game logic followed by rendering and then finish it with end = SDL\_GetTicks(). Finally, I do the regulation by this: delay = 1000/fps - (end - start); then call the SDL\_Delay(delay); if it was greater than zero.

My question is, is this actually doing what I want or is there the possibility that there might be fluctuations? I got to wondering this because sometimes the smallest drawing functions make my cpu usage go up.

# Answer
> 1 votes
No. SDL\_Delay has a granularity of 10ms so it's not suitable for a game loop. It's simple to test: use SDL\_GetPerformanceCounter() & SDL\_GetPerformanceFrequency() to mesure the time taken by SDL\_Delay(1) and you'll see it took 10ms.

In general, get used to measuring the effects of your code.

---
Tags: sdl
---


# Question
Title: b2DistanceJoint with frequency equal to 0 vs b2WeldJoint
What is the difference of `b2WeldJoint` and `b2DistanceJoint`? They both have frequency and also when you put frequency of Distance Joint to 0 it acts like Weld Joint. It seams that you can create Distance Joint effect using Weld Jonit and vice versa.

# Answer
> 6 votes
Thanks for asking Narek. I've struggled with understanding these joints in the past, and I'd like to use this answer to clear up some misconceptions.

# `b2DistanceJoint`

This joint has two input parameters: frequency `w`, and damping `d`. Together they define the *linear* response of the connected bodies. Here I will always consider one body as the ground body (set to `b2StaticBody`) and the other is called the mass (set to `b2DynamicBody`) for simplicity.

To understand the effects of varying the frequency and damping parameters, lets setup a grid of 9 ground and mass bodies where the frequency varies between rows, while the damping varies between columns:

The simulation is initialized with all joints 0.5m offset from their rest length. Here is a gif of what happens when I run this (using RUBE):

As we can see, the frequency controls how fast the oscillations occur, while the damping controls the rate at which the oscillations are damped out.

# `b2WeldJoint`

The description given in the docs is:

> A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate.

Given the name and the description it appears that the primary intention of the weld joint is to fix the relative movement of bodies, but that's not strictly how it functions, which is why I disagree with the naming of the `b2WeldJoint`. It's function would be a lot clearer if it was named `b2AngleJoint`. This is because **it functions as the angular analogue of the the `b2DistanceJoint`** (i.e. the frequency and damping parameters work the same way, except they apply to the angle rather than the linear offset):

EDIT: The `b2WeldJoint` is used as a flexible joint in the box2d testbed cantilever demo. To me anyway, this indicates that the joint can (at least sometimes) be used as a flexible joint.

# Difference

The difference is the `b2DistanceJoint` only affects the relative distance between the bodies, whereas the `b2WeldJoint` affects the relative angle *while* restricting the radial motion. i.e. bodies connected by `b2DistanceJoint`s can rotate around one another freely, while bodies connected via `b2WeldJoints` will always tend to fixed relative positions.

So the claim that `b2DistanceJoint`s and `b2WeldJoint`s with frequencies of `0` are the same is false. In the counter example below `b2DistanceJoint` is on left, `b2WeldJoint` on right, both with zero frequency and initial velocities `v=0,1` for both the masses.

Could not loop the gif perfectly... *sigh*. The block does not stutter in the actual sim, but continues to rotate smoothly.

---
Tags: box2d, physics
---


# Question
Title: How can I render extremely large models?
I'm trying to build a game in Unity similar to the game Kerbal Space Program where there are large celestial bodies that the player can orbit. I'm running into a few problems though. My first issue is that the larger I make a sphere, the slower the game gets. Secondly, whenever the sphere exceeds a certain size, the rendering engine cuts off part of the planet, which means I can only see half the model. How can I do this at the size that KSP has?

# Answer
> 7 votes
> which means I can only see half the model

You can never see the "back" half of the model :P

The following is a high-level overview listing some of the LOD considerations for this type of game. 100% of it may not apply to your game and/or KSP. Also, I haven't specified any implementation details for Unity, since I don't know them yet; rather than define each rendering method, I've described how you'll need to be able to transition between a number of different methods, all geared toward reducing as much of the scene to quads as possible.

**Bill-boarded impostors:**
An *impostor* is a stand-in for the real thing; in this case, a celestial body. In graphics, a *bill-board* refers to a quad that is continuously reoriented such that the quad's face-normal is always pointing directly toward the camera; their full width and height are equally observable from any angle.

**Very, very, near:**
As you approach the surface of a planet, it starts to look "flat". While landing, transition from sphere rendering to quad rendering. This is, essentially, a first-person-shooter camera/perspective (fog near the far-plane). When leaving the surface, transition back to the sphere; "up" starts to become arbitrary, the fog vanishes, atmosphere glow appears, the "sky" becomes black. The height at which you begin the transition may be different, per-object/planet. As you continue to move away from the object, its' textures can transition to progressively lower mip-levels; the sphere geometry begins to produce less detail than a mipped bump-map would.

**Near:**
When the object's details start to become indistinguishable because of mip and/or size, switch to billboards. Update more-distant bill-boards, less-often; this reduces the number of spheres rendered per-second in favor of quads that *look* like the rendered spheres. Essentially, you "cache" the close-up, full-detail, sphere to an off-screen texture every now and then, and just pick a mip out of it that looks "good enough" based on the increasing distance from the camera when you render each billboard. The camera used to render the sphere to the bill-board is set up a little different than the normal one. When approaching a planet, the reverse applies; the mip level increases, bill-boards are updated more, and more, frequently and you move from the bump-map back toward the displacement-map.

**Distant:**
At some point, the majority of the remaining details will be lost and/or compressed to a very small number of pixels. At this point, you can get away without texture sampling and just output a "star-like" color, possibly with a hint of the atmospheric hue.

**Very, very, distant:**
Regardless of composition, very, very, very distant objects are usually rendered as (approximately) white dots, or not at all. A large planet might look like a star when it's somewhat near, but will be mostly indistinguishable next to the parent star's overwhelming relative magnitude. Pseudo-random "twinkling" of the dots gives the illusion that very distant things are happening. You can render the dots to another off-screen texture and apply it to a sky-box/sphere that follows you around. Since it contains only the most distant objects, you won't need to update it very often.

# Answer
> 1 votes
The issue is that you need a LOD algorithm. LOD stands for level of detail and it means essentially your sphere is only as big as it needs to be in each situation. When you are far away it uses fewer polygons. When you are zoomed in close, maybe only part of the sphere is in memory, and that visible section has a lot more detail than usual. There's lots of LOD techniques out there that might help you (:

---
Tags: unity, rendering, performance
---


title: Text rendering techniques for games

text:
# Question
Title: Text rendering techniques for games
I'm researching text rendering techniques for 3D applications, and I'm having a hard time finding information on the topic. Do you know of any other methods of text rendering that are actually used in current games or have a historical significance?

So far I have:

* Using prerendered bitmaps of glyphs / strings as textures,
* converting the glyph vectors to triangle meshes and rendering it as such,
* signed distance fields (popularized by Valve's paper),
* GLyphy.

I haven't managed to find anything else though.

Does anyone know what large engines, such as Source, Unreal, Unity, etc. use?

Sources would also be greatly appreciated.

Thanks.

# Answer
> 1 votes
There is also Resolution independent curve rendering using programmable graphics hardware from Microsoft Research presented at SIGGRAPH '05. Paper is available for download. Some information is also availble online at GPU Gems 3. I don't know if this method has been used in any games.

---
Tags: fonts, text, signed-distance-field
---


title: Instantiation taking too long?

text:
# Question
Title: Instantiation taking too long?
I have a game where there are about 4 empty objects that are my object "spawners". I have two scripts attached to all of them, one that will keep spawning objects from `"basictable"`, and then switch to the other component which will then spawn objects from `"complextable"`.

This is my first script :

```
public void SpawnA() {

    if (destroyer.spawncount < destroyer.spawnchange) { //if condition

        int randomi = Random.Range (0, basictable.Length);
        Instantiate (basictable[randomi], new Vector3 (this.transform.position.x,this.transform.position.y,basictable[randomi].transform.position.z), Quaternion.identity);
        Invoke ("SpawnA", Random.Range (mini, maxi));

    }
    else if (keep){
        this.GetComponent<spawnscript2>().SpawnB();
        keep = false;
    }

```

And the second script :

```
public void spawnB()  {

        int randomi = Random.Range (0, complextable.Length);
        bobo = (GameObject) Instantiate (complextable [randomi], new Vector3 (this.transform.position.x, this.transform.position.y, complextable [randomi].transform.position.z), Quaternion.identity) as GameObject;
        StartCoroutine ("DelayedSpawnC");

}

IEnumerator DelayedSpawnC () {

        yield return  new WaitForSeconds (6);
        destroyer.spawncount = 0;
        this.GetComponent<basicSpawner> ().keep = true;
        this.GetComponent<basicSpawner> ().SpawnA();
}

```

Logically, this should work. And indeed it does. But the problem I'm having is that my "spawner", sometimes works, and sometimes doesn't, some objects from the complextable are always spawned, but in other cases the spawner just does nothing, until it switches to the first script. Is there anything I can do to optimize the spawning process and avoid this? I can't get ahold of why are some blocks spawned and others take much longer, while other blocks don't get instantiated at all.

# Answer
> 1 votes
First off, there's inconsistency in your "DelayedSpawn" method name. When you call StartCoroutine its called "DelayedSpawn", but the coroutine method seems to be named "DelayedSpawnC".

Second, your "spawnB" method seems to select an object at random and the Z position is dependent on which object it chose. According to your description, sometimes it works and sometimes now, so it makes sense that the random is somehow related. Could be that some of the objects in the complextable are empty, null, or their Z position is such that you can't see them.

Last, the code seems to me way more complex than it should be. Just put a boolean telling you if you need to use spawnA or spawnB (or better yet, use a delegate to point to the correct method), and then within the Update() method call the relevant methods for spawning.

That's as much as I can help with the information you provided. Good luck.

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


title: How to deactivate a button in unity 3d

text:
# Question
Title: How to deactivate a button in unity 3d
We have a set of buttons in our game. Each one corresponds to a particular instrument. we have to implement the foll:

a button should become deactivated after being clicked once implying that the same instrument should not be taken twice.

how to accomplish this?

# Answer
```
if(Input.GetMouseButtonUp(0))
this.gameObject.SetActive(false);

```

This will hide the "button" completely from your scene until you decide otherwise.

I recommend you go through the docs so you can figure out these answers by yourself.
> 1 votes

# Answer
If you use Unity superior or equal to 4.6, you can use UI/Selectable-interactable.

The button will cannot be used if *interactable* is set to false.

For example:

```
public Button instrumentButton;

void Update ()
{
    if (canPlayInstrument == false)) {
        instrumentButton.interactable = false;
    }
}

```
> 1 votes

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


# Question
Title: Proper normal vector transformations in normal mapping
**Hello!**

This question is about transforming normal vectors from normal maps properly. I have tried methods from over five sources, still can't get it to work, and I'm really desperate.

Included are three pictures, each one a screenshot from my app. The mesh is just a flattened cube smoothed on the edges. A blue light is always OVER the mesh.

On the first one no normal map is used, and the shader gets normals from interpolating vertex normals. As you can see, the lighting is fine and works as it should. The bottom is not lit.

On the second picture a normal map which is just blue is used - the effect should be the same as in picture one, because the normals all point upwards from the triangle. However, it's broken. The top is half-lit - it looks like the light gets cut off with a diagonal line. The part which is dark on the top is lit on the bottom, even though it should be completely dark, as the light is over the mesh.

On the third picture an actual normal map is used, and as you can see it's broken in a similar fashion to picture 2, except that some of the effects on the map are visible.

The lighting using vertex normals works properly, and the normal maps are sent properly as well, so a conclusion can be drawn that the broken part of my application is the one which either computes tangents/sends them to OpenGL/transforms the normal map using the tangent, normal and binormal vector.

I have been testing this over and over again for a month now, and just can't figure it out. Firstly, here is my function which computes the tangents:

```
GLvoid calculateTangents() {
    for (GLuint i_index = 0; i_index < indices.size(); i_index += 3) {
        // get three vertices describing a face
        Vertex& v1 = vertices[indices[i_index]];
        Vertex& v2 = vertices[indices[i_index + 1]];
        Vertex& v3 = vertices[indices[i_index + 2]];

        // calculate two edge vectors representing the triangle edges
        glm::vec3 edge1 = v2.position - v1.position;
        glm::vec3 edge2 = v3.position - v1.position;

        // calculate the differences in U and V coordinates of the two edges above
        GLfloat deltaU1 = v2.texCoords.x - v1.texCoords.x;
        GLfloat deltaV1 = v2.texCoords.y - v1.texCoords.y;
        GLfloat deltaU2 = v3.texCoords.x - v1.texCoords.x;
        GLfloat deltaV2 = v3.texCoords.y - v1.texCoords.y;

        // expanded matrix inverse
        GLfloat f = 1.0f / (deltaU1 * deltaV2 - deltaU2 * deltaV1);

        // the tangent vector of this face
        glm::vec3 tangent(0.0f, 0.0f, 0.0f);
        tangent.x = f * (deltaV2 * edge1.x - deltaV1 * edge2.x);
        tangent.y = f * (deltaV2 * edge1.y - deltaV1 * edge2.y);
        tangent.z = f * (deltaV2 * edge1.z - deltaV1 * edge2.z);

        v1.tangent += tangent;
        v2.tangent += tangent;
        v3.tangent += tangent;
    }

    for (GLuint i_vert = 0; i_vert < vertices.size(); i_vert++) {
        Vertex& vert = vertices[i_vert];

        vert.tangent = glm::normalize(vert.tangent);

        // Gramm-Schmidt reorthogonalization
        //don't use this for simple meshes like cubes - screws 'em up
        //vert.tangent = glm::normalize(vert.tangent - glm::dot(vert.tangent, vert.normal) * vert.normal);
    }
}

```

It seems to be working fine, I've checked its compatibility with a few tutorials, including it just in case somebody spots an error.

Then, here are the vertex shader parts responsible for sending the normal, tangent and bitangent to fragment/pixel shader:

```
layout(location = 1) in vec3 vertNorm_model;
layout(location = 2) in vec3 vertTangent_model;

uniform mat4 modelToCameraMat4;

smooth out vec3 fragNorm_cam;
smooth out vec3 fragTangent_cam;
smooth out vec3 fragBitangent_cam;

in main():
    // reorthogonalize the tangent and normal using Gramm-Schmidt
    vec3 vertTangent_model_reort = normalize(vertTangent_model - dot(vertTangent_model, vertNorm_model) * vertNorm_model);

    vec3 vertBitangent_model = normalize(cross(vertTangent_model_reort, vertNorm_model));

    // export normal, tangent, bitangent in camera space
    mat3 modelToCameraMat3 = mat3(modelToCameraMat4);
    fragNorm_cam = normalize(modelToCameraMat3 * vertNorm_model);
    fragTangent_cam = normalize(modelToCameraMat3 * vertTangent_model_reort);
    fragBitangent_cam = normalize(modelToCameraMat3 * vertBitangent_model);

```

And lastly, here are the fragment/pixel shader parts doing the normal map transformations:

```
smooth in vec3 fragNorm_cam;
smooth in vec3 fragTangent_cam;
smooth in vec3 fragBitangent_cam;

in main():
    // retrieve a normal vector from map (in tangent space) and move it from [0; 1] to [-1; 1]
    vec3 fragNorm_tangent = 255.0/128.0 * texture(normalSampler, fragTexCoords).rgb - 1.0;

    // transform the normal vector from tangent space to camera space
    vec3 fragBumpNorm_cam = (fragNorm_tangent.x * fragTangent_cam) + (fragNorm_tangent.y * fragBitangent_cam) + (fragNorm_tangent.z * fragNorm_cam);
    fragBumpNorm_cam = normalize(fragBumpNorm_cam);

    // fragNormal_cam is used in lighting
    vec3 fragNormal_cam = fragBumpNorm_cam;

    // if instead of using the normal map vector i use the interpolated vertex normal
    //vec3 fragNormal_cam = fragNorm_cam;
    // i get results like in picture one - proper lighting

```

If anybody manages to spot the issue here, I'd be unimaginably grateful, so thanks in advance.

# Answer
> 0 votes
I finally figured this out, and it's impossible to solve knowing only the code here, because it is actually right. The issue was the way normal maps were uploaded to OpenGL.

In glTexImage2D you specify the internalFormat - the normal map was uploaded to OpenGL using the same code as diffuse textures, which are in non-linear colorspaces, so i was using SRGB\_ALPHA8. For the normal maps to work properly, you have to use RGBA8, or just RGB8.

This was nearly not possible to spot when the normal maps were output through the fragment shader, because the map looked the same as in the file - it was unlinearized again in the framebuffer (glEnable(GL\_FRAMEBUFFER\_SRGB)). I did not realize that it actually should NOT look like it does in the original file when GL\_FRAMEBUFFER\_SRGB is enabled. That is why you should always pay attention to what space the colors are in.

---
Tags: opengl, shaders, lighting, transformation, normal-mapping
---


title: UNITY IEnumerator Function

text:
# Question
Title: UNITY IEnumerator Function
I am currently using the `IEnumerator` function to pause a `for` loop, in which a ball should move towards another game object. From my `print` statements it seems like the ball moves a little, but it's actually never reaching the object and I'm not sure why. I have never used `IEnumerator` so I'm not sure if this is a part of the issue.

```
    public IEnumerator CoUpdate(){
    float waitTime = 8;

    yield return new WaitForSeconds (waitTime);

    for (int i = 0; i <= 19; i++) {
        //Finding Game Objects
        numbers = GameObject.FindGameObjectsWithTag ("num");
        ball = GameObject.FindGameObjectWithTag ("ball");
        float step = speed * Time.deltaTime * 2;

        //Picking the random cube
        index = Random.Range (0, numbers.Length);
        pickedNumber = numbers [index];

        print ("number picked");
        print (pickedNumber.name);

        print ("numer postion");
        print (pickedNumber.transform.position);

        //Moving ball to cube
        target = pickedNumber.transform;
        ball.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

        //Checking balls position
        print ("ball Position");
        print (ball.transform.position);

        //Pause here
        print ("PAUSE!");
        yield return new WaitForSeconds (waitTime);

        //Ball Returns to position
        ball.transform.position = new Vector3 (0, 0, 0);
        print ("ball reset");
        print (ball.transform.position);
    }
}

```

# Answer
> 1 votes
Looking at your comments, I think you want a smooth movement towards the target. To do that, your step is too small, since Time.deltaTime will usually be 0.01666 at 60 FPS. So your step will actually be very small and you will move little before you reset the position again. Instead, you can use this Coroutine instead of Vector3.MoveTowards:

```
 IEnumerator MoveFromTo(Transform objectToMove, Vector3 a, Vector3 b, float step) {
         float t = 0;
         while (t <= 1.0f) {
             t += step; // Goes from 0 to 1, incrementing by step each time
             objectToMove.position = Vector3.Lerp(a, b, t); // Move objectToMove closer to b
             yield return null;         // Leave the routine and return here in the next frame
         }
 }

```

Call it in your Coroutine in place of Vector3.MoveTowards like this:

```
MoveFromTo(ball.transform, transform.position, target.position, step);

```

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


# Question
Title: How do I prevent receiving data from the network from dropping rendering frames in a multiplayer game?
I'm building an HTML5 massively multiplayer online game. I've been working on this project for awhile, but am having some trouble sorting through a couple of performance issues.

Since this is a multiplayer game, information is sent to and received from the network. When a client needs to know about new entities on the screen, the server must stream this data.

Unfortunately, one big problem I'm having right now is that sometimes either a) a lot of data needs to be streamed or b) lots of small pieces of data are streamed in a short amount of time. Both scenarios currently cause the client to drop rendering frames as the client spends its time receiving packets and processing the data.

**What is the best way to prevent the networking data from causing frame rate problems?** I am particularly interested in approaches to this kind of system that minimize frame drop issues, though suggestions tailored to my specific situation are welcome.

**Update:** To elaborate on the type of information sent in my particular case, my client does minimal interpolation and receives updates anytime the state of an entity changes on the server. The client also receives large packets with the entire state of an entity the first time the client needs to know about that entity.

# Answer
tl;dr You control how much data you are willing to process each frame. If a packet is too big, break it into smaller cells and process them one at a time (i.e one each frame). If you get a lot of small packets than split the group into chunks and limit the amount of information processing that is done each frame. The client does not need all the information; the server does so only send the client information that is crucial to the view. The rest could be handled on the server.

# Handling resource intensive tasks

# While maintaining user perceived performance

## preface:

---

### The issue:

You have a *limited* amount of resources to complete a certain task. You also wish to complete this task in a specific time frame (i.e 1/30 seconds). Using HTML5 does not allow you the same freedom and efficiency that you'd get with a native client. If you need more efficiency in utilizing resources you should seriously consider a native client or a plugin based Engine like Unity3D.

## Possible sollutions:

---

### 1. Offloading client responsibilities to the server:

The client could be a *dumb terminal* in the extreme case, only accepting and uploading input from the user as in: `player attacks Goblin Lord` and downloading simple view related instructions from the server as in `display kobold thief at (someX, someY)` or `play attack animation for Goblin[i]` and when you go towards this pattern, the client does not need to receive much data.

### 2. Caching reusable data in advance:

You can store data on the client-side by uploading it during the game startup. If you know for instance that there are Kobolds and Goblins in your game, you can have the client download their stats and store them in memory in advance. Do not make their stats random, give them classes, levels or whatever modifiers you need but keep things organized and known in advance so you don't have to upload everything to the client on the fly. Instead send a small packet like `Kobold Archer Lvl 11`. **Obviously using** `Enum`s for the actual code that is sent to the client to save more bandwidth.

### 3. Optimizing your code with a profiler:

Today it is a lot easier to optimize JS code with things like Chrome DevTools that can be used in Chrome and the insights it provides are more valuable than answers in an online Q&A website. It can help you dig into your code and see what is slowing it down. You may often find there is a loop you can trim down or a function you could optimize that is taking too much CPU resources. You can use something like PageSpeed Insights for Chrome. Look for a profiler suitable for your developer needs and you will find something useful.

### 4. Break a long task into chunks

If a party of 5 Goblins and 7 Kobolds suddenly appear, you don't have to process all their info during one frame. You could break it down and process one task each frame. This kind of optimization depends on the frequency in which intensive tasks appear. It is often unwise to attempt to process all the information at once and it results in spikes in performance. Design your code around that. Create an array of tasks and only perform as much as you can lazily evaluating certain things only when you have free resources or they absolutely needed.

You could buffer things up. If the player line of sight is `9 x 9` squares then have the client aware of a `18 x 18` square and slowly handle entities that are out of site in the buffer zone before it becomes critical (be careful that users could exploit that for an unfair advantage).

### 5. Compromise where it doesn't hurt gameplay experience

Use the framework you are working with to the extent possible performance wise. If you need to trim down some of the functionality or data in the game, consider it as an option. Sometimes you can group similar data and send it once instead of duplicating the work to lessen the amount of bandwidth and CPU used and other times you can eliminate the data altogether. For instance, who needs to know the Wisdom attribute of a skeleton? Or the Charisma of a Kobold? Sometimes excessive data could be eliminated or postponed. For instance who cares what items monsters are carrying unless they were successfully slain.

### 6. The real answer (low level):

Most of what we can offer in reply to a High-level question is patterns , theories and design principles. The real answer is *often* in the code, if we don't see or know your code we can help in a High-level way but someone needs to get down and dirty and actually *inspect* the code. Sometimes code is not properly optimized. Often the answer is to further optimize a few pieces of code and ask about them specifically. If you are not sure about something ask for a code review in the appropriate site, ask a friend or use the chat system here. You can even ask a question about a concise selection of code put in context here.

### 7. Design your game around the problem:

If the problem occurs when lots of entities appear at once, make the game a bit sparser with less mobs and make each mob slightly more powerful instead. If the problem occurs because of players character population density, make another town that attracts some of the players to lessen the amount of players in one area at a time. Give missions that take players to a uniformly random area in the map.

Think what and where the problem occurs and make that far less likely to occur by slightly modifying or tweaking the game mechanics. Remember that games needs to be scalable so you may need to make some compromises or educated decisions about what you place and where.

For any additional details or specifics please use the comments.
> 7 votes

# Answer
I assume that when your network data arrives, its processing diverts enough CPU power to slow down your rendering process.

Are you enforcing a constant framerate or are you just rendering frames as fast as you can?

Assuming you have a constant framerate, you may chose when your network packets are processed. I mean by that that your websocket event should do nothing except adding incoming messages into a waiting list, and somewhere in your game's main loop you process them.

It could go like that (very rough algorithm) :

```
while(playing) {
    render frame
    while (enough time until the next frame is due && messages waiting list is not empty) {
        remove first message from waiting list
        process this message
    }
}

```

This approach also allows you to prioritize your messages; if instead of having only one waiting messages list you have many, you can dispatch message depending of their priority.

That will allow you to process most important messages first, even if some less-important message has been received before them (i.e. if you have a lot of mobs attacking your player, you may delay for a second or two the chat related messages, or information stuffs like "xyzz has join the game" or "dfghf is now level 41").

If you don't enforce a constant framerate... well, I really think you should; the framerate perception will look better at a constant reasonable value (i.e. 30 fps) than if it varies depending of where you are or how many players are around you.

Another pointer to optimize may be to reduce the number of messages sent to clients. i.e. for non-critical events (like chat or informative messages), instead of sending a message every time someone says something you may consider limiting those to 1 message/second/player. The idea is when you have a message of such to send, you just wait for one second before sending it, and if another message of the same kind arrives during this second, you just add its contain to the first message payload.

Same thing for server issued world updates: Instead of sending one message with new coordinates for each player/actor, you may consider packing many of them (all if possible) in the same message. That shouldn't have any perceptible effect if you have a fixed framerate; you just have to send your world update message at the same rate (i.e. every 33ms if you have a 30 fps framerate on the client).

If possible, and assuming you use TCP (so no packet should be lost) you may keep on the server the last "world state" send for each client. That will allow you to only send what have changed since the last update.

This will also reduce network bandwidth you use which is always a good thing.

Bottom line: It's all about prioritization. You just cannot do everything at once, so you have to compromise and to process first what you think is the more important.
> 1 votes

# Answer
The client is written with JS? If so, than you need to use some kind of async library to make network IO in backgraound. There is RxJS and many other (try google: reactive, async etc.). Also consider switch from JS to CloujeScript: some local guys are using it for kind of tasks you've described.
> 0 votes

# Answer
Run the game like any other, calculate data on the client side as needed and simply overwrite when you receive packets from the server.
> 0 votes

# Answer
You can also combine approaches from other answers (esp. splitting work into chunks, and finding bottlenecks in code) with implementing the most CPU-intensive tasks in asm.js \- it's (a subset of) JavaScript, and it's fast on Fx and Chrome (and IE support is coming later).
> 0 votes

---
Tags: rendering, networking, html5, performance
---


# Question
Title: What's the best way to organize small textures in OpenGL?
What's the best way to organize small textures in OpenGL—having them all in a big texture and selecting them with texture coordinates, or using individual OpenGL textures?

Until recently, I used to have all textures in a big pixmap and load that into a single texture. This worked well, but in some situations, I had bright pixels from a neighboring texture leak into the edges of a dark texture, so I decided to split the textures up and load them separately. However, since I now had to switch textures quite often, this significantly increased the frame render time.

So I have basically two options:

* Go with one big texture and find a way to avoid pixel leakage.
* Go with many small textures and try to avoid texture switches as much as possible (which will put some more load onto the CPU) or to speed them up significantly.

Do you have any suggestions how to achieve this?

---

**Edit:** I'm currently using the following texture parameters:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

```

As far as I can tell, these are already the optimal parameters for what I'm trying to do. However, if there is there anything which I can still improve, I'd be glad for a hint.

# Answer
If the textures are the same general "shape" (dimensions, mip levels, etc.) then use texture arrays. You can pack differently "shaped" textures into different arrays if you have any regularity, which you should.

This approach gives you all the advantages of individual textures (e.g., no bleeding) plus all the advantages of a texture atlas (e.g. fewer state changes, bigger batches).

This is how NVIDIA recommends to do pretty much all texturing in modern OpenGL; see the Approaching Zero Driver Overhead GDC talk, particularly the section titled "Packing Textures into Arrays." This is also pretty similar to what Microsoft has recommended for Direct3D programming for years.

Texture arrays are as close as you can get in OpenGL to the descriptor heap/table design of the modern graphics APIs like Mantle or Vulkan or Direct3D 12. If you build your graphics wrapper around the idea of an abstracted texture array storage for all your textures it'll be somewhat easier to port to the new APIs - and actually get moderate efficiency gains from them - when they're out.
> 6 votes

# Answer
Profiling is always the best choice... But I've liked the combined texture approach the most it makes it easier to deal with trying to minimize swaps because you don't have to :)

You may also want to look at some of the sampling options you selected they could reduce the issue of the neighbor pixels bleeding into other textures.
> 0 votes

# Answer
Use big texture, it's better.

Avoiding pixel leakage is no that hard: If you can, use `GL_NEAREST`, else add small empty lines between textures.
> 0 votes

---
Tags: opengl, textures
---


# Question
Title: How should I implement units' enemy "awareness"?
I'm using Unity3d to develop a RTS/TD hybrid prototype game. What is the best approach for "awareness" between units and their enemies? Is it sane to have every unit check the distance to every enemy and engage if within range?

The approach I'm going for right now is to have a trigger sphere on every unit. If an enemy enters the trigger, the unit becomes aware of the enemy and starts distance checking. Does this save some unnecessary checks?

What's the best practice here?

# Answer
> 10 votes
Look into bounding volume hierarchies (BVH). They're most commonly used in collision detection to reduce the number of checks needed when calculating collisions or in rendering to perform frustum culling on objects. Since you're already using spheres, I'd suggest a sphere-tree though other volumes such as AABBs may be more efficient. I'm not sure what sort of support Unity has for such things as I've never used it, but there is probably something for this already within the collision detection or rendering parts of the engine.

Basically, you would want to group enemies that are near each other together into multiple parent spheres. When a unit is moved, you would check it's trigger sphere against the parent sphere instead of checking each enemy. If the trigger sphere intersects with the parent sphere, you would check each enemy within. If it doesn't, you can discard all of the enemies that are within it. You would want to set up multiple levels of spheres based on a maximum sphere size or enemy count for each sphere and perform the check based off of a top-level sphere. Then it's just a matter of walking down the tree in order to check each enemy without needing to perform the distance check for each one.

Steps required each frame:

1. Move enemies
2. Rebuild/update the BVH for new enemy positions
3. Move units and check against sphere-tree.

This can reduce the checks needed when there are lots of enemies but the overhead of updating and storing the tree may not be worth it when there aren't that many. I'm not familiar with Supreme Commander to know what you're after, so I'm just assuming 'hundreds'. You'll need to profile in different situations to find out whether the overhead will be worth it to you.

# Answer
> 8 votes
There is no need to implement BVH's, since Unity's collision engine essentially does that for you already.

Simply attach a large bounding-sphere trigger to each unit *(representing its range)* and handle the `OnCollisionEnter()` and `OnCollisionExit()` callbacks to keep track of which enemies are within range of each unit.

Note that the case you're interested in is when another unit collides with the sphere, *not* when another unit's sphere collides with the sphere.

# Answer
> 1 votes
Another solution that scales very well and can be used for a multitude of other things is an influeunce map. Generate a set of grid tiles around the unit to scan within X radius. Scan these tiles for an enemy standing on one of them. If you want to get the closest enemies, you can sort your set by distance.

This might be the most efficient method, especially if you plan to do other things with the influence map like fog of war or pathfinding.

Here's a video I made explaining the concept: https://www.youtube.com/watch?v=MEd6XV2Pecw.

And here's an implementation: https://www.youtube.com/watch?v=y\_ewoxlZlgc

I recommend not initializing the grid tile's unit collection at startup - but instead only when the collection is needed.

Alternatively, you can use an array of X length if you know there will never be more than X units on a tile.

---
Tags: ai, unity, rts
---


# Question
Title: LibGDX full screen display mode and camera resize
I'm creating a simple 2D platformer and I have problem with my camera y position when I enter full screen mode. But first here's my code

```
screenY = Gdx.graphics.getHeight();

public void updateCamera(){
        camera.position.x += (player1.getHitBox().x - camera.position.x);
        if(screenY < player1.getHitBox().getY() && player1.getHitBox().getY() > (screenY - Gdx.graphics.getHeight())){
            screenChanger++;
        }else if(player1.getHitBox().getY() < (screenY - Gdx.graphics.getHeight())){
            screenChanger--;
        }
        screenY = Gdx.graphics.getHeight() * screenChanger;
        camera.position.y = (screenY - screenY/2);
        camera.update();

        System.out.println(Gdx.graphics.getHeight() + " " + screenY);
    }

```

So here's my results: 1) When I start the game all works fine

2) But when I enter to fullscreen here what I get

3) here how it looks when I zoom out my camera

# Answer
When you "enter full-screen", the base window's border is removed and it is re-sized and moved such that its' ClientBounds == ScreenBounds. When this occurs, the Device is destroyed ("lost"), and needs to be recreated. At the same time, the back-buffer and any other textures or rendertargets that should be "full-screen" must also be re-created with the new size. Recreating them with the wrong dimensions will cause magnification and/or minification artifacts (pixelation, looking "crushed" or "smushed", etc.).

As a function of re-sizing the rendertargets, the gl\_Viewport describing the portion of the render target to use may also need to be updated.

As a function of updating the Viewport, the Camera may also need to use different matrices. For 2D, the View matrix is typically Identity, so you really only need to update the camera's Projection to fit "more world" into the texture. The World matrix is still just World.

LibGDX wraps all of the above into the Viewport class (low-level usage details).

> Have a read through this (high-level usage details). – StrongJoshua
> 1 votes

---
Tags: libgdx, camera
---


# Question
Title: How can I update a Stage-based HUD from another Stage's Actor in libGDX?
I feel like this is a simple problem, but I'm having issues finding the correct search terms.

I have a `Screen` that includes two `Stage`s.

1. The first, `stage`, contains a number of objects deriving from `Actor` and added via the standard `stage.addActor(Actor)`. This is for the actual game objects.
2. The second, `hudStage`, consists of a single `Table` actor. This table includes a button as well as two `Label`s. This is for the static user interface/HUD.

I'm handling touch events on my custom actors in the game stage like the following:

```
public class GameObject extends Actor {
    private final static String TAG = GameObject.class.getName();
    // ...

    public GameObject() {
        // ...

        addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(TAG, "touchDown on GameObject actor: <" + x + "," + y + ">");
                return super.touchDown(event, x, y, pointer, button);
            }
        });
    }

```

This works perfectly and logs what I need. However, I would now like to update the HUD with information about the object the user touched.

My screen has defined the `Label` I want to update (added via `hudStage`), but I'm not sure how to go from an actor in `stage` to the screen, or to the `hudStage` label.

```
public class GameScreen implements Screen {
    Stage stage;
    Stage hudStage;
    // This is the label I want to update.
    Label infoLabel;
    // ...
}

```

I know I can call `setText(String)` on the label, but I'm not sure the best way to bubble the click up. Plenty of examples have simplified versions where objects are defined in the main class (in my case, `GameScreen`) and are able to refer to them that way, but I've already broken these apart.

I started to look at creating a custom event that my actor could trigger, and that the stage would handle, but documentation is sparse and I'm not sure this is required.

I've also thought about scrapping the idea of having a label in the `hudStage` and instead having my actor draw text where the HUD would have. However, from what I continue to see, I think Scene2D is the right direction to go for the UI.

Thanks!

EDIT: What I'm looking for:

1. An actor in `GameScreen.stage` is target of a `touchDown` event.
2. Logic in actor fires and updates object.
3. touchDown event in actor finishes by updating `infoLabel` in `GameScreen.hudStage` **or** updates String value in `GameScreen` (if easier, I'll go this route).

# Answer
To make this work you need the two stages to communicate. There are two ways you could have the result you desire.

1. Have each actor you create (that is touchable) contain a reference to the HUD stage. Then when the actor is touched, simply update the HUD by calling a method with the actor as a parameter (`hudStage.update(thisActor)`).
2. Do not assign listeners to your actors. Instead assign a listener to your HUD stage (not the table within it) that listens for clicks on the entire screen. When a click is registered, call `hit(x, y, true)` and see which actor is hit. Call that actor's update method (or whatever it is you want to do when an actor is touched) and update the HUD's info with that actor.

I think these would be the easiest ways to accomplish what you want, but of course, you can make variations on these two ideas as you need.
> 1 votes

---
Tags: libgdx, scene2d
---


# Question
Title: Is there anything to keep in mind when choosing Boo for Unity development?
I just noticed that Unity has Boo as a compatible language but I haven't seen any tutorials using Boo nor any games. I love Python and would like to code in its syntax - maybe for a small project. Because I haven't seen much Booscript around, I fear that there is lack of support. Is there anything I should be wary of before venturing down this obscure road?

# Answer
> 1 votes
You might want to keep this in mind:

> This means that, as so few people use Boo, and the resources required to support it in the docs are not negligible, we’ve decided to drop support for Boo documentation for the Unity 5.0 release and use our resources in a more constructive way.
>
> When Unity 5.0 launches, we will also drop “Create Boo Script” from the menu. That said, and very importantly, if your project contains Boo scripts, they will still work just as before.

http://blogs.unity3d.com/2014/09/03/documentation-unity-scripting-languages-and-you/

It's unlikely that Boo will be around in Unity with support for much longer now. For a small personal project I guess it's fine, but for something bigger I would not consider writing Boo under Unity to be a worthwhile investment. At the very least, the lack of documentation will hit you quite a bit in the long run *now*.

With Boo's grim future out of the way...

---

> Is there anything I should be wary of before venturing down this obscure road?

As long as you're aware of how the language works compared to C# or UnityScript, it's okay. All three languages compile to the same thing after all, and Unity lets you use all three at the same time as long as you meet some conditions (making sure C# code is compiled before your Boo code in order to reference it from Boo scripts for example).

In short: use Boo if you want, and in case you ever reach the need of some feature that C# has and Boo doesn't, write that feature in C# and use it from Boo.

You *should* be able to translate code between the languages yourself though. Boo isn't the most popular choice so it's wise to be able to turn the C# code you find around the web that solves some problem you have into Boo.

---
Tags: unity, boo
---


title: Task vs Thread with execution queue

text:
# Question
Title: Task vs Thread with execution queue
My game server will have to respond to requests very often, so I consider threading a good option.

But should I use Task class from .NET or have several threads that would execute requests which I would store in a queue (linked list). Which way would be faster?

# Answer
For client Yes. For server not advisable. Loads can be distributed by putting it on queues and let individual servers handle the load. You also have an option to limit the load by assigning what type of task should a server handles. Accounts Server, Game process, Chat etc.

You use thread mainly on client mostly for the purpose of multi-functionality of your games.

Task is a Threading class available in C#. I'm not sure how you differentiate them.
> 1 votes

---
Tags: c#, server, multithreading
---


title: HTML Multiplayer and Hiding Information

text:
# Question
Title: HTML Multiplayer and Hiding Information
I'm in the process of conceiving a multiplayer web-based game of sorts and was looking into different ways of achieving this. Instead of using PHP/MySQL/AJAX like I'm used to, a lot of sites are recommending the use of WebSockets of some kind.

**My big question is, how do WebSocket games hide their information from potential hackers?** It seems like anyone could hit "view source" on a page and find out everything they need to know due to it being written in Javascript, which to my knowledge is sent with the page. Is it possible to make a server desktop application that isn't hosted along with the website? If so, what languages have support for it?

# Answer
> 0 votes
I think you might have some misconceptions about how the application would be structured. You said a "server desktop application" but this a bit contradictory. Indeed, a server does not actually run on the desktop... at least not in the traditional sense.

Let's clear up a few things, then:

1. The users of your application can see your source code but if you design your application properly, this is not an issue. Even if this were a native desktop application, nothing would stop one from using an Assembly debugger and going about reading your code like that.
2. With this in mind, don't store information on the client. Phiilipp touched on this briefly, but I think it is important to "expand" more on this.

Traditionally, for web applications you will use some sort of server and split your logic. If you have confidence in JavaScript, then Node.js is a good choice and using something like Socket.IO. You mentioned you have experience with PHP, so why not PHP Websockets? Ratchet offers an implementation of that here: http://socketo.me/

With this, your important logic would still exist on the PHP server and then the less sensitive stuff on the JavaScript section.

# Answer
> 0 votes
Websockets always connect to a central server.

This allows to implement most of the game mechanics and store most of the gamestate on the server. The server only sends that information to the clients which they are supposed to show to the player and interprets any input from the client as a request which needs to be checked for validity and may be denied.

Designing your network protocol in a way which does not falsely assume that the client is trustworthy (it isn't - not in HTML5 and not in any other technology) does not just result in a much more cheat-proof game but usually also makes the game less bandwidth-intense (not sending updates about every object in the game and instead only for those the player can actually see means less information to transfer via network). This is an important concern for a web-based game, because you will end up paying for traffic.

Libraries which implement the Websocket protocol exist for many programming languages. When there is no such library for your preferred language but it supports raw TCP sockets, you can always create your own implementation from the specification (It's not the most easy to implement protocol, though).

---
Tags: html5, websocket
---


# Question
Title: How to Load a Level for use with the Bullet Physics Library
I am trying to use a level in .obj format loaded with Assimp to generate a `btBvhTriangleMeshShape` to use with the Bullet physics library. I can successfully load `btConvexHullShape`s as well as`btBvhTriangleMeshShape`s and have them collide with each other. However, if I do attempt to generate a `btBvhTriangleMeshShape`, the program crashes on deallocating it. Because of this I think my mistake is in my loading function: `load_static_collision_shape`. Here's the code:

```
#include "Physics.hpp"

#include <GLEW/glew.h>

#include "Structs.hpp"

#include <Bullet/btBulletDynamicsCommon.h>
#include <Bullet/BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h>
#include <Bullet/BulletCollision/CollisionShapes/btShapeHull.h>

namespace
{
    btBroadphaseInterface* m_broadphase;
    btDefaultCollisionConfiguration* m_collision_configuration;
    btCollisionDispatcher* m_dispatcher;
    btSequentialImpulseConstraintSolver* m_solver;
    btDiscreteDynamicsWorld* m_dynamics_world;

    struct Physics_object
    {
        bool dynamic;

        btConvexHullShape* unoptimized_hull;
        btShapeHull* hull_optimizer;
        btConvexHullShape* hull;

        btTriangleMesh* triangle_mesh;
        btBvhTriangleMeshShape* triangle_mesh_shape;

        btCollisionShape* collision_shape;
        btDefaultMotionState* motion_state;
        btScalar mass;
        btVector3 inertia;
        btRigidBody* object;
        Oreg::Model* model;
    };

    std::vector<Physics_object> m_physics_objects;

    void load_dynamic_collision_shape(Physics_object* physics_object, const Oreg::Model& model)
    {
        physics_object->dynamic = true;
        physics_object->triangle_mesh = nullptr;
        physics_object->triangle_mesh_shape = nullptr;

        physics_object->unoptimized_hull = new btConvexHullShape{};
        for(GLuint i : model.indices())
        {
            btVector3 vertex{model.vertices()[i].position.x,
                model.vertices()[i].position.y, model.vertices()[i].position.z};
            physics_object->unoptimized_hull->addPoint(vertex);
        }

        physics_object->hull_optimizer = new btShapeHull{physics_object->unoptimized_hull};
        btScalar margin{physics_object->unoptimized_hull->getMargin()};
        physics_object->hull_optimizer->buildHull(margin);
        physics_object->hull = new btConvexHullShape{
            (btScalar*)physics_object->hull_optimizer->getVertexPointer(),
            physics_object->hull_optimizer->numVertices()};

        physics_object->collision_shape = new btConvexHullShape{*physics_object->hull};
    }

    void load_static_collision_shape(Physics_object* physics_object, const Oreg::Model& model)
    {
        physics_object->dynamic = false;
        physics_object->unoptimized_hull = nullptr;
        physics_object->hull_optimizer = nullptr;
        physics_object->hull = nullptr;

        physics_object->triangle_mesh = new btTriangleMesh{};
        for(unsigned i{0}; i < model.indices().size(); i+=3)
        {
            btVector3 vertex_1{
                model.vertices()[model.indices()[i]].position.x,
                model.vertices()[model.indices()[i]].position.y,
                model.vertices()[model.indices()[i]].position.z};
            btVector3 vertex_2{
                model.vertices()[model.indices()[i+1]].position.x,
                model.vertices()[model.indices()[i+1]].position.y,
                model.vertices()[model.indices()[i+1]].position.z};
            btVector3 vertex_3{
                model.vertices()[model.indices()[i+2]].position.x,
                model.vertices()[model.indices()[i+2]].position.y,
                model.vertices()[model.indices()[i+2]].position.z};
            physics_object->triangle_mesh->addTriangle(vertex_1, vertex_2, vertex_3);
        }
        physics_object->triangle_mesh_shape = new btBvhTriangleMeshShape{physics_object->triangle_mesh, true};

        physics_object->collision_shape = new btBvhTriangleMeshShape{*physics_object->triangle_mesh_shape};
    }
};

void Oreg::Physics::initialize()
{
    m_broadphase = new btDbvtBroadphase{};
    m_collision_configuration = new btDefaultCollisionConfiguration{};
    m_dispatcher = new btCollisionDispatcher{m_collision_configuration};
    btGImpactCollisionAlgorithm::registerAlgorithm(m_dispatcher);
    m_solver = new btSequentialImpulseConstraintSolver{};
    m_dynamics_world = new btDiscreteDynamicsWorld{m_dispatcher, m_broadphase, m_solver, m_collision_configuration};
    m_dynamics_world->setGravity(btVector3(0, -10, 0));
}

void Oreg::Physics::add(Model* model, int mass)
{
    Physics_object physics_object{};
    if(mass) load_dynamic_collision_shape(&physics_object, *model);
    else load_static_collision_shape(&physics_object, *model);
    physics_object.motion_state = new btDefaultMotionState{btTransform{
        btQuaternion{0, 0, 0, 1}, btVector3{model->x(), model->y(), model->z()}}};
    physics_object.mass = static_cast<btScalar>(mass);
    physics_object.inertia = btVector3{0, 0, 0};
    physics_object.collision_shape->calculateLocalInertia(physics_object.mass, physics_object.inertia);
    btRigidBody::btRigidBodyConstructionInfo construction_info{physics_object.mass,
        physics_object.motion_state, physics_object.collision_shape, physics_object.inertia};
    physics_object.object = new btRigidBody{construction_info};
    m_dynamics_world->addRigidBody(physics_object.object);
    physics_object.model = model;
    m_physics_objects.push_back(physics_object);
}

void Oreg::Physics::update()
{
    m_dynamics_world->stepSimulation(static_cast<btScalar>(Oreg::Core::get_delta()), 10);

    btTransform transform{};
    for(Physics_object p : m_physics_objects)
    {
        if(p.dynamic)
        {
            p.object->getMotionState()->getWorldTransform(transform);
            p.model->set_position(transform.getOrigin().getX(),
                transform.getOrigin().getY(), transform.getOrigin().getZ());
        }
    }
}

void Oreg::Physics::terminate()
{
    for(Physics_object p : m_physics_objects)
    {
        m_dynamics_world->removeRigidBody(p.object);
        delete p.object;
        delete p.motion_state;
        delete p.collision_shape;

        if(!p.dynamic)
        {
            delete p.triangle_mesh_shape;
            delete p.triangle_mesh;
        }
        else
        {
            delete p.hull_optimizer;
            delete p.unoptimized_hull;
            delete p.hull;
        }
    }

    delete m_dynamics_world;
    delete m_solver;
    delete m_dispatcher;
    delete m_collision_configuration;
    delete m_broadphase;
}

```

# Answer
> 1 votes
A solution is to avoid deallocating the `btBvhTriangleMeshShape` altogether.

Instead of this:

```
physics_object->triangle_mesh_shape = new btBvhTriangleMeshShape{physics_object->triangle_mesh, true};

physics_object->collision_shape = new btBvhTriangleMeshShape{*physics_object->triangle_mesh_shape};

```

Use this:

```
physics_object->collision_shape = new btBvhTriangleMeshShape{physics_object->triangle_mesh, true};

```

---
Tags: opengl, c++, bullet-physics
---


# Question
Title: How do I make my character stop going left in Unity?
I have this code and my character can go left, right and jump. I don't want the character going left, so how can I remove that. (I'm very new with coding)

```
public class Player: MonoBehaviour {

    public float maxspeed = 10f;
    bool facingRight = true;

    Animator anim;

    bool grounded = false;
    public Transform groundCheck;
    float groundRadius = 0.2f;
    public LayerMask whatIsGround;
    public float jumpFocre = 500f;

    bool doubleJump = false;

    void Start ()
    {
        anim = GetComponent<Animator> ();
    }

    void FixedUpdate () {
        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool ("Ground", grounded);

        if (grounded)
            doubleJump = false;

        float move = Input.GetAxis ("Horizontal");
        anim.SetFloat ("Speed", Mathf.Abs (move));

        GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
    }

    void Update()
    {
        if((grounded || !doubleJump) && Input.GetKeyDown ("up"))
        {
            anim.SetBool("Ground", false);
            GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpFocre));

            if(!doubleJump && !grounded)
            doubleJump = true;
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

```

# Answer
> 2 votes
```
void FixedUpdate()
{
   ...
   if (grounded) doubleJump = false;
   static float move; //Only allocate memory once
   move = Mathf.Max(Input.GetAxis("Horizontal"), 0); //New; nullify negative values
   //move = Input.GetAxis("Horizontal");  //Old; positive and negative
   anim.SetFloat ("Speed", Mathf.Abs (move));
   ...
}

```

or

```
void FixedUpdate()
{
   ...
   static float move; //Only allocate memory once
   move = Input.GetAxis("Horizontal");
   if (move > 0) //Only respond to positive values
   {
      anim.SetFloat ("Speed", Mathf.Abs (move));
      GetComponent<Rigidbody2D>().velocity = new Vector2(...);
   }
}

```

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


# Question
Title: Best way to calculate city influence maps similar to civilisation?
As the title says, imagine you want to generate the influence mask for a city, given that the map is a 2D grid rather than hex. An extra bit is that different points on the map might have different "influence absorpion" values. Some simple scenarios to make it less abstract:
Scenario 1:
City centered at (5,2) has 10 influence
All tiles have influence\_absorption = 1
Tile at (6,2) has 9 influence, therefore within the influence of the city
Tile at (7,2) has 8 influence, therefore within the influence of the city
Tile at (14,2) has 1 influence, therefore within the influence of the city
Tile at (15,2) has 0 influence, therefore out of the influence of the city
Scenario 2:
City centered at (5,2) has 10 influence
All tiles have influence\_absorption = 1, but tile at (6,2) has influence\_absorption=4
Tile at (6,2) has 9 influence, therefore within the influence of the city
Tile at (7,2) has 5 influence, therefore within the influence of the city
Tile at (11,2) has 1 influence, therefore within the influence of the city
Tile at (12,2) has 0 influence, therefore out of the influence of the city

It's like using dijkstra on a 2D grid with single-source, multiple-destinations. Any pointers for good/fast algorithms are appreciated. Also, if this problem has a well-known name, that'd be appreciated as well.

I made the following algorithm (independently like Jon's, thanks btw, it's the intuitive solution I guess):

```
p0 = CITY_COORDS
Initialize all influences with 0
set CITY_INFLUENCE as the new influence at p0
list = [ p0 ]
while list not empty
    p = get point in list with highest influence rating
    pi = get influence at point
    pa = get absorption at point
    new_i = pi -pa
    list_is_updated = false
    for each valid neighbour nb
        nbi = get neighbour's influence
        if new_i > nbi
            set new_i as the new influence at nb
            add nb to list
            list_is_updated = true
    if list_is_updated
        sort list // with selection sort, very fast

```

And I have the following results, which can also be helpful to understand what I'm after:

**Influence absorption**
**Influence mask**
**Influence visualisation (city at the brightest spot)**

# Answer
(A place to start that's easier than comments:)

1. Maintain a list of tiles that need calculating; the initial list contains only the city-tiles.
2. Each city-tile generates influence, X, and adds it to each of its' 8 nearest neighbors, also adding each neighbor to the list. (Does the city pass only 1/8 of its influence to each?) The city-tile then removes itself from the list.
3. While the list is not empty...
4. Tiles don't send or receive 0 influence; the tile received influence, so it must be "in".
5. The tile removes itself from the list and subtracts its' influence factor from the received amount.
6. If there is any remainder, the tile adds it to its' 3 nearest neighbor(s). (Does the tile share only 1/3 of its' influence with each?) The direction that tile's should emit is easily determined with the vector between the tile and the city.
7. Any neighbor that receives influence is added to the list.
8. Goto 3
> 1 votes

---
Tags: algorithm, path-finding
---


# Question
Title: StopCoroutine is not stopping my coroutine in Unity
I'm getting some attacking to work with my units and I noticed that the coroutines seem to start adding up even after the StopCoroutine(IEnumerator) as need called.

I dug around on ways to perform an attack loop, most of the time I found "Use InvokeRepeating" and "Don't use InvokeRepeating". Since invoke uses reflection it's performance heavy anyways, so I'd rather not go down that road.

How do I get my coroutine to stop? Is it because it's in a while loop inside the coroutine? If so, how do I fashion an attack loop without using invoke?

```
//Recieves call when a new enemy is added to the list
public void NewEnemyDetected()
{
    if(currentlyAttacking == null)
    {
        SelectEnemyToAttack();
    }
}

//Recieves call when an enemy leaves the collider area
public void EnemyGone()
{
    SelectEnemyToAttack();
}

//Will select an enemy from the array to attack
private void SelectEnemyToAttack()
{
    if(enemyObjects.Count > 0)
    {
        StopCoroutine(AttackEnemy());
        currentlyAttacking = enemyObjects.ElementAt(0);
        isAttacking = true;
        StartCoroutine(AttackEnemy());
    }
    else
    {
        currentlyAttacking = null;
        isAttacking = false;
    }
}

//Partially hacked together attacking loop
private IEnumerator AttackEnemy()
{
    while(isAttacking)
    {
        Vector3 angle = currentlyAttacking.DetectedGameObject.transform.position - transformV.position;
        angle = angle.normalized;
        GameObject projectile = (GameObject)Instantiate(AttackType, transformV.position, transformV.rotation);
        BlasterAttack projectileAttack = projectile.GetComponent<BlasterAttack>();
        projectileAttack.OnCreation(10, player);
        projectile.GetComponent<Rigidbody>().AddForce(angle * 100);
        yield return new WaitForSeconds(1);
    }
    yield return false;
}

```

Thanks!

# Answer
> 7 votes
StopCoroutine takes an `IEnumerator` object (the routine you want to stop) as parameter.

Here's:

```
StopCoroutine(AttackEnemy());

```

`AttackEnemy` will return a new `IEnumerator` object, so any other coroutine created before won't be stopped (they are different objects).

The right way to stop is to store a reference to the currently running coroutine, for example:

```
IEnumerator attackEnemy = AttackEnemy();
StartCoroutine(attackEnemy);

....

StopCoroutine(attackEnemy);

```

---

Side note looking at the comments:

1. Yes string version is slower and does use reflection
2. Even without considering performances, `IEnumerator` overload is more flexible (It hasn't always been there a was a serious limitation). In fact you can have multiple running coroutine created using the same method and selectively stop only one of them.

# Answer
> 0 votes
Turns out I need to call the method by name with a string instead of the method itself to stop the coroutine.

```
 StartCoroutine("AttackEnemy");
 ...
 StopCoroutine("AttackEnemy");

```

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


# Question
Title: How to design AI to understand its selling decisions?
I am programming a game where there are 4 competitors (players) who have finished goods that they can then sell to given markets for which they have (at most a single) contracts for. Any finished goods is for a given market.

Turn order is important in the game as this will decide who sells first.

```
Scenario.

Turn order: Player #A, #C, #D, #B

```

The problem I'm having is I have no idea how to make the AI players aware of the following factors; they seem to need to know a lot of things which may impact on where to sell first.

For example, AI needs to know.

1. Am I the only person who can sell to a given market? If so, that's fine -- sell all goods to market.

If not, do the following

2. Who are my competitors for a given market and will I be able to sell first?
3. If I sell in Market A, will I still get a chance to sell to Market B when turn order returns to me? (demand for items goes down for every sale and can bottom out)

Indeed, this is one strategy I'm wanting to employ -- sell to a given market because i he does not he might not get a chance to sell again when turn order returns to them.

4. If I sell, should the AI go for most revenue per selling round.

Currently I am looking to order all markets for a given player based upon selling ability (who can sell first)

Basically an array of people who can sell for a given market based on player order.

These people then sell, and we reduce the array by one and repeat the process.

Whilst this solves some problems, it does not solve the bigger problem, which is the AI will just end up selling stuff in the order that of the Markets array; and not specifically to the ones where it is either advatangeous to do so, or will generate them the most money.

I am wondering, how do you design an AI to make coheriant, logical decisions about what when and why they would sell to a given market?

Sorry for the wall of text.

Many thanks

# Answer
> 9 votes
## The minmax tree method

You basically have the AI simulate every possible move it can make and every possible response by the other players for several turns in advance, and then pick the path which is most beneficial to it.

The advantages of this method is that it can usually deal very well with any changes to the gameplay because it only looks at the consequences of a move without having to consider *why* these consequences happened. You can also scale the difficulty very easily by setting the number of turns the AI calculates in advance.

The hardest thing about this algorithm is usually the rating function which determines what "most beneficial" means, but for an economy simulation it is surprisingly easy because you can usually express this in net-worth of the players (having more money and assets than the other players = good, having less = bad).

This method is very popular for games like Chess where you have a limited number of possible moves per turn, no randomness and no information hiding. According to your description your game seems to look like this. But you might be omitting some additional complexity.

When you have a very large number of possible moves, the decision tree becomes so wide that calculating more than one turn ahead takes too long even on a high-end computer.

When you have randomness or information hiding, you can either assume that the most likely event will always happen. Unfortunately this will greatly weaken the AI in case something unexpected happens instead. Or you can have the AI cheat. Have it know what will happen in advance by using the current random number generator state for the simulations and have it take any information into account it shouldn't actually have access to. This is very likely to make the AI frustrating to play against because it will soon become obvious to the player that the AI has an unfair advantage. Still, there is a large number of very successful games which make use of this technique.

## The strategical rating method

This seems to be the method Jon is describing in his answer. In this method you evaluate all possible decisions the AI can make and have certain rules which rate the feasibility of the move based only on the current game situation.

Such rules could be "do not sell when the price is lower than average" or "do not buy when the other players have a lot of the same resource". The AI values all these factors by assigning relative scores to them and then makes the decision which has the best score.

This method requires to have a deeper understanding of the game as a whole because you need to define all the rules and ratings of when a decision is good or bad. This means the AI can not play any better than you could play the game. You can not increase the difficulty (except by cheating), you can only decrease it by making the AI take less rules into account. Hardcore gamers will soon find out how the AI works and find exploitable weaknesses. It also makes the strategy very fragile to changes. Any balance adjustments or new features will require to re-evaluate all AI rules to make sure they still provide good advise. And I hope you don't have an active modding community, because any new feature they throw at the AI will totally break it because it can not deal with things it doesn't know about.

But despite these weaknesses this method is still the most popular one for more complex games. In the 4X and RTS genre most AIs work like this.

# Answer
> 2 votes
(You have not specified a programming language or graphics API)

C# (some variable and method names are made-up, but are named to indicate their purpose)

```
public class Market
{
   ... //Existing stuff
   public int GetScore(Player player)
   {
      int score = 0; //0 == "better than doing nothing"
      if (this.Factor1.Helps(player)) score++; //there is excess demand!!
      if (this.Factor2.Helps(player)) score++; //there is insufficient supply!!
      if (this.Factor1.Hurts(player)) score--; //there is no demand (no margin)
      if (this.Factor2.Hurts(player)) score--; //there is too much supply (saturated)
      return score; //score might be negative
   }
}

```

and

```
public class Player
{
   ... //Existing stuff
   private Market findBestMarket()
   {
      Market bestMarket = null; //reset
      int bestScore = 0; //reset
      foreach (Market market in PlayersMarkets) //Check each of the player's markets
      {
         int score = market.GetScore(this); //Score the current market
         if ((bestMarket == null) ||    //If there is no "best" yet
            (score > bestScore))        //or if this one is better than the "best"...
         {
            bestMarket = market; //save for return
            bestScore = score; //save for score-keeping
         }
      }
      if (bestMarket == null)   //Should only happen
         throw new Exception(); //if PlayersMarkets is empty
      return bestMarket; //return the market with the best score
   }
}

```

---
Tags: game-design, ai
---


title: OpenGL Blending Format

text:
# Question
Title: OpenGL Blending Format
In OpenGL, is there a format for a texture in glTexImage2D that prevents blending, or do you **have** to disable it using glDisable(GL\_BLEND).

Reason for use is that I would like to store additional data in the alpha channel of a texture, but it blends with whatever's behind it.

# Answer
> 0 votes
Now that I know that the context is rendering to a texture frame buffer I can try to answer.

Yes, you do have to `glDisable(GL_BLEND)` otherwise it will blend according to whatever `glBlendFunc` is currently set, which will mess with the RGB channels based on what you're writing to the alpha channel. Then you need to do blending you write it in your shader.

I've done a lot of testing with writing to textures and trying to preserve the alpha channel. Check out this question on stack overflow: https://stackoverflow.com/questions/19674740/opengl-es2-premultiplied-vs-straight-alpha-blending It's not exactly the same thing but might be some help.

Of course you do have to make sure that your texture frame buffer is GL\_RGBA in both places. Mine on iOS looks a little like this:

```
glGenFramebuffers(1, &textureFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, textureFramebuffer);
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glGenRenderbuffers(1, &textureDepthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, textureDepthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, textureDepthRenderbuffer);

```

Of course if you don't need the depth buffer you can skip that part.

---
Tags: opengl, alpha-blending
---


# Question
Title: How to convert pixels to meters in Box2d with Cocos2d-x 3.5?
I am using Cocos2d-x 3.5. I created a simple game with edge bodies and one circular body to test box2d. Physics wasn't working well, so i thought i should convert pixels to meters and use that meters for example on aplying impulses.

I don't know how to do it. I can't find any converting function. Also there is no any PTM\_RATIO variable. I tried to create it myself, but i don't really know how to use it properly. Can you help me please to understand that? Thank you.

# Answer
Models/geometry are created with arbitrary units; if those units happen to already represent meters, no scaling is needed, only translation is needed.

```
model-space coordinate (no units) * World = world-space coordinate (meters)

```

View-space units are the same as World-space. The View matrix translates and orients the world such that the new origin is the camera's location and the Z-axis points in the same direction as camera-forward. Coordinates are now relative to the camera; i.e. a coordinate that is "to the left" of the camera will have a negative X-value.

```
world-space coordinate (meters) * View = view-space coordinate (meters)

```

Projection-space units are intermediate; they represent a percentage of the active rendertarget/viewport. Projection-space is also defined with the origin at the camera's location, moving the camera to the center of the rendertarget/viewport. Coordinates are relative to the center of the screen and are in the range of -1 to 1; i.e. coordinates along the left-most edge of the rendertarget have X-values of -1 and coordinates along the bottom-most edge have Y-values of -1.

```
view-space coordinate (meters) * Projection = projection-space coordinate (unitless)

```

To convert projection-space coordinates into pixels, you convert them from the -1:1 range to the 0:TextureDimension range. Texture-space defines the origin, (0,0), at the top-left corner and (1,1) at the lower-left corner.

```
textureSpaceCoordinate = projectionSpaceCoordinate   //-1 to 1
textureSpaceCoordinate += 1.0f;                      // 0 to 2
textureSpaceCoordinate /= 2.0f;                      // 0 to 1
//A Y-value of 1 corresponds to the top of projection-space
//and the bottom of texture-space; need to invert it
textureSpaceCoordinate.Y = 1.0f - textureSpaceCoordinate.Y;

//If the texture is 800 pixels wide, X-values will range from 0 to 799
pixelCoordinate.X = textureSpaceCoordinate.X * (TextureWidth - 1);
//If the texture is 600 pixels tall, Y-values will range from 0 to 599
pixelCoordinate.Y = textureSpaceCoordinate.Y * (TextureHeight - 1);

```

If you start the above process at Projection and use the view-space coordinate (1, 1), the resulting pixelCoordinate approximates the "PTM\_RATIO"(s).
> 1 votes

---
Tags: box2d, cocos2d-x
---