# Question
Title: Generate 4 vectors rotated in cardinal directions from a central vector
There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code:

```
Vector3 center = point;
Vector3 left = Quaternion.Euler(-30, 0, 0) * center;
Vector3 right = Quaternion.Euler(30, 0, 0) * center;
Vector3 back = Quaternion.Euler(0, 0, -30) * center;
Vector3 front = Quaternion.Euler(0, 0, 30) * center;

```

The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together".

Here is a visualization of what I need:

Test code is attached:

```
using System.Collections;
using UnityEngine;

public class Test : MonoBehaviour
{
    public GameObject centerGO;
    public GameObject leftGO;
    public GameObject rightGO;
    public GameObject backGO;
    public GameObject frontGO;

    ArrayList list = new ArrayList();

    void Start()
    {
        SetCenterPoint(Vector3.up);
    }

    void Update()
    {
        DrawDebugRays();

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            SetCenterPoint(hit.point);
        }
    }

    void SetCenterPoint(Vector3 point)
    {
        Vector3 center = point;
        Vector3 left = Quaternion.Euler(-30, 0, 0) * center;
        Vector3 right = Quaternion.Euler(30, 0, 0) * center;
        Vector3 back = Quaternion.Euler(0, 0, -30) * center;
        Vector3 front = Quaternion.Euler(0, 0, 30) * center;

        centerGO.transform.position = center;
        leftGO.transform.position = left;
        rightGO.transform.position = right;
        backGO.transform.position = back;
        frontGO.transform.position = front;

        list.Clear();
        list.Add(center);
        list.Add(left);
        list.Add(right);
        list.Add(front);
        list.Add(back);
    }

    void DrawDebugRays()
    {
        for (int i = 0; i < list.Count; i++)
        {
            Color color = Color.red;
            switch (i)
            {
                case 0:
                    color = Color.green;
                    break;
                case 1:
                case 2:
                    color = Color.blue;
                    break;
            }
            Debug.DrawRay(Vector3.zero, (Vector3)list[i], color);
        }
    }
}

```

# Answer
Pick a local coordinate system that puts your center direction along the local z+ axis, then rotate the other 4 relative to those coordinates:

```
Quaternion localSpace = Quaternion.LookRotation(centerDirection);

Vector3 backDirection = localSpace * Quaternion.Euler(-30, 0, 0) * Vector3.forward;
Vector3 frontDirection = localSpace * Quaternion.Euler(30, 0, 0) * Vector3.forward;
Vector3 rightDirection = localSpace * Quaternion.Euler(0, -30, 0) * Vector3.forward;
Vector3 leftDirection = localSpace * Quaternion.Euler(0, 30, 0) * Vector3.forward;

```
> 2 votes

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


# Question
Title: How could I implement collision resolution with MonoGame
I'm building a game engine (for learning and self-development purpose), and I'm starting implementing collision resolution, I already have the collision detection part but I cant' find any good article or post about that and how to achieve it in details.

Here's my code for the collision detection:

That's the method called in the `Update` method, the Engine holds a list of BoxColliders called `Colliders`

```
private void CollisionDetection()
{
    foreach (BoxCollider boxCollider in Colliders)
    {
        if (!boxCollider.Collider.HasValue) continue;

        var collider1 = (Rectangle) boxCollider.Collider;
        foreach (BoxCollider boxCollider2 in Colliders.Where(x => !x.Guid.Equals(boxCollider.Guid)))
        {
            if (!boxCollider2.Collider.HasValue) continue;
            var collider2 = (Rectangle) boxCollider2.Collider;

            if (collider1.Intersects(collider2))
                boxCollider.OnCollision(boxCollider2);
        }
    }
}

```

And here's the `OnCollision(BoxCollider other)` method :

```
public void OnCollision(BoxCollider other)
{
    if (other.Collider == null || Collider == null) return;

    var rect = (Rectangle) other.Collider;
    var intersect = Rectangle.Intersect(Collider.Value, rect);

    // TODO : Resolve collision
}

```

I also have basic physic in the Engine so I would like a falling object to stop falling if it is against another collider.

In the case of a player walking on the ground, I guess the ground should apply an opposite force to the player if it collides ?

# Answer
If you have a constant gravity being applied to your entity in your game you could use a CheckIfOnGround() kind of function that would stop applying downward velocity when a object/character was colliding with a ground surface.

I would suggest that over applying opposite force when collision occurs. One issue that could arrive with that functionality would be if an entity collided on multiple objects. This would make the entity move upwards.
> 1 votes

---
Tags: c#, collision-detection, monogame, collision-resolution
---


# Question
Title: Return value from coroutine to non monobehaviour
I have a class which is not a monobehaviour (lets call it "Generation"), and as such running CoRoutines from within are not an option.

I have a monobehaviour (lets call this "TestScript") which needs to call a function within Generation. One parameter required is a Func\>. It then calls that Func multiple times, expecting a result in the form of a double. The problem, is that it takes time to return, it needs to run across many frames, and so it kicks off some Coroutines (as this is in the monobehaviour). I set it to return a Task so that I could use Threading.SpinWait.SpinUntil and only return after the coroutines have exited, but this just hangs the main Unity thread.

Here is the function I am calling:

```
        public void AssessGeneration(Func<NeuralNet, Task<double>> assessment)
        {
            foreach (NeuralNet neuralNet in neuralNets)
            {
                neuralNet.Fitness = assessment(neuralNet).Result;
                neuralNet.fitnessAssessed = true;
            }
        }

```

So, I've tried many other things, such as moving the SpinWait into the Generation class, but still hangs. I've tried calling the function in Generation within a Task on a new thread, but when it attempts to run the coroutines it complains about not being on the main thread.

So - I have a function, in a class not inheriting from MonoBehaviour. It is called from a MonoBehaviour, and must pass in a function which takes a parameter of type NeuralNet, and returns a double. It must return a double after a coroutine has finished, but I can't be blocking the main thread.

# Answer
> 3 votes
It's not true that you can't make a method in a base class working as a coroutine.

If I understood you correctly, the `AssessGeneration` method is inside your base class, `Generation`, and you want it to be able to `yield`.

In order to do so, make its return type an `IEnumerator` instead of `void`:

```
public IEnumerator AssessGeneration(Func<NeuralNet, Task<double>> assessment) {}

```

then call it from your `MonoBehaviour` class `TestScript` using `StartCoroutine`, so you can use `yield` as usual inside `AssessGeneration`.

Simple example:

**Generation.cs**

```
using System.Collections;

public class Generation {
    public IEnumerator AssessGeneration(/*Your Parameters*/) {
        //Your code
    }
}

```

**TestScript.cs**

```
using System.Collections;
using UnityEngine;

public class TestScript : MonoBehaviour {

    Generation generationInstance = new Generation();
    IEnumerator myCoroutine;

    private void Start () {
        myCoroutine = generationInstance.AssessGeneration(/*Your Parameters*/);
        StartCoroutine(myCoroutine);
    }
}

```

**EDIT**

After your comment, here's the code if you have two overloads of the same method.

**Generation.cs**

```
using System.Collections;
using UnityEngine;

public class Generation {
    //This is the overload called from TestScript
    public IEnumerator AssessGeneration(/*Your parameters*/) {
        //Code before calling the second overload
        yield return AssessGeneration(/*Func parameter*/);
        //Code after completion of the second overload
    }

    //Second overload with just the Func parameter
    //If this overload is never called from outside leave it private, otherwise public
    private IEnumerator AssessGeneration(/*Func parameter*/) {
        //Your code
    }
}

```

---
Tags: unity, multithreading, coroutines
---


# Question
Title: Should I send the elapsed time to the fixed step update function from my game loop?
I am making a basic game loop based on this article. This is the nearly final version:

```
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update();
    lag -= MS_PER_UPDATE;
  }

  render();
}

```

But I think the update function should have elapsed time passed to it so that the game state is calculate based on that.

So this should be the correct version:

```
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update(elapsed);   ---------------->>>??
    lag -= MS_PER_UPDATE;
  }

  render();
}

```

Am I right? Because I think a physics engine should always have a delta time to calculate state changes.

# Answer
> 1 votes
## NO.

You can see the article begins with a variable timestep loop that passes `elapsed` as a timestep directly, eg.

```
double lastTime = getCurrentTime();
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - lastTime;
  processInput();
  update(elapsed);
  render();
  lastTime = current;
}

```

But it immediately notes that this variable timestep comes with risks:

> But, alas, there’s a serious problem lurking ahead: we’ve made the game non-deterministic and unstable. ... This instability is bad enough that this example is only here as a cautionary tale and to lead us to something better…

And so the article introduces the fixed timestep as a way to correct for this.

Since the timestep is a fixed constant `MS_PER_UPDATE`, there's no need to pass it as a dynamic argument to the update method - the update method can just reference that constant.

If you really wanted to pass it as an argument though, you'd do this:

```
while (lag >= MS_PER_UPDATE)
{
  update(MS_PER_UPDATE);
  lag -= MS_PER_UPDATE;
}

```

If one passes `elapsed` as you propose, then we get incorrect behaviour.

Let's say `MS_PER_UPDATE = 10` and this frame our `elapsed = 32` and we had `lag = 9` left-over from last frame, making for a new `lag = 41`. We want 40 ms worth of updates to happen (4 fixed steps of 10 ms each, which is as much as will fit in our total accumulated `lag`).

```
           update(MS_PER_UPDATE)       update(elapsed)
---------------------------------------------------------
First loop     update(10)                update(32)
Second loop    update(10)                update(32)
Third loop     update(10)                update(32)
Fourth loop    update(10)                update(32)
---------------------------------------------------------
Total accounted    40 ms                    128 ms

lag carried to next frame    1 ms

```

By passing `elapsed` as our update step, we'd advance the game state 128 ms in a span of only 32 ms this frame, fast-forwarding the game at 4x speed. Obviously not the desired behaviour.

---
Tags: game-loop
---


title: libGDX font generating bug

text:
# Question
Title: libGDX font generating bug
Please, help me with my problem. The character is rendering incorrectly. R symbol looks like N. Also, the symbol ! is not drawn. But this problem was found only on Xiaomi Mi A1. On other devices, such a problem is not detected.

Font generates like so:

