title: D3D11CreateDevice leads to syntax error

text:
# Question
Title: D3D11CreateDevice leads to syntax error
I'm following the book *Introduction to 3D Game Programming with DirectX 11* by Frank Luna (link) and I'm trying to make the empty project in Chapter 4 (don't worry, I don't expect you to read the book)

I'm getting to the point in code where I need to create the Direct3D device context. My code looks at this so far:

```
#include <Windows.h>
#include <D3D11.h>
#include <D3Dcompiler.h>

UINT createDeviceFlags = 0;

#ifdef DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

D3D_FEATURE_LEVEL featureLevel;
ID3D11Device* md3dDevice;
ID3D11DeviceContext* md3dImmediateContext;
HRESULT hr = D3D11CreateDevice(0, D3D_DRIVER_TYPE_HARDWARE, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dImmediateContext);

if (FAILED(hr)) {
    MessageBox(0, L"D3D11CreateDevice Failed", 0, 0);
}

// I added this as the entrypoint for the program - copied directly from microsoft's website
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
{
    return 0;
}

```

The problem is that I'm getting some errors that make no sense at all. Take a look (by the way, I'm using Visual Studio Community 2015):

```
Code    Description                                              File       Line
C2059   syntax error: 'if'                                       main.cpp   16
C2143   syntax error: missing ';' before '{'                     main.cpp   16
C2447   '{': missing function header (old-style formal list?)    main.cpp   16

```

Any help would be greatly appreciated!

# Answer
You need to move your code above the `WinMain` function inside the function.
> 1 votes

---
Tags: c++, directx11
---


# Question
Title: Hide building roof & Hide faces/vertices depending on world location
I'm currently developing a small game for my own enjoyment and I've ran into a problem. As you probably know many third person games (such as Runescape and XCOM, for example) hide the roofs when you enter a building so that you can still see your character. I'm using lwjgl and my current solution is to use clipping planes to simply stop rendering everything above a certain height when the player is inside of a building, but this gives bad results because if there are other buildings or tall entities nearby they are also not rendered above that plane.

I've thought of some solutions - one of them being to simply hide certain faces/vertices when I'm in certain areas. This could also be applied to other things than just buildings as well. Is this the right way to approach this problem? Or is there a better way to handle this?

PS. I'm not very experienced with openGL (especially shaders), so if the solution requires shader work I might need more detailed descriptions.

# Answer
When you get more advanced:

-You'll end up using instancing to draw **ALL** of the roofs at the same time with one DrawInstanced(...) call. In that setup, we can detect which roof we're under (@GarMan) and just omit that one roof instance.

-You could also activate the stencil buffer, draw the roof we're under (without outputting any colors), deactivate the stencil, the draw all of the roofs (the stenciled roof is omitted). Clear the stencil and continue rendering the scene.

There are as many "best ways" to do it as there are people with opinions. I agree with GarMan that the most common and simplest approach is to use bounding shapes to represent volumes; BoundingBox, BoundingSphere, etc.

```
foreach (roof in g_RoofList)
{
  If (roof->boundingShape.Contains(camera->LookAt))
    //Do nothing
  else
    roof.Draw();
}

//or maybe

foreach (building in g_BuildingList)
{
  building->DrawFloor();
  building->DrawWalls();
  //Draw the roof, or the objects inside, but not both
  If (building->boundingShape.Contains(camera->LookAt))
    building->DrawRoof();
  else
    building->DrawInteriorObjects();
}

```

Since you are just beginning, I'd recommend focusing on "doing it" before "doing it right". There's really no getting around the amount of face-planting you'll be doing as you progress, looking back at your previous creations. It will feel like a stranger wrote them.

**Edit per comment:**

```
void RenderScene()
{
  EnableRoofClip();
  //Render only the buildings that contain camera->LookAt
  foreach (building in g_BuildingList)
  {
    If (building->boundingShape.Contains(camera->LookAt))
      building->Draw();
  }

  DisableRoofClip();
  //Render buildings that do not contain camera->LookAt
  foreach (building in g_BuildingList)
  {
    If (!building->boundingShape.Contains(camera->LookAt))
      building->Draw();
  }
}

```

> ...one of them being to simply hide certain faces/vertices when I'm in certain areas. This could also be applied to other things than just buildings as well. Is this the right way to approach this problem? Or is there a better way to handle this?

I don't recommend implementing the following in your game because you already have a method that works, however, you *can* cull vertices on the GPU in a variety of ways and this is one of them:

VertexShaders create an output for **every** input. GeometryShaders can take that output and then choose, on a per-vertex basis, which ones to throw away. As a starting point, implement a simple GeometryShader that outputs every input (does nothing). Then, you can experiment.

There's no, one, right way and there are usually always better ways.
As soon as you implement a better way, you'll find another, even-better, way:

https://en.wikipedia.org/wiki/Feature\_creep
> 1 votes

# Answer
A solution is to use simplistic collision detection between your camera and the characters being rendered. For example you could wrap buildings in simple boxes, collide some rays from your view port (4 corners and center) to the character, and any boxes your ray goes thru needs to be rendered differently.
> 0 votes

---
Tags: java, 3d, shaders, rendering, lwjgl
---


# Question
Title: Android Opengl: Alternate values for gl_FragColor
I'm writing an Android application that utilizes opengl to perform some changes to the camera output. I've written my code in such a way that I finally figured out what is causing the performance issue.

```
#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES sTexture;
uniform vec4 vColor;
const int MAX_COLORS = 6;
uniform float vHues[MAX_COLORS];
uniform float vOffsets[MAX_COLORS];
varying vec2 v_CamTexCoordinate;

float rgb2hue(vec4 c) {
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));

    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return abs(q.z + (q.w - q.y) / (6.0 * d + e));
}

bool isInRange(float a1,float a2, float vOffset) {
    if(a2 < 0.0) {
        return false;
    } else if(abs(a1-a2) < vOffset) {
        return true;
    } else if( a1 > a2) {
        return (1.0 - a1 + a2) < vOffset;
    } else {
        return (1.0 + a1 - a2) < vOffset;
    }
}

vec4 getGrey(vec4 c) {
    float grey = (c.r + c.g + c.b) / 3.0;
    return vec4(grey, grey, grey, c.a);
}

void main() {
    vec4 c = texture2D(sTexture, v_CamTexCoordinate);
    bool hasColor = vHues[0] >= 0.0;
    float hue = rgb2hue(c);
    vec4 test = getGrey(c);
    for(int i=0; i < MAX_COLORS; i++) {
       if(isInRange(hue, vHues[i], vOffsets[i])) {
          //If I uncomment this line the performance gets terrible
          //test = c;
       }
    }
    gl_FragColor = test;
}

```

There is a significant hit to performance (a lot of frames are skipped) when I uncomment the line above. I basically want to use the original color sometimes and a different color depending on some condition. It works but is there a more efficient way to do this? Also, why does this perform so poorly?

# Answer
> 1 votes
First of all, if the line is commented, the compiler can most likely optimize out the loop, which is why the shader runs faster then.

You have a lot of branches (`if`/`else`) in your shader, which is most likely your performance issue. Branching (especially on mobile devices) is something you generally want to avoid.

If your uniforms (hue and offsets) do not change very often, you might consider hardcoding them into the shader (i.e. regenerate the shader whenever they change).

I am not sure about the `rgb2hue` method, but it looks rather vectorized, which is why it might perform fast enough.

Your `isInRange` however is full of branches, which will most likely be the performance bottleneck.

You might want to consider generating a 3D-LUT on the CPU side, and then sample that in your shader. That will most likely be faster than evaluating all those branches.

---
Tags: opengl, android, opengl-es
---


# Question
Title: Efficiently calculating best nearest sphere from a point in 3D space
I have a point in 3D space and a number of spheres (anywhere from 0 to thousands) at random locations in said space.

Each sphere has a property that falls off in a smooth gradient from the centre to the edge.

The point could be inside between 0 and all of the spheres.

How do I calculate the sphere that the point is inside that has the highest 'value' at its current position?

I was wondering if I could get away with just looping through every sphere and adding the ones the point is inside, then looping through those and testing the value. However, the calculation for this needs to be calculated 'instantly', or at least with minimal delay, so I'm wondering is that is too inefficient.

# Answer
You said that the value you describe falls off in a gradient from the center of the sphere. So I suppose it achieves its minimum (e.g. zero) when reaches the sphere boundaries. In that case, there is a very simple way of making your problem easier than using 2 loops.

I guess you already know how to check if a point is inside a sphere, but for the sake of completion, I will quickly summarize it. Let R be the radius of the sphere, C be its center and P be the point whose position is being checked. So:

* if Distance of P to C is greater than R, then P can't be inside the sphere;
* if Distance of P to C is smaller than R, then P is inside the sphere;
* if Distance of P to C is equal R, then P lays over the circumference of sphere.

That said, let's get into your specific setting. In terms of pseudo-code, according to your question you wondered if there was a better way than doing the following:

```
float minvalue = 0; //if your value can go below zero, alter this with the minimum it can achieve
int bettersphere_index = null; //declares the variable that will hold the index of the better sphere, if any (if P is not inside any sphere, than this variable will retain the value you define here). If not initialized as `null`, then it should be initialized always with value below zero.

//this loop goes trough all spheres to check the ones that P lays inside of:
for(int i=0; i<listofspheres.Length; i++)
{
    //check whether point P is within sphere and, if yes, save the sphere
    float distance = Distance(P.transform.position , listofspheres[i].transform.position); //calculates the distance between P and the center of current sphere being evaluated
    if(distance < listofspheres[i].radius) //performs the P in sphere test
    savedspheres.Add(listofspheres[i]); //add the current sphere to a list of saved spheres that will be further evaluated later in the second loop
}

float biggestvalue = minvalue; //declare the variable that will store the greatest value
//this loop goes trough all saved spheres to check which is the best match, as per the definition of your question:
for(int j=0; j<listofspheres.Length; j++)
{
    //check which is the better sphere, as per your definition:
    float distance2 = Distance(P.transform.position , savedspheres[i].transform.position);
    float currentvalue = MapDistanceFromCenterToValue(savedspheres[j]); //this represents your function that converts the distance from sphere center to the desired value
    if(currentvalue  > biggestvalue ) //this is the part that makes the comparison across spheres
    {
        biggestvalue = currentvalue; //update the biggestvalue found so far
        bettersphere_index = j; //update the index of the better sphere found so far
    }
}

```

