title: Unity can't build AssetBundle for iOS

text:
# Question
Title: Unity can't build AssetBundle for iOS
From http://docs.unity3d.com/ScriptReference/BuildPipeline.BuildAssetBundle.html, I am using the sample code

```
using UnityEngine;
using UnityEditor;
public class ExportAssetBundles {
    [MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
    static void ExportResource () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
                                           BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
            Selection.objects = selection;
        }
    }
    [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
    static void ExportResourceNoTrack () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
        }
    }
}

```

To build an AssetBundle. However, whenever I run this on a prefab, I noticed that Unity switches the platform to WebPlayer and THEN builds the bundle. But I need the AssetBundle to be built for iOS and Android - I don't need WebPlayer bundles.

Why does it keep switching to WebPlayer platform whenever I run this? How can I build for iOS and Android?

My prefab is just an object with a Sprite Renderer.

# Answer
Notice in that documentation the optional last parameter: BuildTarget targetPlatform = BuildTarget.WebPlayer

In other words, if you don't explicitly set the target platform then it will default to target web player. To make it target the current platform, tell it: EditorUserBuildSettings.activeBuildTarget

Frankly, I would file this as a bug against that documentation. They should really make this fact more explicit, perhaps by adding it to their sample code or at least having a WARNING note that you should use .activeBuildTarget for mobile platforms.
> 2 votes

---
Tags: unity
---