```
public enum Font {

    FONT_REGULAR (Res.FONT_REGULAR_PATH),
    FONT_LIGHT (Res.FONT_LIGHT_PATH),
    RUSSO_ONE_REGULAR (Res.RUSSO_ONE_REGULAR),
    ;

    BitmapFont font;
    String path;

    Font (String path) {
        this.path = path;
    }

    public BitmapFont get (float size) {
        final String FONT_CHARACTERS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяєїіАБВГДЕЁЖЗИЙКЛМ" +
                "НОПРСТУФХЦЧШЩЪЫЬЭЮЯЄЇІáabcdeéfghiíjklmnoópqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123" +
                "456789][_!$%#@|\\/?-+=()*&.:;,{}\"´`'<>°©™";
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(path));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = (int) size;
        if (size < 1) parameter.size = 1;
        parameter.characters = FONT_CHARACTERS;
        BitmapFont font = generator.generateFont(parameter);
        font.setColor(Color.WHITE);
        generator.dispose();
        return font;
    }

}

```

I use this font.

How can I fix it?

# Answer
I found solution!

I just added this:

```
FreeTypeFontGenerator.setMaxTextureSize(2048);

```

So, full code looks like so:

```
public BitmapFont get (float size) {
    final String FONT_CHARACTERS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяєїіАБВГДЕЁЖЗИЙКЛМ" +
            "НОПРСТУФХЦЧШЩЪЫЬЭЮЯЄЇІáabcdeéfghiíjklmnoópqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123" +
            "456789][_!$%#@|\\/?-+=()*&.:;,{}\"´`'<>°©™";

    FreeTypeFontGenerator.setMaxTextureSize(2048);

    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(path));
    FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();

    parameter.size = (int) size;
    if (size < 1) parameter.size = 1;
    parameter.characters = FONT_CHARACTERS;
    BitmapFont font = generator.generateFont(parameter);
    font.setColor(Color.WHITE);
    generator.dispose();
    return font;
}

```
> 2 votes

---
Tags: libgdx, fonts
---


title: Spherical harmonics lightprobe problem

text:
# Question
Title: Spherical harmonics lightprobe problem
I am trying to add spherical harmonics based ambient lighting to my game but have run into some problems and while trying to solve this I have reduced the test scene to the following very basic scenario.

The scene consists of

* Two walls (red and green)
* Single light probe in the middle. Since a probe is just empty space there need to be some ‘normal’ vector used when integrating over the hemisphere (defined by that vector). To fit this simple example this probe only have two such vectors pointing in opposite directions (i.e. at each wall).

The light source is rotated 360 degrees (2\*PI radians) while the final light solution is evaluated in the two directions.

Now if I simply plot the magnitude of the two light color vectors I get

Since the scene is symmetrical except for the colors I would expect that the magnitude of the ‘color vectors’ (as plotted above) to be identical except for a phase shift. **This, however, does not appear to be the case and this is my problem**.

Further if I simply plot the shadowed solution (i.e. exclude the bounced coefficients), I get

which is what I expect (i.e. seemingly identical except for a phase shift).

Also, if I just take the bounced coefficients into account (i.e. exclude the shadowed), then I get

which again looks reasonable in that the two curves are identical (the color components, not visible in this plot, are rearranged but the magnitude stays the same).

As far as I know I am supposed to be able to add the two coefficient sets (shadowed and bounced) to get the final result but when I do, it just looks wrong as can be seen in the first plot.

I have been stuck on this for quite a while now so if anyone could offer some advice I would appreciate it. I'd be happy to post more details if there is any interest.

# Answer
> 1 votes
Thinking a bit more about the third plot (bounced coefficients only) made me realize that it is not reasonable at all. After closer examination of the code it turned out that there was a copy&paste error in the routine that computes the bounce coefficients (used the sh functions once again). Fixing that resulting in a much better plot for the bounce coefficients

and for the final result we now get

which shows the expected phase shift.

So all in all problem solved for now :)

---
Tags: mathematics, lighting, lightprobes
---


# Question
Title: Correct way of texture-mapping a 2D mesh in libgdx
this is a question regarding the libGDX framework.

I have managed to UV-map a texture to vertices (in 2D) but have come across a few problems that I think might be caused by incorrect order of vertices.

In the first two pictures, you can see a rendering produced by the code-bits below (without blending enabled). It seems fine at first, but you can clearly notice that **the lower triangle seems to have a rough transition**. Is there an easy way to prevent this (without writing too much low level stuff) or is this an expected limitation of this approach?

The second problem occurs with the same code but with **blending turned on**. In the fragment shader, you can see that I adjust the alpha level of each pixel in the region, but with this mesh, **it produces a rather weird and distorted image in the right triangle area**.

Here's the code:

*Shaders*

```
//Vertex shader:
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec4 v_color;
varying vec2 v_texCoords;
void main() {
 v_color = vec4(1, 1, 1, 1);
 v_texCoords = a_texCoord0;
 gl_Position =  u_projTrans * a_position;
}

//Fragment shader:
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
void main() {
 gl_FragColor = v_color * texture2D(u_texture, v_texCoords) + vec4(0, 0, 0, -0.50);
}

```

*Mesh*

```
Mesh m = new Mesh(true, 5, 0,
         new VertexAttribute(Usage.Position, 2, "a_position"), //x,y
         new VertexAttribute(Usage.TextureCoordinates,2,"a_texCoord" + 0)); //u,v
         m.setVertices(new float[]{20f, 360f, 0f,0f, //upper left
                                   60f, 20f, 0f, 1f, //lower left
                                   180f,20f,1f,1f, //lower right
                                   220f, 360f, 1f, 0f, //upper right
                                   20f, 360f, 0f, 0f}); //upper left (closure)

```

*Render*

```
//Gdx.gl.glEnable(GL20.GL_BLEND);
//Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
shaderProgram_mesh.begin();
shaderProgram_mesh.setUniformMatrix("u_projTrans", camera.combined);
texture.bind();
m.render(shaderProgram_mesh, GL20.GL_TRIANGLE_STRIP, 0, 5);
shaderProgram_mesh.end();

```

# Answer
> 1 votes
You're constructing your triangle strip incorrectly.

After the first two vertices, each additional vertex that you specify defines a new triangle, with the far side defined by the preceding two points.

So by putting five vertices in your vertex buffer, you're actually drawing three triangles:

You want only four vertices, arranged in a Z pattern that zig-zags from one side of the strip to the other.

Note that because one side of your quad is smaller than the other, you'll get an affine texture mapping seam along the diagonal. If you want the texture to smoothly taper, you should either make it a rectangle tilted in space so that the camera perspective tapers it for you correctly, or use projective texturing to control this effect in the shader..

---
Tags: libgdx, textures
---


# Question
Title: How do I calculate where which pixel it's reflecting based on a height map?
I saw this How can I Compute steepness for heightmap while looking for a way to reflect pixels. But now that I have the steepness/slope I don't know how to calculate which angle it's pointing at. Imagine if I had an image parallel (directly above my heightmap) with my heightmap and 100(units/pixels) away/above from it, if the steepness is 0, then i just grab a pixel at that same \[x,y\]. Imagine that i am trying reflect what the heightmap would show if i was to be able to see through my image.

But let's say I have a steepness of 1 which i am guessing is 45 degrees since 1/1 is 45 degrees but which pixel should i be grabbing from my image how do I calculate what angle the pixel is coming from \[x,y\].

How would i calculate which pixel(location) is reflected onto the heightmap (imagining that the heightmap is a chrome surface).

I know if the angle is too steep it'll be way outside of the image but I'll just use min/max hack to grab border pixels (unless you can think of another method to handle that) but for angles that are inside my image still...how do I calculate which pixels to reflect.

Basically trying to render an image reflected by height-map when image is placed directly above heightmap with variable input of distance between image and heightmap (use like 100 units as example, but i want to allow user the ability to change this distand)

Please explain in easy terms as sometimes I don't understand rare mathematics notation/symbols.

Thanks in advance.

EDIT: This got me searching for calculating normal for heightmap I think I found what I was looking for.

# Answer
> 0 votes
https://stackoverflow.com/questions/5281261/generating-a-normal-map-from-a-height-map

No real reflection or complex stuff like ray tracing. But I was able to use the 2nd answer to calculate normal of height-map which i then grabbed the pixel at that normal coordinate to use for my GIMP script.

---
Tags: heightmap, reflection-rendering
---


# Question
Title: Get / Calculate edges of a 3D object - C #
I need to get all vertices in the edge position of a determinate object 3D (in this case a path).

See the image:

My question is, how can I get only the edges vertices, like the image?

# Answer
One option is to iterate over all your triangle faces tallying up a count of each edge.

Any internal edge is shared by two faces, any external edge will appear only once.
> 1 votes

---
Tags: unity, c#, mathematics, geometry
---


# Question
Title: Batch/Combine multiple Graphics.DrawProcedural-Calls in Unity
I have multiple calls to `Graphics.DrawProcedural` in my Unity-project. E.g. I'm drawing 1000 procedural geometries that share the same material and get their positions/meshes from a `ComputeBuffer`.

At some place in my code I'm doing something like this

```
foreach(ProceduralGeometry pG in proceduralGeometries)
{
    pG.Draw();
}

```

Where draw sets the Materials buffer accordingly and calls `Graphics.DrawProcedural`.

Is there anything I can do to batch all these geometries together? Currently I perform over 1000 DrawCalls (seen in the frame inspector) which happen to be very expensive performancewise.

Thanks in advance!

# Answer
> 1 votes
Why not just collect a few buffers with different objects and direct them to compute shader?

Here is a sketched quick, not tested, example (no time to create the objects themselves). Structurally, I think it will be clear:

**Compute Shader**

```
#pragma kernel CSMain

RWTexture2D<float4> Result;

int countObj;
RWStructuredBuffer<int> obj;
RWStructuredBuffer<float3> vertexs;