Well, you can't achieve what you want without iterating trough the spheres, i.e. there is no analytical solution to such a problem. However, you don't have to use two loops to achieve that. And you can also drop one of the distance calculations and use SquaredDistances instead of Distances for the P-in-sphere tests. These minor things can result in a significantly more performant way of achieving what you want. In pseudo-code:

```
float minvalue = 0; //if your value can go below zero, alter this with the minimum it can achieve
int bettersphere_index = null; //declares the variable that will hold the index of the better sphere, if any (if P is not inside any sphere, than this variable will retain the value you define here). If not initialized as `null`, then it should be initialized always with value below zero.
float biggestvalue = minvalue; //declare the variable that will store the greatest value

//one single loop trough the spheres:
for(int i=0; i<listofspheres.Length; i++)
{
    float squareddistance = SquaredDistance(P.transform.position , listofspheres[i].transform.position); //calculates the SQUARED distance between P and the center of current sphere being evaluated. See: https://stackoverflow.com/questions/3693514/very-fast-3d-distance-check

    if(squareddistance < listofspheres[i].radius*listofspheres[i].radius)  //performs the P in sphere test, using squared distance - which, of course, demands that R needs to be squared too
    {
        float distance = Math.Sqrt(squareddistance); //just calculate the real distance, i.e. applying the squareroot, when it will be really needed, which means when you already know P is inside sphere.
        float currentvalue = MapDistanceFromCenterToValue(distance); //this represents your function that converts the distance from sphere center to the desired value

        if(currentvalue  > biggestvalue ) //this is the part that makes the comparison across spheres
        {
            biggestvalue = currentvalue; // update the biggestvalue found so far
            bettersphere_index = i; //update the index of the better sphere found so far
        }
    }
}

```

In the end, the variable `bettersphere_index` will hold the index of the sphere you wanted to find out (i.e. the index of its position within the `listofspheres` array). If `bettersphere_index` ends up being `null` (or equal the below zero value you defined at the beginning, before the loops), you know that point P was not inside any sphere in the scene.

Notice that, as previously pointed, I used SquaredDistances instead of Distances to test P within sphere. That's a very common simple optimization, see more about it here: Very fast 3D distance check?. Lastly, it means that if by any chance you can adapt your function that converts distance from center to custom value, to use SquaredDistances instead of Distances, then you can also avoid doing the square-root calculation in the code and have yet more performance gains.
> 0 votes

# Answer
The basic problem you are facing is having to multiply iterate and the cost of doing so each frame. (Apologies if my DirectX lingo confuses)

You feel that the only option available to you is to:
Iterate through and evaluate **every** sphere against the point, every frame.

But, what you'd really *prefer* to do is:
Iterate through and evaluate **every** sphere against the point, every frame, **simultaneously**.

Good news! You can **easily** accomplish that by moving your current algorithm to a `ComputeShader`. Good news; doing so is **rediculously** easy!

Right now, you index the "current sphere" by a `for(i=0; ...)`. With a `ComputeShader`, we can `Dispatch` a fixed number of threads or thread groups based on how many spheres there are, and index the sphere list using `SV_ThreadID`. Each thread, **simultaneously** evaluates your falloff formula against the point. If we start off with an empty `AppendBuffer`, and only `Append` where the falloff is non-zero, we end up with a list of only the spheres that influence the point, as well as the calculated influence for each.

At this point, you can retrieve the "instantly" filtered list and iterate it on the CPU. However, since it was **so** easy to implement the first, why not just create a second one:

This one uses the previously created `AppendBuffer` as a `ConsumeBuffer`. This will only contain a couple of variables like `BestInfluence` and `BestInfluenceSphereIndex`, initialized to their most-negative values. We'll use a single thread and a plain, old, `for` loop that will `Consume()` each influencing sphere from the buffer, and compare it to `BestInfluence`. If `BestInfluence` is lower, replace both with the current sphere.

At the end, you are left with the "best nearest sphere from a point in 3D space", which you can then read back on the CPU. This method has *approximately* "fixed" performance. The first `ComputeShader` will take about the same time to finish, regardless of sphere-count (thread-count). You say you won't be calculating this every frame, but what you mean to say is that it's **impossible** to do so every frame and still maintain a good framerate. Well, now you can do both!

The most important factor here, is that the CPU only has to tell the GPU "go". The CPU can continue on, updating your camera, objects, etc. **while** the GPU crunches the spherical falloff. You're doing more than one thing at a time and one of those things is operating on all of its' inputs at the same time.

---

The new shaders can feel like scary, intimidating beasts that should be avoided at all costs. Spend a good week learning each of them now, so that your future designs can include their use. You'll find that each one, approached individually, is actually not that hard to understand. If you are successful implementing the `ComputeShaders` described, you'll have expanded your limits exponentially. When you are able to fully utilize every shader stage, you can, then, combine them and discard any previously perceived limitations.
> 0 votes

---
Tags: 3d, algorithm, efficiency
---


# Question
Title: Frame Rate Independence for Non-Linear Increases
So while working on my game, I decided that I would have a speed variable increase in the fashion

```
speed += 1/speed;

```

with the goal being that in the beginning it increases fast and then it increases slow as it gets higher. However this is being called each frame and I need to make it framerate independent, however just scaling it based on time doesn't give the same results throughout. How would I go about creating a framerate independent increase that dampens like this?

# Answer
> 1 votes
I believe this will be a frame rate independent alternative for this type of movement:

```
speed = Math.log(time + 1) / Math.log(Math.E) + startingSpeed;

```

This sets speed equal to `ln(time + 1)` which increases at a rate of `1/time`. You want the `+1` because `ln(t)` is negative while t is less than 1 (and greater than zero).

Just have `time` start at zero and increase it by `deltaTime` or the equivalent every update.

Also, for the sake of performance you could store the value of `Math.log(Math.E)` in a variable and use it instead when calculating speed.

---
Tags: java, frame-rate
---


# Question
Title: Making only parts of a mesh destroy in UE4
I am making a 3d, 3rd person shooter game where I want everything to be destructible. UE4 makes this possible by making meshes destructible, but the problem is that when the mesh is damaged, it destroys completely. This is not what I want, I would like to keep the destruction limited to some volume of the mesh proportional to the bullet's size. Also, the ground must be vulnerable to explosives and must crater as a result. I was just wondering if there was a way to limit the effect of the destruction to some part of a mesh only.

# Answer
> 1 votes
Disclaimer: I do not know unreal.

But a general solution to this can be implemented using voxels. This should be easy to implement for the terrain. Contrary to popular belief, voxels mustn't be cubes. Nvidia has great documentation about this: https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch01.html.

For characters you can position the voxels relative to the skeleton bones if you want to really shoot holes through bodies.

---
Tags: unreal-4, shooter
---


# Question
Title: Get all the gameobjects for a SceneManager scene in Unity
I'm using the new SceneManager to load multiple scenes in the same structure adopting the Additive method. I find it extremely useful but I wonder if there is a way to get all the GameObjects for a specific scene. When multiple scenes are loaded I see the GameObjects clearly separated by scene in the hierarchy but I cannot find a way to access the specific hierarchy of a single scene via script. Is that possible? The findGameObject method I think returns the GameObjects for all the scenes..

# Answer
> 4 votes
You can get all the root Game Objects of a specific scene using `SceneManagenent`, that will return an array of `GameObject`.

```
GameObject[] _rootGameObjectsOfSpecificScene = SceneManager.GetSceneByName("YOUR_SCENE_NAME").GetRootGameObjects();

```

Replace `YOUR_SCENE_NAME` with your scene name.

---
Tags: unity, scenemanager
---


# Question
Title: GlViewport-code doesn't work in one specific screen?
I am currently working on a small game using LibGDX and Java.

However, I have found one oddly specific problem. I want the game to resize so that it never has to be cropped and so it never has to cut anything off - basically just setting the viewport so everything still fits onto the screen on resize. Sounds simple.

Now, I have the code for that in place. All of my screens extend one BaseScreen in which I defined the following code:

```
@Override
public void resize (int width, int height) {
    Vector2 size = Scaling.fit.apply(Constants.GAME_WIDTH, Constants.GAME_HEIGHT, width, height);
    int viewportX = (int)(width - size.x) / 2;
    int viewportY = (int)(height - size.y) / 2;
    int viewportWidth = (int)size.x;
    int viewportHeight = (int)size.y;
    Gdx.gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
}

```

(Note, I have not written this code by myself, it is one of the few pieces of code I searched online for as I had no previous experience with LibGDX)

Now, this code works absolutely fine in almost every screen - just not in the RoomScreen, which is the screen where the main gameplay is happening. Which is quite a bummer, as it basically makes the game look really shitty except for multiples of my game size (the constants are set as 480 and 272).

Now, I have absolutely no idea why this is the case. I read that this might be because transforms are pushed, but not pulled afterwards, but I did not find any instance of this in my code.

I also tested wether the code is executed, and it indeed is. All variables are correctly set, it simply doesn't work.

If any of you is able to help me, I would be unbelievably thankful!

The full code is currently only available in my Dropbox, as my own Git server recently crashed. Here is the link: https://www.dropbox.com/sh/evvw5kiqcfos7fu/AADwogpkwl1RWj2QcI6eePyda?dl=0 (I am terribly sorry that I am only able to share it this way, but I am afraid that sharing every relevant class in this post itself would in the end result in pasting all my code here, making it almost unreadable. If any of you has a better idea than this, please tell me, I'll gladly share it otherwise!)

If you are wondering, the screen classes are in the folder "screen".

# Answer
> 0 votes
Okay, after doing a metric butt-ton of debugging I seem to finally have figured out how to solve this - quite peculiar - problem, even though I don't really like the solution.

I am not sure why, but the LibGDX people chose to make a FrameBuffer set the viewport on every `begin()` call. This is problematic in so far that on an end() call, it seems like the original viewport is not properly restored, even though it should be as far as I can gather from the source code.