# Question
Title: Checking for collisions on a 3D heightmap
I have a 3D heightmap drawn using OpenGL (which isn't important). It's represented by a 2D array of height data. To draw this I go through the array using each point as a vertex. Three vertices are wound together to form a triangle, two triangles to make a quad. To stop the whole mesh being tiny I scale this by a certain amount called 'gridsize'.

This produces a fairly nice and lumpy, angular terrain kind of similar to something you'd see in old Atari/Amiga or DOS '3D' games (think Virus/Zarch on the Atari ST).

I'm now trying to work out how to do collision with the terrain, testing to see if the player is about to collide with a piece of scenery sticking upwards or fall into a hole.

At the moment I am simply dividing the player's co-ordinates by the gridsize to find which vertex the player is on top of and it works well when the player is exactly over the corner of a triangle piece of terrain.

However...

How can I make it more accurate for the bits between the vertices? I get confused since they don't exist in my heightmap data, they're a product of the GPU trying to draw a triangle between three points. I can calculate the height of the point closest to the player, but not the space between them.

I.e if the player is hovering over the centre of one of these 'quads', rather than over the corner vertex of one, how do I work out the height of the terrain below them? Later on I may want the player to slide down the slopes in the terrain.

# Answer
> 0 votes
Trying to interpolate across the triangles and working out which triangle to use was working, but it was strangely jittery if I used the data to move a player across the surface of my heightmap.

A bit of Googling turned up this page http://www.gamesandcode.com/blog/xna-project/rolling-the-ball which shows some XNA code for rolling a ball across a heightfield.

In that the code uses bilinear interpolation to work out the height based on the whole 'quad' which is accurate enough for what I want (and now I think about it, is probably what OpenGL is doing to draw these pieces of geometry anyway).

Here is the code I managed to create

(position.x and position.y are the player's co-ords, gridsize is the width of the 'quads' in GL co-ords)

```
    float xpos = position.x/gridSize;
    float ypos = position.z/gridSize;

    double intpart;
    modf(xpos, &intpart);
    float modX = (position.x - intpart * gridSize) / gridSize;
    modf(ypos, &intpart);
    float modY = (position.z - intpart * gridSize) / gridSize;

    float TopLin = Lerp(GetHeightAt((int)xpos, (int)ypos),
        GetHeightAt((int)xpos + 1, (int)ypos), modX);
    float BotLin = Lerp(GetHeightAt((int)xpos, (int)ypos+1),
        GetHeightAt((int)xpos + 1,(int) ypos+1), modX);
    return Lerp(TopLin, BotLin, modY);

```

Lerp is a simple function that interpolates from a to b in steps of t (0 ... 1):

```
float Lerp (float a, float b, float t)
{
    return a + t * (b - a);
}

```

# Answer
> 2 votes
You have a few options:

* As Robert Swain suggests, test for an intersection between a line that represents the player and the particular quad or triangle the player is currently over.
* Use interpolation to see what the height is directly below the players position.

The interpolation could be easier to implement. See this question about interpolation for a triangle. As seen in the example image they provided:

Your character is at `x` and the points you have data for are surrounding the player at 3, 5, 7.

# Answer
> 0 votes
Sounds like the intersection of a line and a plane. The plane is that defined by the the vertices of the triangle underneath the player position. The line is parallel to the vertical axis but rooted at the player position. If you look up the intersection of a line and a plane, you should be able to get on the right path. :-)

# Answer
> 0 votes
The method I use is called barycentric interpolation.

I would write a guide how to do it, but I don't think I could possibly sum it up better than this tutorial.

---
Tags: 3d, collision-detection, mathematics, terrain
---


title: Drawing image with an angle

text:
# Question
Title: Drawing image with an angle
Edit: the images below aren't supposed to have whitespace. I am just trying to show you that i am trying to create a rectangle from a 1x64 image, positioned as shown in the second picture

I know how to rotate an image like that in XNA

But how is it possible to draw a sprite in this angle this way ?

I can't seem to be able to find an answer on that and i'm sort on ideas

# Answer
> 2 votes
What you want is a **skew matrix**. XNA has no built-in mechanism for creating one. Fortunately we can write our own:

```
Matrix CreateSkewX(float angle)
{
    Matrix skew = Matrix.Identity;
    skew.M12 = (float)Math.Tan((double)angle);
    return skew;
}

Matrix CreateSkewY(float angle)
{
    Matrix skew = Matrix.Identity;
    skew.M21 = (float)Math.Tan((double)angle);
    return skew;
}

```

(Note: These are untested, and I might have X and Y reversed.)

Check out this answer for more details.

# Answer
> 0 votes
You could draw it in 3d. Actually rotate it around the "up" axis. What's actually quite ironic though, is that you're already showing how it could also be done: You could split your sprite in strips vertically, drawing them at a small y offset from eachother. Note however that this skews the sprite, rather than actually rotating it. Not knowing if that's good enough for your application, I'm not sure what you should do. I would say that if you have to rotate it more that 45 degrees, you would probably be better off making a quad of "VertexPositionTexture", which you can freely position and rotate however you please, set up a camera (projection matrix), and rendering it, using the texture you want.

---
Tags: xna, c#, 2d, monogame
---


# Question
Title: How do I control which calculations are done on the CPU and which are done on the GPU?
My current understanding is that anything done in a shader file is done on the GPU, and anything done in my (Java, in my case) code is done on the CPU.

Is this an accurate description?

# Answer
> 20 votes
That's the gist of it.

In principle, the platform could, conceivably, do whatever it wants. One could imagine an advanced operating system doing just-in-time translation of compiled code from, say, x86 to GPU code. Similarly, OpenGL drivers could run whatever it wants on the host CPU.

But really, what you just described, is what happens.

# Answer
> 7 votes
Generally, Yes. Java is used to write programs that run on the cpu. Shader languages (cg,hlsl, et al) are used to write programs that run on the gpu.

An exception to the rule would be using third party apis which can bridge the gap.

# Answer
> 3 votes
david van brink answered your question in general.

But like he says, OpenGL driver could run stuff on the CPU, and it actually happens a lot. Especially with compatibility contexts, where some weird legacy functions cannot be implemented on the graphic cards. They require software emulation. For example, I've heard before that stippling is executed on the CPU. You can expect also surprises with picking.
These surprises can happen even more on MacOS using 2.1 contexts, because Apple has unified the view of OpenGL quite well accross their hardware range, and some smaller hardware lacks some stuff that has to be emulated. It goes so far as to actually be possible to execute the ENTIRE OpenGL 2.1 spec fully on CPU, if the context creation code specifies a software device explicitely.

Conversely, code that is executed through computing libraries like vexcl or boost compute, or microsoft's AMP, or nVidia thrust, CAN be executed on the GPU or the CPU depending on API setup flags.

And for the finish touch, inside the CPU you also have a DSP architecture with the part of it we call SIMD. Intel's ispc compiler provides help in generating code that is "ensured" to run on SIMD lanes with lots of performance diagnostics at compile time to help you make the most of it. Add OpenMP to that and you can get multithreaded SIMD, which approaches the concepts of GPUs. If you have a high end CPU and low end GPU, this can actually be more performant.
http://ispc.github.io/

---
Tags: shaders, gpu
---


title: Explaining Unity Sprite-Default Shader

text:
# Question
Title: Explaining Unity Sprite-Default Shader
I would like to know why we would use alpha blending in that shader for just rendering a sprite, which is just a texture ? What is tint color ? Why we multiply the alpha value by the color here ?

```
fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color; // why ?
c.rgb *= c.a; // why ?
Shader "Sprites/Default"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Fog { Mode Off }
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile DUMMY PIXELSNAP_ON
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;
                c.rgb *= c.a;
                return c;
            }
        ENDCG
        }
    }
}

```

# Answer
The "tint" color is a color that gets modulated (multiplied) with the texture color. This color is used with sprites for effects like making the player sprite blink red when hit by an enemy. To do so, you could set the tint to red when the player gets hit and leave it red for a couple frames, them restore it to white. Do that repeatedly for a few seconds and you'd have a blink effect for your sprite.

Multiplying the texture's `RGB` with the `A` could be used to give you a fade in/out effect. The alpha channel in the RGBA is a normalized value in the \[0,1\] range, so if you were to multiply the RGB with an alpha of say 0.2, you would get a very dark sprite. Multiply it by 1 and you will get the texture color as it is. You could get this same effect by multiplying the color with a back/white tint, BTW.

Finally, alpha blending should be on to ensure that sprites that have transparent areas get drawn properly. Most sprites have transparencies, so blending is required, otherwise the transparencies would be draw as if they where filled with some color. If you are sure you don't have transparencies in your sprites, then alpha blending could be safely disabled.
> 2 votes

---
Tags: unity, shaders
---


title: Textures not rendering on part of Cube

text:
# Question
Title: Textures not rendering on part of Cube
Hello all I have been trying learning opengl and have rendered a colorful cube and decided to texture it, now when I run the program the textures render on all of the faces except for the back face and bottom face where I just get a very light brown color her is a picture to show what is happening :

I think it may have something to do with my texture coordinates but I have the same texture coordinates for every vertex, here is the Vertex data I pass in :

```
static const Vertex VertexBufferData[] =
{
    //front face

    //1st triangle
    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //second triangle
    Vertex(glm::vec3(1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //left face

    //1st Triangle
    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //2nd triangle

    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(-1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //right face

    //1st triangle

    Vertex(glm::vec3(1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //2nd triangle

    Vertex(glm::vec3(1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //Top face

    //1st triangle

    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //2nd triangle

    Vertex(glm::vec3(-1.0f, 1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(-1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //Bottom face

    //1st triangle

    Vertex(glm::vec3(-1.0f, -1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //2nd triangle

    Vertex(glm::vec3(-1.0f, -1.0f, 0.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //Back face

    //1st triangle

    Vertex(glm::vec3(-1.0f, 1.0f, -2.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(-1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

    //2nd triangle

    Vertex(glm::vec3(-1.0f, -1.0f, -2.0f),
    glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)),

    Vertex(glm::vec3(1.0f, -1.0f, -2.0f),
    glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),

    Vertex(glm::vec3(1.0f, 1.0f, -2.0f),
    glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f)),

};

```

The paramaters for Vertex are : `Vertex(glm::vec3 pos, glm::vec3 color, glm::vec2 textCoord)` Here is my texture code :

```
Texture::Texture(std::string filename)
{
    int Width, Height, NumCompononents;

    m_Texture = 0;
    if (filename.empty()) return;
    unsigned char * imageData = (unsigned char*)stbi_load(filename.c_str(), &Width, &Height, &NumCompononents, 4);
    if (imageData == nullptr)
    {
        std::cerr << "Failed to load Texture for : "<< filename << std::endl;
        return;
    }
    else std::cout << "Texture successfully loaded!!!" << std::endl;

    glEnable(GL_TEXTURE_2D);

    glGenTextures(1, &m_Texture);
    glBindTexture(GL_TEXTURE_2D, m_Texture);

    glTextureParameterf(m_Texture, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTextureParameterf(m_Texture, GL_TEXTURE_WRAP_S, GL_REPEAT);

    glTextureParameteri(m_Texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTextureParameteri(m_Texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Width, Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

    stbi_image_free(imageData);
}
void Texture::Bind(unsigned int unit)
{

    assert(unit >= 0 && unit <= 31);
    glActiveTexture(GL_TEXTURE0 + unit);
    glBindTexture(GL_TEXTURE_2D, m_Texture);
}

Texture::~Texture()
{
    glDeleteTextures(1, &m_Texture);
}

```

Here is the Object file where I render the Cube:

```
#include "Object.h"
#include <glm\glm.hpp>
#include <glm\gtx\transform.hpp>
#include <iostream>

Object::Object(const Vertex * VertexBufferData, unsigned int numVertices)
{
    m_NumVertices = numVertices;
//  std::cout << m_NumVertices<< std::endl;
    std::vector<glm::vec3> Colors;
    std::vector<glm::vec3> Positions;
    std::vector<glm::vec2> TexCoords;

    for (unsigned int i = 0; i < numVertices; i++)
    {
        Colors.push_back(VertexBufferData[i].m_Color);
        Positions.push_back(VertexBufferData[i].m_VertPos);
        TexCoords.push_back(VertexBufferData[i].m_texCoord);
    }
    glGenVertexArrays(1, &m_VertexArrayID);
    glBindVertexArray(m_VertexArrayID);
    // Generate 1 buffer, put the resulting identifier in Vertexbuffers
    glGenBuffers(1, m_Vertexbuffers);

    SendPositionData(Positions);
    SendColorData(Colors);
    SendTextureData(TexCoords);

}

void Object::SendColorData(std::vector<glm::vec3> Colors)
{

    glBindBuffer(GL_ARRAY_BUFFER, m_Vertexbuffers[1]);
    glBufferData(GL_ARRAY_BUFFER, m_NumVertices * sizeof(Colors[0]), Colors.data(), GL_STATIC_DRAW);
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(
        1,                  // attribute 1 which is the color of the vertices
        3,                  // size
        GL_FLOAT,           // type
        GL_FALSE,           // is it normalized
        0,                  // stride
        (void*)0
        );

    glBindVertexArray(1);
}
void Object::SendPositionData(std::vector<glm::vec3> Positions)
{
    // send the vertices to OpenGL
    glBindBuffer(GL_ARRAY_BUFFER, m_Vertexbuffers[0]);
    glBufferData(GL_ARRAY_BUFFER, m_NumVertices * sizeof(Positions[0]), Positions.data(), GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(
        0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
        3,                  // size
        GL_FLOAT,           // type
        GL_FALSE,           // is it normalized
        0,                  // stride
        (void*)0
        );

    glBindVertexArray(0);
}
void Object::SendTextureData(std::vector<glm::vec2>TexCoords)
{
    glBindBuffer(GL_ARRAY_BUFFER, m_Vertexbuffers[2]);
    glBufferData(GL_ARRAY_BUFFER, m_NumVertices * sizeof(TexCoords[0]), TexCoords.data(), GL_STATIC_DRAW);
    glEnableVertexAttribArray(2);

    glVertexAttribPointer(
        2,                  // attribute 2 the TexCoordinates
        3,                  // size
        GL_FLOAT,           // type
        GL_FALSE,           // is it normalized
        0,                  // stride
        (void*)0
        );

    glBindVertexArray(2);
}

void Object::Draw()
{
    glDrawArrays(GL_TRIANGLES, 0, m_NumVertices); // Draw all triangles starting with vertex0 to m_NumVertices
}
Object::~Object()
{

}

```

# Answer
> 1 votes
Usage of `glVertexAttribPointer` is suspicious.

```
glVertexAttribPointer(
    2,                  //
    3,                  // Mistake in TexCoords, should be 2
    GL_FLOAT,           //
    GL_FALSE,           //
    0,                  // Should be size of your vertex
    (void*)0            // Should be offset within vertex
);

```

Check the documentation to see if you use it right. Examples: https://www.opengl.org/wiki/VBO\_-\_just\_examples

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


# Question
Title: How to determine areas of pixels of different colors or luminosities?
I want to create a program that determines all the areas of a given picture that have a different color, or the same color with different luminosities.

Are there known algorithms that do this job ? I would love to study such algorithms and implement them.

Thank you in advance for any help.

# Answer
> 2 votes
I've been researching Sobel Filters for edge detection. I then use that information to identify bounding information so I can crop out borders programmatically.

I also like OMGtechy's comment on converting to `YCrCb` or `YUV` and throwing out the Luma component. MSDN has an article on RGB to YUV Strangely enough, looks like it's HLSL (shader).

# Answer
> 0 votes
One possible approach is this:

1. Convert to the YCrCb colour space and discard the Luma (Y) component.
2. Compute a quality metric (see below),
3. See if the quality metric is above a threshold (see below),

**Quality Metrics**

* ASNR
* PSNR
* SSIM

**Threshold**

This will be largely trial and error; you'll just have to tweak it until you get the results you want. I'd start at about 50 for PSNR/ASNR, or 0.9 for SSIM and work from there.

---
Tags: image, color, pixel
---


title: Normal Mapping issue

text:
# Question
Title: Normal Mapping issue
The first image shows a spotlight shining correctly on the floor. The second image shows the same spotlight but rotated 180 degrees.

The first is correct, the second is not.

The third image shows the light "half if and half out"

Can anyone understand what is happening here?

Normal mapping code:

Shader.fs

```
vec3 CalcBumpedNormal()
{
vec3 Normal = normalize(normal0);
vec3 Tangent = normalize(tangent0);
Tangent = normalize(Tangent - dot(Tangent, Normal) * Normal);
vec3 Bitangent = cross(Tangent, Normal);
mat3 TBN = mat3(Tangent, Bitangent, Normal);

return normalize(TBN * (255.0/128.0 * texture2D(normalMap, texCoord0.xy).xyz - 1 ));
}

```

The model is Sponza by crytek. Loaded using Assimp Model Loader.

# Answer
The sponza model from crytek loads bump map from an .mtl file where I found the "bump" map for the flooring..

map\_bump textures\spnza\_bricks\_a\_diff.tga bump textures\spnza\_bricks\_a\_diff.tga

If you take a look at these textures, they are clearly not normal / bump maps, and as the image name suggests; they are diffuse textures.

If you swap the two names with the corresponding normal texture that is supplied "spnza\_bricks\_a\_ddn.tga" then the normals work correctly.

Thanks
> 0 votes

---
Tags: opengl, graphics, lighting, normal-mapping, bump-map
---


# Question
Title: What is the simplest way to calculate distance in a 3D environment?
What is the simplest way to programmatically calculate difference between two points in a 3D game environment?

I am trying to sort a list of light sources by how close they are to an entity, so that only the four closest light sources affect an entity at any given time.

# Answer
Compute the vector representing the displacement between the two points `p0` and `p1`:

```
v = p1 - p0

```

and then compute the length of that vector:

```
distance = sqrt(dot(v, v))

```

---

A vector in this case is an element of the real 3D coordinate space, so it has three components (X, Y and Z). A point also has the same three coordinates, and we can subtract two points from eachother to get the vector representing the *displacement* between those points. Both vector and point subtraction is done component-wise, which means you do the operation on each component separately. For the first line above (`v = p1 - p0`), you're basically doing

```
v.x = p1.x - p0.x
v.y = p1.y - p0.y
v.z = p1.z - p0.z

```

where (`v.x` et cetera are the individual scalar components of the vector, and so on).

In the second equation we're taking the vector dot product of `v` with itself. The dot product has lots of useful applications but in this case I'm just using it for brevity. The dot product of a 3D vector has a *scalar* result (a single number), and that number is calculated for two vectors `a` and `b` as

```
(a.x * b.x) + (a.y * b.y) + (a.z * b.z)

```

which in our specific case translates to

```
(v.x * v.x) + (v.y * v.y) + (v.z * v.z)

```

This is the same as "`v.x` squared plus `v.y` squared..." When you take the square root of that resulting scalar, you get what is known as the *magnitude* or *length* of the vector. The length of the vector is the distance you travel when, starting from some origin (`p0` in this case) you displace yourself *by* the vector arriving at some destination (`p1`).

It is thus the quantity you want to sort your entities by. Note however that if you *only* need to compare distances, and not otherwise use the actual accurate value of the distance, you can omit the slightly-costly square root from the computation since it will not change the relative ordering of the values.
> 18 votes

# Answer
`abs(x1-x2) + abs(y1-y2)`, as proposed by this answer will not always be correct. If you are willing to perform two more multiplication, you can perform an exact ordering without the cost of a squareroot.

Consider the distances from `(0,0)` to the points `(3, 4)` and `(5, 1)`. The distances are `5` and `~5.09`, but the abs algorithm shows `(5, 1)` as being closer.

If you want to compare absolute differences without performing the square root, compute the square of the euclidian distance like this:

`(x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)`
> 2 votes

# Answer
abs(x1 - x2) + abs(y1 - y2) + abs(z1 - z2) is much more efficient than using square root. If you don't need the actual distance, and just need to compare distances, this is the way to go.

There will be a margin of error here, so it will give you a rough sort. Thanks to David for pointing this out
> 1 votes

# Answer
You could use the distance formula:

Formula:

`sqrt((p2.x - p1.x)^2 + (p2.y - p1.y)^2 + (p2.z - p1.z)^2)`

Code:

```
Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2) + Math.pow(p2.z - p1.z, 2))

```
> 0 votes

---
Tags: 3d, mathematics
---


# Question
Title: How can I test if the mouse draw on the active tiles?
I want to draw some sprites in a tiledmap where the tiles are active. I want to draw with the mouse, so how could I compare the position of the mouse, the sprite position and the position of active tiles? I tried to compare: `sprite.getX`, `screenX` and `cell.getTile (). getProperties (). containsKey ("active")` but I can not get the position of the active tiles.

# Answer
> 1 votes
The libgdx camera type OrthographicCamera has an unproject method. Supplying this method with the screen coordinates of the mouse click will give you a position in world space you can then use collision detection with on your tiles.

The following code shows how you might get the mouse coodinate and traslate it into a world space point.

```
Vector3 clickPos = new Vector3();
clickPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(clickPos);

```

At the end of this code snippet you can expect clickPos to now relate to a position in world space.

As noted by the API documentation, setting the z value of the input vector will give you a position at a distance along the ray spanning from the near to far plane. In the example, the z value is 0 therefore the returned coordinate will be on the camera's near plane. However, assuming this is orthographic this should be fine.

Getting the cell could then be done using getCell;

```
TiledMapTileLayer.Cell cell = TiledMapTileLayer.getCell(clickPos.x, clickPos.y);

```

---
Tags: libgdx
---


title: Rotating point around another point

text:
# Question
Title: Rotating point around another point
I can't manage to rotate point around another point.

I did some searching around google and found algorithm that should work and it kinda does but it also moves the point I am rotating closer to pivot point.

Here is whole class where the problem is

```
public class Player {

float rotation;
Vector2 position;
Vector2 center;

public Player() {
    position = new Vector2(Core.WIDTH / 2 - 10, Core.HEIGHT - 50 - 10);
    center = new Vector2(Core.WIDTH / 2, Core.HEIGHT / 2);
    rotation = 0;
}

public void turnRight() {
    rotation += 0.001;

    position.x = (float) (Math.cos(rotation) * (position.x - center.x) - Math.sin(rotation) * (position.y - center.y) + center.x);
    position.y = (float) (Math.sin(rotation) * (position.x - center.x) + Math.cos(rotation) * (position.y - center.y) + center.y);
}

public void render(ShapeRenderer sr) {
    sr.circle(position.x, position.y, 20);
}

}

```

# Answer
```
public class Player {

float rotation;
Vector2 position;
Vector2 center;
float length;

public Player() {
position = new Vector2(Core.WIDTH / 2 - 10, Core.HEIGHT - 50 - 10);
center = new Vector2(Core.WIDTH / 2, Core.HEIGHT / 2);
rotation = 0;
}

public void turnRight() {
    rotation += 0.001;
    length = Math.sqrt(((position.x - center.x) * (position.x - center.x)) + ((position.y - center.y) * (position.y - center.y)))

    position.x = (float) (Math.cos(rotation) * length + center.x);
    position.y = (float) (Math.sin(rotation) * length + center.y);
}

public void render(ShapeRenderer sr) {
    sr.circle(position.x, position.y, 20);
}

}

```

Changing it to this should work. I don't like using square roots because they're terribly slow (using a few each frame is not a problem, using hundreds is.) I suggest you read up on trigenometry, because the calculation you posed makes little sense. No offense intended. Also, I noticed `position = new Vector2(Core.WIDTH / 2 - 10, Core.HEIGHT - 50 - 10);`. Are you sure you don't mean it to be `position = new Vector2(Core.WIDTH / 2 - 10, Core.HEIGHT / 2 - 10);`?
> 1 votes

# Answer
```
float rotation = 90f;
while(true)
{
    position = CircleRadius * new Vector2(Math.Cos(MathHelper.ToRadians(rotation)),
    Math.Sin(MathHelper.ToRadians(rotation))) + center;
    rotation += 1f;
}

```
> 2 votes

---
Tags: mathematics
---


# Question
Title: Problem with update/render in game loop (scrolling view, render interpolation)
I use SFML 2.2 and program a 2d prototype game (2d mario style where the camera follows the player).

I am experiencing the buggy imagery during rendering, for example a chunk of vertex array blocks are misplaced which gives an awful visual/glitches.

In other words: the render does not match the expected state at the time at which the frame is presented to the user.

I've read several game-related articles regarding game loop, time step, etc and I *do* understand what's going on, but cannot spot the bug.

What I do: perform scene updates with fixed UPDATE\_STEP value (it then gets used when calculating, for example, the Player's new position, being applied to the velocity, etc). Then I use the remained slice of time since the last update divided by UPDATE\_STEP as a ratio (0..1) to perform the interpolation during rendering.

Basically I change the position of my Player and calibrate the Camera accordingly, all the rest of the game scene (tile map represented as a vertex array) remains untouched.

Could you help me to figure out where's my mistake? Here we go:

```
void gameLoop() {

    const sf::Time UPDATE_STEP = sf::seconds(1.0f / 120.0f);
    sf::Time timeSinceLastUpdate = sf::Time::Zero;
    _renderWindow.setFramerateLimit(60);
    sf::Clock clock;

    while (_renderWindow.isOpen()) {

        sf::Event event;
        while (_renderWindow.pollEvent(event)) {

            _curGameScene->processEvent(event);

            switch (event.type) {
            case sf::Event::KeyPressed:
                switch (event.key.code) {
                case sf::Keyboard::Escape:
                    _renderWindow.close();
                    break;
                default:
                    break;
                }
                break;
            case sf::Event::Closed:
                _renderWindow.close();
                break;
            default:
                break;
            }
        }

        _curGameScene->processKeyboard();

        sf::Time dt = clock.restart();
        timeSinceLastUpdate += dt;

        if (timeSinceLastUpdate > sf::seconds(0.25)) {
            timeSinceLastUpdate = sf::seconds(0.25);
        }

        while (timeSinceLastUpdate >= UPDATE_STEP) {

            _curGameScene->update(UPDATE_STEP.asSeconds());
            timeSinceLastUpdate -= UPDATE_STEP;
        }

        //RATIO FOR INTERPOLATION DURING RENDER
        const float alpha = timeSinceLastUpdate.asSeconds() / UPDATE_STEP.asSeconds();

        //normal draw
        _renderWindow.setView(_renderWindow.getDefaultView());
        _curGameScene->render(_renderWindow, sf::RenderStates::Default, alpha);

        //ortho draw
        _renderWindow.setView(_renderWindow.getDefaultView());
        _renderWindow.draw(infoText);
        _curGameScene->renderOrtho(_renderWindow);

        _renderWindow.display();
    }
}

```

my \_curGameScene has the player sprite entity, the camera, which follows him, and the tile map (implemented as a vertex array). so, in the update() method I do:

```
void LevelScene::update(float dtExpandedInSeconds) {
    _player->update(dtExpandedInSeconds);
}

```

player's update method is as follows:

```
virtual void update(float dtExpandedInSeconds) {

    //store the previous position of the sprite
    _prevPos = _pos;

    //calculate the new position of the sprite
    _pos.x = _pos.x + _vxy.x*dtExpandedInSeconds;
}

```

then when we invoke the LevelScene's render method:

```
void LevelScene::render(sf::RenderTarget &target, sf::RenderStates renderStates, float ratio) {

    //CALCULATED POSITION OF THE CAMERA TAKING INTO ACCOUNT THE RENDER RATIO
    const sf::Vector2f viewCenter = _camera->calcPos(ratio);

    sf::View view = target.getView();
    view.setCenter(viewCenter);
    target.setView(view);
    target.clear(_bgColor);

    _tileMap->render(target, renderStates, ratio);
    _player->render(target, renderStates, ratio);
}

```

which involves the Camera's calcPos method:

```
const sf::Vector2f &calcPos(float ratio) {

    sf::Vector2f followPos = _sprite2Follow->getPos();
    sf::Vector2f followPrevPos = _sprite2Follow->getPrevPos();

    //HERE COMES THE INTERPOLATION
    _calcPos.x = followPrevPos.x*ratio + followPos.x*(1.0-ratio);
    _calcPos.y = followPrevPos.y*ratio + followPos.y*(1.0-ratio);

    if (_calcPos.x <= _halfViewWH.x) {
        _calcPos.x = 0;
    } else if (_calcPos.x <= _mapWH.x - _halfViewWH.x) {
        _calcPos.x = _calcPos.x - _halfViewWH.x;
    } else {
        _calcPos.x = _mapWH.x - _viewWH.x;
    }

    if (_calcPos.y <= _halfViewWH.y) {
        _calcPos.y = 0;
    } else if (_calcPos.y <= _mapWH.y - _halfViewWH.y) {
        _calcPos.y = _calcPos.y - _halfViewWH.y;
    } else {
        _calcPos.y = _mapWH.y - _viewWH.y;
    }

    _calcPos.x += _halfViewWH.x;
    _calcPos.y += _halfViewWH.y;

    return _calcPos;
}

```

The Player's render method:

```
virtual void render(sf::RenderTarget &target, sf::RenderStates renderStates, float ratio) {

    _sprite.setPosition(_prevPos.x*ratio + _pos.x*(1.0-ratio), _prevPos.y*ratio + _pos.y*(1.0-ratio));
    target.draw(_sprite, renderStates);
}

```

**UPDATED**: I have a bit better results when I do not take the remained part of time slice into consideration and perform an additional update with that part, i.e.:

```
void gameLoop() {

    //... as above

    _curGameScene->processKeyboard();

    sf::Time dt = clock.restart();
    timeSinceLastUpdate += dt;

    if (timeSinceLastUpdate > sf::seconds(0.25)) {
        timeSinceLastUpdate = sf::seconds(0.25);
    }

    while (timeSinceLastUpdate >= UPDATE_STEP) {

        _curGameScene->update(UPDATE_STEP.asSeconds());
        timeSinceLastUpdate -= UPDATE_STEP;
        ++updatesCnt;
    }

    //ADDED
    _curGameScene->update(timeSinceLastUpdate.asSeconds());
    timeSinceLastUpdate = sf::Time::Zero;

    _renderWindow.setView(_renderWindow.getDefaultView());
    _curGameScene->render(_renderWindow, sf::RenderStates::Default); //NO ALPHA IS PASSED
    //ortho draw
    _renderWindow.setView(_renderWindow.getDefaultView());
    _renderWindow.draw(infoText);
    _curGameScene->renderOrtho(_renderWindow);
    //
}

```

Player's update method now doesn't have the alpha value either, it sets the sprite image using just Player's \_pos.

# Answer
> 2 votes
I think you have inverted the alpha in the interpolation. It should be `curr*alpha + prev*(1-alpha)`.

From Fix Your Timestep!:

> `State state = currentState * alpha +
>  previousState * ( 1.0 - alpha );`

In fact you are rendering an interpolated status that has 1 time-step of latency, so

```
Actual time elapsed |----------|---_______|
Time simulated      |----------|__________|
Rendered time       |---_______|__________|
Render latency         |------- ---|
                       |  1-a  | a |

Legend:
- one tenth of time-step used
_ one tenth of time-step not used
| marks time-steps separation

```

---
Tags: 2d, game-loop, sfml, fixed-timestep, bug
---


title: Multiple models not drawing

text:
# Question
Title: Multiple models not drawing
I got Camera, Terrain and player working, moving around, etc. When I try to add another player (another model to draw) it just dont any of the models. Here is my code;

```
public class World
{
    public Terrain terrain;
    public NewPlayer player;
    public List<NewPlayer> players = new List<NewPlayer>();

    public World(NewPlayer player)
    {
        this.player = player;
    }

    public void AddPlayer(NewPlayer _player)
    {
        players.Add(_player);
    }

    public void SetTerrain(Terrain terrain)
    {
        this.terrain = terrain;
    }

    public void Draw(NewCamera camera)
    {
        terrain.Draw(camera);
        foreach (NewPlayer _player in players)
        {
            _player.Draw(camera);
        }
        player.Draw(camera);
    }
}

public class Terrain
{
    GraphicsDevice graphicsDevice;

    // heightMap
    Texture2D heightMap;
    Texture2D heightMapTexture;
    VertexPositionTexture[] vertices;
    int width;
    int height;
    public Vector3 position;
    public BasicEffect basicEffect;
    int[] indices;
    Matrix worldMatrix;

    // array to read heightMap data
    float[,] heightMapData;

    public Terrain(GraphicsDevice graphicsDevice, Vector3 position)
    {
        this.position = position;
        this.graphicsDevice = graphicsDevice;
        RecreateWorld();
    }

    public void SetHeightMapData(TerrainData data)
    {
        this.heightMap = data.HeightMap;
        this.heightMapTexture = data.Texture;
        width = heightMap.Width;
        height = heightMap.Height;
        LoadHeightData(heightMap);
        SetVertices();
        SetIndices();
        SetEffects();
    }

    private void LoadHeightData(Texture2D heightMap)
    {
        width = heightMap.Width;
        height = heightMap.Height;

        Color[] heightMapColors = new Color[width * height];
        heightMap.GetData(heightMapColors);

        heightMapData = new float[width, height];
        for (int x = 0; x < width; x++)
            for (int y = 0; y < height; y++)
                heightMapData[x, y] = 0;// heightMapColors[x + y * width].R / 5.0f;
    }

    public void SetIndices()
    {
        // amount of triangles
        indices = new int[6 * (width - 1) * (height - 1)];
        int number = 0;
        // collect data for corners
        for (int y = 0; y < height - 1; y++)
            for (int x = 0; x < width - 1; x++)
            {
                // create double triangles
                indices[number] = x + (y + 1) * width;      // up left
                indices[number + 1] = x + y * width + 1;        // down right
                indices[number + 2] = x + y * width;            // down left
                indices[number + 3] = x + (y + 1) * width;      // up left
                indices[number + 4] = x + (y + 1) * width + 1;  // up right
                indices[number + 5] = x + y * width + 1;        // down right
                number += 6;
            }
    }

    public void SetVertices()
    {
        vertices = new VertexPositionTexture[width * height];
        Vector2 texturePosition;
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                texturePosition = new Vector2((float)x / 25.5f, (float)y / 25.5f);
                vertices[x + y * width] = new VertexPositionTexture(new Vector3(x, heightMapData[x, y], -y), texturePosition);
            }
            //graphicsDevice.VertexDeclaration = new VertexDeclaration(graphicsDevice, VertexPositionTexture.VertexElements);
        }
        graphicsDevice.SetVertexBuffer(new VertexBuffer(graphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.None));
    }

    public void RecreateWorld()
    {
        this.worldMatrix = Matrix.CreateTranslation(this.position);
    }

    public void SetEffects()
    {
        basicEffect = new BasicEffect(graphicsDevice);
        basicEffect.Texture = heightMapTexture;
        basicEffect.TextureEnabled = true;
    }

    public void Draw(NewCamera camera)
    {
        Matrix worldMatrix = Matrix.CreateTranslation(-width / 2.0f, 0, height / 2.0f);
        basicEffect.View = camera.viewMatrix;
        basicEffect.Projection = camera.projectionMatrix;
        basicEffect.World = worldMatrix;
        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            graphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3);
        }
    }

}

public class NewPlayer
{
    Model model;
    public string Guid;
    public Vector3 position = new Vector3(8, 1, -3);
    public Quaternion rotation = Quaternion.Identity;
    public Matrix worldMatrix = Matrix.Identity;

    public NewPlayer(Model _model)
    {
        model = _model;
        foreach (ModelBone bone in model.Bones)
        {
            bone.Transform *= Matrix.CreateScale(0.01f);
        }
    }

    public void RecreateWorld()
    {
        worldMatrix = Matrix.CreateRotationY(MathHelper.Pi)
            * Matrix.CreateFromQuaternion(rotation)
            * Matrix.CreateTranslation(position);
    }

    public void Draw(NewCamera camera)
    {
        RecreateWorld();
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index]
                    * worldMatrix;
                if (camera != null)
                {
                    effect.View = camera.viewMatrix;
                    effect.Projection = camera.projectionMatrix;
                }
            }
            mesh.Draw();
        }
    }

    public void MoveForward(float speed)
    {
        Vector3 addVector = Vector3.Transform(new Vector3(0, 0, 1), this.rotation);
        this.position += addVector * speed;
    }

    public void MoveBackward(float speed)
    {
        Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), this.rotation);
        this.position += addVector * speed;
    }

    public void Yaw(float amount)
    {
        this.rotation *= Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(amount), 0, 0);
    }

    public void ChangeBoneTransform(int boneIndex, Matrix t)
    {
        model.Bones[boneIndex].Transform = t * model.Bones[boneIndex].Transform;
    }
}

```

If I only got the player variable, it draw everything fine, but if I add one player at the list, it doesnt draw any player. Is there anything wrong in the code??

EDIT: This is my code to add players, the value of position and rotation is the same as the initial player, i move backward a little so it dont draw at the same location both players.

```
NewPlayer player = new NewPlayer(Jangada.getInstance().humanModel);
player.Guid = message.PlayerLoginPacket.Player.PlayerGuid;
player.position = Util.fromPosition(message.PlayerLoginPacket.Player.PlayerPosition);
player.rotation = Util.fromQuaternionMessage(message.PlayerLoginPacket.Player.PlayerRotation);
Util.getWorld().players.Add(player);

```

This is LoadContent function, I load the model and add the "player" variable to World:

```
humanModel = Content.Load<Model>("human");
world = new World(new NewPlayer(Content.Load<Model>("human")));

```

Here some Screenshots:

So I got the problem solved, but cant figure out why is it doing it, I copied the fbx file to another file so now I got human.fbx and human2.fbx and it worked. dont kniw why

# Answer
Please say for what are this variables?

```
public NewPlayer player;
public List<NewPlayer> players = new List<NewPlayer>();

```

And why are you drawing both player an players, but not only players?

> If I only got the player variable, it draw everything fine, but if I add one player at the list, it doesnt draw any player. Is there anything wrong in the code??

Please provide the code snippet where you create and add players.

**UPDATE**

So, problem in that you apllying scale each time you create model. If model is same instance you will get to small model to see it.
> 0 votes

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


# Question
Title: How can I implement a real-time game loop in a text-based game?
I am trying to make a short text game with c++ to help me learn the language. I have made a version that basically displays texts, waits for an input, once the input is received it displays text, and so on. What I want to do now is make it so that it doesn't wait for the input. Real-time if you will. So certain values keep changing while the player is sitting, and if he sits for too long that game changes in a major way.

My problem is that I can't figure out how to incorporate this in a my game loop. I have a while loop that has a input function, an update function, and a display function. Is this just something I have to do with a wait function?

(I am just using Visual C++ and nothing else).

# Answer
> 1 votes
One approach would be to create a second thread (CreateThread() I think?), in addition to the one that's waiting for input. The second thread could run continuously, check the actual time, update state, and so on. (Probably with a small Sleep, also, so it doesn't pin the CPU at 100%.)

Messages should be passed from your console-reading loop to the game loop in thread-safe queues. Ideally, should disable keystroke echoing on input, and let your game loop do all the printing, so user input display and game output can be controlled as you see fit.

Alternatively, you can have one loop for everything, and poll the keyboard state like described here: https://stackoverflow.com/questions/2067893/c-console-keyboard-events. You'd compare the keyboard state each time through the loop and see which keys have changed, to infer keyup/keydown events.

That SO answer covers some other console-input methods, also, which could work in a one-loop solution.

# Answer
> 1 votes
The Windows API includes "character mode" functions, which deal with consoles and console input at a lower level than the C++ standard library functions. You can make use of these to create a real-time text-based game loop (there are also useful functions in the API for drawing large blocks of characters at a time, which is helpful for creating smooth animation in text-based games).

The main function you'll want to concern yourself with is `ReadConsoleInput`, which allows you to create a simple game loop as follows:

```
while(update()) {
  // ...do something...
}

```

where `update()` looks like:

```
bool update () {
    INPUT_RECORD record[kRecordCount];
    DWORD recordCount = 0;

    auto result = ReadConsoleInput(inputHandle, record, kRecordCount, &count);
    for (auto index = 0; index < count ; ++index ) {
        switch(record[index].EventType) {
          // ...
        }
    }

    return trueIfGameIsStillRunning;
}

```

This is the first step towards a real-time loop. In this basic form, however, `update` will block if there are no events. There are also some events you will miss (mouse movement events) unless you configure the console input handle accordingly.

For many purposes, the blocking nature of the function is acceptable, but if it isn't, you can have a full real-time loop by using a wait function, supplying the console input handle (`inputHandle` above) to the function. The wait function will block until input is available or until the specified timeout occurs. You can use, for example, `WaitForSingleObject` with a very low timeout and check the return value, which indicates if the wait timed out or if the event was signalled. If the former, you process a frame of game updates without player input and wait again (if the latter, you process the player's input).