[numthreads(16, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    for (int i = 0; i < countObj; i++)
    {
        for (int j = 0; i < obj[i]; j++)
        {
            drawVertex(vertexs[j]);
        }
    }
}

```

**C#**

```
class Class1 : MonoBehaviour
{
    struct Obj
    {
        public Vector3[] vertexPos;
    }

    Obj[] MyObjects = new Obj[1000];
    private Vector3[] vertexsAll;

    public ComputeShader CShader;
    private int[] VertexToObject; // Count Vertex to One object
    private ComputeBuffer obj;
    private ComputeBuffer vertexs;
    private int CountObj;

    int IdCS;

    void bufferCompiller()
    {
        CountObj = MyObjects.Length;
        VertexToObject = new int[CountObj];
        int AllCountVertex = 0;

        for (int i = 0; i < MyObjects.Length; i++)
        {
            AllCountVertex += MyObjects[i].vertexPos.Length;
        }

        vertexsAll = new Vector3[AllCountVertex];

        int IndexVertexAll = 0;
        for (int i = 0; i < MyObjects.Length; i++)
        {
            VertexToObject[i] = MyObjects[i].vertexPos.Length;
            for(int j = 0; j < MyObjects[i].vertexPos.Length; j++)
            {
                vertexsAll[IndexVertexAll] = MyObjects[i].vertexPos[j];
                IndexVertexAll++;
            }
        }

        obj = new ComputeBuffer(VertexToObject.Length, sizeof(int));
        obj.SetData(VertexToObject);

        vertexs = new ComputeBuffer(vertexsAll.Length, sizeof(float) * 3);
        vertexs.SetData(vertexsAll);

        IdCS = CShader.FindKernel("CSMain");
        CShader.SetInt("count", CountObj);

        CShader.SetBuffer(IdCS, "obj", obj);
        CShader.SetBuffer(IdCS, "vertexs", vertexs);

        CShader.Dispatch(IdCS, 32, 32 / 8, 1);
    }
}

```

---
Tags: unity, c#, shaders, procedural, compute-shader
---


# Question
Title: What causes the difference between these boxes?
I have recently started using Blender and I notice that the light (from my game) on default box is different from the one I downloaded. The below picture shows that.

They have the same normal direction in Blender. Thanks in advance.

# Answer
Left one has normal-per-side. Right one has normal-per-vertice. Causes of that - materials settings, smoothing groups/settings, manual disconnection of sides..
> 0 votes

---
Tags: opengl, java, blender
---


# Question
Title: Maintain Vuforia tracking during Unity Ad
My game uses Vuforia pos and ground plane tracking.

During gameplay players are given the option to watch a video to gain additional health.

When 'No' is chosen gameplay resumes fine. However when 'yes' is chosen Vuforia tracking is lost during the video and afterwards all gameobjects are locked in a static position in relation to the AR camera.

Is there anyway to maintain pos tracking during the video?

# Answer
> 0 votes
I would create a script that listens for when the yes button is pressed. There i would turn off mesh renderers, character controllers, etc. And when the ad ends and tracking is resumed vuforia will turn those back on. If you want to turn off more than what vuforia controls, then you could use the vuforia trackable behaviour and stick them inside of OnTrackingFound and OnTrackingLost. I normally take all that code and stick it inside of one of my own classes.

Good luck.

---
Tags: unity, vuforia, unity-ads
---


# Question
Title: How Could I accommodate Gender Fluid Players In My Game
I'm world building for a fantasy MMORPG and I really want to have a safe and acceptable environment for all possible players. Of course I am going to be realistic and have prejudice in game, it wouldn't be believable if everyone got along. However I personally feel that if a paying consumer of my game feels like having a non binary character, why should I limit them and make them feel uncomfortable? They could always make two separate characters, but then there's a lack of sync and feeling that they are one person. My team also discussed having a feature that switched between avatars while keeping gear and skills. Another idea was a sort of illusion spell that would alter the players body to a set form based off of their original facial shape and general traits. I would like to hear more suggestions and thought of this topic in games, or if something like this has been done before, even if it was not intended for gender fluid people. **In the end I would like to have a believable way for a player to switch between male and female in game.**

**Previous Comments**

*Do characters in the game have the possibility to beget offspring (male) or to give birth to offspring (female)? Otherwise, they are not male and female, but rather masculine and feminine: which is a much simpler problem, and one that should have minimal impact, if it has any impact at all. Actually, what exactly would be the impact of switching the identifier of a character from Cao Pi to Guo Nüwang? (One of those names is feminine, and the other masculine; which is which is left as an exercise.)*

*We are working on a function for players to have NPC children. So if they had gotten pregnant they would not be able to change the sex of their avatar, that would cause problems. This is more of gender and appearance, not so much biological sex. Though I guess it would be plausible for them to be pregnant, and then get some one else pregnant after giving birth. If of course it wasn't illusion magic.*

*It seems like you already know your answer. If it's about gender and appearance, then it's about how a character is physically portrayed. Right? So for example, in an typical MMORPG, you purchase a breastplate from the local armory, you'll have a 'male' version and a 'female' version. Perhaps just give an option to purchase a variety or degree of masculine and feminine armor regardless what biological sex your player is. For example, a male player can purchase a very feminine looking breastplate.*

*we have plenty of possible answers. It's more of what would make people feel most comfortable. A lot of gender fluid people can have body dysmorphic disorder, and some of them play games for gender comfort. It's like a self applied therapy where you can be what ever you identify with, and others will see and accept you as that gender. So masculine and feminine armor would work and is probably an idea we will use, we don't want someone to feel confined to one gender. Especially because gender fluid people can change from masculine to feminine day to day. the armor also means they may have to buy multiple sets. also some one may feel strongly masculine one day, and strongly feminine another, making a gender ambiguous character a bit awkward.*

# Answer
> 4 votes
*Disclaimer: I am not genderfluid, nor am I a psychologist or gender therapist. I have had regular and friendly contact and conversation over several years with at least two genderfluid people, one of which I have met personally. I am speaking purely from a game design standpoint and make no claims of special qualification to comment on genderfluidity.*

**Character Sex and Gender**

The very first question you should ask yourself is whether it is necessary at all to assign characters a binary sex and gender at all. This depends mostly on whether you have game mechanics that require such information about a character to be present. The children you speak of may be one such mechanic, as might the prejudice you mentioned which I assume includes NPC reactions. However, these things aren't as straightforward as one might think.

For example: If NPCs react to you in gender-specific ways, how do they determine what gender your character has? Do you have to choose from a predefined list at what kind of gender your character will register? Do you calculate a masculinity/femininity score from character appearance that the NPCs recognize? (BTW don't do that, as you'd be opening the can of worms about what is masculine or feminine being essentially arbitrary and based on stereotypes.) If you have to choose, can you choose a third (fourth, fifth...) option? And if so, is this actually so important to your game that you have to do it this way? It generally isn't a problem to have NPCs address you by non-gendered titles and you can portray prejudice along race and class lines just as well - or have gender prejudice take place between NPCs rather than direct it at the players who, by the way, if they're playing your game for the comfort of being able to play according to their identity might not necessarily appreciate this conflict directed at them - opinions will vary.

Then there's the problem of having children: you stated this was a fantasy scenario, so why exactly do you need a male and female to procreate anyway? I assume you're not going to display a PIV cutscene. Are you planning to have the mother go through actual 9 months of pregnancy? I sort of doubt it. Chances are your characters will enter the house/bed, some kind of jingle plays and you'll have a child. In a world where there's magic I wouldn't really care that much about two women or men or people of various genders having children with each other through magical insemination/gestation. And if you want to include player pregnancy you could easily just have the players choose which partner carries the child. You have the privilege of magic, use it.

**Character Appearance**

As I said in my comment, just have sliders for everything, hips, breasts, muscles, options for facial hair, hairdos of all kinds and a variety of voice options with a few androgynous ones. Leave the gender option out and let people look as feminine and/or masculine as they like (including not at all). Modern technology makes a lot of gender-specific clothing options unnecessary as the clothing has to seamlessly adapt to the body shape or the character, regardless of how tall, wide and curvy they are. Characters with big breasts will have big bulges (except in plate armour where that doesn't make sense) and characters with long legs will have longer trousers or skirts to match.

Allow the players to go back to the appearance menu in some easily accessible way, probably through transformation magic. Maybe have a magic circle in player houses and guild halls - resist the urge to monetise this function, as you'd specifically be exploiting those who your question is trying to be inclusive of (and props for that by the way).

**Believability**

For in-game explanations I prefer transformation magic as stated. Go a step further though and integrate this into the lore of your game. Maybe player characters are special precisely because they're able to change their form at will and that's their heroic superpower! Include some quests in which you disguise as someone else to sneak into a secret/forbidden area to integrate the form-changing into the gameplay.

# Answer
> 3 votes
Do not give player-characters an explicit gender.

As Pahlavan suggested in a comment to the question, have your character editor offer sliders for both feminine and masculine characteristics, so players can create a character which looks as male, female, androgynous or ambiguous as they want.

When it comes to pronouns used in dialog, you might want to give players a wide variety of options. Allow them to choose between standard-male (he, his, him), standard-female (she, her, her), gender-neutral (they, their, them) or custom (let them enter any strings they want). Assume any NPC simply guesses the pronouns of each PC correctly.

To accomodate gender-fluid people, you should allow to change look and pronouns during the game with relatively little effort. Don't think about it too much, just handwave it with magic or technology (depending on setting). I used to be a developer on an MMORPG where we had a "plastic surgeon" NPC which was performing both gender reassignment and character re-customization. We used to make it extremely expensive as a money sink, but then nobody would use it. So we just made it free. This proved to be very popular with our community. If you need more money sinks, choose something which actually affects gameplay or offers cosmetic options not available from the start.

However, one thing you should think careful about is allowing namechanges. There is just too much abuse potential here. MMOs are about social interactions. When people can change their names, then nothing stops them from changing their name, being mean to people, change it back and not have any repercussions whatsoever. *If* you choose to allow namechanges, at least try to provide some transparency about who changed when to which name.

Regarding having children: If this is an integral aspect of the game, consider to do this through adoption instead of pregnancy. Skyrim went that route in the Hearthfire DLC to avoid having different mechanics for male and female player-characters. This also solves a lot of other problems like having to implement whole game systems for pregnancy and caring for infants which likely don't synergize well with the other mechanics of your game.

---
Tags: game-design, character
---


# Question
Title: Why can't I put a source image in my Image component?
I can't put an image here as source image, and I have trouble figuring out why.

What did I miss?

# Answer
> 2 votes
It looks like you have the editor settings configured for 3D defaults.

This means that when you import a new image file into your project, Unity assumes by default that you want to use it as a Texture asset, for texturing 3D models, skyboxes, etc. or using as a shader input.

But for UI, you want to treat that image as a Sprite. This packs the image data in a particular way that's efficient for the UI rendering system, and includes metadata for common 2D/UI operations.

To mark your images as Sprites, select them in the Project assets browser, and the Inspector window will update to show the images' import settings.

In the Texture Type drop-down at the top, select "Sprite (2D and UI)" then hit Apply. Your images should now show up as selectable for UI Image components and SpriteRenderers

---
Tags: unity
---


title: Unity 2D map and walkable collisions

text:
# Question
Title: Unity 2D map and walkable collisions
I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it.

Player has capsule collider.

The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge.

Here is a sketch I've made.

Is there a way to tweak this ?

# Answer
> 3 votes
Make the capsule collider on his feet and not on his whole body. So he could walk all the way to the ledge.

---
Tags: unity, 2d
---


# Question
Title: Why does component.GetComponent<Rigidbody>() return "null", when a rigid body is NOT attached?
In the following code, when `T` is `Rigidbody`, calling `componentToLookIn.GetComponent<T>()` returns `"null"` when there is no rigidbody attached, instead of simply `null`:

```
public static class ComponentExtensions
{
    public static bool TryFindComponent<T>(this Component componentToLookIn, out T componentToLookFor)
    {
        componentToLookFor = componentToLookIn.GetComponent<T>();
        return componentToLookFor != null;
    }
}

```

Here is the debug window:

As a result, `componentToLookFor != null` ends up being `true`, which is obviously not what I want.

When I invoke `componentToLookIn.GetComponent<T>()` where `T` is **NOT** `Rigidbody`, `null` is returned as expected when there is no component of type `T` found.

What is so special about components of the `Rigidbody` type that `GetComponent<Rigidbody>()` behaves differently?

**EDIT:**

For contrast, here is the debug window when `GetComponent<BoxCollider>()` is invoked on a game object that does not have any component of the type `BoxCollider`:

As you can see, the `value` of `childComponent` is simply `null`, not `"null"`. `componentToLookFor != null` therefore returns `false`.

# Answer
This happens only when running in the Unity editor, and only with certain built-in component types.

In a release build, `GetComponent<T>()` always returns `null` if the GameObject does not have a component of type `T` attached.

When running inside the Unity Editor, `GetComponent<Rigidbody>()` instead returns a Rigidbody component that's been marked as a "stub" - an empty reference that perhaps the developer forgot to wire-up in the inspector. (It's not the string "null", that's just how it's configured to print when represented as text)

For these, Unity's overridden `==` operator for types deriving from `UnityEngine.Object` will return `true` when comparing to `null` (similar to what happens if you hold onto a reference to a component after it/its GameObject has been destroyed).

But the fact that it's *not* really null lets Unity offer more descriptive error messages, like...

* "Unassigned Reference Exception" (Inspector field not populated)
* "Missing Component Exception" (GetComponent\<\> with no matching component attached)
* "Missing Reference Exception" (Component has been destroyed)

---

So, if Unity's `==` is overridden to compare as equal to `null` in this case, why doesn't your null check work?

Because your generic method doesn't know that `T` is a `Component`, so it doesn't know to apply Unity's overridden operator.

To solve this and get consistent null detection between Editor and builds, you can add a `where T : Component` type constraint to your method, or cast your reference to a Unity type like a component first, then do your comparison with that.
> 3 votes

---
Tags: unity
---


# Question
Title: How can I apply a mesh collider in Unity to an entire imported model rather than a single piece?
I have a series of models from Blender I'm importing to Unity as .blend files and I need mesh colliders applied to each one.

What I'm finding is that with any model that is constructed of multiple primitives, applying the mesh collider to the object is unsuccessful. The mesh collider can't find the mesh. Unity seems to treat each shape inside the model as a separate object. I've even noticed that the Unity editor will allow me to select a single piece of a model and drag it away if I'm not careful. This is unexpected behavior and somewhat alarming.

I've discovered that if I apply a separate mesh collider to each individual piece inside the model, the colliders will find the sub-meshes and the collision detection will work. My primary concern at the moment is that this is monotonous. For example, if I have the following model of a road intersection, then I'll need to individually select each of the seven pieces and create a mesh collider for each one.

How can I apply a mesh collider to the entire model in one move?

**UPDATE:**

Based on some feedback and some thoughts on my own, I'm redesigning the road pieces to simply be solid road on the bottom with the sidewalks on top. This way, I'll only need one collider for the bottom, for now (if I don't care about testing collisions with the sidewalk edges yet).

I'm hesitant to merge the meshes into a single mesh at this time, though, since I'm potentially not done modelling street pieces yet. This also doesn't address the long-term question of what to do in the final version of the game.

Unity primitives have automatic collision detection, but simulating hills this way and still having the pieces meet seamlessly is difficult. They also won't do curved surfaces as far as I know.

I'd rather not use box colliders, since that will involve a lot of painstaking zooming in and tweaking of tiny values to get them perfect. It also seems that box colliders will only rotate *with* a model and not *to* a model that's already sloped.

What I'm trying to avoid is spending almost as much time messing around with the colliders as I did modelling these bits in the first place.

Sticking with the mesh colliders is looking like the best option for now, since most of these shapes are simple, 6-sided objects and it's only a couple of clicks to add a mesh collider to each shape. It sounds like if I do it this way, it might be smarter to keep the meshes un-merged, since I would then be using a mesh collider on a concave object.

# Answer
> 1 votes
The best way to do this would be to combine all meshes in blender and make a single mesh, preferably with lower quality, and use that. ButI wouldn't really recommend that for performance reasons, especially for something as simple as a road.

However it is possible to have a `box collider` and have it rotated. Assuming that you create a road mesh that is flat, create a `box collider` and attach it to the road. Now if you place your road mesh on a scene (moving it around, rotating or scaling it) the box collider does the same. This is what I'd recommend.

---
Tags: unity, models, blender, meshcollider
---


# Question
Title: How can I change the speed mode in Update?
I want to decide if the speed will be randomly or constant.

In the top of script:

```
[Header("Speed")]
public float constantSpeed;
public float minRandomSpeed, maxRandomSpeed;
public bool randomSpeed = false;

```

In Start:

```
private void Start()
    {
     RandomSpeed();
    }

```

In Update

```
private void Update()
    {
        RandomSpeed();
    }

```

RandomSpeed:

```
private void RandomSpeed()
    {
        for (int i = 0; i < instancesToMove.Length; i++)
        {
            if (randomSpeed)
            {
                movementSpeeds[i] = Random.Range(minRandomSpeed, maxRandomSpeed);
            }
            else
            {
                movementSpeeds[i] = constantSpeed;
            }
        }
    }

```

The problem is in the RandomSpeed if randomSpeed is true it will keep giving the movementSpeeds each frame a new random values. But I want that when randomSpeed is true give movementSpeeds new speed values only once. Then if I will set the randomSpeed false then true again then give again new random speed values.

# Answer
# Don't do this:

```
private void Update()
{
    RandomSpeed();
}

```

The *only* thing you should do during `Update()` regarding speeds is to check to see *if the value of `randomSpeed` has changed,* and if so, generate new values (assuming that you want the boolean to change at runtime). You do not, and should not, generate new speed values every frame.
> 1 votes

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


# Question
Title: Rotating a sphere so point lines up with the camera
I'm trying to make a world map in Unity that contains a rotating globe with landing sites on the perimeter. What I want is that when a player clicks on the landing site the globe rotates so that the landing site is centered. I've been trying to find the right way to use the Quaternion class but not much luck.

Here is my latest attempt which doesn't work. The landing sites are parented to the globe but the camera and globe are separate.

```
    void Update()
    {
        if (_selectedLandingSite != null)
        {
            var rotation = Quaternion.FromToRotation(_selectedLandingSite.transform.localPosition, MainPlanet.transform.forward);

            var trans = Game.Game.Instance.MainCamera.gameObject.transform;
            var lookDirection = new Vector3(trans.position.x, trans.position.y, trans.position.z);
            lookDirection = rotation * lookDirection;

            var _lookRotation = Quaternion.LookRotation(_selectedLandingSite.transform.localPosition);

            //rotate us over time according to speed until we are in the required rotation
            MainPlanet.transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * 1);

            //MainPlanet.transform.rotation =
            //  Quaternion.RotateTowards(MainPlanet.transform.rotation, _targetRotation, 1);
        }
    }