This means that the fix is actually rather simple, just reset the viewport after the faulty FrameBuffer `end()`. Of course this is by far not the ideal solution, as it does make the game rather stuttery, but I'll have to resort to this if I cannot figure out shaders properly.

---
Tags: opengl, java, libgdx, viewport
---


title: Display text one character by one

text:
# Question
Title: Display text one character by one
In a game over screen I am trying to display the text "GAME OVER" one character by one.

```
public float letterPause = 0.2f;
string message;
private TextMesh textComp;

public void DeathMenu()
{
    GameObject text = GameObject.Find("Text_Score");
    TextMesh textComp = text.GetComponent<TextMesh>();
    textComp.text = "GAME OVER";
    message = textComp.text;

    StartCoroutine (AnimateFinalScore ());

}//end of Setup Death Menu

IEnumerator AnimateFinalScore()
{
    foreach (char letter in message.ToCharArray()) {

        textComp.text += letter;

        yield return null;
        yield return new WaitForSeconds (letterPause);
    }
}

```

The code is not working; it generates the following error message:

```
NullReferenceException: Object reference not set to an instance of an object

```

This error message points to the `textComp` variable in the `DeathMenu()` method.

# Answer
> 2 votes
> now the error message points to the textComp.text += letter; variable in the IEnumerator();

The reason for this is the way you've defined the `textComp` variable:

```
public void DeathMenu()
{
    GameObject text = GameObject.Find("Text_Score");
    TextMesh textComp = text.GetComponent<TextMesh>();
    ...

```

By declaring a variable inside the `DeathMenu` method, it is *local to that method's scope*.

This means that any code outside of `DeathMenu`'s curly braces {} can't see the `textComp` variable - in fact it's cleared as soon as `DeathMenu` returns (immediately after starting the coroutine).

This happens even though you've defined `private TextMesh textComp;` as a member variable at the top of the class. By repeating the definition inside `DeathMenu` you are declaring a new local variable with the same name, which masks the member variable. So you never assign any value to the member variable, and it still has the default value of `null` when `AnimateFinalScore` tries to work with it.

So, there are three ways to fix this:

* `Find` and `GetComponent` again inside `AnimateFinalScore()` but this is a bit wasteful.
* make sure the member variable version of `textComp` gets used by removing the `TextMesh` in front of the assignment in `DeathMenu`, so you're no longer declaring a new local variable. The downside to this is that you're holding this reference for the lifetime of the instance, when from what you've shown here you only really need it for the duration of the animation.
* (my recommendation) pass the value of `textComp` when starting the coroutine:

```
    ...
    StartCoroutine (AnimateFinalScore (textComp));
}//end of Setup Death Menu

IEnumerator AnimateFinalScore(TextMesh textComp)
{
    ...

```

Now code inside `AnimateFinalScore` knows what `textComp` is, because it's defined within that method's scope as one of its arguments. You can do away with the member variable version entirely, unless you have other code that needs it (in which case, use the second bullet point instead)

# Answer
> 1 votes
Try to make somethin like this:

```
char[] letters = message.ToCharArray();

```

and then in your foreach:

```
foreach (char letter in letters) {

        textComp.text += letter;

        yield return null;
        yield return new WaitForSeconds (letterPause);
    }

```

Not sure if that's the problem but i once had something similar with a string which I tried to trim. The trim function can't be called on a string like

```
string.Trim();

```

you need to call it like this:

```
string = string.Trim();

```

That might be similar to your problem.

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


# Question
Title: How to have separate UI section in Monogame?
So I have a game, and you can move and attack and move the camera around, etc...but I want to have a section of the screen dedicated to Character info like health, etc.

How do I make a fixed section for that and have the game window next to it?

# Answer
> 2 votes
Start a new SpriteBatch draw call, and provide it with a View projection that will draw in screen space instead of world space.

---
Tags: c#, monogame
---


title: Optimising Voxel World Rendering

text:
# Question
Title: Optimising Voxel World Rendering
There are a couple of questions like this already. This one is different because it is specifically about rendering, as opposed to navigation and generation. I've implemented suggestions from here already.

The current optimisations are:

* Only render block faces that aren't adjacent to another face
* Render blocks in chunks, each chunk as one mesh (VAO)

According to the NetBeans profiler, 96% of time is spent on the `glfwSwapBuffers(long window)` method, which is when OpenGL renders the scene. This implies that my other operations are efficient enough, compared to rendering.

What else can I do to improve rendering performance?

The chunk size is 16x16x16 voxels. Sample renders and FPS:

* 64 chunks : 500 FPS
* 125 chunks : 300 FPS
* 1000 chunks : 45 FPS
* 4096 chunks : 12 FPS

# Answer
> 2 votes
For my voxel game, i have (only) implemented:

* Rendering block faces only adjacent to another face.
* Using one VBO per chunk (And another for liquids)
* Frustrum culling at chunk level
* Backface culling

Altough I haven't done it myself, you can also perform some greedy meshing algorithm, "mixing" same type cubes into same triangles. Imagine you have 4 stone blocks, collindant to each other. When drawing the front face of each block you could draw 2 triangles per block, being 8 triangles in total. However, you can take advantage of the fact that all those blocks are of the same type, and you can draw 2 big triangles that cover all those 4 blocks instead. However this method can become tricky to use when each block haves different brightness levels, but anyways, considering that in a voxel game most of the blocks often have the same brightness (No artificial light and full sunlight or no artificial light and no sunlight), this can greatly improve your perfomance.

Nonetheless, i don't think your problem lies there. With almost the same optimizations than you, I can run smoothly more than 14440 chunks, while performing gpu-heavy algorithms (Cascaded shadow mapping, water shading), in a fairly old PC. For all those optimizations, the most important one is "Only rendering block faces that aren't adjacent to another face". Before implementing it, I was only able to draw ~20 chunks at most without lagging. Almost all the perfomance improvements i had been able to achieve relied on **making this optimization work on all cases it should** (For example, in the chunk limits, being for example x=0 and x=15, some of the collindant cubes are outside the chunk. Are you considering this special case? If not, you will be drawing the "outline" of each chunk, killing perfomance). If you disable collisions and go "into" the terrain, you should ideally not see anything drawed, only the terrain outline. It is possible that your problem lies there.

There is a simple test that can help you. Count the number of triangles you are generating, using a static var. Create a flat world, being only the y=0 cube coordinate of the y=0 chunk full, and the rest of the cubes empty. Check how much triangles the program had generated. Now, do a full world, with all cubes full excepting the last cube layer of the last chunk, being air. If the "Only rendering block faces that aren't adjacent to another face" optimization works right, **the number of triangles generated should be equal than the number of triangles in the "empty world" case**, altough the number of cubes is way higher.

Also, you should check that you are only binding textures at the beggining of the program (Or at least only a few times when rendering), that you are using the same shader program without switching it when drawing each chunk, etc.

Hope it helps.

# Answer
> 2 votes
There are quite a lot of way to optimize voxel based rendering, some of them are:

Octrees

Octree is a way to store voxels, you have a root, wich sometimes is the chunk itself, then you have 8 smaller chunk in it, then those also have 8-8 even smaller chunks, etc...

In a chunk with the size of 64, you have the main chunk as root, then 8 smaller chunks, each containing 8 blocks.

After you grouped together all the blocks, then you can do some optimizations, for example, if an octree doesn't have any data in it, delete it or don't even try to render it.

Frustum culling

You get the faces wich are inside the camera's frustum, so they are visible for the user, and only render those.

---
Tags: opengl, java, rendering, lwjgl, lwjgl3
---


# Question
Title: SDL or SFML: which is the best option if I only want to use OpenGL for my graphics?
I've read a lot about creating graphics with OpenGL in SDL and SFML over the past few days, and I want to know which one I should pick. As mentioned in most of the things that I've read, both allow the programmer to use OpenGL.

However, I want to know which one would serve me best if I wanted to do graphics in OpenGL only. From what I've read, SFML does not work as well with OpenGL as SDL. Is this true?

To reiterate, I will only be using SDL or SFML for features like audio, input, and networking. All graphics will be done with OpenGL code that I write.

Also, I read a bit on LWJGL and LWJGL is essentially what I want, but I am much better at C and C++ than Java so I would like to use SDL or SFML. Which one is most similar to LWJGL?

# Answer
> 2 votes
SFML and SDL are both great libraries. I have used them both and IMO are very much interchangeable. The one thing that is very different is the structure of the library itself.

SDL is a C library, and the API is simply a bunch of C functions you can call. SFML is a C++ lib and is OO in nature. If you have a look through the docs, you will notice that right away. This is not to say you cannot or should not use SDL with C++. It just may make more sense for you logically to use them with their native languages.

For me, using SDL with my C projects makes sense since the procedural nature of the library works well with C code (obviously). There is a C binding for SFML as well http://www.sfml-dev.org/download/csfml/ which rewrites the parts of SFML that would not be compatible with pure C.

As for comparisons to LWJGL, just compare the feature lists. I havent used LWJGL much but after taking a quick glance just now it seems to be doing something very similar to SDL and SFML. They are all providing a nice way to access OpenGL, as well as providing convenient ways to accept input, display images, use audio, etc.

Honestly I think you will be happy either way. Take a look at the docs, the community, and the support and just make a decision. They both serve very similar purposes and are 2 sides of the same coin.

# Answer
> 0 votes
Well, I ended up writing my own abstraction layer. I just found it easier in the end to integrate with OS specific features. For example, in Mac OSX I can take advantage MFi Controllers using the GameControllers Framework.

So I have my OpenGL graphics engine(C++), then an abstract input engine that handles keyboard, mouse and controller. It was easy to port to Windows using GLFW and just implement the abstraction layers as wrappers around GLFW.

Writing your own abstraction layer is a good exercise in OO techniques, if you're into that, and it allows more direct control at the cost of development time.

---
Tags: opengl, lwjgl, sdl, sfml
---


# Question
Title: Shader models, when to use "ps_4_0_level_9_x" instead of "ps_4_0"
I've made a very simple post processing shader for my 2D game. It produces scanlines by dimming every other line. For this I use the position of the pixel on the screen.

When using `ps_4_0_level_9_3`, I receive the message:

`shader model ps_4_0 feature level_9_3 doesn’t allow reading from position semantics`

So I switched to just `ps_4_0` and things work fine. I probably won't be using any advanced shaders in my 2D game.