This method avoids the complexity of threads (although it does involve the complexity of events, which are thread synchronization primitives, so it's not totally trivial), but doesn't require you to set up a full-blown message pump and window (and thus lets you stay in an otherwise pure "text-based" environment you are presumably already familiar with).

# Answer
> 0 votes
If you are using windows, I would suggest building a simplified GUI with a text-input field.

However, you have an option in the .NET framework to use `System.Console.KeyAvailable` with `System.Console.ReadKey`. This is the solution I would use in C# (but also available for C++)

For Windows: The SO questions in this thread suggest using conio.h which is a non-standard C library in certain "MS-DOS Compilers" which include functions similar to `KeyAvailable` and `ReadKey`. Such as `kbhit` and `_getch` it also lists `PeekConsoleInput` and `ReadConsoleInput` which I think are `windows.h` functions.

For Linux/POSIX systems, I'd suggest ncurses. I haven't used it in a long while, but I enjoyed it.

# Answer
> 0 votes
Instead of using a blocking function such as getline, you will want to get input without blocking.

On Windows, you may implement the message loop and check for keyboard events. You then add the pressed key to your input buffer. When the user presses return you evaluate the input just as you do right now. When the user presses delete, you move back one position in your input buffer, etc.

Wikipedia article about the message loop: https://en.wikipedia.org/wiki/Message\_loop\_in\_Microsoft\_Windows

---
Tags: game-loop, windows, text, text-based, realtime
---


# Question
Title: Vector-based Pong-ball bounce calculations
I'm making a 2D game with pads and balls, sort of like Pong, in Unity 4.6.1. The calculations, however, won't be (very) Unity-specific. The pads are going to appear in various rotations, and therefore the physics for bouncing the balls off the pads, have to be vector-based.

**EDIT: The solution to the proposed problems is posted at the bottom!**

My wishes:

1. Depending on where the ball hits the paddle, it should bounce off in an angle of between -90 and 90 degrees, where the middle of the pad would give 0 degrees, and the extremities on each side should give -90 or 90 respectively. (The numbers are just for reference.)
2. The current direction of the ball, should be taken into account, so the resulting bounce vector, will be a product of the normalized velocity vector of the ball, and the calculated and normalized directional vector from the pad-bounce (see "Point 1"). (NOTE: The speed of the ball after the bounce is handled later!)

On the image below, the red arrow is the velocity vector of the ball. The effect of "Point 1" is the blue arrow, and the end-result implementing the functionality of both "Point 1" and "Point 2", is the green arrow.

Additional information:

1. The pads can change in size. I always have the following variables available: current width in units, standard width in units, and current scale as a float.
2. The ball has a circle collider, which is not a trigger.
3. The pads have a manually fitted polygon-collider, matching the bend on it. This is a trigger.

Using the code below, I almost have it going, but not quite. It's not working consistently.

**Mind the big edit below!** "Point 2" has been solved.

"Point 1" isn't being computed correctly, mostly because I'm having trouble finding a calculation that's precise. When I created my first Pong game, it was easy, because I could just see the difference in ball.y and pad.y and hold that against the width of the pad. I can't for the life of me figure out how to do that using vectors.

"Point 2" is giving me trouble, because I can't figure out how to calculate the normal vector for the pad. The calculations noted in this other answer and here say, that I need to get this normal correct to get the right bounce.

**This code is in "OnTriggerEnter2D(Collider2D col)" on the Pad:**

```
GameObject ball = col.gameObject;
BallScript ballScript = col.gameObject.GetComponent<BallScript>();

// We know the ball has hit the pad, so we raycast to see where it hits.
RaycastHit2D hit = Physics2D.Raycast(
    new Vector2(ball.transform.position.x, ball.transform.position.y),
    ball.rigidbody2D.velocity);

// Get the normal for the hit. I think this is also not going to work for my purposes,
// since my pad isn't square)
Vector2 n = hit.normal;
n.Normalize(); // this has to be normalized

// Get the velocity vector of the ball
Vector2 v = ball.rigidbody2D.velocity;
v.Normalize(); // I normalize v, because I want to add speed manually later

float dotOfvn = Vector2.Dot(v, n);

// Always reports -1f or 0.9998f, most likely because n is the same as v
// (or the exact opposite, I'm not sure)
Debug.Log("Dot: " + dotOfvn);

// Apply the function...
Vector2 R = -2 * dotOfvn * n + v;

// Without the following, the ball always returns in the same direction it came from.
// With the following, I almost have it all functioning, except when a ball comes
// flying as in image 2 (below).
R += (Vector2)((ballScript.transform.position - _transform.position) / currentPadScale).normalized;
R.Normalize();

ball.rigidbody2D.velocity = R * ballScript.speed;

```

Result of the current code is, that everything seems to almost work, but this image shows a situation that happens often, which proves it doesn't. Red arrow is the velocity vector of the ball, and the blue is where the pad sends it upon being hit.

As the code-comments state, I'm not sure which parts I'm doing correctly, but I'm sure it is solvable. I would very much appreciate a helping hand.

Sincerely, Ultroman.

## EDIT

I've solved part of my problem. Namely "Point 2". **EDIT: For the full solution, scroll down further!**

Here's the code:

```
GameObject ball = col.gameObject;
BallScript ballScript = col.gameObject.GetComponent<BallScript>();

Vector2 n = _transform.up;
Vector2 v = ball.rigidbody2D.velocity;
v.Normalize(); // I normalize v, because I want to add speed manually later

float dotOfvn = Vector2.Dot(v, n);

Vector2 R = -2 * dotOfvn * n + v;

R.Normalize();

ball.rigidbody2D.velocity = R * ballScript.speed;

```

This bounces the ball from the pad, as if the pad was a wall, and it works at any angle. So far so good. The missing piece I was looking for, was that \_transform.up is essentially the normal vector for my pad. It might be \_transform.right or an inversion of either, depending on how the sprite is positioned at import. Mine is positioned like so: \<=====\>

Setting n = \_transform.up and v to ball.rigidbody2D.velocity is redundant, but is in this example for clarity, so the function retains its variable-names, v and n.

Now, all I need to do, is solve "Point 1". I can't just use the length between the position of the ball and the position of the pad. It will not be precise enough.

It's a right triangle, and I know one side (position of the ball to the position of the pad). I need to know that length, and I need to figure out how I can know which side of the middle the ball struck. Otherwise, I won't know in which direction to apply additional force, left or right.

Rest assured, I will post the complete solution when I find it, so that others can use it!

## COMPLETE SOLUTION:

I've kept some extra variables, to make it easier to see how they fit into the mathematical functions. Optimize it yourself :) Don't make local variables if you can help it!

This code is placed inside my script on the pad itself, in its OnTriggerEnter2D(Collider2D col). The ball has a rigidbody2d which is NOT a trigger, but the pad is a trigger.

```
// The ball colliding with my pad (I've checked its tag before getting here!)
GameObject ball = col.gameObject;

// Holds the ever-increasing speed of my ball, which is to be updated
// for each pad-bounce.
BallScript ballScript = col.gameObject.GetComponent<BallScript>();

// The formula for a standard wall-bounce is:
// -2*(V dot N)*N + V
// where V is the incoming velocity of the ball, and N is the normal-vector
// for the wall/pad i.e. upwards/outwards from the pad, when the long side
// of it is left-to-right, and top and bottom are up and down respectively.
// Because my pad-sprite is like this <======>, I use _transform.up.
// For other implementations using pad-sprites that are turned differently,
// _transform.right or an inversion of either might be used.

Vector2 v = ball.rigidbody2D.velocity;

// I normalize v, because I want to make a change in speed later (below).
// Not normalizing can also introduce weird behavior in the functions, so to be safe,
// you can use your v.magnitude, which is the length/speed, and apply it afterwards.
// More on that later.

v.Normalize();

// We need the dot-product of v and n for the function.
float dotOfvn = Vector2.Dot(v, (Vector2)_transform.up);

// A clean 0,0 vector2. I want to make it so the players can choose which type
// of bounce they want, and even mix them, so I've split up the two ("Point 1"
// and "Point 2"), so I can add their effects separately.
Vector2 R = new Vector2();

// I add the effect of the wall-bounce to my R.
// If you ONLY want a wall-bounce, this is the function you want, and in that case,
// you can skip the normalization of v above, so you don't need to manually apply
// v.magnitude afterwards. But if you want to continue, I advise you to follow the
// code as written.
R += -2 * dotOfvn * (Vector2)_transform.up + v;

// Now R represents the realistic bounce-vector, that the ball would have if it
// had struck a flat wall.

// Now, on to the Pong-style bounce!

// We want to also be able to take into account the Pong/Arkanoid-style of bouncing
// from the pad, where the ball shoots in a different direction, depending on where
// it hits the pad. The further from the middle, the sharper the exit-angle.

// That means we have to be able to interpolate between the normal-vector for the
// pad (upwards), and the vector going along the pad (sideways).
// The function for getting a percentage-interpolated vector between two vectors is:
// A*t + (1-t)*B
// where t is the percentage you want to be close to A compared to how close you want
// to be to B.

// To be able to use this, we need to know how far from the middle the ball struck.
// We want to find the length from where the ball hit, to the middle of the pad,
// but not directly from the position of the ball, but from where it hit, and it
// has to be from a point on the pad's sideways normal-vector, to be precise.
// (See the last image of this post for clarification)

// We know the ball has hit the pad, so we raycast to see where it hits.
// You have to make sure that your raycast can only hit the pad. Do some layering or
// something, so it doesn't hit anything else first.
RaycastHit2D hit = Physics2D.Raycast(new Vector2(ball.transform.position.x,
        ball.transform.position.y), ball.rigidbody2D.velocity);

// We find the vector from the hit-point to the position of the pad.
Vector2 vectorFromHitPointToPadCenter = hit.point - (Vector2)_transform.position;

// Then we can use the Dot-procuct of that vector and our pad's sideways vector,
// to determine the length we wanted (see the last image in this post).
float length = Vector2.Dot(vectorFromHitPointToPadCenter, _transform.right);

// Now, a percentage as a float, where 1.0f is 100% and -1.0f is -100%.
// This tells us how far from the middle of the pad the ball has hit in %.
// If it is negative, then it has hit the left side of the pad.
// E.g. if it is -1.0f, the ball has hit the far left extremity of the pad.
// You'll have to figure out your "halfCurrentPadWidth" variable yourself.
// It should be half the width of the pad in units.
var percentageOfLengthVSHalfPadLength = length / halfCurrentPadWidth;

// We apply A*t + (1-t)*B
// Again I add this to my existing vector. If you ONLY want this standard Pong-
// bounce, just use this, and forget the wall-bounce math above, and change
// the += to just =.
R += (Vector2)_transform.right * percentageOfLengthVSHalfPadLength +
                (1 - percentageOfLengthVSHalfPadLength) * (Vector2)_transform.up;

// Gotta normalize.
R.Normalize();

// Apply speed to the ball. If you just want the ball to continue at its present
// speed, you can replace ballScript.speed with ball.rigidbody2D.velocity.magnitude.
ball.rigidbody2D.velocity = R * ballScript.speed;

```

# Answer
> 1 votes
A quick guess, your raycast collides with the ball. Usually you shouldn't call a raycast without specifying what objects it is allowed to hit.

Also notice that your calculated point of collision, and thus also the calculated normal, does not take the size of the ball into account. If the ball is small this might not be a big issue, but it could lead to the ball intersecting the pad without the raycast hitting the pad.

### Answer to edit

To find the length you marked you simply need the dot product of your centre-to-centre vector and a unit vector along the length of the pad. That will give you the signed length.

Using the collision normal still seems like a good idea, in my experience getting the physics right gives a pretty good feeling for the player.

---
Tags: unity, mathematics, vector
---


# Question
Title: Is there a 2d physics engine that can model fluids and gases?
At this point the platform and programming language don't matter I would just like to know if something out there exists for this. Any help is appreciated.

# Answer
> 8 votes
Look into what Q-Games used for Pixeljunk Shooter. It is a 2d game with pretty involved fluid physics. I'm not sure if they used a homegrown or middleware physics engine, but the information is probably out there somewhere.

# Answer
> 6 votes
Well i havn't looked into this, but i know for a fact that almost any physics engine can emulate the idea. Box2D, etc.

Basically have particles bouncing around, off surfaces and eachother (faster for gasses) but also give them a constant gravity like effect (liquids would all have the same, but some gases you might want to rise slowly).

If you link up the outer particles you will get a polygonal shape representing the mass

OR

if you simply draw a pixel or particle graphic over each particle, you can achieve a cloud effect for the mass instead.

# Answer
> 6 votes
The only library I could come up with that specifically deals with fluids is Fluidic. It is pretty alpha and only has one release, though. The physics library Bullet supports 'smoothed-particle hydrodynamics', a technique used to model fluids. Although the library is geared towards 3D, you could apply constraints to one axis to make it work in 2D.

My recommendation would be, as I already mentioned in some comments on other answers, to use a standard physics engine like Box2D or Chipmunk and use a number of circles to model the water (with gravity) or gas (without gravity) and combine these together into one water or gas body. You can apply some constraints on the individual bodies to make them 'clump' together so you can simulate viscosity. Have a look at this video to see how the individual bodies (modelled as squares in the video) work together. Note, however, the technique used in this video is not the same as mentioned in this paragraph. You can use the video to get a feel of how the circles interact with each other and try to mimic this with the constraints present in the physics library used.

The interesting part comes when you want combine multiple circles into body of water. The most straightforward solution I can come up with is drawing each circle as a metaball so they appear as part of a larger body. You can find the math and some example code behind these bodies here.

# Answer
> 3 votes
It's been a few years since this question was posted, but I came across it while searching, so I thought I'd update it.

Google released LiquidFun (open source) for the Box2D system. It has some limitations, but it's a quick way to get started with liquid, sand, etc particles with pretty decent performance.

https://github.com/google/liquidfun

PixelJunk has a great approach, but it's a private library. They shared an amazing level of details in their talk at GCD 2010.

---
Tags: 2d, physics
---


# Question
Title: What is "convexity" in the context of game design?
I have overheard game designers mentioning something called *convexity* in games. This seems to be a game-design-specific concept, different from (although possibly related to) that in geometry or game theory. Unfortunately there are very few sources online mentioning it, let alone a definition. From what I could gather, it has something to do with player choices.

So what is convexity? How does it manifest in a game? What's an example of it, or the lack of it? Is it a good thing, a bad thing, or if it depends, when is it good, when is it bad?

# Answer
The oldest reference to "convexity" I could find was a paper that cited S. Rabin's "Introduction to Game Development" concept

> A branching narrative where multiple paths through a game converge.

My words, not his. Rabin's actual words are:

> "\[player choices\] gradually narrow back down again to a few, or single action the player must accomplish"

You'll often see a decision graph like this:

Used to represent a "convexity"; one ending point with multiple paths to it.

This can be used to give the player the illusion of choice by presenting the player with many ways to get to the same outcome.

Extra Credits made a good episode about the illusion of choice where they discussed this without using the term "convexity", they used the term "beads on a string" narrative. I recommend watching this episode to get a sense of why this narrative structure is useful as a game designer.

The short version is: creating multiple paths that get to the same point allows you the designer to create the illusion of a larger possibility space for the player than you actually have to spend budget implementing.

This is good when the player doesn't notice. I like to think of Randy Pitchford's presentation about the "magical side of games" where he discusses the choices available to the player in the first few moments of Borderlands that have absolutely no bearing on what happens in the game but enhance the player's experience just for having those choices available.

This can be bad when players do notice and feel constrained by it; the term you'll hear in RPG circles for this is "railroading". As @Peethor mentioned in the Mass Effect series, when players realized the multitude of "choices" they made throughout the series had effectively zero influence on the final outcome. I would add that Lionhead's Fable was similar, all of the choices made in the morality system during the entire game were completely wiped out by one big unavoidable event at the end. Breaking that illusion can be painful for players. It can also be powerful, as in Final Fantasy X, I won't spoil it but the convexity in that game was such a surprise that I was *happy* about being devastated by it.
> 13 votes

# Answer
Convexity is what makes a player feel freedom of choice, while being steered down a predetermined path. For example, take any game in the mass effect series. You usually get a lot of different choices in conversations, even allowing you to choose if someone should live or die. If the person you killed in the conversation was supposed to do something meaningful in the story, he's usually replaced by somebody who will then do that meaningful thing.

You get choices on how to complete a mission, but the story will not continue until you've completed it. The pinnacle of this is actually the ending of mass effect 3. The game allows you to choose a lot of different things and in the end \[SPOILER ALERT\] you really only change the color of the explosion.

Convexity is a good thing, because it allows the player to have freedom of choice, while still following an awesome story. Convexity is also a bad thing, because developers usually boast about you being able to choose your own destiny while really, your choices boil down to the same scenario. (Sometimes conversations let you choose to piss someone off or kiss his ass. Pissing him off will start a fight, while kissing his ass makes him angry... starting a fight) Max Payne is an example of a game without convexity. In the first game, you will have the choice to kill an innocent person. Do so, and it's game over. That's no choice, that's just linear gameplay. Max Payne 2 allows you to kill someone you believe is innocent. He's not. If you let him live, you'll have to kill him about 60 seconds later.

There are games where you get true freedom of choice (or something very close to it at least), but because the game has to be able to adapt to an infinity of scenarios, the gameplay usually isn't very deep (take spore for example; millions of planets to explore and they're all empty, boring pieces of land with little diversity.)