```

# Answer
```
var toCamera = Quaternion.LookRotation(camera.position - globe.position);

```

Gives a rotation that spins the z+ axis to point from the globe to the camera.

```
var toSite = Quaternion.LookRotation(site.localPosition);

```

Gives a rotation that spins the z+ axis to point to the landing site in the globe's local space.

```
var fromSite = Quaternion.Inverse(toSite);

```

Gives a rotation that spins the site so that it sits along the local z+ axis.

Chaining it together:

```
globe.rotation = toCamera * fromSite;

```

Is a rotation that will that will spin the site so that it faces the camera.
> 3 votes

---
Tags: unity, c#, camera, rotation, sphere
---


title: OBJ Loader not working correctly

text:
# Question
Title: OBJ Loader not working correctly
I'm currently trying to implement my own OBJ Loader for use with FreeGLUT with C++. This is my current OBJ Loader: #include "OBJLoader.h" #include #include #include #include #include

```
Mesh* OBJLoader::LoadModel(char* path)
{
Mesh* mesh = new Mesh(); //New Mesh

std::vector<Vertex> vertices;
std::vector<TexCoord> textureCoords;
std::vector<Vector3> normals;

//Loads OBJ file from path
std::ifstream file;
file.open(path);
if (!file.good())
{
    std::cout << "Can't open texture file " << path << std::endl;
    return nullptr;
}

std::string text;
while (!file.eof())
{
    file >> text;
    if (text == "v")
    {
        Vertex vertex;

        file >> vertex.X;
        file >> vertex.Y;
        file >> vertex.Z;

        vertices.push_back(vertex);
    }

    if (text == "vt")
    {
        TexCoord texCoord;

        file >> texCoord.U;
        file >> texCoord.V;
        textureCoords.push_back(texCoord);
    }
}

file.close();

mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
    mesh->vertices[i].X = vertices[i].X;
    mesh->vertices[i].Y = vertices[i].Y;
    mesh->vertices[i].Z = vertices[i].Z;
}

mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
    mesh->texCoords[i].U = textureCoords[i].U;
    mesh->texCoords[i].V = textureCoords[i].V;
}

return mesh;
}