My questions are:

1. By setting the pixel shader to 4\_0 only, what impact does that have for my game (if any) - is it a mistake to 'downgrade' the pixelshader?
2. How do I know what pixelshader version to use? I found this: Direct3D featurelevels but I'm unsure when to use what shader? Is there a list like "for windows use this", "for mobile this" or is it, use the lowest version that supports the feature you need?

# Answer
> 2 votes
Theoretically, you do want to use the lowest level you possibly can. The lower the level, the wider the range of hardware that your game supports, and the more people that can play (and buy) your game.

That said, as you're using DX10/11 already, you're already targeting markets that actually use Vista and up, which mostly coincide with the markets that have DX10-level hardware or better. Targeting SM 5.1 is probably a mistake, but 4.0 is likely just fine.

Given that DX9-level hardware is getting rare for anyone running Vista up these days, I tend to just stick with shader model 4.0 as a minimum. That said, you may feel differently. At least one source indicates that 20% of gamers can't run DX10 either due to hardware or OS, though it doesn't qualify that with market demographics.

There are markets where DX9 is sadly still the API of choice, but those are markets you're very unlikely to have any luck in for a variety of non-technical reasons (e.g. national laws that make life difficult for foreign games, nationalist loyalty from gamers towards domestic game manufacturers, or wildly different game design preferences than present in the West).

This of course is one of the supposed advantages of GL vs DX. With GL, you can use the latest hardware features even on older Windows versions. The flip side is that the drivers are likely out of date and buggy, so your GL app is likely to generate far more support requests and unhappy customers than a DX version. This is why, for example, the browsers all implement WebGL via a DX layer on Windows rather than just using GL directly. Even when the current drivers are high quality, folks on older Windows OSes are far far more likely to be running out of date drivers, and not even know how to upgrade them.

The out-of-date driver problem also affects DX, though to a far lesser degree. I'd suggest targeting only modern Windows OSes unless you have a very strong reason to indicate that XP users make up a significant portion of your target market, as the cost of targeting XP (in terms of development, testing, support, etc.) is just getting higher and higher as time goes on.

**TL;DR**: lower feature levels will widen your potential audience but probably by an insignificant amount.

# Answer
> 1 votes
From what I understand, shader model 3.0 is for directx9, 4.0 is for directx10 and 5.0 is used by directx 11. The 4.0\_feature\_level\_9\_3 is for dx9 but with some features from dx10.

---
Tags: directx, monogame, hlsl
---


# Question
Title: Unity: Adjusting 2D physics for different mobile resolutions
I created a test project to see how different mobile resolutions affects Unity's 2D Physics.

They way I handled the resolutions was to contain all the objects (including non-UI objects) in a Canvas and use a Canvas Scaler component to adjust for multiple resolutions. Although this approach is probably not one of the ways the Canvas was not meant to be used, it works well when working with a single orientation.

Despite the quick solution to handle the multiple resolutions, there seems to be the issue of the physics acting differently depending on what aspect ratio is being used.

Images can be viewed here: https://i.stack.imgur.com/mszoX.jpg

The green and blue blocks both have the Rigidbody2D and Box Collider 2D components. The floor (big white block) only has a Box Collider 2D component.

As you can see from the images above, the different aspect ratios cause the blocks to collide with the floor at different times. Also, when using rigidbody.addforce in the Y direction, the different aspect ratios cause the blocks to jump at different heights.

Obviously these issues could cause an unfair advantage in a game with support for several resolutions.

So how would I go about adjusting the physics so that the blocks fall and jump at the same rates relative to the different resolutions?

Also if there is a more practical way to adjust for multiple resolutions that doesn't involve a plugin and doesn't break physics, let me know!

# Answer
> 1 votes
Instead of using the canvas scaler as a solution, I went the route of DMGregory's suggestion and ended up finding this blog by Adrian Lopez that worked perfectly for my needs.

It turns out that using the canvas scaler to adjust gameobjects with physics components can impact the way gameobjects respond to the physics engine when changing from one aspect ratio to another. This approach would require fine tuning of the physics components' members to create consistent physics across all aspect ratios. Clearly, this is counterproductive to my original idea of a simple aspect ratio adjuster. This revelation and DMGregory's suggestion helped me decide to use another approach.

For the new approach, I went about researching different ways to adjust the camera and came upon the blog I linked earlier in my answer. What this approach does is re-size the camera according to the current screen height and width to add a letterbox or pillarbox effect in order to keep consistency across multiple resolutions. A bonus is that this approach does not alter the physics when changing to different aspect ratios.

---
Tags: unity, rigid-body-dynamics, rigidbody
---


# Question
Title: Unity animations - Is the animation component really deprecated?
I was looking for a way to create simple transform animations for 2d objects. As example, I wanted to animate all the objects of the scene when the game is paused (i.e. I just want to move the objects outside the screen boundaries with a nice animation). I think that creating an Animator Controller for something like this is not really useful for two reasons:

1. I don't know where the objects are at runtime. **Please correct me if I'm wrong**, I think I cannot dynamically change the value of a keyframe attached to an animation controller, so if I just start a transform animation the sprite will jump at the first keyframe value and then performs the animation. Terrible result.
2. If I have 200 objects I should create 200 animation controllers with 200 animations.

Creating animation programmatically would be great, but I read on forums and here on stackexchange that you cannot dynamically handle keyframes... and that I HAVE to use the Animation Controller, otherwise I can use the Legacy animation system (that to me sounds so... deprecated :P)

Then I checked this page of the documentation: http://docs.unity3d.com/ScriptReference/Animation.html

They talk about the "Animation" component... and they don't say this element is Legacy/Deprecated. Looking at this page it seems that I have a lot of control over Animation actually... but know I'm completely confused! Is this component deprecated or not? Should I always use the Animation Controller instead?

# Answer
I would accomplish it by adding an Animator component and an animation clip I wanted to play for the duration of the motion (e.g. a helicopter flying off would play an appropriate animation clip where the blades spin faster or the helicopter angles itself and so on).

I would then code the movement itself with a simple script or by allowing an existing movement script to do it.

```
private bool animateExit = false;

private void Update()
{
    if(animateExit)
    {
        AdjustPosition(1f, 1f);
    }
}

public void AnimateExit()
{
    // plays the exit animation
    GetComponent<Animator>().SetBool("exit", true);
    animateExit = true;
}

// handles the movement
private void AdjustPosition(float x, float y)
{
    transform.position += new Vector3(x, y, 0f) * Time.deltaTime;
}

```
> 1 votes

# Answer
To use old animation component click on your model and set animation to legacy then remove any animation controllers from it and add and animation component. Yeah I think in your case it will be better but check out animation override controller , its use when objects have same animations and you dont have to make same controllers again and again .
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How do i approach these inheritance problem? (Pokemon Gen III)
I'm currently making a Pokemon clone on Python just for the heck of it. After fiddling a bit with some GBA ROM editing tools, i've found out that on these games there are, among other things:

* Events placed on a map, each with a script that is run when you interact with it (Either by running into them or pressing the A button at them). Examples of this are Signposts, hidden items, doors, and more importantly...
* NPCs, which, aside from having scripts (talking, triggering a pokemon battle, etc) can move and/or look around (at least some of them).
* The Player character, which can also move and look around, controlled by the human player or by some outside event that may be manipulating it. But the Player itself is not an event, as it has no associated event scripts on its own. It just triggers everyone else's.

So how should i go about recreating this with Python? By using multiple inheritance, i'd get something like this:

```
class Event(object):
    def __init__(self, x, y script):
        self.x = x
        self.y = y
        self.script = script

class Moving(object):
    ''' objects that can move '''
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction

    def move_one_space_to(self, direction):
        self.x += direction.x
        self.y += direction.y
        self.turn_to(direction)

    def turn_to(self, direction):
        self.direction = direction

class NPC(Event, Moving):
    def __init__(self, x, y, script, movetype):
        Event.__init__(self, x, y, script)
        Moving.__init__(self, x, y, DOWN)
        self.movetype = movetype

class Player(Moving):
    # many methods that an NPC shouldn't have go here
    pass

```

However, even though i may be sidestepping any problems that come with it, i'm still reluctant to use multiple inheritances. So...

Should i stick with this approach? And if not... why not? and can you post a better one?

# Answer
There is a principle in software engineering called DRY which stands for Don't Repeat Yourself.

You might notice that both `Event` and `Moving` have the properties `x` and `y`. This leads to a strange situation in your class `NPC`, which now has two pairs of coordinates, one inherited from `Event` and one inherited from `Moving`. You will have a hard time squishing all the bugs which result from these two getting out of sync.

When you observe duplication of properties, then you should consider to extract these into a common base class. In this case I would create a base-class like `GameObject` with the properties `x` and `y` and have anything inherit from it which has a location in the game world. `Moving` would then inherit from `GameObject` and add logic for changing the position (like finding and following paths from A to B).

Regarding your events: What you call `Event` isn't an event. It is an `EventTriggerArea` which causes an event to happen when the player steps into them. The event is the script attached to it (or rather the invocation thereof).

`NPC`s are also a source of events, but they are triggered completely differently (by pressing A while facing them, not by stepping into them). This is a case where two classes having the same property ("script") does not necessarily mean that they should have a common base-class, because the property *means* something differently for each.

A signpost is just an NPC with no movement behavior and a hidden item is just a signpost with no sprite. You said not all NPCs move around, which doesn't make them any different from signposts. So I would see how far I get with representing them with the NPC class. Or maybe you end up with an abstract base-class `NPC` with two inheriting classes `ImmobileNPC` (inheriting from `NPC` and `GameObject`) and `MobileNPC` (inheriting from `NPC` and `Moving`).
> 2 votes

# Answer
Yes this is probably a bad idea, what will happen is you end up with all sorts of nonsensical unrelated things inheriting all sorts of related things.

This sort of class composition usually just creates problems and inflexible interfaces. If your NPC moves, give it a boolean. Since your NPC's movement is no doubt determined by its mind, or a path let it happen in the script during your game loop. Additionally, your player while moving in reality is controlled. Completely different methods the only relation is in some real world concept of movement, not the code. Which is the inherent problem, it doesn't create any coherent relation to have them both subclass `Moving`.
> 1 votes