So really, it's not a good or bad thing. It depends on what you want your game to be. It is a huge impact on the flow of the game, so it's a good thing to consider when designing your game. If you're forcing a player down a predetermined path, it better be one hell of a ride.
> 10 votes

---
Tags: game-design, terminology
---


# Question
Title: How to deal with different resolutions in a 2D game?
For example, you have a sprite of mario with a size of 20px x 20px. This sprite however was made for a game resolution of 1000px x 1000px. What if you want to provide a different game resolution as an in-game option? You could offer to change the game resolution to 2000px x 2000px, but then Mario should be drawn again for this particular resolution. And if you offer many resolutions, this can be very much to draw and the amount of space the image files will take, are going to get too big.

So, my question, what's the trick here?

# Answer
> 1 votes
If you've made sprites at a low resolution, they become smaller when you change to a higher resolution. To counteract this, scale your sprite at runtime. Just bear in mind: if you do this, you won't see a difference between the high and low resolution, because you're simply scaling a low resolution sprite. This is only useful if you want to adapt to 16:9 screens as well as 4:3. If you want your sprites to look PRETTIER at a high resolution, just draw them in that high resolution by hand, and scale them down if you are using a lower resolution.

By scaling down, I actually mean rendering them at a scaled size at runtime. Don't create multiple assets for multiple resolutions. That's insane.