```

What I do is create 3 vectors to hold the vertices, texture coords and normals, I then put the data in the corresponding vectors from the OBJ file and then finally loop through these vectors to add them to basically 3 array's which will contain the vertices, texture coordinates and normals so I can use them with "glVertexPointer" and "glTexCoordPointer" (I haven't loaded in normals yet but I will eventually)

The problem is that I'm not sure why my model is displaying really strange. It seems like it should work but the model I'm rendering which is meant to be sonic looks like... this:

Is there something I've done wrong? I imagine it's to do with the faces at the bottom of the OBJ File though I just want to make sure.

**EDIT** This is the section of code I'm using to put the values from the vectors into the array's used in glVertexPointer and glTexCoordPointer:

```
mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
    mesh->vertices[i].X = vertices[i].X;
    mesh->vertices[i].Y = vertices[i].Y;
    mesh->vertices[i].Z = vertices[i].Z;
}

mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
    mesh->texCoords[i].U = textureCoords[i].U;
    mesh->texCoords[i].V = textureCoords[i].V;
}

```

# Answer
> 1 votes
I think the issue is that you're not using the face data. The vertex data you've parsed dictate the point locations of the geometry, but the ordering there doesn't usually correspond to where the \*triangles lie.

In face, if you squint at the points of your current triangles, you can kind of see a Sonic head, two arms in a T Pose, and two large feet. This means the vertex positions are correct.

Your triangles should be fixed once you parse and render the face data from the OBJ.

---

> How exactly should I do it? Like can I use the indices within my glDrawElements call which takes in indices or should I be use the indices to rearrange the vectors containing vertices and tex coords

Yes, you can use the indices with glDrawElements. You'll have to subtract one from each index since OBJ indices start at 1 and OpenGL indices start at 0.

---
Tags: opengl, rendering, obj
---


# Question
Title: How can I procedurally find a wall that separates two or more points on a grid-based map?
I'm trying to generate walls that cut off a given point from other given points. The attached image shows the sort of thing I'm after:

1. Blue separated from Red.
2. Blue separated from Red and Yellow.
3. Blue separated from Red with tile obstructions.
4. Multiple Blue separated from multiple Red.

Any ideas how to do this?

# Answer
> 8 votes
I will present a general concept and three solutions using that concept.

Concept is an *Influence map*: For each location in the map, you are going to store a number that represent the distance to each color point. That way, for each position you can query how far it is from blue, red, green, etc. We call the result is the influence map.

For more detail on the motivation, creation and use of influence maps in games see: The Mechanics of Influence Mapping: Representation, Algorithm & Parameters.

*I have no idea what this wall is for, my head canon is that we are talking about a strategy game, and the AI is deciding where to place the walls. To do that, there are plenty of approaches besides the presented here. A simple approach would be placing walls at a fix distance from the color points and combine the areas when they overlap – and, of course, do not build them over obstacles – the advantages of this method are that it guarantees that the walls are not too far away to send troops to defend them and it is very cheap computationally. I am assuming you want something more complex.*

**Solution 1**:

To find a way to wrap blue, find the difference between the distance to blue and to any other thing, for each point. **Addendum**: The area where the diffrerence is positive is the domain of influence for blue. If you take the domains of influence for every color point, you can build a Voronoi Diagram. *Thanks to Sirisian for mentioning them.*

We can argue that for a point close to blue, the difference will be positive, and for a point close to another color point, the difference will be negative. Given that the distance is a continuous function, by the intermediate value theorem, we can argue that at least one point in the middle the difference will approach zero. A solution would be to trace a wall that minimizes the distance between all the tiles where the difference approaches zero.

Whatever or not that solution takes into account obstacles depends on the distance function. If you only use the Manhattan or Euclidean distances without considering possible paths, then the resulting wall will not take advantage of existing obstacles in the map.

Note: this solution approaches equal area for blue and the rest in a flat scenario.

**Solution 2**:

In abstract, you can find choke points between the area of influence of blue and the others, and then place the walls there. Doing this will place walls in places where the influence is not in equilibrium (the walls my end closer to one side) but will minimize the length of the walls.

A useful approach to find choke points is to break the scenario into convex nodes and create a network that represents the scenario. You will start assuming you will put walls around the nodes that directly have blue, and then start advancing over the network (always increasing the distance from blue) and considering the length of the wall if you placed it surrounding what you have advanced so far. Your solution is the position that had minimum length (and the locations of the walls are the choke points).

In practice, the algorithm is a bit more complicated than that because there might be ramifications in the scenario. You only need to consider each ramification once, and pick the best position for the wall for that ramification.

**Solution 3**:

The first solution has the problem that it might lead to wall that is too long. The second solution has the problem that it might lead to walls that are too far away from blue.

Notice that working with pixels, tiles, or working with a network the concept of the influence map, as a representation of the distance to the color points is valid and useful. Thus, it is possible to apply the solution 1 over the network of convex nodes.

My third solution is to combine the above approaches. Once you are working over the network, you can consider the length of the wall and the difference in influence – and any other metric you want – as a single indicator metric “cost” that you can optimize.

---
Tags: procedural-generation, tiles, tilemap, grid
---


# Question
Title: Unity: input axis raw for touch returning fractions
I am not going to show any script, which may make it complicated. In unity ,when I used the cross platform input manager for touch buttons, the raw axis values returned are in small fractions(like 0.4321,0.1123) sometimes even smaller values, like 1.2322e-10. I want the value to be 1(when keypressed) or 0(when keyreleased). Where am I going wrong, what should I do then?

The function I used CrossPlatformInputManager.GetAxisRaw("Horizontal")

# Answer
> 0 votes
That returns the **coordinate** of the touches, not whether someone is touching the game. Check if it's larger, then 0 to check if it's being held

---
Tags: unity, input, touch
---


# Question
Title: Box2D and OrthographicCamera working incorrectly
I'm trying to build a simple game where TileMapRenderer renders a labyrinth, a ball moves in it and camera follows it. I'm currently having the following bug:

For some reason, the game renders the world incorrectly. The gamescreen is cleared with the following method:

```
private void clearScreen() {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

```

Which is basically red, and the camera seems to show it incorrectly while moving.

Camera movement method:

```
public void moveCamera() {
    GameInfo.camera.position.set(player.body.getPosition().x,
            player.body.getPosition().y, 0);

    // LEFT
    if(GameInfo.camera.position.x < GameInfo.WINDOW_WIDTH / 2){
        GameInfo.camera.position.x = GameInfo.WINDOW_WIDTH / 2;
    }

    // UP
    if(GameInfo.camera.position.y > GameInfo.WORLD_HEIGHT_PIXELS / 100.0f - GameInfo.WINDOW_HEIGHT / 2) {
        GameInfo.camera.position.y = GameInfo.WORLD_HEIGHT_PIXELS / 100.0f - GameInfo.WINDOW_HEIGHT / 2;
    }

    // DOWN
    if(GameInfo.camera.position.y < GameInfo.WINDOW_HEIGHT / 2) {
        GameInfo.camera.position.y = GameInfo.WINDOW_HEIGHT / 2;
    }

    // RIGHT
    if(GameInfo.camera.position.x > GameInfo.WORLD_WIDTH_PIXELS / 100.0f - GameInfo.WINDOW_WIDTH / 2f) {
        GameInfo.camera.position.x = GameInfo.WORLD_WIDTH_PIXELS / 100.0f - GameInfo.WINDOW_WIDTH / 2f;
    }
}

```

As you can see, I'm using Box2D physics for the ball.

Setting up the camera:

```
public static OrthographicCamera camera = new OrthographicCamera();

public static void setCamera() {
    camera.setToOrtho(false, 8.0f, 4.5f);
}

```

Rendering method:

```
public void render () {
    batch.setProjectionMatrix(GameInfo.camera.combined);
    clearScreen();
    moveCamera();
    GameInfo.camera.update();
    Game.tiledMapRenderer.setView(GameInfo.camera);
    Game.tiledMapRenderer.render();
    batch.begin();
    batch.draw(player.texture,
            player.body.getPosition().x - player.radius,
            player.body.getPosition().y - player.radius,
            player.radius,                   // originX
            player.radius,                   // originY
            player.radius * 2,               // width
            player.radius * 2,               // height
            1.0f,                          // scaleX
            1.0f,                          // scaleY
            player.body.getTransform().getRotation() * MathUtils.radiansToDegrees,
            0,                             // Start drawing from x = 0
            0,                             // Start drawing from y = 0
            player.texture.getWidth(),       // End drawing x
            player.texture.getHeight(),      // End drawing y
            false,                         // flipX
            false);                        // flipY
    player.updatePlayer();
    Game.checkStateOfGame(player);
    batch.end();
    //GameInfo.doPhysicsStep(Gdx.graphics.getDeltaTime());
    Game.world.step(1/60f, 8, 3);
}

```

It's not only while moving either. As soon as the game starts, the red block is visible like seen in the first picture.

Also the red blocks seem to always be coming from left and down, never from up or right...

What could be wrong in here?

# Answer
> 0 votes
Solved.

For some reason, Tiled (the software I did the TiledMap with) was bugging out. I had a background layer below everything and I had just painted it with a brush with a light blue texture. I deleted the background layer and used the bucket fill tool instead, saved it and it started working right away.

So for some reason according to Tiled, everything was painted properly. But as soon as the TiledMapRenderer started rendering it, the clear screen started overrunning some parts.

---
Tags: java, libgdx, camera, box2d, tilemap
---


# Question
Title: In OpenGL, is it a bad idea to "combine" immediate mode and retained mode for the sake of GUIs?
Suppose I have a 3D scene being drawn with `glDrawArrays(...)` and I want to render something simple, like a 2D overlay. Would it be a bad idea to use immediate mode for such a thing, instead of setting up a 2D renderer with retained mode?

Example:

```
void Draw()
{
    // Draw the 3D scene:
    // *does stuff*
    glDrawArrays(...);
    // *some other stuff*

    // Setup a quad with immediate mode (for something like a vignette overlay)
    glBegin(GL_QUADS);
    glTexCoord2f(...); glVertex2f(...);
    glEnd();
}

```

# Answer
It is a bad idea insofar as it is nonsensical. There is nothing to "set up" that you have not already done, except for an ortho projection matrix (which you will have to do in any case).

Portability is probably not a problem, although it should be. IHVs seem to be *very* reluctant to drop support for immediate mode for the foreseeable future (it seems to "work fine" even in core profiles), so although immediate mode should have died out long ago, it will probably stay forever. Performance is another story. Do you really want something that accounts for 0.1% of the scene complexity to consume 15-20% of the CPU time -- GL calls are *relatively* lightweight, compared to e.g. DX, but they are not free -- and 15-20% of *real* frame time due to stalling the pipeline? Can you even afford that with your time budget? Most games can't.

And then of course, the quirks. Oh the quirks. The apparent beauty of immediate mode is that it is (seemingly) easy and straightforward to do something like drawing a couple of quads quick. In reality, immediate mode can be such a pain in the rear, it's so full of non-obvious pitfalls.
On the other hand side, it is just as easy (and more straightforward if you ask me!) to just write a small 5-LOC function `DrawQuad` which when called adds vertex coordinates and indices to a memory buffer and increments a counter. Which, surprise, you can then draw with `glDrawArrays/Elements` and which you can reuse (the GPU copy, not just the userland copy!) the next frame as-is as long as nothing is changed.
Immediate mode must, there is no other way, allocate a buffer and do a PCIe transfer every time. Or, something equivalent in latency (GPU reading main memory over the bus, whatever). The driver cannot possibly know (or assume) that the data remained exactly the same as the frame before.

Getting data to the GPU is a high-speed, but also a *high-latency* operation. Not only is the bus transfer *per se* a complicated, high latency protocol (several protocol layers, packetizing, acknowledgements, etc.), but also not all GPUs are even able to transfer and draw at the same time, or if they can do it, they may not be able at all times to switch between or initiate new operations freely while doing something different. Read as: *Thou shalt not transfer vainly*.
> 8 votes

# Answer
I personally only see it as being bad for two reasons:

1. It is very outdated and deprecated. And,
2. It is much slower than the modern ways of drawing with OpenGL.

But, if it's working out, and performance isn't going to be an issue, and if it is not a problem for you to use deprecated OpenGL functions in your program, then I believe you could do it. It will be slower have TONS and TONS of GUIs, but if it's not that many, again, go for it.

Understand this, though. That at the end of the day, OpenGL is doing the same thing; drawing to the screen. Immediate mode is just much slower if you have a lot of things being processed. So, you should pick what is the most useful for the task you have in mind. Hope this helps you out!
> 11 votes

# Answer
Another downside is that it makes your code less portable. Certain OpenGL variants do not support immediate mode at all, for example, OpenGL ES. (and as bigger-caliber Android-based devices such as tablets gain more traction, it could become important)
> 2 votes

# Answer
Using immediate mode is completely unnecessary for gui related work.

To create a simple gui item, let's say, a button:

1. You need a quad/triangle strip mesh,
2. A texture for the mesh
3. An orthographic projection transform

In this way, you can just write a simple pass-through shader that ignores lighting considerations, and you just scale the gui item to a pixel scale, or some percentage of the window, and then do a painters algorithm for rendering.

In this way, you can do a full ui system with all the performance benefits of retained mode.
> 1 votes

---
Tags: opengl, gui
---


# Question
Title: In Photon, What happens networked GameObject's ownership when master client disconnects?
I'm creating multiplayer game with Photon. When player disconnects, especially master client does, every GameObject instantiated from Master client is gone, so I can prevent with this:

```
PhotonNetwork.autoCleanUpPlayerObjects = false;

```

Now GameObjects are still there even Master is gone, but what about their ownership? I needed to destroy some of enemies when they dies, but if master is gone and other player got selected as Master, is he automatically receive ownership of them too?

If not, is there a way to do that automatically? Any advice will very appreciate it!

# Answer
> 1 votes
I just asked to the Photon's forum, and I got the answer.

The point is it's not.

Setting autoCleanUpPlayerObjects will not transfer ownership to new master client automatically.

To do that, you must create GameObject with PhotonNetwork.InstantiateSceneObject, not PhotonNetwork.Instantiate.

---
Tags: unity, multiplayer, photon
---


# Question
Title: Better way than url-encoded query stings to pass data from PHP to Flash?
For the turn-based browser Flash RPG I'm working on, I'm using url-encoded query stings to pass data from PHP to Flash. Basically, Flash posts a request to PHP, then PHP pulls some data from a MySQL database, does some calculations and echos something like "health=100&mana=50&strength=10" which Flash reads. It seems to work fairly well, but I'm wondering if there is a better way to do it? As I go along, the number of character stats is increasing, and after inventory slots, it will probably be around 100 variables. All that only needs to be pulled from the MySQL database through PHP once at the beginning though, with much smaller queries during gameplay.

# Answer
What you have here is basically a RESTful webservice API. The client communicates with the backend using HTTP requests with the request parameters in the query string. The backend then answers the request with the requested data in the body of the response. Using the query-string syntax for the response is unusual. Most people would use something like JSON or XML, but it's not a completely unreasonable solution.

Using RESful webservices is a very common architecture choice for client-server application. The main advantage is that it is not technology-specific. You can consume it with client applications implemented in any technology which can do HTTP requests. This is especially important in a case like yours where you are working with an obsolete technology like Flash. Down the line you will be forced to abandon it due to lack of browser support. But as long as you are using web services to communicate with your backend, you will very likely be able to keep using them with your new game client.

In the context of game development, there are however two drawbacks:

1. It usually sends text data. You might be able to save a lot of bandwidth when you use some binary encoding. `health=100&mana=50&strength=10` uses 30 bytes of text to communicate 3 integers. You could do that with 12 bytes if you just send 3 32-bit binary numbers. Even less if 16 bit or 8 bit are sufficient in your case (8 bit would be enough in this particular example, but I don't want to assume you won't ever have more than 256 in any of these attributes). And this doesn't even account for the HTTP header which will be sent in both directions with every message and can be several hundred bytes.

Note that webservices **can** return binary data. It's just a very uncommon thing to do. But don't let that stop you.
2. HTTP uses the TCP protocol. This is fine for slower-paced games. But it isn't suitable for action-oriented games where every millisecond of latency matters. When your game is one of these, it would be better to use UDP if possible.

Flash supports UDP, but only on the Adobe Air profile, not for the web player. But the usually recommended replacement for Flash web applications (HTML5 + Javascript) does not support UDP either. So when you want to use UDP, you will have to transit from a web application to a native game client.
> 1 votes

---
Tags: flash, actionscript-3, php, mysql
---


# Question
Title: How to draw a string to the screen by fading in one letter at a time?
I'm making a text adventure-style game with MonoGame. I have created a TextBox class which prints text onto the screen one letter at a time (like it's being typed). It does this by storing received text in a buffer string, and using `Update()` to periodically push letters into the output string, which is then drawn to the screen (I've written a function for wrapping, so I've had no problem there).

However, this method has some significant limitations - inability to change the font or colour of individual lines, for example - but there is something specific I am trying to achieve: I want each new letter to fade gradually onto the screen instead of just appearing instantly. So far, I've had no luck finding a way to do this.

At the moment, I've been attempting to remake the TextBox class to print each character with its own draw call, allowing me to change a letter's colour - and therefore alpha - individually. However, I've ran into a problem. I am using `spriteFont.MeasureString()` to allow me to draw the letters in the correct positions relative to each other, but it hasn't been giving me the values I need. Letters are drawn too close together, as it seems to be measuring the actual pixel width of the glyph, rather than the space they would take up if the string was printed all at once.

So, my question is: is there a way around this particular problem with `MeasureString`, or is there another solution entirely to make each letter fade in individually?

# Answer
You're facing into a problem that most game devs face in relation to enriching your HUD/User interface to be more dynamic.

In the end, you either find a library, or define your own requirements and write your own functions. It's a well duh moment yes, but chances are that libraries might be a 90% fit if you find the right one, even better if you can find an opensource one close to your needs and can contribute. But that's getting extreme to a degree.

The other extreme, write your own. I chose this path myself, and for me it was the right fit. I had a need to not only integrate text glyphs but also icons (such as xbox controller icons into my text). All I can give you is a few tips on what I found to work.

* Define exactly what functionality you are after. It will save you so much time if you can just sit down and define all the things you would need, then want and what would be a nice to have.
* Weigh up the compromises on libraries or if you were ever using something like Unity, plugins for example.
* If you choose the coding route, then you do have flexibility. Things I have learnt from my own build.

+ Every glyph is an object, work out what attributes you need.
    + Do not build all the functionality into the glyph object. But basic stuff like colour, size, font type, alpha etc, fit perfectly (and fit what you are thinking of above).
    + Overlay your glyph string functionality over the top. You have all the data, so you can create your overlay functions such as width. Others you might want to consider is things like centring text.

I have some classes I have written to enable the above mentioned functionality, they are a little embedded in my game. But i'm happy to discuss/share what I have if you do proceed down that path.
> 1 votes

# Answer
Rendering type is quite a difficult task, and it looks like you're trying to re-implement the text renderer with tools that aren't meant for that. See if you have access to some plugin or other open-source tool that allows you to render rich text. Then you'll have more control over how the letters are rendered.
> 0 votes

---
Tags: monogame, text
---


# Question
Title: Script executes fine but randomly crashes with NullRefferenceExpectation
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie_Spawn : MonoBehaviour
{
    public float timer = 0.0f;
    public bool m_spawn = false;
    public GameObject m_Zombie;
    Vector2 pos;

    void Update()
    {
        if (m_spawn == true)
        {
            timer += Time.deltaTime;
            if (timer > 2.0f)
            {
                pos = Camera.current.ViewportToWorldPoint(new Vector2(1f, 0.135f)); //this executes fine but will Null out randomly
                Instantiate(m_Zombie, pos, Quaternion.identity);
                timer = 0;
            }
        }
        else
        {
            timer = 0f;
        }
    }
}

```

# Answer
It's clearly written in the documentation:

> Use this function (`Camera.current`) only when implementing one of the following events: MonoBehaviour.OnRenderImage, MonoBehaviour.OnPreRender, MonoBehaviour.OnPostRender.

Outside of those three callbacks, you need to use `Camera.main`
> 0 votes

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


# Question
Title: How to keep a cubic bezier curve symmetric while moving points
I have created a cubic bezier curve using the Unity editor. How can I preserve the bezier curve symmetry when moving the end points or control points/anchor points? Please see my code below and the image:

UPDATE

Generally, when one of the end points (A or B) is moved, the control points (cp1 and cp2) will also move to correct the distance between them preserving the symmetry. Likewise when one control point is moved, only the other control point will move mirroring it’s movement (along/about the line of symmetry) to preserve the symmetry.

Bezier:

```
public static class Bezier {

public static Vector3 GetPoint (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
    t = Mathf.Clamp01(t);
    float oneMinusT = 1f - t;
    return
        oneMinusT * oneMinusT * oneMinusT * p0 +
        3f * oneMinusT * oneMinusT * t * p1 +
        3f * oneMinusT * t * t * p2 +
        t * t * t * p3;
}

public static Vector3 GetFirstDerivative (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
    t = Mathf.Clamp01(t);
    float oneMinusT = 1f - t;
    return
        3f * oneMinusT * oneMinusT * (p1 - p0) +
        6f * oneMinusT * t * (p2 - p1) +
        3f * t * t * (p3 - p2);
}
}

```

BezierCurve:

```
[RequireComponent(typeof(LineRenderer))]
public class BezierCurve : MonoBehaviour {

public Vector3[] points;
LineRenderer lr;
public int numPoints = 49;
bool controlPointsChanged = false;

bool isMoving = false;

public void Reset () {
    points = new Vector3[] {
        new Vector3(1f, 0f, 0f),
        new Vector3(2f, 0f, 0f),
        new Vector3(3f, 0f, 0f),
        new Vector3(4f, 0f, 0f)
    };
}

void Start()    {

    lr = GetComponent<LineRenderer> ();
    lr.positionCount = 0;
    DrawBezierCurve ();

}
public Vector3 GetPoint (float t) {
    return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
}

public void DrawBezierCurve ()  {
    lr = GetComponent<LineRenderer> ();
    lr.positionCount = 1;
    lr.SetPosition(0, points[0]);

    for (int i = 1; i < numPoints+1; i++) {
        float t = i / (float)numPoints;
        lr.positionCount = i+1;
        lr.SetPosition(i, GetPoint(t));
    }
}

public Vector3 GetVelocity (float t) {
    return transform.TransformPoint(
        Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
}

public Vector3 GetDirection (float t) {
    return GetVelocity(t).normalized;
}
}

```

BezierCurveEditor:

```
[CustomEditor(typeof(BezierCurve))]
public class BezierCurveEditor : Editor {

private BezierCurve curve;
private Transform handleTransform;
private Quaternion handleRotation;

private const int lineSteps = 10;

private const float directionScale = 0.5f;

private void OnSceneGUI () {
    curve = target as BezierCurve;
    handleTransform = curve.transform;
    handleRotation = Tools.pivotRotation == PivotRotation.Local ?
        handleTransform.rotation : Quaternion.identity;

    Vector3 p0 = ShowPoint(0);
    Vector3 p1 = ShowPoint(1);
    Vector3 p2 = ShowPoint(2);
    Vector3 p3 = ShowPoint(3);

    Handles.color = Color.gray;
    Handles.DrawLine(p0, p1);
    Handles.DrawLine(p2, p3);
    Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

    curve.DrawBezierCurve ();

    if (GUI.changed) {
        curve.DrawBezierCurve ();
        EditorUtility.SetDirty( curve );
        Repaint();
    }

}

private void ShowDirections () {
    Handles.color = Color.green;
    Vector3 point = curve.GetPoint(0f);
    Handles.DrawLine(point, point + curve.GetDirection(0f) * directionScale);
    for (int i = 1; i <= lineSteps; i++) {
        point = curve.GetPoint(i / (float)lineSteps);
        Handles.DrawLine(point, point + curve.GetDirection(i / (float)lineSteps) * directionScale);
    }
}

private Vector3 ShowPoint (int index) {
    Vector3 point = handleTransform.TransformPoint(curve.points[index]);
    EditorGUI.BeginChangeCheck();
    point = Handles.DoPositionHandle(point, handleRotation);
    if (EditorGUI.EndChangeCheck()) {
        Undo.RecordObject(curve, "Move Point");
        EditorUtility.SetDirty(curve);
        curve.points[index] = handleTransform.InverseTransformPoint(point);
    }
    return point;
}
}

```

Preferably, I would like to be able to toggle the bezier curve symmetry on and off.

# Answer
Here's a method that seems to work OK.

First I created a little mirror structure to help make the symmetry math clearer:

```
public struct MirrorPlane {
    public readonly Vector3 normal;
    public readonly Vector3 center;

    public MirrorPlane(Vector3 direction, Vector3 center) {
        normal = direction.normalized;
        this.center = center;
    }

    public static MirrorPlane Between(Vector3 a, Vector3 b) {
        Vector3 difference = (b - a);
        Vector3 average = 0.5f * (a + b);

        return new MirrorPlane(difference, average);
    }

    public Vector3 Reflect(Vector3 point) {
        Vector3 difference = point - center;
        float signedDistance = Vector3.Dot(difference, normal);

        return point - 2f * signedDistance * normal;
    }
}

```

Then I added some symmetry properties to the BezierCurve MonoBehaviour:

```
public enum SymmetryMode {
    Off,               // Do not enforce symmetry.
    MirrorFarHandle,   // When moving A, CP2 mirrors CP1
    MirrorNearHandle   // When moving A, CP1 mirrors CP2
}

public SymmetryMode symmetry;

// How much should the non-mirrored control point follow
// when the endpoint is moved? 0 = stationary, 1 = match end motion.
[Range(0, 1)]
public float symmetryBlend;

```

Then I added a little structure to the editor script to keep track of changes inside the ShowPoint method:

```
struct Change {
    public int index;
    public Vector3 displacement;

    public static Change Unchanged {
        get {
            return new Change { index = -1 };
        }
    }

    public static implicit operator bool(Change change) {
        return change.index >= 0;
    }
}

// ShowPoint now logs the change if it's making, if any.
private Vector3 ShowPoint(int index, ref Change change) {
    Vector3 point = handleTransform.TransformPoint(curve.points[index]);
    EditorGUI.BeginChangeCheck();
    point = Handles.DoPositionHandle(point, handleRotation);
    if (EditorGUI.EndChangeCheck()) {
        Undo.RecordObject(curve, "Move Point");
        EditorUtility.SetDirty(curve);

        // Log change.
        change.index = index;
        Vector3 newPoint = handleTransform.InverseTransformPoint(point);
        change.displacement = newPoint - curve.points[index];

        curve.points[index] = newPoint;
    }
    return point;
}

```

Lastly, the guts of the OnSceneGUI now have this:

```
// Initialize an empty change, and log changes made inside the ShowPoint()s
var change = Change.Unchanged;

Vector3 p0 = ShowPoint(0, ref change);
Vector3 p1 = ShowPoint(1, ref change);
Vector3 p2 = ShowPoint(2, ref change);
Vector3 p3 = ShowPoint(3, ref change);

// If there's a change we need to mirror symmetrically....
if (change && (curve.symmetry != BezierCurve.SymmetryMode.Off)) {
    // One control point will move to mirror the other.
    int lead;

    if (change.index == 1 || change.index == 2) {
        // If we moved one of the control points,
        // it leads, and the other follows to mirror it.
        lead = change.index;

    } else {
        // Otherwise, we moved an endpoint,
        // and our symmetry mode determines which control point gets mirrored.
        bool mirrorCP2 = (change.index == 0)
                       ^ (curve.symmetry == BezierCurve.SymmetryMode.MirrorNearHandle);

        lead = (mirrorCP2) ? 1 : 2;

        // This lets us either move the non-mirrored control point
        // in step with the endpoint, or keep it stationary, or any intermediate.
        curve.points[lead] += curve.symmetryBlend * change.displacement;
    }
    // Select the other control point and mirror it from the leader.
    int follow = 3 - lead;
    var mirror = MirrorPlane.Between(curve.points[0], curve.points[3]);
    curve.points[follow] = mirror.Reflect(curve.points[lead]);
}

```
> 4 votes

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


title: Implementing Customizable Input

text:
# Question
Title: Implementing Customizable Input
I am trying to brainstorm how to create customizable input. Any help would be greatly appreciated, but here's my best guess so far.

I could create a custom 'Input' class, with Methods to call for each input. Like public bool IsRight()", "public bool IsJump()", etc. Then I could call these methods from any other class.

However, I cannot figure how I would assign these different methods to different keys such that:

```
public bool IsRight(){
    if (keyboardState.IsKeyDown(Keys.Right)){
        return true;
        }
    return false;
}

```

works, but I could change the input from 'Right' to 'D', or so on.

# Answer
> 1 votes
Gabriele's answer provides a pretty neat way to handle input generically, but for rebindable keys I don't personally prefer the callback approach, since I don't like having to maintain that map of callbacks whenever keybindings change.

Disclaimer: Following answer is in C++ but most of the concepts should be applicable to other languages as well.

Instead, I essentially just store controls in a struct:

```
struct Controls
{
    Key m_MovementUp;
    Key m_MovementDown;
    Key m_MovementLeft;
    Key m_MovementRight;

    Key m_Shoot;
}

```

Every input device (you could use inheritance to a `struct ControlsBase` and add a similar struct for controller buttons) holds an instance of the controls struct. When the device is initialized, you could load the keys from a file to the members, and at shutdown you could write the keys to the file. Your settings menu can build displays for each input device, and alter the values of the control keys.

The abstraction of "input device" is not necessarily necessary, since your input manager could perhaps just map the controls to an index (`std::map<PlayerID, Controls*> m_Controls`), and query those from the gameplay code:

```
Player::Player(PlayerID id)
{
    m_Controls = InputManager::GetControls(id);
}

void Player::Update()
{
    if (keyboardState.IsKeyDown(m_Controls->m_MovementRight))
    {
        MoveToRight();
    }
}

```

Since `m_Controls` is a pointer to the global controls struct, the gameplay code will automatically use the right key if the player for an example rebinds keys from the pause menu.

# Answer
> 0 votes
(There might be a better way, but this is what i've come up with; This approach is *inspired* by Unity)

Ref link: https://github.com/gabrielevierti/Advent3D/blob/master/Core/Core/src/Logic/input.h

As you can see, i made an enum, called keycode, which lets me choose which key on the keyboard is pressed by the user. There is also a boolean array, which contains the state of each key. By creating a 'getKey(KeyCode)' type of function, we can get the keycode from the 'KeyCode' enum, and the corresponding boolean in the 'keys' boolean array will be set to it's state(either true -\> pressed; false-\> released). The same approach can be applied to Buttons, like mouse buttons or joystick buttons, joystick axis, and basically any type of input, VR too for example.

If we want to check if the X key was pressed, all we do is:

```
If(Input::GetKey(KeyCode.X))
{
    //the X key was pressed
}

```

I'm using GLFW as a base, and I'm deriving from it. This is not the smartest way to do it, since we are just "renaiming" GLFW values to ours, but hey it's still a valid option.

**Map Based approach**

As suggested to me in the past (from Tyyppi77), you could use a map based approach: you basically store a map of function callbacks, that get invoked when a specific key is pressed.

```
class Input
{
public:
using Callback = std::function<void()>;

void addBinding(int key, const Callback& callback)
{
    m_Callbacks[key].push_back(callback);
}

void onKeyPress(int key)
{
    for (Callback& callback : m_Callbacks[key])
    {
        callback();
    }
}
private:
std::map<int, std::vector<Callback>> m_Callbacks;
};

```

This way you can add callbacks based on your needs, just by creating `std::functions`. You could call `onkeypress()`, specify the correct key, and the corresponding callback will get invoked.

---
Tags: input
---


# Question
Title: Does a detailed texture take longer to render?
Let's say I want to render a square; its texture is "square.png."

Is it easier for the computer to render it if the texture is just a plain color?

And what about if it is a *very noisy* texture with completely random colors here and there?

Or what if that texture is noisy in the sense that every pixel in it is different from one to another, but only by a tiny bit?

# Answer
Like most things in game development, and especially in game graphics, the answer is "it depends"

## Texture Size

The resolution of your texture can have an impact on rendering speed. The more pixels it contains, the more raw data there is to upload to the GPU, and the less of the texture we can fit in cache at a time, so the shader might hit more pauses while it waits for the right part of the texture to get pulled into cache.

Using mipmapping can reduce the impact of this. With mipmaps, we store a chain of downsized versions of the texture, which at first sounds like even more memory to schlep around. But it lets us read from the smaller versions when the texture is displayed at a small size on the screen (like a distant object in perspective), so our samples make better use of the texture cache, rather than jumping all over. This also reduces aliasing.

## Texture Detail

The content of your textures doesn't have an impact on rendering efficiency most of the time.

A colour is just a bunch of numbers as far as the GPU is concerned, so it doesn't care much what those numbers are, it just funnels them through its math the same way. It doesn't do anything fancy like remembering "Oh, I've seen a pixel in this green before, I'll just re-use the same output I calculated last time I saw this input" so whether your texture is all one colour or random sparkles, your GPU is doing the same work.

Unlike formats like PNG & JPG, which compress more efficiently in predictable areas of the image, and eat up more bits in complex regions, GPU texture formats like BTC, ETC, PVRTC, or even raw RGBA use a fixed number of bits per block of pixels. So making your texture more or less detailed while keeping the same compression format won't change its data size or impact data transfer and cache-related efficiency.

But, if you use a particular kind of detail that your previous compression doesn't preserve well, you might be forced to change your whole image to use a different format, which could again change its data size.

## Shader Branching & Indirection

Here's the biggest asterisk in the situation: you might be using this texture colour input to make decisions, like an `if()` branch. Here, detail matters for speed.

GPU shading units work on blocks of pixels in batches, running the same instructions in parallel on multiple streams of data. So when some pixels in the block take one branch of the `if` and other pixels take the other, the whole batch has to go through *both* branches (masking out the results that don't apply to one set of pixels or the other)

If your input changes in a smooth/predictable way, then you'll likely have many blocks that only need to take a single branch, and these both-branch cases will be limited to narrow bands around the transition border. But if your input is random-ish, we'd expect most blocks to take both branches and slow down the rendering.

This can also happen if you're using one texture to control lookups into a second texture, like a distortion or index map. If the first texture jumps around randomly, then we'll be sampling from scattered, random-ish spots of the second texture, making less consistent use of our texture cache and waiting longer to get the data we need, on average.

---

So, overall: no, the content of the texture doesn't have much impact on rendering speed, except for the cases when it does. ;)
> 39 votes

# Answer
Along with DMGregory's excellent answer above, there is, perhaps, one case where the complexity of a "texture" can affect the rendering performance and that is where the results of a previous render are used as a source in a subsequent one, e.g. shadow maps/reflections/environment maps.

Some modern hardware may apply lossless compression to these buffers: for example PowerVR has PVRIC, AMD, Delta Colour Compression, and ARM has something similar. The aim of these compression techniques is to reduce overall bandwidth which, in turn, can improve rendering performance.

The simpler the data, be it depth or colour (integer or floating-point), the better these schemes will work. Of course, I wouldn't suggest deliberately simplifying your rendering output just for these to function better, but avoiding using noisy data might help in some circumstances.

Also, doing sparse sampling of frame/depth buffers which use these schemes, in a vain attempt to lower bandwidth, won't help because they are very likely to be block based.

Further you might find these two SE Computer Graphics questions and answers of interest:
> 1 votes

---
Tags: textures, graphics
---


# Question
Title: How can I reduce amount of graphics to draw for a smooth 2D character evolution transition?
I'm working on a game where the player has a character that can be fatter or skinnier, and maybe other transitions. Not only the height and width could change, but the complete appearance of the body.

I'm using separately the body parts for animations, and I can handle the animation transition pretty well.

I was thinking about drawing all the graphics to make nice and smooth transitions, but for example if the character has 20 states, and it has minimum 8 parts/state, I have to draw 160 graphics. It seems too much for me.

Is there a way to reduce the amount of work to have all of these states? I'm open to completely different techniques too.

# Answer
> 1 votes
Throw an explosion over everything you want to hide.

---
Tags: 2d, animation, graphics
---


# Question
Title: How to release a new level without having to publish a new version
What can I do to extend the gameplay. So if I know that I will update the game with new levels and dont want to publish a new version every time I have a new level. How can I handle this.

Ex: I have a unity3d game with 3 levels now and I know that i will have a 4th level. So what should i do in order to extend the game play without publishing a new build after i finish making the 4th level?

I wanna download the new level on the fly instead of new release

I know i need to use external help like a server to import all the files but how would that work?

I am using same scene and different setups to implement levels. I am currently hardcoding the levels. But if that's wrong I can change it.

# Answer
> 1 votes
When your levels are defined in sourcecode, then you can't add more levels without releasing a new version of the complete game build. So instead of hardcoding your level setups, move the layout of each level to a file in a format of your choice.

You can then download those files from a webserver when your game starts using the `WWW` class.

In order to not having to download all the levels again and again on each game restart, the game should store any already downloaded level on the hard drive. I would recommend to first download a text file which lists all the available level files. Check which files are already on the local hard drive, and then download only the missing ones with additional WWW requests. But keep in mind that not all the build targets supported by Unity allow filesystem access. If you want to publish for the platforms which don't support it, you need to find a different solution.

The only persistent storage system which is guaranteed to work everywhere is `PlayerPrefs`. But this system is designed to hold a handful of configuration keys. It's not designed to hold large amounts of data.

If your distribution channel supports incremental updates of game assets, you can might also be able to use these to only update the level file(s).

Another side-effect of having levels in form of files is that it allows your community to create their own levels. An active community of level designers can be great for you. It means your game gets a constant stream of more and more content and you don't need to pay a cent for that. The downside is that you will now have a harder time to sell more levels in form of DLC, because your new levels compete with the free levels provided by the community. But you still have the advantage that only you can release DLC which adds new game features.

---
Tags: unity, unity-networking, levels, patching
---


# Question
Title: Can a straight line be called a polygon?
According to the definition of Polygon, If a Poly-line's first and last points are connected then it is called Polygon. See the image below. I have P1, .... P5 Polyline. If I draw a line from P5 to P1 then it will be called polygon or not? I am confused here.

# Answer
Technically? Yes. It's no different to, say, a polygon with the shape of a D with 5 points viewed edge-on.

A polygon is just a closed shape which has 3 or more vertices and edges. A shape with only two vertices is just a line. Meanwhile a shape with 3 vertices and only 2 edges cannot be a closed shape: most libraries would just join the first and last vertices and *make* it a closed shape then fill it in; otherwise it's just a series of lines!

As far as your graphics library is concerned, yes it's probably a polygon, but that depends on the library.
> 7 votes

# Answer
more sides there are in a polygon the angle is larger, nearing 180 deg. a Googolgon ( a polygon with 10 to the power 100 sides) has an angle of ~180 degrees.

so.. if you keep drawing a straight line, with infinite number of sides, this line will meet the starting point at infinity, right?

I am not a math guy, was trying to teach my 9yr old about a plygon and started reading. Am I wrong?
> 0 votes

# Answer
The line is a polygon in computing, since it is composed of 3 or more points, connected by straight lines. The computer doesn't have to understand whether they are on a single line. It just "connects the dots".

But it can be discussed whether it is a polygon in terms of geometry. According to most definitions of a polygon in geometry, polygons are 2-dimensional shapes. The shape in your post is only one dimensional, so in my opinion it is not a polygon.
> -1 votes

# Answer
A line does not make a closed boundary, so a line is never a polygon.
> -2 votes

# Answer
A line is not a shape, a shape is an enclosed figure, and if a regular line counts as a shape, its not, because the line would be opened, and not enclosed, which IS a shape if the figure is enclosed. Many lines can make a shape, and for a circle, a bent line, is not a line, its a curve.
> -3 votes

---
Tags: mathematics
---


# Question
Title: How can I produce 3D environments for VR from HDRI images?
I have a question regarding to the HDRI maps as many some of you have a bit of experience in this field especially for Oculus Rift platform!

I've been trying to achieve a 3D landscape from this HDRI map. (Also I highly recommend this website for others :)!)

I even decided to render in Maya few images from the orthographic perspective but unfortunately still no luck.

See the results here on YouTube.

Is there any other method to reconstruct 3D models just from images and use them to create environment?

# Answer
It's very hard to reproduce a 3d environment from a single image, in fact, it's pretty much impossible, even for humans.

For instance, these images:

You can't really tell whether the man at the back is a giant or they are simply the same distance away from the camera.

However, if you have a lot of images with known positions of the same area, then you can reconstruct it. This is called photogrammetry.

It's usually done using preprocessing (because it can take a long time), but real time versions do exist.
> 2 votes

---
Tags: 3d-meshes, unreal-4, virtual-reality, hdr
---