---
Tags: python, inheritance
---


# Question
Title: How do I draw individual pixels in the distance?
Hello everyone I am working with unity3d and I am faced with a task. I have a list of 3D points and I want to draw a pixel for every point on the list that exists after my cameras frustums far-plane. After I draw each of the pixels I would like to add a few simple effects to them. Sorry for the terminology I am new to unity! Any help is much appreciated.

# Answer
> 2 votes
You can do this by constructing a custom Mesh and using the Points topology. This tells Unity to render every indexed vertex of the mesh as a single pixel.

```
Mesh CreatePointMesh(Vector3[] points)
{
    Mesh mesh = new Mesh();
    mesh.vertices = points;
    // You can also apply UVs or vertex colours here.

    int[] indices = new int[points.Length];
    for(int i = 0; i < points.Length; i++)
       indices[i] = i;

    mesh.SetIndices(indices, MeshTopology.Points, 0);

    return mesh;
}

```

I'm not sure I fully understand what you're asking with regard to being "after" the camera far plane, so here are two interpretations:

* **Draw individual pixels for each point nearer than the far plane:** you're done - the above technique does this out of the box. :)
* **Draw individual pixels only for content farther than the far plane:** (maybe you're drawing something else nearer, like fully-shaded polygons) To do this, you'll want two cameras: one with your normal near & far planes which renders your near content, and a second whose near plane starts at the other camera's far plane, and whose far plane is very much further out. This second camera should be set to see the layer containing your point mesh created above, while the first camera sees only layers containing the near content. The second/far camera should render before the first/near one, which should clear depth values in order to ensure your content layers correctly. This will result in some overdraw, but since the points mesh is only drawing pixels at a time it probably won't be excessive.

# Answer
> -1 votes
> "How do I draw individual pixels in the distance?"

**Short answer:**

You can't. Pixels aren't 3D and 3D space is not defined by pixels.

**Workaround:**

Pixels don't define the 3D space of your game world, but they do define the 2D space of your screen. While it is impossible by definition to draw a pixel in 3D space, it is possible to map a 3D object onto the camera and draw a pixel on the screen representing the result of that transformation. You'd then be circumventing the 3D rendering system in order to draw directly to the screen. Here is something to get you started. Also, you might also need to use a bit of math to know where to draw the points.

Alternatively, and definitely something I'd recommend, is don't draw pixels - draw spheres. Just scale a sphere down super small until it ends up filling about 1 pixel. You can even scale the sphere based on distance from the camera to make sure it stays about the same size regardless of how near or far the camera is from it.

**Disclaimer:**

I'm not an expert in Unity, and there may very well be an easy technique to accomplish the first workaround automatically.

---
Tags: unity, shaders, fragment-shader
---


# Question
Title: How to publish a game on steam as a company?
I have noticed people put games on steam like http://steamcommunity.com/sharedfiles/filedetails/?id=627434907 where you see the developer profile but how do I get one like http://store.steampowered.com/app/71340/ where it's just a game and the publisher information at the bottom?

# Answer
> 2 votes
The first link that you are seeing is a greenlight game that it isnt released yet. So the process is: As an Indie Developer, you put your game in the greenlight, after that community shows interest and then you can release your game, you'll get a game page as that one with just the game and the publisher infos, a standard one.

---
Tags: steam
---


# Question
Title: how to start the game without entering into menu screen
i am trying to play the game without entering to menu screen. i have placed only one scene. my ui and game both is placed within the same scene. in my game over screen i have two buttons. for home button i give

```
Application.LoadLevel (Application.loadedLevel);

```

by this code is loading the scene from the begning and its working perfectly. in my another button i want to play the game direcly without showing the main menu. so i tried

```
Application.LoadLevel (Application.loadedLevel);
launchGame();

```

but after loading the level my second line launchGame() is not working. how can i solve this problem? please help

# Answer
> 1 votes
There are two features you could use to solve this problem: static variables, and `DontDestroyOnload()`. A static variable is not tied to a certain object, so it will not be erased/inaccessible after reloading the scene. For example, you could add this to a "GameManager" component in your scene:

```
enum GameState { Menus, Battle };
public static GameState gameState = GameState.Menus;

void Awake()
{
    if (gameState == GameState.Battle)
        launchGame();
}

```

And your button would set this new state before reloading the scene:

```
GameManager.gameState = GameManager.GameState.Battle;
Application.LoadLevel(Application.loadedLevel);

```

The other method to have game logic continue running is to have a game object and script that persists when the level is reloaded. To stay persistent, that script must call `DontDestroyOnLoad(gameObject)`. This technique is more complicated, since after reload, you'll end up with two objects in your scene. You'll need care to ensure the correct object is used. (A loader script is sometimes used for this, so the manager will never be duplicated in the scene--the loader will simply need to be smart enough not to load when not needed.)

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


# Question
Title: controll mouse cursor movement speed in unity
Im searching for a way to lower my mouse movement cursor speed and not to let the user move it fast but i dont know how. i searched in internet but could not find something Usefull. thank you for helping.

# Answer
> 2 votes
Assuming you're getting mouse movement by Input.GetAxisRaw, you can simply multiply this by a sensitivity value, for example;

**Sensitivity Vector;**

```
Vector2 sensitivity = new Vector2(0.5f, 0.5f);

```

**Calculating factorized mouse movement**

```
Vector2 mouseMovement = new Vector2(Input.GetAxisRaw("Mouse X") * sensitivity.x,
                                    Input.GetAxisRaw("Mouse Y") * sensitivity.y);

```

To do this you'll need to setup your Input Manager (Edit -\> Project Settings -\> Input) with the following two values;

Alternatively, if you want the value to be fixed, (and not changed in an options menu for example), you can manually change the *Sensitivity* value of the two mouse fields to your liking. Hope this helped you.

---
Tags: unity, input
---


# Question
Title: GameObject does not exit through the left side of the screen
I'm trying to make a game object wrap around, so that as it exits through the right side of the screen it enters through left, and vice versa.

The code snippet below is what I'm working on.

```
Vector3 Pos = mainCam.WorldToScreenPoint(transform.position);
Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f));

if (Pos.x > Screen.width)
        transform.position = new Vector3(LS.x, transform.position.y, transform.position.z);

if (Pos.x < 0)
        transform.position = new Vector3(RS.x, transform.position.y, transform.position.z);

```

So far, exiting through the right and re-entering through left works, but the game object does not exit through the left side of the screen. There seems to be a barrier preventing it, or maybe my parameters for the second if statement are wrong.

# Answer
It looks like you're trying to define `LS` & `RS` in normalized device coordinates (where -1 x is the left edge, +1 x is the right, and 0 z is the near plane):

```
Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f));

```

But Camera.ScreenToWorldPoint takes inputs in **pixels** (except for the z axis, which is measured in world units)

So when your character leaves the left side of the screen (their pixel coordinates' x value is less than 0) and you set them to the same x position as `RS`, you're moving them just about **1 pixel to the right** \- which is why it looks like they're not moving at all.

Instead you probably want something like this:

```
Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(0, 0f, 1f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(mainCam.pixelWidth, 0f, 1f));

```

Note that I also increased the z component. This won't matter if you're using an orthographic camera, but if you ever switch to a perspective camera having a zero here will squash all outputs from `ScreenToWorldPoint` down to the camera position itself.

You may also want to add a little buffer or hysteresis here, so that the character doesn't visibly teleport back-and-forth, but has enough room to move fully off-screen and re-enter from the other side.

You might also want to use ViewportToWorldPoint, which works in coordinates normalized into the 0-1 range. The bottom-left of the viewport is (0,0); the top-right is (1,1).
> 1 votes

# Answer
If there is a barrier, it seems position.x should never be less than 0. Verify that the values from world to screen are not constrained and that there isnt a problem with actually moving the objects elsewhere.
> 0 votes

# Answer
In here:

```
Vector3 LS = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));

```

I imagine you ment to write:

```
Vector3 LS = mainCam.ScreenToWorldPoint(new Vector3(0, 0, 0));

```
> 0 votes

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


# Question
Title: How should I efficiently clear and redraw my canvas with lots of animated sprites?
My current solution is to clear the entire canvas and redraw all sprites on every requestFrame(). This works but feels inefficient:

1. I only need to clear the part of the canvas made invalid by animations.
2. I only need to redraw objects that intersect the invalid part of the canvas.

I can track invalidated sections, and during requestFrame() I can find out which objects intersect an invalid section and redraw only them, but I'm not sure if that's an improvement or a step back. If I have 100 sprites and 10 of them are moving, that means I need to do 10 searches through all 100 sprites. Tall order for every request frame.

I can also put every sprite on its own canvas and remove sprite interaction from the equation, but I haven't been able to find insight into how many canvases is too many.

This seems like a problem that's been solved already, but I haven't found any resources on the topic.

# Answer
> 3 votes
The first thing you should do is figure out if you actually have a problem.

Is the way you're clearing the canvas now slow? Are you dropping frames because of how you clear the canvas? Regardless of how it looks (for now), remove the call that clears the canvas and measure again. Are your paint cycles a lot faster now?

Basically, I wouldn't worry about this until you know it is a problem. The technique you're looking for is dirty rectangle updating, but it is computationally more expensive and until you know what it saves you it's hard to make the proper engineering decision here.

---
Tags: javascript, html5, html-canvas, design-patterns
---


# Question
Title: How can I correctly instantiate an octree in UE4?
I tried to create a simple Octree like this: (I looked at the FMeshTriOctree source code since no question in answers.unrealengine.com helped me)

```
// My FVertex class is slightly more complexe, but let's say it's something like this:
class FVertex : public FVector
{
      int32 ID;
}

struct FVertexOctreeSemantics
{
        enum { MaxElementsPerLeaf = 16 };
        enum { MinInclusiveElementsPerNode = 7 };
        enum { MaxNodeDepth = 12 };

        typedef TInlineAllocator<MaxElementsPerLeaf> ElementAllocator;

        FORCEINLINE static FBoxCenterAndExtent GetBoundingBox(const PBS::FVertex* Vertex)
        {
            return FBoxCenterAndExtent(Vertex->GetBoundingBox());
        }

        FORCEINLINE static bool AreElementsEqual(const PBS::FVertex* A, const PBS::FVertex* B)
        {
            return A==B;
        }

        /** Ignored for this implementation */
        FORCEINLINE static void SetElementId(const PBS::FVertex* Element, FOctreeElementId Id){}
};

typedef TOctree<PBS::FVertex*, FVertexOctreeSemantics> FVOctree;

```

But when I instanciate my octree it returns:

```
Fatal error: [File:D:\BuildFarm\buildmachine_++depot+UE4-Releases+4.9\Engine\Source\Runtime\Core\Private\Misc\CoreMisc.cpp] [Line: 975]
The TOctree() constructor is for internal usage only for hot-reload purposes. Please do NOT use it.

```

What can I do?

# Answer
The error is telling you that the default constructor of `TOctree` isn't something you're supposed to use directly. Instead, use a different constructor. You probably want to use the one that takes a center point and an extent:

```
TOctree(const FVector& InOrigin,float InExtent)

```

If you notice, the example source code you linked to stores a pointer to the octree type:

```
TUniquePtr<FMeshTriOctree> MeshTriOctree;

```

which it then instantiates as

```
MeshTriOctree = MakeUnique<FMeshTriOctree>(
  Bounds.GetCenter(),
  Bounds.GetExtent().GetMax()
);

```

The default constructor is only available when building with hot-reload constructors enabled; if you were to disable that option you'll get a regular old compile error, so you shouldn't rely on that constructors existence.
> 1 votes

---
Tags: c++, unreal, octree
---


# Question
Title: Text field is null while running but not in inspector
I've encountered a strange problem. In my game I have a prefab called UiManager. It has two public Text-fields, one for score, and one for lives. I only have one instance of this prefab and I've assigned the two Text-fields with two text-objects. Yesterday it worked well.

Today I reopened my project and started the game and when I collected a life I got a null reference on the text field Lives. Now clearly it is not null, I tried to delete my instance and recreate it and then assigning the Text-fields again, and it worked.

I then saved my project and exited Unity and reopened my project and now the issue was back again, a null reference on Lives. Also I noticed that it is not possible to apply ui-objects to a prefab (?).

Anyway, does anyone have any idea why this occurs?

Have a nice day!

# Answer
> 1 votes
There must be only one reason in my view.

If you are trying to attach any object to *prefab* from *hierarchy* then your information will be last till exactly that very prefab exists.

Means if you create a new instance of that prefab then your fields will be empty.

But **YES** your prefab will save the reference if you drop elements from Unity Project Explorer, not from Hierarchy.

---
Tags: unity, gui
---


# Question
Title: How to make transitions between images in canvas (unity)
So I have 3 same images, but with different colors which I want to cycle in my menu. They are only with different hue/saturations and I want them to slowly reduce their alpha 1 by 1 so that the one behind pops up and then restart the cycle.

I'm trying to set a public image and reduce it's alpha, but it's not smooth.

# Answer
> 0 votes
please more describle your problems by picture or your code but you can easily smooth it by `Time.deltatime` in your code:

```
    using UnityEngine;
    using UnityEngine.UI;
    using System.Collections;

    public class FadeOut: MonoBehaviour
    {
        public Image FadePanel;

        void Update ()
        {
            Color newColor = FadePanel.color;
            newColor.a -= 1*Time.deltaTime;
            FadePanel.color = newColor;
        }
    }

```

or you can Find your Image by FindGameObjectWithTag

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ReduceAlpha: MonoBehaviour
{
    void Update()
    {
        Image healthImage = GameObject.Find("GameObject").GetComponent<Image>();
        Color newColor = healthImage.color;
        newColor.a -= 1*Time.deltaTime;
        healthImage.color = newColor;
    }
}

```

# Answer
> 0 votes
No offense, just for information, provided answer by brother **smkplus** is really not that optimized.

* It is in `Update` due to that, these lines will be executed per frame with and without reason.
* In 2nd option, `GameObject.Find` is in `Update`, believe me or not, it is a crime bro :)

I'd suggest to use Unity's gift `Coroutine` for that.

Here is an example code,

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Help8 : MonoBehaviour
{
    public Image _image;
    public float _fadeSpeed = 0.05f;

    void Start ()
    {
        StartCoroutine (Fadeout (_image, _fadeSpeed));
    }

    void Update ()
    {
        // Update is empty for this purpose.
    }

    // You can use it for multiple images, just pass that image.
    IEnumerator Fadeout (Image image, float speed)
    {
        // Will run only until image's alpha becomes completely 0, will stop after that.
        while (image.color.a > 0) {

            // You can replace WaitForEndOfFrame with WaitForSeconds.
            yield return new WaitForEndOfFrame ();
            Color colorWithNewAlpha = image.color;
            colorWithNewAlpha.a -= speed;
            image.color = colorWithNewAlpha;
        }
    }
}

```

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


# Question
Title: How should player be able to hear 2D spatial sound?
Let's say there is a multiplayer 2D game and a 2D spatial sound system, in which sound volume decreases, when distance to the sound position increases. E.g. explosion happens. Should player hear it if it's outside the camera's viewport zone? Basically, how big should a max distance to sound position should be? How is it handled in other 2D games?

# Answer
> 2 votes
I would say it works best if you can hear things that are just outside the screen too. This helps in creating the illusion that the world continues outside the screen. Try to set it up so that the volume is linearly connected to the distance from the player.

volume = distance/maxAudibleDistance

maxAudibleDistance would be for example 75% of your screen size, assuming your character is always in the center of the screen. Then you could hear explosions faintly if they happen 25% distance outside your screen.

---
Tags: 2d, sound, sound-effects
---


# Question
Title: Calculate matrix transformation components separately
It is possible to calculate the translation, rotation and scale that were used to build a matrix?

I mean if I have a matrix `M` can I calculate the rotation, scale, and translation it represents?

Of course I could save each component in the matrix individually, but can I recover this information from just the matrix data?

# Answer
> 7 votes
Assuming the following matrix multiplication convention, where \\$M\\$ is the matrix you want to decompose, and the \\$\vec p\\$ variables represent points as column vectors with a w coordinate \\$p\_w = 1\\$...

$$\begin{array}{lc} \vec p\_{transformed} = M \times \vec p\_{local} & M=\begin{bmatrix} m\_{00} & m\_{01} & m\_{02} & m\_{03} \\ m\_{10} & m\_{11} & m\_{12} & m\_{13} \\ m\_{20} & m\_{21} & m\_{22} & m\_{23} \\ 0 & 0 & 0 & 1 \\ \end{bmatrix} \\ & \text{where $M$ is assumed to be}\\ & \text{decomposible into: }\\ \vec p\_{transformed} = T \times R \times S \times \vec p\_{local} &M = T \times R \times S\\ \end{array}$$

Here the component matrices are:

* Translation by a vector \\$\vec t = (t\_x, t\_y, t\_z)\\$: $$T=\begin{bmatrix} 1 & 0 & 0 & t\_x \\ 0 & 1 & 0 & t\_y \\ 0 & 0 & 1 & t\_z \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}$$
* Rotation by an orthonormal rotation matrix \\$R\\$ (with determinant 1), and...
* Axis-aligned scale by \\$(s\_x, s\_y, s\_z)\\$: $$S=\begin{bmatrix} s\_x & 0 & 0 & 0 \\ 0 & s\_y & 0 & 0 \\ 0 & 0 & s\_z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}$$