I mentioned 16:9 and 4:3. When the ratio between the width and height of the screen changes, you'll have to decide for yourself how you want to handle that. At some point, you've decided to show a certain area of your game world on screen. If I change from 4:3 to 16:9 (or any other widescreen format), are you going to add some viewable area to the sides of your already viewable area, or are you going to cut some parts off the top? In other words, you'll have to decide for yourself if you need the width to stay the same, or you need the height to stay the same.

---
Tags: 2d, sprites, resolution
---


# Question
Title: Unity3D sprites vs Mesh Quads - Depth, Blending, Shadows
I'm new to unity but not new to game development. In my OpenGL ES 2.0 (mobile) games I create a vertex array of all my "sprites" and stuff it in a VBO. Then draw them as I need them one at a time, back to front, and turning on and off depth test and blending as I go to build my scene. Probably not super efficient (as maybe batch drawing) but I get 60fps on modern devices.

This particular scene has a "paper" background, writing ON that paper (same Z depth), then 3d objects over top of that. The 3d objects cast shadows on to the paper. (I can post a screenshot if necessary.)

To accomplish this I render my shadow map of any object that casts shadows. Then render my scene with a shadow shader on the paper, not on the stuff that's on the paper, but then back on for the 3d objects floating above or sitting on the paper.

Now I'm switching to Unity3D and porting this working game over.

I'm having 2 problems that I can't figure out.

1. Being new to unity I brought in my sprite sheets and set them "Advanced" but as sprites and sliced them up with the Sprite Editor. But the Sprite Renderer doesn't have checkboxes for Casting or Receiving shadows. Are sprites only for 2d games with no shadows and lighting? Do I have to switch to all Mesh Quads and use the mesh renderer and manually handle all my "sprites"?
2. In Unity with the paper and all the stuff that is drawn on the paper at the same Z I'm having depth issues. In my OpenGL version I do `glDisable(GL_DEPTH_TEST);` and enable blending, draw the "ink" stuff, and then re-enable depth and draw the rest of the 3d scene. In Unity I can't figure out how to turn off depth or to get blending to work. Since the ink has to be drawn ON the paper and thing drawn over that I can't use a different camera.

# Answer
A couple days of googling, testing, coding and I have it all figured out.

**1. Shadows on Sprites..**

There is a work around to having sprites cast and receive shadows. This thread in the unity forum has a way to do it with sprites: http://forum.unity3d.com/threads/why-cant-sprites-gameobjects-cast-shadows.215461/

The other way is to create your own sprite manager and create a mesh of a bunch of quads. This was the route I took. There are also sprite managers already out there but I wrote my own.