Then **it is possible to compute *a choice of* translation \\$T\\$, rotation \\$R\\$, and scale \\$S\\$ with the same combined result as \\$M\\$.**

But there is *no guarantee that these will be the same values originally used to create* \\$M\\$, as we'll see below.

You also may **lose precision due to rounding errors along the way**, so you should **avoid repeated round-trip conversions** between \\$M\\$ and \\$T \\, R \\, S\\$, such as when laying out objects in a level editor, saving and loading as you go.

This also goes for updating the transform of a dynamic object at runtime. Being able to rebuild the matrix from raw translation, rotation, and scale values will help you avoid harmful rounding errors.

So, **it will almost certainly be worth keeping the extra memory to store your original transformation parameters**, both for consistency from a user's perspective, and for accuracy/stability.

That said, if it's something you're using in a read-only manner, or you need to reconstruct transformation parameters from baked data which only contains combined matrices, you can do it like this...

---

First, the translation vector is the image of the origin position vector after transformation:

$$\vec t = M \times \begin{bmatrix}0\\ 0\\ 0\\ 1\end{bmatrix}$$

Which we can look at as simply extracting the last column of the matrix. In pseudo-code:

```
Vector3 translation = Vector3(matrix[0, 3], matrix[1, 3], matrix[2, 3])

```

The scale can be computed as the length of the basis vectors multiplied by `M`:

$$s\_x = \Vert M \times \begin{bmatrix}1\\0\\0\\0\end{bmatrix} \Vert, \quad s\_y = \Vert M \times \begin{bmatrix}0\\1\\0\\0\end{bmatrix} \Vert, \quad s\_z = \Vert M \times \begin{bmatrix}0\\0\\1\\0\end{bmatrix} \Vert$$

Which is just the length of each of the first three columns interpreted as vectors. In pseudo-code:

```
Vector3 scale;
for(int i = 0; i < 3; i++) {
    scale[i] = sqrt(
                 matrix[i, 0] * matrix[i, 0]
               + matrix[i, 1] * matrix[i, 1]
               + matrix[i, 2] * matrix[i, 2]);
}

```

If your scales can be negative then you have an added complication to solve. A reflection in *any one axis* is identical to a reflection in a *different* axis combined with a suitable rotation, and a reflection in two axes is equivalent to a pure rotation.

So, you'll need to pick a convention for resolving this. One is to detect whether there is a net reflection (ie. a reflection along 1 or 3 axes) using the determinant/triple-scalar product and decide by fiat that it should be represented by a reflection along the x axis:

```
if dot(
       cross( Vector3(matrix[0,0], matrix[1,0], matrix[2,0]),
              Vector3(matrix[0,1], matrix[1,1], matrix[2,1])),
       Vector3(matrix[0,2], matrix[1,2], matrix[2,2])
   ) < 0)
then
   sx *= -1

```