**2. Depth testing, draw ordering, and blending...**

In my situation I had written a custom shader to do `ZTest Always` and had even tried offsetting the test with `Offset 0, -1`, but it still wasn't drawing the object in front. The reason was the draw order. It was drawing the front object first and then the back object. So the `ZTest Always` on the front object didn't matter cause it was being overwritten by the background.

This page: (https://docs.unity3d.com/Manual/SL-SubShaderTags.html) explains it but it took a little while to sink in. This guy explains it well: (http://www.youtube.com/watch?v=9ZmnbvH3lDo)

Basically you have to do both. Set the `ZTest` setting AND make sure you're dealing with the draw order. Unity renders things in batches. So I set the paper to be `"Queue" = "Background"` and the stuff being applied to the paper as `"Queue" = "Transparent"`. But you just have to set the queues to make sure the batch draws are happening in the correct order.

Also, as described in the above unity docs link, you can set up your own queues and dial in the draw order to your needs. `"Queue" = "Transparent+1"` or `"Queue" = "Transparent+10"`
> 1 votes

---
Tags: unity, sprites, depth-buffer, blending
---


# Question
Title: Lots of bouncing balls sink into each other
I'm trying to model a system that simulates an arbitrary number of bouncing balls with some gravity. So far I've come up with a solution that can be seen here: https://github.com/ahahalol/BouncingBalls

It works fine if the number of balls is small (a few dozens) or if I do not set any gravity. But once I turn gravity on and set the number of balls to a few hundreds, the balls "on the bottom" start sinking into each other over time as new balls fall on them "from the top".

Here's a picture that shows lots of sinking balls when I have gravity and hundreds of balls:

I want a system that perfectly simulates rigid balls physics: no matter how many objects "on top" push the ones "on bottom", nothing should ever sink. How can I achieve this?

# Answer
> 1 votes
Let's say I have three circles. (I'm gonna say circles because if I called them balls, that sentence would sound weird.) What this example is doing is looking if two circles are overlapping. If they overlap, it'll calculate the distance between the two circles, and the required distance based on the radiusses (radii? whatever). It then moves the circles away from eachother.

As I mentioned, we have three circles. Circles A, B, and C are right next to eachother, lined up. We move circle A to the right (to the other circles). First, it checks if circles A and B overlap. They do, so the function moves them away from eachother, and they don't overlap. Then it checks if circles A and C are overlapping. They don't. Circles B and C? They do, because circle B has been moved to the right. So the calculation runs again, pushing them away from eachother. All circles have now been checked for collision with all other circles, but because circle B has been pushed back to the left by the last collision check, it's overlapping with circle A!

A way to resolve this would be to check, when two circles overlap, if moving both of them will cause one of them to overlap with another circle. You could then check if you can move that other circle away to make room, but this would take an absurd amount of resources to pull off. It's unusable for a game. What to do: get more room or less circles.

---
Tags: movement, physics, rigid-body-dynamics
---


# Question
Title: Set box collider size in meters instead of percents
TL;DR: Can I set the size of a collider in meters instead of fractions of the size of the object it's in?

I'm implementing a classic NES game, and my scale is 1 meter = 16 pixels. I have an 8x1x1m prism with a rigidbody, and I need its box collider to be smaller than it by one pixel on every side- to have the dimensions (8 - 1/16 - 1/16) x (1 - 1/16 - 1/16) x (1 - 1/16 - 1/16). (I'm subtracting the width of two pixels from each dimension because each dimension corresponds to two sides.)

When I set the size of the collider to (0.5, 1, 1), though, it interprets those numbers as fractions of the size of the prism instead of as meters. This results in a 4x1x1m collider instead of a 0.5x1x1m collider. Is there a way I can set the size in meters instead of percents? I'll save me a little bit of math, and, more importantly, it could prevent some floating point errors, especially if I switch to a scale with more pixels per meter.

# Answer
I usually use a transform hierarchy like this:

```
Entity Object
  -> Visual
  -> Collision

```

The "Entity Object" is at unit scale (1,1,1) and contains the rigidbody and whatever the "main script" for a particular entity is. This keeps the inspector clean and means the transform viewed by the main script is predictable.

The Collision object is also kept at unit scale, so the units used in the collider(s)'s inspector fields are world units (meters).

The visual and its children can be at any transform you want, without impacting the physics or interpretation of the inspector properties of the others.

This pattern also makes it easy to make variants on a game entity which use the same rules/behaviours but a different visual/collision.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: How can I add banking and rotation to this object manipulation script?
I have made a drone script that allows user to move in four directions and ascend/descend.
I found a nice **tilt** snippet which makes the thing bank when it moves. However, when I include this, the rotation I input using "f" and "h" keys works but the drone snaps back to it's **original** **orientation** (not position in space, but the angle of the object on the Y axis).
I would like to be able to **bank** and also **rotate** the drone, what should I change?
Here is the C# script attached to the drone:

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public float power;

    /**
     * Every update perform tranlations and rotations based on user input.
     * */
    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rigidbody.velocity = movement * speed;

        // Add the tilt. (When this line is left out, rotation performs as expected)
        // When it is left in, the drone rotates but snaps back to it's original orientation on key release.
        rigidbody.rotation = Quaternion.Euler (rigidbody.velocity.z, 0.0f, rigidbody.velocity.x * -tilt);

        // Ascend.
        if (Input.GetKey ("t"))
        {
            rigidbody.AddRelativeForce (Vector3.up * power);
        }

        // Descend.
        if (Input.GetKey ("g")) {
            rigidbody.AddRelativeForce (Vector3.down * power);
        }

        // Rotate clockwise.
        if (Input.GetKey ("h"))
        {
            transform.Rotate(0, 5, 0, Space.Self);
        }

        // Rotate anti-clockwise.
        if (Input.GetKey ("f"))
        {
            transform.Rotate(0, -5, 0, Space.Self);
        }
    }
}

```

Maybe also worth noting that when I leave the **tilt** line in, any rotation I apply to the drone in transform properties is not applied, when taken out, I can set the starting orientation fine.

# Answer
> 1 votes
Your tilt line is stomping over whatever rotation the drone had and applying a new one. Just like writing:

variable\_a = 42;

will replace whatever value was in variable\_a before, the same happens with rotations, unless you use some type of combining operator like multiplication or Lerp.

To fix this, you can build a rotation that takes both inputs into account and apply it once.

But I think the clearest way to do it is with a transform hierarchy. In your hierarchy view, parent some objects so that it looks like this:

```
Drone (Contains rigidbody and control script)
 -> DroneBody (Contains rendered geometry, colliders...)

```

Modify your script so that in Start() you store a reference to the DroneBody object...

```
_droneBody = transform.Find("DroneBody");

```

Then change your tilt line to....

```
Vector3 localVelocity = transform.InverseTransformDirection(rigidbody.velocity);
_droneBody.localRotation = Quaternion.Euler (localVelocity.z, 0.0f, localVelocity.x * -tilt);