(if `sx` or any other scale is zero then you're dealing with a planar, line, or point projection, so we can express it as a rotation without reflection)

With \\$S\\$ in hand we can divide it out to reconstruct an appropriate \\$R\\$:

$$R=\begin{bmatrix} \frac{m\_{00}}{s\_x} & \frac{m\_{01}}{s\_y} & \frac{m\_{03}}{s\_z} & 0 \\ \frac{m\_{10}}{s\_x} & \frac{m\_{11}}{s\_y} & \frac{m\_{13}}{s\_z} & 0 \\ \frac{m\_{20}}{s\_x} & \frac{m\_{21}}{s\_y} & \frac{m\_{23}}{s\_z} & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}$$

Note that if one of \\$s\_x\\$, \\$s\_y\\$, or \\$s\_z\\$ is zero, you'll want to replace the corresponding column with the cross product of the other two to avoid a divide by zero error.

If two axes have zero scale, you can pick two arbitrary unit vectors mutually orthogonal with the remaining axis. If all three axes have zero scale, you can let the rotation matrix be the identity matrix, \\$R = I\\$, since a point is a point regardless of rotation.

By construction \\$R\\$ *should* be an orthonormal rotation matrix, but in practice numerical errors can cause it to deviate, so including an error-correction step where you orthonormalize it is probably a sensible precaution.

You can use the usual methods to convert that rotation matrix into an equivalent unit quaternion or Euler angle triplet if needed, so I won't elaborate on that here.

# Answer
> 0 votes
You can multiply translation, rotation, and scale matrices to get one, final movement matrix.

If you are asking how to extract the values from one final product of several translation, rotation, and scale matrices, then no. It is like trying to find the chosen divisor of a number, say 16. It can be 4, 2, 8, etc.

There is no method to do this (get IDENTICAL translations, rotations, and scales to your original values) unless you have previous matrices, in which case you can divide (for the 16 example: say that you know one of the divisors is 8. Then, you can divide by 8 to get 2 -\> this logic is a little different for matrices).

If you are asking how to get translation rotation and scale values from one matrix dedicated to one of those things, then that is easy. It depends if you are using column major or row major order. For that, use this helpful link: http://www.codinglabs.net/article\_world\_view\_projection\_matrix.aspx

Transformation:

```
TransformxAxis.x TransformyAxis.x TransformzAxis.x Translation.x
TranformxAxis.y  TransformyAxis.y TransformzAxis.y Translation.y
TransformxAxis.z TransformyAxis.z TransformzAxis.z Translation.z
0                0                0                1

```

\*depends if you are in 3D or 2D

Translation:

```
1 0 0 Translation.x
0 1 0 Translation.y
0 0 1 Translation.z
0 0 0 1

```

Scale:

```
Scale.x 0 0 0
0 Scale.y 0 0
0 0 Scale.z 0
0 0 0       1

```

Check the link for all of them-\> Under "Transformation matrix"

---
Tags: c++, mathematics, directx, directxmath
---


# Question
Title: Resolving A counters B, who is countered by C, who could be.... in an ATB
There are 4 player character slots and 8 enemy slots. I'm using a combat system that's similar to ATB from FF4; You select a move, there's a waiting period depending upon the move, during which other moves can happen, and then it is executed. The problem is some moves counter other moves and this changes targeting.

**Example:**

Enemy A is targeting Player 1 with Stampede. Player 2 decides to use a sweep attack on Enemy A to stop it. If nothing else happens, this causes Player 2 to become the new target for any damage dealt by Enemy A's Stampede (he's jumping in there and breaking up the attack, if damage is dealt, it's to him now).

**Here's the problem:** If Player 2 is being countered then he can't counter Enemy A, unless whoever is countering Player 2 is also being countered, in which case he can, unless someone is countering the ... and I'm not sure the cases ever end, even with just the 12 participants.

I need a working theory on how to logic through it smoothly in a pile of code that isn't Mount Everest. How do I narrow the results until I figure out the exact result?

Using GML if it matters.

# Answer
This is a really simple problem if you stop thinking about what happens to everything at once, and deconstruct it: **moves can either happen, or be countered**. Then all you have to do is figure out where the sequence begins, set it off there, and let everything resolve each other. It's like dominoes.

Games like Magic the Gathering models this as a **stack**. Whenever a player plays a move, the opponent can play another move to counter it, but nothing happens yet, it all goes on a stack - literally a stack of moves/cards, if that's easier to visualise. The first player can then play something to counter that, and so on and so on, building the stack up until someone stops. Then the stack is "unwound", from the top to the bottom. The topmost move works because it isn't countered, but the one below it is countered so it doesn't work. Now you're left with a smaller stack, but it works the same way: **the topmost move in the stack works; the one below it doesn't because it is countered.** That's it. You don't need to worry about how big the stack is, which moves are countered by the counter of the counter of the whatever. It's just these questions:

* Is this move countered? (yes/no)
* What happens if this move is, or isn't countered? (this if countered, or that if not countered)
* (Logical) stack of moves (add moves to the top, resolve them from top to bottom)

## Example

Let's try an example game, and we'll build up the stack.

**Enemy A attacks Player 1 with Stampede**

Imagine we add this to a stack now:

```
|                                        |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```
* Is this move countered? (**no**, because it's the topmost item on the stack)
* What happens? (**Player 1 totally gets their ass stampeded**)
* What happens to the stack? (**it becomes empty**)

So far so good, easy. Now let's play Player 2's counter...

**Player 2 sweep attacks Enemy A**

Now our stack grows:

```
|                                        |
| Player 2 sweep attacks Enemy A         |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```

We resolve these moves from the top to the bottom. So let's do Player 2's sweep first:

* Countered? (**no**, it's top of stack)
* What happens? (**Enemy A's attack gets countered by Player 2**)
* Stack? (**1 move left**)

Let's pause here. The sweep attack you've defined isn't a simple counter. It **changes the target of the countered move to the countering player.** This means that, in addition to tracking whether moves are countered, you also need to track **which player/enemy did the countering.** Then we are left with this stack:

```
|                                        |
| Enemy A attacks Player 2 with Stampede |  <-- different target!
+----------------------------------------+

```

And keep going...

* Countered? (**yes, by Player 2**, this means the target changes to Player 2)
* What happens? (**Player 1 2 totally gets their ass stampeded**)
* Stack? (**empty**)

There's some trickiness going on with the counter just then, but notice that the way the stack works doesn't change. Now let's imagine something countering Player 2's sweep:

**Enemy B steals Player 2's broom**

...because sweeping is done using brooms right? Yeah...

```
|                                        |
| Enemy B steals Player 2's broom        |
| Player 2 sweep attacks Enemy A         |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```

You should know how the stack works now. **The steal succeeds, Player 2's sweep gets cancelled** because they don't have a broom.

```
|                                        |
|              *poof!*                   |
|          *poof! cancelled!*            |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```

The result: **Player 2 loses their broom, Player 1 totally gets their ass stampeded**.

**Player 3 chastises Enemy B**

Stealing is bad and is easily prevented by chastisement. Our stack is starting to get pretty tall, but no worries, it works all the same.

```
|                                        |
| Player 3 chastises Enemy B             |
| Enemy B steals Player 2's broom        |
| Player 2 sweep attacks Enemy A         |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```

The chastisement works!

```
|                                        |
|              *poof!*                   |
|      *poof! Enemy B feels guilty*      |
| Player 2 sweep attacks Enemy A         |
| Enemy A attacks Player 1 with Stampede |
+----------------------------------------+

```

Player 2 can now do the sweep:

```
|                                        |
|              *poof!*                   |
| Enemy A attacks Player 2 with Stampede |  <-- different target!
+----------------------------------------+

```

The result: **Enemy B feels guilty, Player 2 totally gets their ass stampeded**.

## What you need

As you can see, it doesn't matter whether a move is countered because there's a move countering the move countering the move countering itself... it's only a binary choice: **is it countered or not**. You use a stack to track which moves counter which.

GML has the **ds\_stack** data structure.

And, to handle complex counters like the sweep move (which modifies the moves that it counters), track **which player did the countering**.
> 3 votes

---
Tags: game-design, game-mechanics, logic
---


# Question
Title: C# - How to properly play background songs in XNA
So I'm using the game states (`enum`) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this:

```
bool songStart = false;
Song song1;
Song song2;

// LoadContent method:
song1 = Content.Load<Song>(".\\Songs\\mainMenuTheme");
song2 = Content.Load<Song>(".\\Songs\\mainGameTheme");
MediaPlayer.IsRepeating = true;

// Update method:
switch (CurrentGameState)
{
case gameState.mainMenu:
        if (CurrentGameState == gameState.mainMenu && !songStart)
    {
        MediaPlayer.Stop();
        MediaPlayer.Play(song);
        songStart = true;
    }
    else if (CurrentGameState != gameState.mainMenu && songStart == true)
    {
        MediaPlayer.Stop();
        songStart = false;
    }
break;
case gameState.gamePlaying:
        if (CurrentGameState == gameState.gamePlaying && !m_SongStart)
        {
            MediaPlayer.Stop();
            MediaPlayer.Play(song2);
            m_SongStart = true;
        }
        else if (CurrentGameState != gameState.gamePlaying && songStart == true)
        {
            MediaPlayer.Stop();
            songStart = false;
        }
break;

```

So if I am in `mainMenu`, the first song plays; when I go to `gamePalying` the first song stops and the second one starts playing. If I return to `mainMenu`, the `mainMenu` song plays. My issue however, is that if I click `Play game` and the state moves to `gamePlaying` `there is no background music!` What could've caused the problem? Please help me fix it, I'm stuck for a whole week.

# Answer
> 1 votes
This is an old thread, but I noticed it didn't *really* have an answer. I worked up this:

```
switch (currentGameState)
        {
            case GameState.MainMenu:
                if (musicState == MusicState.Playing && currentGameState != lastGameState)
                {
                    MediaPlayer.Stop();
                    musicState = MusicState.NotPlaying;
                }
                if (musicState == MusicState.NotPlaying)
                {
                    MediaPlayer.Play(song_mainTheme);
                    musicState = MusicState.Playing;
                }
                break;

            case GameState.GamePlaying:
                if (musicState == MusicState.Playing && currentGameState != lastGameState)
                {
                    MediaPlayer.Stop();
                    musicState = MusicState.NotPlaying;
                }
                if (musicState == MusicState.NotPlaying)
                {
                    MediaPlayer.Play(song_actionTheme);
                    musicState = MusicState.Playing;
                }
                break;
         }

```

You have to make sure to assign lastGameState = currentGameState at the end of the loop, so the next time it runs through it won't start the song over 60x a second. And of course a way to switch states through the case.

# Answer
> 0 votes
Looking over the code you should be able to :

```
switch (CurrentGameState)
{
case gameState.mainMenu:
       MediaPlayer.Stop();
       MediaPlayer.Play(song);
break;
case gameState.gamePlaying:
       MediaPlayer.Stop();
       MediaPlayer.Play(song2);
break;
}

```

I wasn't sure if calling .Stop() without music playing would throw an error, if it does, that's when you could do

```
try {
MediaPlayer.Stop();
}
     catch (exception e)
{
     // Probably do nothing.
}

```

# Answer
> 0 votes
Like in your original post, you have one boolean that is set to true only when you change state. like when you click some button in menu.

on part where you change `CurrentGameState` set also `stateChanged` to true. and this code will be exectuted only once in your update funciton.

```
if(stateChanged){
   MediaPlayer.Stop();
   switch (CurrentGameState)
   {
      case gameState.mainMenu:
         MediaPlayer.Play(song);
      case gameState.gamePlaying:
         MediaPlayer.Play(song2);
   }
   stateChanged = false;
}

```

for such cases my mainMenu have beside `Update`, `Draw`, `Reset`, `Dispose` have `Init` funciton (that load textures, music, buttons, level...) that is exectued only once when somebody change state to mainMenu using similar logic.

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


title: Open-World objective/goal idea

text:
# Question
Title: Open-World objective/goal idea
My game is an open-world. But i'm stuck on the goal/objective. Is there a list of goals/objective for an open-world games?

# Answer
This is a good question, and I know a group of people who have addressed this question in the following link; in the video, some of the ways in which games fulfill the player's desire has been discussed in general terms.

https://www.youtube.com/watch?v=uepAJ-rqJKA

There are a number of needs that games fulfill, an open-world game may fulfill the following depending on the content, theme and modes of play:

1) sense of discover: if your game focuses on content and has an attractive landscape, players may derive pleasure in discovering new things, in which case, you can place set-pieces like ancient ruins that tells a story, and the player is trying to find all the ruins to reveal the story, all the while roaming a landscape that is pleasant to look at and move through.

2) fantasy: if your game allows the player to be more than a normal human being and someone/something the player would like to be, such as a fish or a bird or some mythical creature, than the player will enjoy the role playing as the avatar. For such games, I suggest a story-driven series of objectives like fighting enemies, finding items, finding locations etc., since in such games the important part is the role-playing, the goals the player try to fulfill may not need to be significant in themselves, so long as they are consistent with the theme of the protagonist and the world.

3) narrative: if your game is set in a world where the player instinctively feel curious, then you can prepare a compelling story that resonate with the theme. For example, if your world is set in a vast desert with debris of spaceships scattered about, the player will want to know who were in the spaceships, why have they fallen, who is the protagonist etc. In narrative-focused games the objectives should not be too complex or involve too much repetition, since these may either become unnecessarily frustrating or distracting.
> 1 votes