```

This way your yaw code (on the "f" and "h" keys) isn't fighting over the same rotation that your tilt is modifying. Yaw happens at the parent level, and tilt happens at the child level. (This will still stomp any inspector rotation you use at the child level, mind)

(The addition of localVelocity ensures that the drone bank direction changes correctly as the drone yaws around, rather than being backwards after the drone has made a U-turn)

---
Tags: c#, unity, rotation, quaternion
---


# Question
Title: What's wrong with my method of getting intermediate rendering to my postprocessing shader?
I'm working on a project in OpenGL. Earlier this week, I successfully implemented Deferred Shading, but I'm not sure how to pass the information from the Deferred Shader to the Post Processing Shader.

```
glBindFramebuffer(GL_FRAMEBUFFER, fboId);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y)); // Render on the whole framebuffer, complete from the lower left corner to the upper right

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//...Drawing for Opaque objects, pass all transparent objects to a seperate texture
//after having drawn them using Forward Shading

//glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y));

// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Use our shader
glUseProgram(quad_programID);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gBuffTextures[0]);
glUniform1i(gBuffPosnID, 0);

//More Textures

//Uniforms

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 2*3 indices starting at 0 -> 2 triangles

glDisableVertexAttribArray(0);

```

So far this works just fine. Now here's the difficult part - passing the final image to the post processing shader.

```
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y));

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glUseProgram(post_programID);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gBuffTextures[0]);
glUniform1i(UniformPostImage, 0);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, gBuffDepthTextures);
glUniform1i(UniformDepthImage, 1);

glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, dirt);
glUniform1i(UniformDirtImage, 2);

glUniform1f(UniformTime, (float)currentTime);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 2*3 indices starting at 0 -> 2 triangles

glDisableVertexAttribArray(0);

```

I'm loading the image from the deferred shader normally, and passing it using:

```
layout(location = 0) out vec3 image;

```

All I recieve is the first texture I pass, the position shader. Can anyone tell me how to pass the image from the deferred shader to the post processing shader?

# Answer
Your problem is where you commented out `glBindFramebuffer(GL_FRAMEBUFFER, 0);`. You need to bind to a different FBO there, otherwise you lose everything you just rendered when you call `glClear` a couple lines down. Because of this reading from and writing to the same FBO texture at once cannot work. You'll need a separate FBO and texture to write to.
> 1 votes

---
Tags: textures, shaders, deferred-rendering, post-processing, frame-buffer
---


# Question
Title: Where can I find OpenGL state changes profiling?
Is there any benchmark that actually measure state changes cost in OpenGL 3.x/4.x and gather an average statics for all graphics cards? (I don't want to optimize only for my old AMD card, I'm not even sure I'm profiling it correctly).

I found some profile data but is dated against fixed function pipeline wich is somewhat obsolete.

Actually seems FBO setup is the slowest operation (after swapping buffers wich is done only once), but I want to know in average "how much slower" it is compared in example to a texture binding. So that I can take says a 10% error treshold and try to organize up-front gl calls.

# Answer
Yes. FBO, shader (changing the currently active program, not necessarily shader state itself) and texture state changes tend to be the most expensive. Conversely, vertex pointers and uniforms tend to be the cheapest states to change.

It is almost impossible to actually calculate the expense of any one state change in modern GL implementations; you might pay a small validation cost up-front while the driver defers the heavy lifting until your next draw call or does certain tasks (e.g. pixel transfer data conversion) in parallel when possible. Rather than trying to profile down to the state change level, have you considered using OpenGL timer queries and partitioning your frame draw into a series of timed tasks?

Timer queries will give you a much better picture of how much time is spent actually doing work in the render pipeline. If you compare the time taken to finish a frame using CPU timers versus the sum of times taken for all pipeline tasks, that will give you some information about non-GPU related overhead. For example, if your entire frame finishes in 5 ms but the CPU blocks for VSYNC (let us assume 60 Hz), you will have a difference of 11 ms between the two numbers. That means there is 11 ms worth of idle GPU time per-frame (in this case because VSYNC is blocking). If you did not know how VSYNC works, that number would be very troubling ;)

In my own work, I calculate the time taken to build shadow maps, fill G-Buffers, composite lights, stream texture/mesh data, HDR post-process, apply anti-aliasing, etc. I can honestly say that knowing which state is the most expensive never delivers worthwhile optimization results but knowing which render *task* is bottlenecking, on the other hand, is an effective use of your time. You will probably figure out the former by solving the latter.
> 5 votes

---
Tags: opengl, c, profiler
---


title: Vector magnitude in orientation

text:
# Question
Title: Vector magnitude in orientation
First, a quick overview of my problem: I have a game entity which has a quaternion to represent its rotation/orientation. It also has a 3D vector in world space for its linear velocity. From the perspective of the entity there are also 3 virtual axes (the standard z=forward/backword, y=up/down, x=left/right).

With those relevant pieces, I want to find the amount of velocity relative to one of the entity's virtual axes (i.e. how fast is it moving to *its* right) so that I can display that to the player and/or apply a counteracting force in that direction.

I have a vague idea that I need to transform the unit vector corresponding to the direction I'm querying by the orientation quaternion and then calculate the angle between the result and the velocity vector. Then with that angle figure out how much of the velocity magnitude is in the target direction (maybe using cosine?).

# Answer
Turn the quaternion into a 3x3 matrix, transpose it (shortcut for the inverse of a purely rotational matrix), apply this matrix to your world space vector and you now have your model space velocity vector (entity's virtual axes: X=right, Y=Up, Z=forward or backward).
> 2 votes

---
Tags: mathematics, vector, orientation
---


# Question
Title: Multiplying by delta not giving smooth movement
I started working on my first proper game but reached a problem straight away. In short I have a game that runs most of the time at 60 fps. ( I am using Libgdx a popular Java framework) but my game object which has a constant velocity and is multiplied by delta, is not moving smoothly. I have tried turning vsync on and off but that does not help. My speed variable is -100, and it is only moving vertically downwards so it is pretty clear if it is moving jerkily or not. Here is my quite simple code:

```
public class Ball extends AbstractGameObject {

private TextureRegion tex = Assets.instance.ball;
private float speed;

public Drop(Vector2 pos, float speed) {
    super(pos);
    this.speed = speed;

    width = 17;
    height = 32;

    type = Type.Ball;

}

@Override
public void update(float delta) {
    pos.y = pos.y + (speed * delta);
    rect.set(pos.x,pos.y,width,height);

}

@Override
public void render(SpriteBatch sb) {

    sb.draw(tex, pos.x, pos.y, width, height);

}

public float getSpeed() {
    return speed;
}

public void setSpeed(float speed) {
    this.speed = speed;
}

}

```

It was previously of my understanding that by multiplying by the elapsed seconds since the last frame, it would guarentee smooth movement. Is thing wrong? If so, any suggestions on how to make it smoother?

# Answer
This could be due to double & triple buffering and processing spikes, probably due to GC.

* frame 0, delta 0, display buffer 0, draw buffer 1
* time passed: 0.016
* frame 1, delta 0.016, display buffer 1, draw buffer 0 (at +0.016)
* time passed: 0.016
* frame 2, delta 0.016, display buffer 0, draw buffer 1 (at +0.016)
* time passed: 0.032 **hickup**
* frame 3, delta 0.032, display buffer 1 **(drawn for +0.016 but it's been 0.032ms in reality)**, draw buffer 1 (at +0.032)
* time passed: 0.016
* frame 4, delta 0.016, display buffer 0 **(drawn for +0.032 but its been 0.016 in reality)**, draw buffer 1 (at +0.016)

Because the delta is the one between the previous two frames there is always a reaction delay in your frame rate compensation which cause the perceived hitches.

Delta time works when the frame rate drops in a smooth manner over a long period of time but causes extra-jerky movements when there are random spikes.

Note also that moving by -100 * 0.016 gives you a movement of 1.6 pixels per frame causing your sprite to move 1 pixel, 2 pixels, 1 pixel, 2 pixels, 2 pixels, 1 pixel...

Try changing your speed to -61 instead, this will give you 1.016666687 pixel per frame which might help.
> 1 votes

---
Tags: java, libgdx, movement, game-loop
---


title: Cavity map generation

text:
# Question
Title: Cavity map generation
I am looking for an algorithm how to generate cavity (or curvature) map. There seems to be no refernce to it, only final solutions like xNormal software, but that is not what I want. I am looking for a way how to do it, not for a final solution.

I have also found this site: http://wiki.polycount.com/wiki/Curvature\_map, but again, mostly references how to do it in specified soft (maya etc).

On my input, I have a mesh and a normal map. From this, I have calculated curvature on my mesh, and now I would like to extend this info with more details from normal map.

# Answer
You can compare the polygon surface to the surface at the end of its normals (or a small factor of)

Calculating it with a normal map is similar. iterate over the polygon using the normal map's texels.
> 1 votes

---
Tags: algorithm
---


# Question
Title: Rotate camera keeping player not in the middle
Here I have a 2D top down game. Currently the camera is set on the player position. The player constantly points to mouse position.

I want to modify this setup having the camera to be set slightly forward in the `player.transform.up` direction but when I try it as the mouse gets closer to the character it starts looping because as the mouse approache, the camera turns but also change the mouse position so the camera needs to turn again, and so on.

this is the camera update

```
transform.position = new Vector3 (player.transform.position.x, player.transform.position.y, -10) + player.transform.up * camDistance;

```

and this is how the mouse position gets updated

```
mousePos = Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x, Input.mousePosition.y, -5)) - transform.position;

```

any clue?

# Answer
> 0 votes
It's going to be a tiny bit of work. To fix this you will need to **manage your own cursor in world-space** using relative movements of the mouse to move it rather than a screen space cursor.

Using `Screen.lockCursor` (http://docs.unity3d.com/ScriptReference/Screen-lockCursor.html)

And `Input.GetAxis("Mouse X")`, `Input.GetAxis("Mouse Y")` (http://docs.unity3d.com/ScriptReference/Input.GetAxis.html) to get relative mouse movements.

You keep a world-coordinate mouse position and add the mouse delta (relative) movements to it. This way when the camera moves the cursor doesn't move relative to the player/world.

The cursor will be *in the world* rather than *on the screen*.

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