---
Tags: game-mechanics
---


title: Problem in power up generation

text:
# Question
Title: Problem in power up generation
I am trying to instantiate an obstacles, Currency and Power up in the game. i am using same script to instantiate all. obstacles and currency are working perfectly but power ups is not generating in a game. it displays an error message

NullReferenceException: Object reference not set to an instance of an object ElementsGeneratorss.instantiateElement (Int32 elementNumber, Vector3 v3Position, Single CurrentAngle, Vector3 hitInfoNormal) (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:312) ElementsGeneratorss.generateElements (Int32 elementNumber, Single fLocation, Boolean bStartPatch) (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:225) ElementsGeneratorss+c\__Iterator1.MoveNext () (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:115)

i used C# Script

```
private void instantiateElement(int elementNumber, Vector3 v3Position, float CurrentAngle, Vector3 hitInfoNormal)
{
    if (elementNumber < 0)
        return;

    Transform ObjectHandle;

    if (elementNumber < iObstacleCount)//obstacles
    {
        // for generating obstacles. its working perfectly
    }
    else if (elementNumber >= iObstacleCount && elementNumber < (iObstacleCount+iPowerupCount))//powerups
    {
        ObjectHandle = elements[elementNumber].tPrefabHandle[elements[elementNumber].iPrefabHandleIndex];
        elements[elementNumber].iPrefabHandleIndex++;
        if (elements[elementNumber].iPrefabHandleIndex >= elements[elementNumber].tPrefabHandle.Length)
            elements[elementNumber].iPrefabHandleIndex = 0;
        ObjectHandle.gameObject.SetActive(true);
        ObjectHandle.up = hitInfoNormal;
        ObjectHandle.position = v3Position;
        ObjectHandle.localEulerAngles = new Vector3(0,0,0);
        ObjectHandle.Rotate(0,CurrentAngle,0);
        ((PowerupScriptss)ObjectHandle.GetComponent(typeof(PowerupScriptss))).initPowerupScript();
    }
    else if (elementNumber == (iObstacleCount+iPowerupCount))//currency
    {
        // for generating currency. working perfectly
    }
}

```

# Answer
Set the currency value to a very low number, e.g. if you set the value to 10 it will generate a large count.
> -2 votes

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


title: Unity 5.3.1: Single player is broken

text:
# Question
Title: Unity 5.3.1: Single player is broken
In Unity I converted my single player game to a multiplayer game. Now, the single player game does not work anymore because the objects are disappearing on start, due to the network identity.

What is the best practice for still using the same objects in a single player game?

My question is about a general implementation, and not about something in my game specific.

**Example:**

We create a simple single player game:

* Make a sphere
* Make a script to move it with arrows

We have a single player game!!

* Change the script to be a networkbehaviour
* Check for islocalplayer in the script
* Make the sphere a network identity
* Make a network controller

Now we have a multiplayer "game"!

HOWEVER

If we now want to play this game singleplayer, it will not work. Just try adding the sphere to a scene. It will disappear on start.

What can I do to make the object usable in both single and multiplayer scenes?

# Answer
> 1 votes
You may be overthinking it. Perhaps you can simply start your game as a host and not allow any additional connected players.

The NetworkManager enables your game to have multiple clients. It does not require you to. Trying to build a second version of your game for single players is often needless effort.

# Answer
> 0 votes
From Philipp's answer here:

For an online Multi player game, we take pong game as example.

The MVC pattern is a good solution here. You would need three different controllers:

* The `LocalPlayerController` which is sending commands to a paddle by listening to the local input devices. If you have multiple input devices (keyboard, mouse, gamepad...) it might be a good idea to further subclass it into the one it listens to. In any case, these class(es) should be used in both singleplayer and multiplayer, because it makes no difference for the control who you are playing against.
* The `AIController` which analyzes the current game state and sends commands to an ai-controlled paddle.
* The `RemotePlayerController` which listens to a network socket and interprets the incomming messages as commands to a paddle.

Regarding network output: This would not be another Controller, this would be another View. A view is not just something you see on the screen. It is any form of output representation of the model (the model in the context of game development would be the game state). It can be a graphical output on the screen or a data stream sent over the network. In this case the `NetworkView` would observe any paddles controlled by `LocalPlayerControllers` or `AIControllers` and translate their movement to the network.

---
Tags: unity, multiplayer, single-player
---


# Question
Title: Game states & passing data between scenes
I'm not entirely sure if I'm doing this right, but I always considered the scene system in Unity as some sort of state management (rather than e.g. a level system) which allows to group the contents (entities, components) into the usual main states of the game (menu, ingame), which can then be invoked or replaced together.

Now I have a very specific concern and I have no clue how to deal with that in Unity, mostly because of it's abstractions from code and other restrictions:

My game features a procedurally generate terrain where as I'd like to tweak the generator before actually launching it. The tweaking is done in some sort of 'pre-game' state (as part of the main menu) where the values are stored in e.g. TerrainData model class. Usually in other engines, I'd to it like this:

1. Providing an UI within the menu state to tweak the parameters of the game
2. Storing the parameters in a view model (and data model)
3. Instantiate the ingame state (which requires said data model in the .ctor
4. Pass the data model to a generator and start the generation

Now, here are the main problems:

* Most types in unity (scenes, monobehaviors) do not allow constructors because they use it for themselves
* It doesn't seem possible to instantiate scenes manually (there's only e.g. Application.LoadLevel("") which only takes the name of the scene, not a instance reference etc.
* it doesn't seem possible to pass data between scenes, without reverting to awkward workarounds such as singletons, playerprefs, DontDestroy etc. which are all not really suitable for this case.

So, how can I properly solve this? Is there a better way to manage states rather than scenes? Prefabs maybe?

Backlink to UntityAnswers question: http://answers.unity3d.com/questions/1149480/game-state-management-and-passing-data-between-sce.html

# Answer
Singletons, PlayerPrefs and the DontDestroyOnLoad flag are already three ways to pass data between scenes. There is also a fourth one: `static` variables which do not use the Singleton pattern but are only available to the local class.

There is also `SceneManager.LoadScene ("play_scene", LoadSceneMode.Additive);` which loads a new scene without destroying anything in your current scene. That means you can use this method from your UI to load the play-scene without destroying your UI and the data model it operates on and then initialize the scene from the UI. Caveat: You can't use the Unity editor to assign objects from the Game-Scene to inspector properties of objects in the UI-Scene, so you will have to extract them from the scene graph with `GameObject.Find` and `GetComponentInChildren`. After setting up the play-scene, you can remove everything which belongs to the generator-scene with `SceneManager.UnloadScene("generator_scene");`.

Another option would be to implement your generator tweaking GUI in the actual game scene. Put your whole game scene in one parent-object and set it to deactivated when the scene loads. Then put the whole generator-UI into a different object and activate it. Put any shared stuff (like the model you operate on) in a third one.

When the user made their input and clicks "OK", deactivate the generator UI game-object and activate the actual game game-object.
> 2 votes

---
Tags: unity, procedural-generation, scene, game-state
---