# Question
Title: Omnidirectional light (point) shadow mapping bug: everything's lit up white
I am facing a really frustrating problem. After looking at a lot of tutorials (probably all existing on net, not kidding), i tried to do the point light shadow mapping using a cube texture.

The problem is: when i try to visualize my cube map, EVERYTHING is white.

I have no clue what is causing this.

**Here is what it looks like when i try to visualize my cube map:**

***(NOTE THAT MY MODELS ARE at (-1,0,0) and (1,0,0) respectively and my light is at (0,2,0) )***

**And here what it should looks like (Not my project, but just for the colors)**

Here is my cubeTexture class:

```
Shadow::Shadow(e_LightType* light) {
    m_type = light;

    [.... non-usefull code before ....]

    else if (*m_type == e_PointLight) {
        glGenFramebuffers(1, &m_depthMapFBO); //Create frame buffer
        m_shadowWidth = 1024; //Set shadow map size
        m_shadowHeight = 1024;

        glGenTextures(1, &m_depthMap);
        glBindTexture(GL_TEXTURE_CUBE_MAP, m_depthMap);

        for (GLuint i = 0; i < 6; i++) { //MAYBE ERROR WITH ++I
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT32F, m_shadowWidth, m_shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
        }

        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

        glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
        glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_depthMap, 0);

        glDrawBuffer(GL_NONE);
        glReadBuffer(GL_NONE);

        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
            std::cout << "Framebuffer not complete!" << "\n";

        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        m_aspect = (GLfloat)m_shadowWidth / (GLfloat)m_shadowHeight;
        m_near = 1.0f;
        m_far = 25.0f;
        SetShadowProjection();
    }

}

void Shadow::SetShadowProjection() { //Private
    m_shadowProjection = glm::perspective(90.0f, m_aspect, m_near, m_far);
}

void Shadow::SetShadowTransformMatrixs(glm::vec4& position) {
    glm::vec3 lightPos = glm::vec3(position.x, position.y, position.z);
    m_shadowTransformMatrixs.clear();
    SetShadowProjection();

    for (int i = 0; i < 6; ++i) {
        glm::mat4 m(1);
        glm::mat4 r;

        switch (i) {
        case 0:
            r = glm::mat4(glm::vec4(0, 0, -1, 0), glm::vec4(0, -1, 0, 0), glm::vec4(-1, 0, 0, 0), glm::vec4(0, 0, 0, 1));
            break;
        case 1:
            r = glm::mat4(glm::vec4(0, 0, 1, 0), glm::vec4(0, -1, 0, 0), glm::vec4(1, 0, 0, 0), glm::vec4(0, 0, 0, 1));
            break;
        case 2:
            r = glm::mat4(glm::vec4(1, 0, 0, 0), glm::vec4(0, 0, 1, 0), glm::vec4(0, -1, 0, 0), glm::vec4(0, 0, 0, 1));
            break;
        case 3:
            r = glm::mat4(glm::vec4(1, 0, 0, 0), glm::vec4(0, 0, -1, 0), glm::vec4(0, 1, 0, 0), glm::vec4(0, 0, 0, 1));
            break;
        case 4:
            r = glm::mat4(glm::vec4(1, 0, 0, 0), glm::vec4(0, -1, 0, 0), glm::vec4(0, 0, -1, 0), glm::vec4(0, 0, 0, 1));
            break;
        case 5:
            r = glm::mat4(glm::vec4(-1, 0, 0, 0), glm::vec4(0, -1, 0, 0), glm::vec4(0, 0, 1, 0), glm::vec4(0, 0, 0, 1));
            break;
        }

        m = glm::translate(m, lightPos);
        m = r * m;

        m_shadowTransformMatrixs.push_back(m_shadowProjection * m);
    }

    /*m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
    m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
    m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0)));
    m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0)));
    m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0)));
    m_shadowTransformMatrixs.push_back(m_shadowProjection * glm::lookAt(lightPos, lightPos + glm::vec3(0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0)));*/
}

void Shadow::RenderToDepthMap() {
    switch (*m_type) {
        case e_DirectionnalLight:
        case e_Spotlight:
            glViewport(0, 0, m_shadowWidth, m_shadowHeight);
            glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
            glClear(GL_DEPTH_BUFFER_BIT);
            break;
        case e_PointLight:
            glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
            glViewport(0, 0, m_shadowWidth, m_shadowHeight);
            glClear(GL_DEPTH_BUFFER_BIT);
            break;
    }
}

```

I create a new light that incorporate a shadow of type point light.

Here is my render function (With both rendering pass)

```
void Render() {
    //--------------- SHADOW ------------------
    glCullFace(GL_FRONT);

    GLuint texLoc;

    m_Shaders[e_CubeShadowMap]->Bind();

    m_lights[0]->GetShadow()->RenderToDepthMap();
    m_lights[0]->GetShadow()->SetShadowTransformMatrixs(m_lights[0]->GetPosition());

    for (int i = 0; i < 6; i++) { //i++ maybe error since i did ++i in shadow class
        GLuint location = glGetUniformLocation(*m_Shaders[e_CubeShadowMap]->GetProgram(), "shadowMatrices");
        glUniformMatrix4fv(location + i, 1, GL_FALSE, glm::value_ptr(m_lights[0]->GetShadow()->GetShadowTransformMatrixs()->at(i)));
    }

    m_Shaders[e_CubeShadowMap]->SetUniform("lightPos", m_lights[0]->GetPosition());
    m_Shaders[e_CubeShadowMap]->SetUniform("far_plane", m_lights[0]->GetShadow()->GetFar());

    if (m_objectPool.size() > 0) {
        for (Model* m : m_objectPool) {
            m->Render(m_Shaders[e_CubeShadowMap]->GetProgram());
        }
    }

    m_lights[0]->GetShadow()->Unbind();

    //--------------- Normal rendering with shadow  ------------------
    glCullFace(GL_BACK);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set black as clear color - Set him the depth
    glViewport(0, 0, glutGet(GLUT_SCREEN_WIDTH), glutGet(GLUT_SCREEN_HEIGHT));

    m_Shaders[e_Shadow]->Bind();
    m_Shaders[e_Shadow]->SetUniform("lightPos", m_lights[0]->GetPosition());
    m_Shaders[e_Shadow]->SetUniform("viewPos", m_camera->position());
    m_Shaders[e_Shadow]->SetUniform("far_plane", m_lights[0]->GetShadow()->GetFar());

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_CUBE_MAP, *m_lights[0]->GetShadow()->GetDepthMap());

    if (m_objectPool.size() > 0) {
        for (Model* m : m_objectPool) {
            m_Shaders[e_Shadow]->Bind();

            texLoc = glGetUniformLocation(*m_Shaders[e_Shadow]->GetProgram(), "diffuseTexture");
            glUniform1i(texLoc, 0);

            texLoc = glGetUniformLocation(*m_Shaders[e_Shadow]->GetProgram(), "depthMap");
            glUniform1i(texLoc, 1);

            m->GetMaterial()->GetDiffuseTexture()->UseTexture(GL_TEXTURE0); //Use diffuse

            m->Render(m_Shaders[e_Shadow]->GetProgram());
        }
    }

    glFlush();
}

```

And finally here are all 5 shaders used for doing all this

**(first pass : vertex, geometry, fragment)**

**PASS 1 - VERTEX** #version 330 core in vec3 position; in vec2 texture; in vec3 normal;

```
uniform mat4 model;

void main(){
    gl_Position = model * vec4(position,1.0);
}

```

**PASS 1 - GEOMETRY**

```
#version 330 core
layout (triangles) in;
layout (triangle_strip, max_vertices=18) out;

uniform mat4 shadowMatrices[6];

out vec4 FragPos; // FragPos from GS (output per emitvertex)

void main()
{

     //iterate over the 6 cubemap faces
     for(gl_Layer=0; gl_Layer<6; ++gl_Layer) {
        for(int tri_vert=0; tri_vert<3; ++tri_vert) {
            FragPos = gl_in[tri_vert].gl_Position;
            gl_Position = shadowMatrices[gl_Layer] * FragPos;
            EmitVertex();
        }
        EndPrimitive();
     }

}

```

**PASS 1 : FRAGMENT**

```
#version 330
in vec4 FragPos;

uniform vec4 lightPos;
uniform float far_plane;

out float color;

void main()
{
    // get distance between fragment and light source
    float lightDistance = distance(FragPos,lightPos);

    // map to [0;1] range by dividing by far_plane
    lightDistance = lightDistance / far_plane;

    // Write this as modified depth
    gl_FragDepth = lightDistance;
}

```

**(second pass: vertex, fragment)**

**PASS 2 : VERTEX**

```
#version 430
in vec3 position;
in vec2 texture;
in vec3 normal;

#define MAX_SHADOW_MATRIX 10

out VS_OUT {
    vec4 FragPos;
    vec3 Normal;
    vec2 TexCoords;
} vs_out;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position,1.0f);
    vs_out.FragPos = model * vec4(position,1.0f);
    vs_out.Normal = transpose(inverse(mat3(model))) * normal;
    vs_out.TexCoords = texture;
}

```

**PASS 2 : FRAGMENT**

```
#version 430
out vec4 FragColor;

in VS_OUT {
    vec4 FragPos;
    vec3 Normal;
    vec2 TexCoords;
    vec4 FragPosLightSpace;
} fs_in;

uniform sampler2D diffuseTexture;
uniform samplerCube depthMap;

uniform vec4 lightPos;
uniform vec3 viewPos;

void main()
{
    // Get vector between fragment position and light position
    vec3 fragToLight = fs_in.FragPos.xyz - lightPos.xyz;
    // Use the fragment to light vector to sample from the depth map
    float closestDepth = texture(depthMap, fragToLight).r;

    FragColor = vec4(vec3(closestDepth * 255) , 1.0);

}

```

To be honest, im pretty sure its about the first pass (cube texture aint filling anything in) but i dont know why.

Here are the main sources i used:

# Answer
> 1 votes
```
void main()
{
    // get distance between fragment and light source
    float lightDistance = distance(FragPos,lightPos);

    **// map to [0;1] range by dividing by far_plane
    lightDistance = lightDistance / far_plane;**

    // Write this as modified depth
    gl_FragDepth = lightDistance;
}

```

If you map the planes into a linear mapping like this then you can easily get results like this.

Typically you want a mapping that puts the near geometry into a much wider range than the far geometry. Otherwise you can often run into issues like this if the geometry is close to the camera.

This tutorial talks about it.

http://www.learnopengl.com/#!Advanced-OpenGL/Depth-testing

Try implementing this into your shader. I suspect that will clear up your problem.

---
Tags: opengl, c++, shadows, cubemap
---


# Question
Title: Using normal maps to output world-space normals
Im using deffered shading and here is my g-pass Vertex shader code:

```
vec3 T = normalize(vec3(transform * vec4(tangent, 0.0)));
vec3 N = normalize(vec3(transform * vec4(normal, 0.0)));
vec3 B = cross(T, N);
vs_out.TBN = mat3(T, B, N);

```

And my Fragment shader code...

```
gNormal.xyz = normalize(fs_in.TBN * (texture(normal, fs_in.uv).rgb * 2.0 - 1.0));

```

Usually, you would times your light direction and/or view direction with TBN. However, my g buffers are taking up more bandwidth than they should, and i would prefer to get world space normals from the normal map. How should i go about doing so?

EDIT: Apparently, this *should* output world space... but it isnt. So i guess something here is wrong.

Tangent generation function:

```
void CalculateTangents() {
        tangents.clear();
        for (int i = 0; i < vertices.size(); i += 3) {
            glm::vec3 edge1 = vertices[i + 1] - vertices[i];
            glm::vec3 edge2 = vertices[i + 2] - vertices[i];
            glm::vec2 deltaUV1 = uvs[i + 1] - uvs[i];
            glm::vec2 deltaUV2 = uvs[i + 2] - uvs[i];

            GLfloat f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y);
            glm::vec3 tangent;
            tangent.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x);
            tangent.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y);
            tangent.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z);
            tangent = glm::normalize(tangent);

            tangents.push_back(tangent);
            tangents.push_back(tangent);
            tangents.push_back(tangent);
        }
    }

```

There is a point light "attached" to the camera (which clearly isnt working) and the reflection is wrong.

# Answer
http://www.thetenthplanet.de/archives/1180

I suggest that you use this form instead. Instead of doing a complete transform of your data it works the other way around if that makes any sense. So that way it's much easier to tell what's going on and you can more easily work with the normals themselves.

Otherwise all you can do is know you have a bug...somewhere. And not necessarily in the code but it could be in your data as well.

This tutorial will help you show actual normals using geometry shader.

http://mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=17
> 0 votes

---
Tags: opengl, glsl, normal-mapping
---


# Question
Title: Can you get polygon collider 2d shape from a sprite?
When you create an object with polygon collider 2d from inspector, unity automatically generates polygon collider that approximately fits the sprite. My question is if there is a way to do that when creating an object from a script? While searching for a solution I found that each sprite has a sprite mesh which has vertices. I tried setting those as a path for my collider, but the result is a mess: their order appears to be messed up. My current code:

```
         Sprite spr; // I get that in other part of the code
         GameObject go = GameObject)Instantiate(prefab,gameObject.transform);
         go.GetComponent<SpriteRenderer>().sprite = spr;
         go.GetComponent<PolygonCollider2D>().SetPath(0, spr.vertices);

```

# Answer
> 1 votes
Use `AddComponent<PolygonCollider2D>()` to generate collider runtime.

```
void Start ()
{
    gameObject.AddComponent<PolygonCollider2D>(); //collider for itself
    obj2.AddComponent<PolygonCollider2D>(); //collider for other object
}

```

`SetPath()` is used to manipulate vertex runtime.

---
Tags: unity, sprites, meshcollider
---


title: Fast texture pixel access using SDL2

text:
# Question
Title: Fast texture pixel access using SDL2
People have asked questions on fast pixel manipulation, but I'm looking to read the RGB color values of each pixel.

I've heard of `SDL_RenderReadPixels` but in the docs it says:

> WARNING: This is a very slow operation, and should not be used frequently.

Is there an SDL2 function that returns an array of all the pixels of a texture or an SDL2 routine that I can use to loop over each pixel?

# Answer
> 5 votes
SDL2's "texture" rendering API is designed for accelerated graphics in mind; this is where you upload textures to your graphics hardware beforehand, and then render that texture by referring to it.

This is why textures are write-only, and can only be written to if:

* the texture was created with the `SDL_TEXTUREACCESS_STREAMING` flag
* you lock the texture before writing using `SDL_LockTexture`

So if you want to do pixel manipulation, you should do it in-memory, using a plain pixel buffer (or sometimes an `SDL_Surface`). Then when you're done, create a texture out of the buffer. If you do this repeatedly with the same texture, use a texture with the aforementioned `SDL_TEXTUREACCESS_STREAMING` flag. This is still very slow though because it's unaccelerated.

For efficient pixel manipulation, the standard practice is to write **shader code**.

---
Tags: sdl, sdl2
---


# Question
Title: libGDX - Scene2d Actions or Frame Animation, which is better for performance?
I only use Scene2d for the UI layer of my libGDX game. But I need some animations like fading or rotating on my players.

Which is better for performance:

Scene2d fade action or having multiple frames with different opacity and using them in the Animation class?

Also scene2d rotate action or having multiple frames with different angle?

Thanks!

# Answer
I write in *LibGDX* for a while and in my opinion it's better to write players movement/rotation/jumping in the code directly and leave `Actions` for the UI.

It depends if it's a single-player game like a platformer, or a fast-paced multiplayer game, but usually you should not use `Actions` for the player because Actions are pooled/queued and they'll be slower than the manual setup.

Rotation and fading can be made on `Actions` or Universal Tween Engine but if you need more elements in the future like jumping/shooting and custom, precise interpolation for movement you should have your own system.

* Actions for the UI
* Manual for the player's movement/jumping/input etc.
> 1 votes

---
Tags: libgdx, animation, performance, scene2d
---


title: Glew isn't initializing

text:
# Question
Title: Glew isn't initializing
I making a game on visual studio, I am still learning though. SO I create the window the context and then initialize glew. Glew doesn't initialize I just get a self-created error(cout written by me) so if you guys could tell me how I can get deeper into the problem and find out what the actual problem is. I have researched but there is no exact answer to my question/problem.

EDIT: I have tried glExperimental.

# Answer
> 3 votes
Fortunately the GLEW source code is available, so we can check that and determine possible causes.

The main reason why GLEW will fail to initialize is if there is no GL context when you call glewInit. This is the first check done by glewInit and it will return GLEW\_ERROR\_NO\_GL\_VERSION.

Possible causes for that include:

* You called glewInit before creating your context or making it current.
* Your context failed to create.
* Your context is not current.

The next reason why glewInit may fail is if the GL version string is malformed. glewInit checks for the presence of a dot ('.') in the string, and also checks that the last character of the major version is between '0' and '9'. If these checks fail it will also return GLEW\_ERROR\_NO\_GL\_VERSION.

The final reason why glewInit may fail is if your OpenGL implementation is GL 1.0 only (no modern GL implementation - not even the software implementation on Windows - is 1.0, but IIRC it will fail this check on an original 3DFX Voodoo graphics from 1996). In this case it will return GLEW\_ERROR\_GL\_VERSION\_10\_ONLY.

Otherwise glewInit will succeed.

Setting glewExperimental has *nothing* to do with whether or not glewInit succeeds; what this does is relax some of the stricter (but more correct) extension verification.

In your case your should verify the following:

* Check the *actual* error returned by glewInit as it will tell you what went wrong.
* Check that your Window creation succeeded.
* Check that your context creation succeeded.
* Check that your context is current (e.g via wglMakeCurrent) before calling glewInit.
* Check your GL renderer and version by calling glGetString (GL\_RENDERER) and glGetString (GL\_VERSION) - these are both GL 1.1 and so are not dependent on GLEW; you can safely call them even if glewInit fails.
* Check that your GPU actually supports the functionality your trying to access; if you call glewInit, if you check e.g GLEW\_ARB\_vertex\_attrib\_binding, but if your GPU doesn't support that extension, then you can't use it and nothing GLEW does can make it otherwise.

# Answer
> 2 votes
As per the very first sample in the basic GLEW documentation, if `glewInit()` doesn't succeed, it returns an error code. If you pass that error code to `glewGetErrorString(errorCode)`, that will give you a human-readable string describing what the error was, which presumably will guide you toward finding out what you're doing wrong.

But if I was a betting person, I'd bet that you haven't actually created an OpenGL context before trying to initialise GLEW. That's usually the problem that people run into.

But you've provided no code to show what you're doing and you haven't described the specifics of the problem you're having (which function call failed, how it failed, what error code it returned, etc; you haven't even actually told us that it was `glewInit()` which failed; my comments above had to take that as an assumption), so it's hard to actually give you any assistance beyond pointing you to the documentation (link above).

# Answer
> 0 votes
You don't give any details, but make sure you initialize OpenGL first and make sure that this initialization works. Usuaully glew itself is fairly foolproof. If you still have problems then give my answer a comment and I will take a look.

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


# Question
Title: what can be done to improve the ultimate insane real time strategy game AI?
I had this chat with a friend of mine about whether an AI can be created or not that could beat any human without resource cheating in a real time strategy game. An AI that would play almost perfectly. The AI of today's games have many areas that can be improved, most of them rely on resource cheating, a better early base developement because of that, and attacking in waves.

Still, the question is what would need to be done to improve on this to obtain the ultimate AI. Also, if you have any example of a game where a certain feature was used it would be great.

**Edit:** There is little clarification i can provide for those who haven't read the title or the few paragraphs describing the problem. This is about real time strategy games and the ultimate AI. That means Strarcraft, Warcraft, Generals, Red Alert, Age of Empires, AI War etc. Games that have more than one difficulty level, but the focus here is on the ultimate challenge.

tenpn has a fantastic post filled with great resources. Thank you, tenpn! I wish more people would contribute in that direction.

# Answer
It's kind of a difficulty question to answer. To state what needs improving, you need to have some known AI to work from. However here are some examples of RTS AI from aigamedev.com (registration required):

Unfortunately most of the really good stuff is behind the paywall.

A common AI solution is the Goal-Orientated Action Planner, which uses rules to form plans to satsify goals. It's been around a while now but it's very cool. There's a brief overview (pdf) available on Jeff Orkin's site about how it's applied to an FPS, but exactly the same principle (with different rules and goals) works for RTSs.

Many RTSs will use heirarchies of GOAPs, with different levels recieving goals from the level above, and concerned with different levels of detail of the battlefield. I read a great article on some WWII hex wargame's AI that was structured like this, but for all that is google I can't find the link now. Gold star for anyone who can help me out.

Of course the effectiveness of GOAPs and other planners depend on how well you parse your game world, and how refined your actions and goals are.

Other common tech includes Utility architectures (pdf) for scoring and priorities, and blackboards for parsing the game world.
> 12 votes

# Answer
The point is, if you've got an AI

> that could beat any human without resource cheating in a real time strategy game

then you have a game no one will play becuase they couldn't get past the first level.

The hardest part of AI programming is making the AI beatable, but beatable by someone with a bit of skill. Make it too easy to beat and players will be put off by a lack of a challenge, make it too hard and again, people will get fed up with being beaten all the time.

So it's not about creating complex AI (which isn't difficult, after all, the AI can process everthing within its playing area simultaneously whereas a player can only process what's on screen), but more about creating a balanced game.
> 6 votes

# Answer
A lot could be done but my immediate reaction to this question was a counter-question: why would anyone want the ultimate RTS AI? And why doesn't this person just play online, against another human opponent?

The crux is: it's not the problem to make the AI unbeatable, it's the problem of making it think fast enough (eg. it **has** to take shortcuts) to be able to play against 3 or even 7 AI opponents on the same map with a regular computer. Even today, and tomorrow, and I expect it won't have changed even ten years from now.

The next issue is: as long as the AI follows strict rules, it will be exploitable. Even fuzzy rules will make it vulnerable to exploits. The AI would have to learn, and it would have to make mistakes - intentional and unintentional. It would also need to surprise you. And then you're playing against another human being. Since AI doesn't even come close to copying a human's way of thinking both algorithmic and in terms of processing power, you're much better off not wasting your time on a single player AI that's not nearly as much fun to play against as another human being, if only for the social factors involved.
> 3 votes

# Answer
What you define as 'resource cheating' is like 'boost balancing' in racing games. The 'boost' is used to try and keep the pack in relatively close proximity to each other to create the illusion of a tight race. If the player isn't in the lead it may keep the CPU player in sight, and if the player *is* in the lead it keeps the pressure on by putting opponents directly on your tail, even if the CPU itself is a mediocre driver.

In an RTS you're looking at a collection of values which can be arranged optimally. You know exactly how long it takes to obtain a resource, how much building items costs, map traversal times, etc.

If you're the one who has created the tables and has the info readily available to you it's just a matter of number crunching the data to find the best ratios for output.

But how much fun is it to play against an enemy who always does exactly the same thing based on the context of the playing field?

So you add chaos. You give the AI an efficiency on a sliding scale. You have it harass the player. If the player appears to be doing too well, you have the AI cheat a bit and give it some extra resources or reinforcements to keep the player on their toes.

You want the player to feel the satisfaction of facing a challenging opponent, rather than spanking a weak AI or being slaughtered by Hal9000. The perfection of a CPU opponent lies in its imperfection. :)
> 1 votes

# Answer
One big thing is that you have to keep up with the strategic development of the game. No amount of development will let a AI win a Starcraft 1 match (in fair play) if it thinks a core army of marines is the way to play a Terran vs Terran game.

Not only will this keep the AI from getting consistently beaten due to its choice of obsolete strategy, but having a greater repertoire of approaches to the game will make the AI more engaging, if the AI makes viable choices along the way.

A rich strategy tree even allows for a difficulty slider; e.g. the insane Zerg AI will tend to take flexible approaches that can adapt to the enemy and rapidly expand when given the opportunity, but at the normal difficulty level it is likely to pick more rigid builds and be less prone to mass expansions.
> 0 votes

---
Tags: ai
---


# Question
Title: Should I use SAX or DOM to parse Game dialogue/text events in XML?
I'm planning to put all my text dialogue/events in an XML file and then use either SAX or DOM parser in Java to retrieve the correct text.

I'm intending for there to be A LOT of text in this game, so which parser would make more sense to use?

I know SAX has to go through the whole document and I need the text to be retrieved more or less immediately while a DOM parser needs to store the DOM in memory and, as I said, I'm going to have a lot of text in it, plus the rest of the game requires memory too.

I'm developing for PC. Which parser would generally make more sense to use?

# Answer
Typically, if you just want to retrieve one specific datum in an XML file (such as, e.g., the text of one specific dialog) a SAX parser will give you faster access times because it does not have to instantiate as many objects as the DOM parser does when it builds a complete tree-representation of the XML document. You say that the SAX parser has to go through the whole document, which is true, but the DOM parser has to do that too, of course, or else it couldn't build the document.

That said, you need to know your use case. Do you want to keep all text dialogue/events in memory at all times, or do you just occasionally want to read from disk? The DOM parser takes more time to read in a long document, but once you have the DOM tree, you can probably query specific data points faster than reading the XML again and again with a SAX parser.

However, if you plan on keeping all text in memory at all times, you might want to consider a completely different data structure than the DOM tree. If you think, e.g., about a HashMap or something like this as a custom data structure, than a SAX parser could be used to easily and quickly populate your data structure when the game is initialized. Using your own data structure might give you advantages in terms of in-memory size as well as access time.

Finally, XML in general might not be the best solution if you're actually thinking of tons of data. It's not the most human-friendly data format for one, but also, there are simply better (read: specifically made for that) solutions to handling large data. For example, you could use a slim data base, such as e.g. sqlite instead. This way, you don't have to worry about parsing at all.
> 1 votes

---
Tags: java, game-design, xml
---


# Question
Title: Communicate Unity application via a series of Json
I am working on communicating unity application via a series of Json. Since I am new to JSON, I don't have any idea how that work with Wnity.

Here is my JSON structure

```
{
    "id": “id",
    "payload": {
            “image”: "Image Url”
            "text":"text message"
            "option" : {
               "option1":"1" ,
               "option2": "2"
                }
    }

```

}

Now I have created a button in Unity scene. I have hardcoded the image and text data. When I click on the button the data should get converted into Json and should send JSON data to the server and print a data log message.

I have used this code.Iam getting the output

```
using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
public class JsonScript : MonoBehaviour {
JsonData json;
void Start()
{
    Data data = new Data();
    data.id = 1;
    data.payload = new Payload() { text = "wwwwwww", image = "hello" };
    //json = JsonMapper.ToJson(data) ;
    string json = JsonUtility.ToJson(data);
    P (json);
    //      P(json + "\t\n");

 }

// Use this for initialization
void P(string aText)
{
    print (aText +"\n");
}

```

}

```
  [System.Serializable]
 public class Payload
  {
    public string text;
       public string image;
 }

     [System.Serializable]
    public class Data
  {
        public int id;
        public Payload payload;
  }

```

The output is getting displayed in a single line

{"id":1,"payload":{"text":"wwwwwww","image":"hello"}}

But I need the output to be printed as the Json format.I tried giving space.

Can anybody please help me out?

# Answer
> 3 votes
https://docs.unity3d.com/Manual/JSONSerialization.html
The documentation has very detailed explaination. In your case the classes/structures (that store data ) should look like:

```
[Serializable]
public class Payload
{
    public string imageUrl;
    public string text;
}

[Serializable]
public class Data
{
    public int id;
    public Payload payload;
}

```

Mark them with Serializable attribute so that they can be serialized.
To serialize it , you do:

```
Data data = new Data();
data.id = <any id>;
data.payload = new Payload() { imageUrl = <any url>, text = <any text> };

string json = JsonUtility.ToJson(data);

```

And to convert the json string back into data you do:

```
var data = JsonUtility.FromJson<Data >(json);

```

That's it, hope this helps.

---

**Edit 01**: Pretty format JSON
(in the same documentation as above )

> Controlling the output of ToJson()
>
> ToJson **supports pretty-printing the JSON output**. It is off by default but you can turn it on by passing true as the second parameter.

So i guess all you need to do is just :

```
string json = JsonUtility.ToJson(data,true);

```

Honestly, I havent tried it yet but I do believe in what the documentation says :D

---

**Edit02** :

```
[Serializable]
public class Option
{
    public int option01;
    public int option02;
}
[Serializable]
public class Payload
{
    public string imageUrl;
    public string text;
}

[Serializable]
public class Data
{
    public int id;
    public Payload payload;
    public Option option;
}

Data data = new Data();
data.id = <any id>;
data.payload = new Payload() { imageUrl = <any url>, text = <any text> };
data.option= new Option() { option01 = 1, option02 = 2 };

string json = JsonUtility.ToJson(data,true);

```

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


# Question
Title: Changing motion clips via script in Unity
is there a way in Unity to access the Motion clip of an Animator State and change it at runtime via script? I am trying to do a character shop in my 2D game. My idea is, when i click a GUI button it would just select different motion clips but the states would stay the same. It's just a simple Jump and Idle state, parameters dont change. I just want to feed in different animation clips for different characters.

# Answer
Yes, but you would do this via the Mechanim state machine. Create a transition and set it to change via a Trigger.

Doing it this way, when you want to swap animation states, you simply do this:

```
Animator.SetTrigger ("Swap");

```

If you want to set the Animator Motion directly, it is a little more complicated. You will need to create Animation Controllers, and then swap them using the AnimatorOverrideController.
> 2 votes

---
Tags: unity, c#, animation, character
---


# Question
Title: How can i track the progress of a level's completion in unity?
the map is linear, i meant in a "god of war" map kind of way. Meaning the map in not straight, and has lots of curves in it. Actually, the world's x in the begging of the level halfway through the map increases in value, but at the finish, it is even lower than the spawn point.

How can I measure the player's progress through the level? I want to use the progress percentage to trigger certain events. Like defying an object's location, based on the percentage of the progress in the level (like setting the height of the moving light hovering above the player to y = 15, when the progress is between 20% and 30%. And when the progress goes between 30 and 40, y changes to 20).

Any ideas for my situation?

# Answer
For the door opening I would normally use triggers. Just create a collider, mark it as a trigger, and place the code for whatever you want to do inside 'OnTriggerEnter'.

You can use a simple script to hover an object above the player.

example: (in Update) transform.position = player.position + Vector3.up * hoverHeight

However, if you really want a percentage, you can do that. Start by calculating the map length (the distance between the starting point and the finish line). If your level is linear, the difference between one axis should be fine. Then, every frame (or whenever the player moves) divide the distance between the player and the finish line by the map length.

example:

(in Start) float MapLength = finish.position.x - spawn.position.x

(in Update) float percent = 1 - (finish.position.x - player.position.x) / MapLength

If you placed the player into the map using the inspector instead of using a spawn point, you can use player.position instead of spawn.position and it should work just as well.

EDIT: For a quick approximation, you could log the distances between all of the checkpoints. Then all you have to do is add the distances up to the last checkpoint, then from the last checkpoint to the player to get the distance from the start. distanceFromStart / totalDistance = percentageComplete
> 1 votes

# Answer
First, set a StartPosition and a EndPosition:

```
float StartPosition = 0;
float EndPosition = 2000;

```

Then, in your Update() method, you are going to want to normalize your player's position, based on these start and end points:

```
Update() {
    float x = transform.position.x;
    float normalized = (x - StartPosition) / EndPosition;

    Debug.Log("Percentage Completed: " + (normalized * 100).ToString());
}

```
> 1 votes

# Answer
I'm not sure what cost there is to using the NavMesh, but if you only need increments in say... 10%, you can always just create trigger colliders across the entire walkable path at each 10% section (or 5% or whatever you want) and as the player crosses those triggers, a variable increases that holds them (and then they are destroyed so that the player doesn't walk backward, hit it again, and increment progress).

This can also allow you to create triggers at custom locations. You mentioned that you want events at certain distances into the level. Really, you wouldn't even need to track a percentage this way - you can just use a trigger at a specified location to trigger the event that you want.
> 0 votes

# Answer
Place some invisible objects along the path of your player's progress which have a Collider attached to them with the "Is Trigger" property on. Position the objects and shape their colliders in a way that the player can not move around them. This ensures that they all get triggered while the player moves through the level. Whenever the player enters such a collider, set the percent-completed to a new value:

This is how I would implement the behavior of these triggers in C#:

```
class CompletionTrigger : MonoBehaviour
{
    public float completion; // completion when reaching this trigger
    public static float playerCompletion; // players current global completion

    OnTriggerEnter(Collider other) {
         if (/* other is the player */) {
              playerCompletion = completion;
         }
    }
}

```

I left out the part where you find out if the object which triggered the collier is the player and not something else. There are countless ways to do this, and the best one depends a lot on how you structured your project. So before I suggest a way which might be unnecessarily difficult in your particular case I decided to leave that to you.

Every trigger with this behavior will have a public property "Completion" which you need to manually set in the Inspector. Set it to the approximate completion at the position where you place it.

You will then have a global variable `CompletionTrigger.playerCompletion` which you can access from any other script whenever you need the current completion for whatever reason.

When you want certain events to happen at certain points in the level (like for example open a door when the player moves close to it), you should also use trigger colliders with attached scripts.
> 0 votes

---
Tags: unity, maps
---


# Question
Title: What should be created first in a video game?
When starting developing a video game, should one focus on creating the environment *(buildings, trees, mountains etc)* first or the A.I. *(Playable character, NPCs etc)*?

# Answer
> 42 votes
The first step is to create a minimum viable product.

A MVP is the absolute minimum which can be considered a playable game. It doesn't need any graphics yet except for some placeholders. It should just accept basic input and implement the most core game mechanics.

Then iterate from there.

The reason is that you need a test-bed for testing out if your game idea actually works. You could waste months developing assets and AI for a game idea which turns out to not be fun at all when actually played and you would be forced to trash it all.

Also, it's next to impossible to design assets and AI "blind" without being able to put them in the game and experience for yourself how they look and feel when actually playing with them. When you have no working prototype game to put these into you might end up wasting countless hours. You will design and polish assets which you will then redesign from scratch when you have finally the chance to see them in the game. And after that you might end up throwing them away anyway because you decide to remove the game mechanic which uses them for not being fun.

Then when you have your prototype, the question "AI first or graphics first" is quite nonsensical because you usually have programmers and artists working on each in parallel. However it is important for them to communicate, because look and behavior of actors in a game need to match. The player will expect that a "bulky brute" enemy behaves differently than a "nimble speedster" enemy. The process can be driven by the programmers ("We are programming an object which behaves such-and-such, come up with how it could look"), by the artists ("We are designing an object which looks such-and-such, come up with a way how it could behave") or it could be a synergetic process where both sit together and brainstorm ideas for new game entities. Whatever process works for your particular team.

# Answer
> 4 votes
You should figure out the story you want to tell, and the purpose of the game. These will guide everything else and give the user something to come back to time and again.

# Answer
> -1 votes
Starting with a story line always helps. Then, the character and the environment are of equal importance. choose the environment next, because that helps determine what the character can do. The character comes last, because the environment has mostly fixed physics

---
Tags: ai, project-management
---


# Question
Title: Why are games using interpreted languages instead of compiling code into libraries and calling them at runtime?
Say I want to include a game mechanic where players are invited to code up some algorithm to control robots which would defeat the enemy and protect the tower efficiently. Most games I've seen to implement something like that, support Lua. But what if they accepted a .Net compiled library with implemented in C# (or Java for example) interfaces, essentially doing the same thing? How is it a better or a worse choice?

Code may (not) compile in either case. Some players may (not) be familiar with one of the languages. The computer may not have .Net (or Java) framework installed (but then the game usually comes with at least some redistributable packages, so it may as well include those too). These obvious arguments go either way. Is there some important reason that interpreted languages are the norm, and not compiled which I'm not aware of?

# Answer
Generally compiled languages are avoided as scripting languages because of the overhead of compiling them. Many of the points in the answers to Why do we use scripts in development? *are* relevant (even though I agree your *question* isn't a duplicate).

Primarily the choice comes down to iteration speed: it is (often) way faster to omit the compilation step entirely to achieve quicker turnaround times for testing new features or tweaking existing ones during development. When it comes to then exposing that scripting mechanism to players as a core gameplay feature, why switch to a different language?

The overhead of the interpretation or JIT-compilation or whatever used by the scripting language is *usually* not sufficient enough to warrant switching out the entire scripting technology stack to one that is pre-compiled when ship time rolls around. Particularly since that new technology stack probably hasn't been battle-tested and stressed during development nearly as much as the "interpreted" option everybody was using up until ship time.

As an extreme over-generalization, languages designed to be compiled offline tend to be heavier-weight and more cumbersome to integrate (and lock down) as scripting languages as well, including when it comes to debugging tools. When that generalization holds, that often contributes against that language in the cost/benefit analysis.
> 5 votes

---
Tags: scripting, metaprogramming
---


# Question
Title: How to sort entities order by nearest entity distance?
I have created a comparator class called `DistanceSquaredComparator` and implements it with `Comparator<Entity>`. Then in the override compare method, I get the distance square of each nearby position to owner position, then get the signum int value to return. Now the problem is I don't know if this is the efficient way of sorting the array by nearest distance.

```
Entity owner

@Override
public int compare(Entity o1, Entity o2) {
    Vector2 ownerPosition = Mapper.transform.get(owner);
    Vector2 nearby1 = Mapper.transform.get(o1).position;
    Vector2 nearby2 = Mapper.transform.get(o2).position;
    return (int) Math.signum(nearby2.dst2(ownerPosition) - nearby1.dst2(ownerPosition));
}

// usage

DistanceSquaredComparator comparator = new DistanceSquredComparator();
ImmutableArray<Entity> players = ...
ImmutableArray<Entity> enemies = ...
Array<Entity> sortedEnemies = ...
... // fill sortedEnemies

for(Entity player: players) {
    comparator.setOwner(player);
    sortedEnemies.sort(comparator);
}

```

In the image below, green circle is the observer while the red circle is the observables.

# Answer
If you are precomputing this sorted array once only, then this is perfectly fine (even doing an actual distance calculation with square roots is probably ok in that case).

If your entities are moving around and you have to resort this array every frame then you will probably want to implement an acceleration structure of some sort, like a Quadtree in order to get away with only sorting a subset of all your entities.

Without knowing more detail about your intended use case its hard to provide any more specific advice.
> 1 votes

---
Tags: libgdx, sorting
---


# Question
Title: What is Surface.set_colorkey() in Pygame?
In pygame, what does `Surface.set_colorkey()` do? Explain it in a very easy way please. Also, what exactly does it do? I heard it makes parts that are the same color as the colorkey transparent, but what is the point of that?

# Answer
It sets the color value that considered transparent when doing color-key transparency.

Color-key transparency is a technique that causes pixels matching the key color to be ignored (and thus become transparent) when rendering an image. It's a technique that was used a lot more frequently in the past, when we would still do CPU-side blitting of 2D images to the screen.

It was often used to make sprites look like they were sitting on the background images, instead of surrounded by a rectangle of dead, hot-pink pixels. Indeed, this is generally the point of any sort of transparency technique: to hide pixels you don't want to see, or to make them partially visible to achieve a certain effect.

Color-key transparency only supported fully-visible or fully-hidden pixels. These days it is largely superseded by alpha compositing, which uses a fourth dedicated channel in addition to the red, green and blue color channels to hold opacity information and blends the final pixels together based on the that information.

Color keying is fairly simple and required simpler assets. It can still be done fairly quickly, especially on modern CPUs, and so still survives in some APIs.
> 1 votes

---
Tags: pygame, color
---


# Question
Title: Intented name for my game already exists as a book title
I have found that the name I have planned for my game have been already used for the title of a book.

After checking the trademark database, this is the description they have used:

*"Paper Goods and Printed Matter"*

Would I be infringing the trademark if I use the same exact title for my game ?

(Looks like the owner wanted to trademark the same name as a videogame in 2006, but they didn't complete the proccess: *Abandoned-failure to respond or late response*)

# Answer
Having the same name is fine so long as they are obviously distinct entities with no intention of causing confusion for gain (and some kinds of trademark registrations can also cause problems). If the name immediately brings to mind the other product, you're probably asking for trouble; otherwise, it's just a coincidence.

There are a number of books that have the same titles as totally separate books (and likewise movies with the same titles as other movies). Just google "books with the same name" or "movies with the same name" for examples.

That said, the fact that you've now gone and searched out the book and filed proof of your knowledge of the conflict on the Internet does put you on worse footing. It's still probably ok, but if it's *not* ok and you publish anyway, you may have just opened yourself up to additional lawsuits. There's a reason that "real companies" *never* talk about their in-development products until after they're all cleared by legal and ready to publicly announce. (Another is just good ol' competitive advantage.)

To be sure, naturally, ask an intellectual property lawyer. To be safe, just pick a different name.
> 5 votes

---
Tags: legal, trademark
---


title: Rotating pitch and yaw causes roll

text:
# Question
Title: Rotating pitch and yaw causes roll
So I'm new to working with a 3D space and not sure how to fix my problem, I basically have a turret that rotates along its Z axis, and pitches along it's Y but after rotating 180 on the Z axis the turret points down as I completely understand despite being unexpected.

I have a fiddle with what I'm working on here https://jsfiddle.net/2v4ezmaz/2/

So the question is, how do I make it rotate like it does in blender where the barrel end stays pointing up while rotating the z? After lots of reading it's all to do with cross vectors since the .rotation property is euler angles which I think is my problem. I need to use quaternions but I can't logically see what needs to happen.

My brain is thinking of it as needing to reset the rotation back to its default then apply Z rotation and apply the Y rotation, but that can't be right.

After reading http://blog.wolfire.com/2010/07/Linear-algebra-for-game-developers-part-4 I'm sure my answer is there somewhere but I cant think what the code needs to be to do what i want.

Any pointers would be super helpful since my brain is fried reading/trying vector and matrix rotations.

# Answer
It appears the two rotations are being applied in the wrong order.

Simply add:

```
turret.eulerOrder = 'ZYX';

```

somewhere, and three.js will now apply the Z rotation first.
> 0 votes

---
Tags: 3d, rotation, three.js
---


# Question
Title: Attached objects to public Text removed on play mode (Unity)
As you can see when I play the game the 'touch anywhere to start' object goes away. How do I fix this?

*I have added all the relevant code*

# Answer
The `starttext` field is being set to null because *you told Unity that's what you wanted it to do.*

1. At edit time, you assigned a `Text` instance to the public `starttext` variable in the inspector for your `StartSceneManager` component.
2. You run the game, and `StartSceneManager.Start()` is called:

`void Start() { starttext = GetComponent<Text>(); }`
3. This method overwrites `starttext` with the return value of `GetComponent<Text>()`, discarding whatever you put into that variable at edit time.
4. `GetComponent<Text>()` looks for a `Text` component *attached to the same GameObject* as the component it's running in (`StartSceneManager`). Since the StartSceneManager object has no `Text` component attached, the return value is `null`.

The fix is, if you want to assign the `Text` component to use at edit time in the Inspector, don't overwrite it in `Start()`.
> 2 votes

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


title: Better streaming economy algorithm?

text:
# Question
Title: Better streaming economy algorithm?
Does anyone here have experience making games with streaming economies? I am working on a game and am looking for a better way to handle the economy. I feel like there must be a better algorithm than what I am using.

Background:

* `ResourceBin` objects contain resources
* `Settlement` objects contain `ResourceBin` objects
* `Settlement` objects have three queues of `Building` objects in arrays (Low, Medium, and High priorities)
* `Building` objects have a `nextTick()` method that accepts a `ResourceBin` and modifies it

Right now on every tick the `Settlement` class will loop through all of the `Building` arrays starting with High and working towards Low. On each `Building` object it calls the `nextTick()` method and passes its `ResourceBin`. After making sure that the transforms won't cause any Resource to become negative, the `nextTick()` method modifies the `ResourceBin` and exits. If any of its transformations would cause a Resource to become negative it just exits.

The issue with this is that the entire system depends heavily on the order in which the buildings are processed. I also can't have it proportionally affect the resource transformations if you are low on resources (like what is done in Total Annihilation).

Does anyone know how other games implement streaming economies? Is there a better way to do this?

Also let me know in the comments if a code example would be useful. I can pastebin one if need be.

# Answer
> 1 votes
This sounds a bit like a variation on the Knapsack Problem.

For this problem we have a set of items, each with a weight (resources needed) and a value (importance). Given a finite weight budget (resources held) we want to know what is the subset of items we can choose that fits into our budget while maximizing the subset's total value. Although NP-Hard, there are well-studied algorithms to solve this efficiently for modestly-sized problems.

The knapsack problem typically assumes that an item can only be taken or not - that there's no value in taking half of an item. If you can take a fraction of an item, and the value of the partial item is exactly proportional to the fraction of it that's taken, then there's a simple `O(n log n)` algorithm:

1. Sort the items in descending order of the ratio `value / weight`
2. Take complete items off the top of the list as long as you have enough budget remaining.
3. Once you can no longer take the next complete item in the list, take the largest fraction of it that you can.

However, it's not clear whether the value in your scenario follows this rule exactly. If the same buildings need resources every tick, then this would lead to high-bang-for-buck buildings taking the lion's share and starving everything else.

Maybe that's a good thing - maybe those buildings really are so important - it's hard to say without knowing more of your game design.

Think on this for a bit, and if you need a different way of divvying up resources, try editing your question to include a few example cases to sketch out the desired behaviour. (eg. "Given this many resources and the following buildings... the algorithm should give x resources to building A, y resources to building B...)

---
Tags: algorithm, c++, economy, mmorts
---


# Question
Title: Game Maker - How to change color palette using shader and texture?
How can I change the color of the application surface using a texture?

https://en.wikipedia.org/wiki/List\_of\_8-bit\_computer\_hardware\_palettes

https://en.wikipedia.org/wiki/List\_of\_8-bit\_computer\_hardware\_palettes#/media/File:CGA\_palette\_color\_test\_chart.png

My fragment shader looks like this:

```
varying vec2 v_vTexcoord;
varying vec4 v_vColour;

void main()
{
    gl_FragColor = v_vColour * texture2D( gm_BaseTexture, v_vTexcoord );
}

```

# Answer
One way would be to have another 1D texture which holds your texture palette. You could then have a uniform which is an offset for the start of the palette. If you turn on texture wrapping, you can simply add the offset to the x coordinate when you sample the texture and you'll be able to rotate the palette.
> 1 votes

---
Tags: shaders, glsl, game-maker, fragment-shader
---


# Question
Title: can you explain the following java code for image processing?
here outdata is buffer of size\[8\*1024\],can you tell me the exactly what will happened after execution of above lines??

# Answer
> 1 votes
Your code looks like it takes an array with rgba values in the format `[R, G, B, A, R, G, B, A...]` and compresses it to the `[RGBA, RGBA, RGBA...]` format using bitwise operations (`<<` and `&`).

The `& 0xFF` part is called bitmasking, it makes the last 8 bits of the number stay the same, but others are zeroed.

```
0000110011101110 & 0xFF -> 0000000011101110

```

The `number + (number2 << 8)` concatenates the numbers, so the first 8 bits will contain the first number, the second 8 bits will contain the second number

```
10101010 << 8 -> 1010101000000000
10101010 + (11101110 << 8) -> 1110111010101010

```

---
Tags: java, image-processing
---


title: Adding collisions to a 3D mmorpg game

text:
# Question
Title: Adding collisions to a 3D mmorpg game
I'm creating a mmorpg game with a little team, and we want to add a player-objets collisions system. We want players to be able to walk on a heightmap ground, and walk/be blocked by objects.

I found the bullet physics library (I already used his Java wrapper), but I don't know how to make it enough efficient for a VERY huge map, and a lot of players on it.

In this game, there will be a very huge world (loaded by a chunk system), with all players on the same world. So how can I made an efficient way to make player(AABB)-objects(shapes with triangles) collision system in a very big map?

# Answer
You need to keep splitting your world into little parts. There are plenty ways of handling collisions between a height map and objects, but in the end, every method has the same problem; The Amount.

So you already took the first step, by deviding your world into chunk's. Next you need to change your server in way, that the server handles physic updates per chunk. Now you need to do the standard collision of an object against a heightmap to position it correctly. Next do collision against all objects with collision in one chunk.

For now you have a working solution. Next you need to take care of, finding the sweet spot for server X for chunk size. Find a good standard size of chunk the server is able to handle collision against quick, per users active at the same time.

So if many users are online on the same server the same time, chunk sizes need to shrink, as less players are online chunk sizes can grow.

You also need to be aware of, that there will be a max, that server X can handle the same time.

You could drastically raise your performance, if collision between player isn't mendatory, so only heightmap and physical objects.

In the end, it's a long way of optimizing these parameters and finding the sweet spot or even making it dynamically change.
> 3 votes

# Answer
I'm an independent game dev. myself, and I found a way to add collisions in 2d. I'm not sure if it'll work in a 3D game, but I'll try my best. If the player x y and z coordinates are a certain number it should collide on, then you could make that in an if statement. I'm sorry if that doesn't help, but I hope it does!
> -3 votes

---
Tags: collision-detection, physics, collision-resolution, mmo
---


# Question
Title: Converting to JSON String with JsonUtility.ToJson
I am working on converting and displaying the JSON String with unity. I have done coding for it

```
using UnityEngine;
using System.Collections;
using LitJson;
using SimpleJSON;
using System.IO;
public class TestDelete : MonoBehaviour {

JsonData json;
void Start()
{
    Data2 data = new Data2();
    Payload2 data2 = new Payload2();
    data.command = "state";
    data.payload = new Payload2()
    {
        text = "wwwwwww",
        image = "hello"

    };
    data2.option = new Option () {
        A1 = "k",
        A2 = "J"

    };

    string dataValue =data+ data2.ToString();
    string json = JsonUtility.ToJson(data,true);
    P(json + "\t\n");

}

// Use this for initialization
void P(string aText)
{
    print (aText +"\n");
}

}

  [System.Serializable]
  public class Payload2
   {
     public string text;
     public string image;
      public Option option;

    }

  [System.Serializable]
   public class Data2
   {
     public string command;
     public Payload2 payload;
   }

   [System.Serializable]
   public class Option
    {
      public string A1;
      public string A2;
    }

```

This code of working fine.But with the output Iam having problem.The out is displayed as follow

```
{
"command": "state",
"payload": {
    "text": "wwwwwww",
    "image": "hello",
    "option": {
        "A1": "", // not getting displayed
        "A2": ""   // not getting displayed
    }
}

```

}

the string value A1 and A2 is not getting displayed.What will be the issue with my code.Can anybody help me sorting out this issues

# Answer
> 1 votes
The strings are on initial value because you never set `data.payload.option` to anything.

You set up a variable `Payload2 data2`, but you never assign it in any way to anything of the variable `data`.

Try replacing `data2.option = new Option () {` with `data.payload.option = new Option () {`

By the way: I have no idea what the line `string dataValue =data+ data2.ToString();` is supposed to do, because the variable `dataValue` isn't used anywhere.

---
Tags: unity, c#, serialization, json
---


# Question
Title: HTML canvas, Node WebSocket and multiplayer game like slither.io. How to send visual data over websockets?
Where to start creating a multiplayer game like slither.io, agar.io, etc.

I need only learn how to draw live positions and other data of all players into one fullscreen HTML5 canvas with update frequency +/-100ms.

I already have websocket server but that is only chat. I dont know sending images of players and positions. My first idea is sending every 100ms array of all players positions, current position on the map and all other data of players.

```
var worldSize = [10000,10000]; //width and height in px
var currentPosition = [5000,5000]; //center on the map
var players = new Array();
//on player join
players.push({
    id: 1,
    name: "test",
    position: [1234,850], //random position on the map
    points: 100 //example points
});

//on player eat point find that player, update players[index].points+1 etc.

```

This is only my (bad) idea and I not tested it because I dont know how start, how to send visual game data via websockets. How?

**Update**

I checked slither.io game WebSocket console and all frames is `Binary Frame (Opcode 2)` and `Binary Frame (Opcode 2, mask)`. This is short version of array of all players and their positions and all other data? Or?

For example if game play 1000 peoples, that array will be too long. This will lag browser?

# Answer
When you have a massive multiplayer game, then giving everyone information about everyone is often overkill (upload bandwidth on the server would increase quadratic with the number of players). In many cases it is completely sufficient to only send updates about those players which are close enough to appear on the player's screen and omit updates for those further away.

Further, you can sometimes safe traffic by only informing players about things which change, not things which stay the same. In agar.io, for example, players often move with a constant speed in a constant direction. When neither speed nor direction changed since the last tick, you don't need to resend that information. The same applies to player information like name, color, size etc. Don't resend information which didn't change.
> 2 votes

# Answer
You don't send visual data over websockets, you only send the positions, then use that to draw the images on the screen.

You should do **everything** on server side, collision detection, updating entities, etc.
> 0 votes

---
Tags: html-canvas, websocket, html
---


title: How to flip a BC6/BC7 texture?

text:
# Question
Title: How to flip a BC6/BC7 texture?
I have some code to load DDS image files into OpenGL textures, and I'd like to extend it to support the BC6 and BC7 compressed formats introduced in D3D11. Since DirectX and OpenGL disagree about whether a texture's origin is in the upper-left or lower-left corner, my DDS loader flips each image's pixels along the Y axis before passing the pixels to OpenGL.

Flipping compressed textures presents an additional wrinkle: in addition to flipping each row of 4x4-pixel blocks, you also need to flip the pixels within each block. I found code here to flip BC1/BC2/BC3 blocks, and from the block diagrams on MSDN it was easy to adapt the BC3-flipping code to handle BC4 and BC5. The BC6 and BC7 formats look significantly more intimidating, though. Is there a similar bit-twiddling trick to flip these formats, or would I have to fully decompress and recompress each block?

**UPDATE:** It turns out the texture flip was only necessary because my texture coordinates were being incorrectly inverted at export time. Removing both flips made the code both simpler *and* faster (thanks Humus!). Flipping BC6/BC7 blocks may still be an interesting challenge, but it's no longer relevant to my original scenario.

# Answer
> 6 votes
I suspect it is indeed possible to flip BC6-7 blocks with much less work than a full decompress and recompress, but it's still no picnic and is *much* more complex than flipping BC1-5 blocks.

First of all, BC6-7 have a variety of modes that can be selected per block. The modes have completely different binary layouts, so you'd pretty much have to write a different flip routine for each mode (there are ~20 of them altogether, IIRC).

Another difficulty is the partitioned modes, where the pixels in the block are partitioned into 2 or 3 subsets, each with its own RGB line segment. The partition must be chosen from a predefined set; the ones for BC6 can be seen here. The problem is that this partition set is not symmetric under vertical flips. However, I suspect it *is* symmetric under some combination of vertical flips and interchanging the two subsets. For example, looking at the partition #22 (6th row, 3rd column) at that link, there is no vertically flipped version of it in the table, but if you vertically flip *and* interchange 0s and 1s, you end up with the partition #9 (3rd row, 2nd column). I haven't verified that every partition can be flipped this way, nor have I checked the ones for BC7 (which also includes partitions with 3 subsets).

Even if that works, you're still not home free. In BC1-5, the order of the two endpoints of the RGB line segment was used to switch modes, but in BC6-7 the order of endpoints is chosen to fix one bit of the per-pixel indices in each partition subset. Therefore if you change the partition around you might also have to swap the order of endpoints.

And last but not least, in BC6-7 the endpoints are often delta-compressed (i.e. one endpoint is stored at full precision and the others are stored as lower-precision deltas from it). Swapping partition subsets and endpoint order will switch which endpoint is the high-precision one, so you'll have to shuffle the low-precision bits around and negate some deltas.

All in all, it doesn't seem like there's any fundamental showstopper (though I haven't actually written the code), but it sure would be a lot of work to flip or rotate these formats. If possible, I'd recommend flipping the images in your art pipeline *before* they get compressed.

(BTW, the fullest specification of BC6-7 I've found is the ARB\_texture\_compression\_bptc spec; I also wrote a blog post about the BCn formats awhile back.)

# Answer
> 0 votes
The flipping is only a matter of default on the two formats. You can go against the default.

This is probably better to do on the OpenGL side, because OpenGL is lower level, and thus less likely to lose optimization when doing things like this.

---
Tags: opengl, graphics, textures, dds
---


# Question
Title: How do I compile a C# script at runtime and attach it as a component to a game object
The idea here is to let users program the behaviour of an agent in a way that reminds of the "Screeps" game, where you get to develop code which later runs and dictates the behaviour of your units.

My idea is to let users develop the behaviour or their units with C# code, compile that code at runtime and attach it as a MonoBehavior to an existing game object.

How can I achieve this?

# Answer
I haven't done this myself, so this answer is based on an article by exodrifter (I just Googled "unity runtime compile" and found 4 answers right at the top, so don't neglect to try searching yourself!)

What you're describing is possible, but not without pitfalls:

* Use .Net 2.0 compatibility level, otherwise some namespaces you need may be absent.
* Not every platform will allow you to compile new C# from strings at runtime - specifically Android and iOS disallow this.
* Out of the box this works on Windows, but not on Macs/Linux unless the user has the Mono SDK installed. You can include aeroson's mcs-ICodeCompiler to build this functionality into your game as a plugin.

## exodrifter's example code (modified to add a component)

(refer to the article for full details - I just want to include enough here that this answer is a useful signpost even if the linked article goes down)

```
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using UnityEngine;

public class RuntimeCompileTest : MonoBehaviour
{
    void Start()
    {
        var assembly = Compile(@"
        using UnityEngine;

        public class RuntimeCompiled : MonoBehaviour
        {
            public static RuntimeCompiled AddYourselfTo(GameObject host)
            {
                return host.AddComponent<RuntimeCompiled>();
            }

            void Start()
            {
                Debug.Log(""The runtime compiled component was successfully attached to"" + gameObject.name);
            }
        }");

        var runtimeType = assembly.GetType("RuntimeCompiled");
        var method = runtimeType.GetMethod("AddYourselfTo");
        var del = (Func<GameObject, MonoBehaviour>)
                      Delegate.CreateDelegate(
                          typeof(Func<GameObject, MonoBehaviour>),
                          method
                  );

        // We ask the compiled method to add its component to this.gameObject
        var addedComponent = del.Invoke(gameObject);

        // The delegate pre-bakes the reflection, so repeated calls don't
        // cost us every time, as long as we keep re-using the delegate.
    }

    public static Assembly Compile(string source)
    {
        // Replace this Compiler.CSharpCodeProvider wth aeroson's version
        // if you're targeting non-Windows platforms:
        var provider = new CSharpCodeProvider();
        var param = new CompilerParameters();

        // Add ALL of the assembly references
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            param.ReferencedAssemblies.Add(assembly.Location);
        }

        // Or, uncomment just the assemblies you need...

        // System namespace for common types like collections.
        //param.ReferencedAssemblies.Add("System.dll");

        // This contains methods from the Unity namespaces:
        //param.ReferencedAssemblies.Add("UnityEngines.dll");

        // This assembly contains runtime C# code from your Assets folders:
        // (If you're using editor scripts, they may be in another assembly)
        //param.ReferencedAssemblies.Add("CSharp.dll");

        // Generate a dll in memory
        param.GenerateExecutable = false;
        param.GenerateInMemory = true;

        // Compile the source
        var result = provider.CompileAssemblyFromSource(param, source);

        if (result.Errors.Count > 0) {
            var msg = new StringBuilder();
            foreach (CompilerError error in result.Errors) {
                msg.AppendFormat("Error ({0}): {1}\n",
                    error.ErrorNumber, error.ErrorText);
            }
            throw new Exception(msg.ToString());
        }

        // Return the assembly
        return result.CompiledAssembly;
    }
}

```

## Warning

Be **very** careful when letting your game compile & run scripts you didn't write yourself. These scripts could be made to do just about anything the player's user account has privilege to do - delete or corrupt user files, download and run malware, snoop personal information, all of that.

As much as we might try to block & detect these cases, I'd never be especially confident we'd caught them all - there's always the possibility some C# language feature I didn't know about lets them access features I thought were cut off.

If the script is only created by the local player, then they can break the game in arbitrary ways, but can't do anything to their computer they lacked permission to do anyway. But if players can share scripts, download them from a network resource, or can be tricked into copying-and-pasting a script they didn't write, then this becomes an attack vector that can be exploited.

If you want to allow programming by the player without opening up this kind of vulnerability, consider writing your own virtual machine to parse/interpret/execute the player's scripts in a more limited environment that you control completely.
> 11 votes

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


# Question
Title: Can free Unity Store assets be used in non-Unity games?
Does Unity Store allow to use assets listed as free in games built without the use of Unity engine? It's a pretty big place for free assets and I wonder if this isn't against the Unity Store's usage agreement.

# Answer
I got an email response from a customer service engineer at Unity's Zendesk:

> You can purchase assets from the Asset Store, **or download our free assets**, and use them personally and commercially in your game.
>
> You may use the majority of assets from the Unity Store in other engines without limitation. Please take some time to look at our terms documentation for further details on limitations of usage. This is found here: https://unity3d.com/legal/as\_terms
>
> Once you have purchased an asset from the store, it becomes yours to do with as you like within your games and apps. You will be able to use them in your game for commercial use with no extra payments.
>
> **You can also use free assets** in your game for commercial use. Using Unity assets is fine, though please be aware that many developers use Unity to create their games and most are aware of the assets we provide. For an original game they might not be the best fit.
>
> You cannot resell the asset, or include it in an asset type product.

This answers my question about free assets specifically.
> 3 votes

# Answer
The information you seek is readily available through the Asset Store ToS and EULA. To me, it infers that you are free to do so. The only catch appears to be that you ***must*** download the assets through Unity, and that you are purchasing a *license* for the asset.

All that aside, I am not a lawyer. To make matters more difficult, you can be sued for anything. For example, you might be legally allowed to use the assets in a competitors engine. That does not mean the Unity team (or any other involved party) can not sue you. It does not even mean that they will lose their case, if they sue you. If the case still makes it to court, it is still up to the judging party (often a jury, but again, this may not always be the case) to decide. In some cases, they may decide that pre-existing legal documentation such as a EULA is overridden, due to other unforeseen issues such as common use and precedent.

All legal mambo-jumbo aside, I took the liberty of asking a Unity representative through contacts they provide on the website. Having been asked if **any** asset could be used in a competing engine, or even in a custom home-brewed engine, the reply was ***"In short yes this is allowed"***.

Note that it is common for all assets to be referred to as "purchased" once the user acknowledges acquisition, be it through a checkout system or through initiating the download. It is also not uncommon for users to have to "purchase" free assets, although the price should still be listed as $0. Reasons include processing the assets through the same system, that *still* expects and processes a sale price (sometimes behind the scenes), and in order to issue a receipt of the transaction (which is just as valuable if you ever need to *prove* that Unity provided these assets to you for free, in the first place).

---

As per request, I replied to Alex and asked if this would include the *free* assets. His reply confirms that yes, it *does* include assets you do not need to actually *purchase*.

> In regards to your query, yes this is correct, **all assets downloaded** will go into the directories previously mentioned.
> 14 votes

# Answer
Interesting question, as this impacts freedom of developers creating games in Unity that may need to move to a different framework over the time (and thus take some of the free or purchased assets outside Unity).

**I'm not a lawer**. I have read through ASSET STORE TERMS OF SERVICE AND EULA (all caps from the original).

What I take from there, regarding your question, is that you shall check each Asset particular license, especially as some may include Open Source content which license must prevail. However, in general terms, Unity asks all publishers to agree to a common license, and it does not limit the content to Unity (as of September 2016):

> Licensor grants to the END-USER a non-exclusive, worldwide, and perpetual license to the Asset to integrate Assets only as incorporated and embedded components of **electronic games and interactive media** and distribute such electronic game and interactive media. END-USER may otherwise not reproduce, distribute, sublicense, rent, lease or lend the Assets.

There are other relevant parts you shall check, for example *"You may not access Unity Store in any way except via Unity"*.

Also make sure you check these related threads:
> 4 votes

---
Tags: unity, legal
---


# Question
Title: Setting Square to Dim in Color on MOUSEUP
I'm trying to create a simple recreation of the popular memory game "Simon" using C and SDL2. The idea is that the game is a small window with four squares of different colors that are purposefully dim. When the player clicks on a square, I want it to "light up" until the player let's go of their mouse button, in which it returns to it's original dim color.

I have this working to an extent, but the problem is that it only works if the player let's go of the mouse button while the pointer is over the square. If they let go anywhere else, the square stays lit up.

Here is the example code:

```
if(e.type == SDL_MOUSEBUTTONDOWN && mouseX >= 10 && mouseX <= 110 && mouseY >= 10 && mouseY <= 110) {
    if(e.button.button == SDL_BUTTON_LEFT) {
        SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
        SDL_RenderFillRect(renderer, &squareOne);
        SDL_RenderPresent(renderer);
    }
}

if(e.type == SDL_MOUSEBUTTONUP && mouseX >= 10 && mouseX <= 110 && mouseY >= 10 && mouseY <= 110) {
    if(e.button.button == SDL_BUTTON_LEFT) {
        SDL_SetRenderDrawColor(renderer, 0, 50, 0, 255);
        SDL_RenderFillRect(renderer, &squareOne);
        SDL_RenderPresent(renderer);
    }
}

```

As you can see, I'm looking for the user to be clicking in a very specific area, and waiting for them to "unclick" in that same specific area. There has got to be a better way to do this. Would anyone do me the pleasure of offering a few hints?

# Answer
Simply removing your if-statements concerning the position of the mouse cursor from the `SDL_MOUSEBUTTONUP` event check should work. That way the position would play a role if the mouse is clicked, but from what I could gather it doesn't matter where you release the mouse. So don't check for the mouse position on release.

A better way perhaps would be to split this behaviour into smaller class methods (or functions, in case you are doing this in pure C). Those hardcoded mouse position values won't last very long. You for an example might want to consider adding a boolean value to a `Square` struct, which could handle rendering the correct texture (or filled rectangle) to the screen, depending on the state of the boolean value.
> 0 votes

---
Tags: sdl, c
---


title: only one tile being drawn xna c#

text:
# Question
Title: only one tile being drawn xna c#
I have been looking at tile engines for the past few days and decided to have a go at my own one for educational purposes. I want to use different textures for the tiles of my map, for example 1 = grass, 2 = sky, 3 = dirt etc.. I am having this problem where the tiles will draw using only one specific texture although I provide multiples. I have been following tutorials here and there and searching online to try and find this problem but to no avail.

In the example below in the LoadContent function I load three different textues into my TileMap object and Console.WriteLine states that there actually are 3 textures loaded into the list.

I was under the impression that the draw method in the TileMap would set the index to the tile ID corresponding to a tile texture and then that specific tile would be drawn on the map in game. for example, index 1 would equal the first texture in the list, index 2 would equal the second texture and so on. Is this a correct assumption or am I way off?

Also, can you give me any help/pointers on ways to fix this issue of only one texture showing on the screen.

Thank you in advance.

**Tile Map**

```
 class TileMap
    {
        private MapCell[,] mapCell;
        public const int TILE_WIDTH = 64;
        public const int TILE_HEIGHT = 64;

    private List<Texture2D> tileList = new List<Texture2D>();

    public TileMap(int[,] exisitingMap)
    {
        //initialise this to a new multidimensional array;
        mapCell = new MapCell[exisitingMap.GetLength(0), exisitingMap.GetLength(1)];
        // x always starts on one
        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(0); y++)
            {
                mapCell[y, x] = new MapCell(exisitingMap[y, x]);
            }
        }
     }

    public void loadTextureFiles(ContentManager content, params string[] fileNames)
    {
        Texture2D tileTexture;
        foreach (string fileName in fileNames)
        {
            tileTexture = content.Load<Texture2D>(fileName);
            tileList.Add(tileTexture);
            Console.WriteLine(tileList.Count + " Tile texture count ");
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {

        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(0); y++)
            {
                // setting the index to the tile ID
                int index = mapCell[y,x].TileID;
                Texture2D texture = tileList[index];

                spriteBatch.Draw(texture, new Rectangle( x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT), Color.White);

            }
        }
    }
}

```

**Map Cell**

```
class MapCell
{
    public int TileID { get; set; }

    public MapCell(int tileID)
    {
        tileID = TileID;
    }
}

```

**Game1**

```
TileMap tileMap = new TileMap(new int[,]
    {
        { 0,0,0,0,0,0,0 },
        { 1,1,1,1,1,1,1 },
        { 0,1,1,2,1,1,1 },
        { 0,2,1,3,1,3,0 },
        { 0,3,0,3,0,0,0 },
        { 0,0,0,2,0,0,0 },
        { 0,0,0,1,0,1,0 },
    });

 protected override void LoadContent()
    {
        new SpriteBatch(GraphicsDevice);
        tileMap.loadTextureFiles(Content, "Tiles/Tile1", "Tiles/sky", "Tiles/dirt" );
    }

protected override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin();
        tileMap.Draw(spriteBatch);
        base.Draw(gameTime);

        spriteBatch.End();
    }

```

# Answer
> 2 votes
In the constructor of MapCell swap tileID with TileID:

```
public MapCell(int tileID)
{
    TileID = tileID;
}

```

Also in the Draw code you need to change:

```
int index = mapCell[y, x].TileID;
if (index > 0) //check if there is a tile
{
    //subtract the index by one to start by the first index, which is 0
    //[0] = tex1, [1] = tex2, [2] = tex3
    Texture2D texture = tileList[index - 1];

    spriteBatch.Draw(texture, new Rectangle(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT), Color.White);
}

```

---
Tags: c#, xna, monogame, tiles, tilemap
---


# Question
Title: C++ Instantiating objects as function arguments / parameters (base and derived classes)
I've noticed with some functions in C++ that accept objects (e.g. constructors), you can actually create the object within the function argument e.g. (this example uses an SDL\_Point as the main parameter)

```
//Constructor for custom object
object::object(SDL_Point spawn_location);

//Declaration of new object
SDL_Point new_point {0, 0};
object new_object(new_point);

//Alternatively, this also works
object new_object(SDL_Point{0, 0});

```

My question is, is this also possible with derived classes? My thinking behind this is that I have a single base class with a large number of derived (and derived derived etc) classes that I'd like to instantiate using a single function (to set various variables and add to a common vector). Current this looks like this:

```
void create_new_object(base_class object_to_create)
{
//Do new object stuff
}

```

This works:

```
my_derived_class new_object;
create_new_object(new_object);

```

However, I get an error (expected primary-expression before new\_object) with this:

```
create_new_object(object new_object);

```

Is this strictly a base / derived class issue, a difference between functions and constructors, or is there something more I need to do to allow the function to accept the instantiation of objects within its parameters?

Thanks

Nathan

# Answer
> 0 votes
Bugger, solved this about two minutes after I posted the question

The answer is not to use names for the temporary objects used as arguments in functions, i.e.

```
create_new_object(object());

```

Rather than

```
create_new_object(object named_object());

```

# Answer
> 1 votes
1) Not certain polymorphism works unless it is a pointer/reference parameter, it might be the case that the base-class part of your derived class is just cut and pasted into the argument , "slicing"

2) Watch out when the constructor parameter is some kind of reference, the compiler usually complains if one tries to create the object in place (i think it is just an rvalue then unless the parameter it is trying to bind to is const&) (personally I don't understand why, but I guess the c++ creators didn't think one would like to create something that is destroyed right after the fuction call is complete)

---
Tags: c++, objects
---


title: Problems with BlendOp Max

text:
# Question
Title: Problems with BlendOp Max
I'm trying to write a shader that doesn't blend additively etc etc. I'd like to take whichever of the source or destination colours is brighter and use that and `BlendOp Max` seemed like the tool for the job.

However, as you can see below, the shadow of one light seems to be occluding the other, which doesn't match up with how I understand `BlendOp Max` is supposed to work:

Could anyone clarify where I'm going wrong or provide an alternative?

Interestingly, `Blend One One` is working fine, however, `BlendOp Add` (along with all the other `BlendOp`s apart from the 'logical' ones) are creating the same issue.

**Update**

Shader Code:

```
Shader "Lantern/Flat Pullup" {
Properties {
    _LitTex ("Lit (RGB)", 2D) = "white" {}
    _UnlitTex ("Unlit (RGB)", 2D) = "white" {}
    _Pullup ("Pull up Point", Range(0,1)) = 0.7
    _BlendSize ("Blend Size", Float) = 0.3
}
SubShader {
    Pass{
        Tags { "LightMode" = "ForwardBase" }
        LOD 200

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform sampler2D _UnlitTex;
        uniform float4 _UnlitTex_ST;
        uniform sampler2D _LitTex;
        uniform float4 _LitTex_ST;
        uniform float _Pullup;
        uniform float _BlendSize;

        uniform float4 _LightColor0;

        struct VI {
            float4 vertex : POSITION;
            float4 tex : TEXCOORD0;
        };

        struct V2F {
            float4 pos : SV_POSITION;
            float4 tex : TEXCOORD0;
            float4 posWorld : TEXCOORD1;
        };

        V2F vert(VI v){
            V2F o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.tex = v.tex;
            o.posWorld = mul(_Object2World, v.vertex);
            return o;
        }

        float4 frag(V2F i) : COLOR {
            float3 flatReflection = _LightColor0.xyz *
                (1 / length(_WorldSpaceLightPos0.xyz - i.posWorld.xyz));

            return lerp(
                tex2D(_UnlitTex, i.tex.xy * _UnlitTex_ST.xy + _UnlitTex_ST.zw),
                tex2D(_LitTex, i.tex.xy * _LitTex_ST.xy + _LitTex_ST.zw),
                clamp((length(flatReflection) - _Pullup + _BlendSize) / (2 * _BlendSize), 0, 1)
            );

        }

        ENDCG
    }

    Pass{
        Tags{"LightMode" = "ForwardAdd"}
        //Blend One One
        BlendOp Max
        LOD 200
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform sampler2D _UnlitTex;
        uniform float4 _UnlitTex_ST;
        uniform sampler2D _LitTex;
        uniform float4 _LitTex_ST;
        uniform float _Pullup;
        uniform float _BlendSize;

        uniform float4 _LightColor0;

        struct VI {
            float4 vertex : POSITION;
            float4 tex : TEXCOORD0;
        };

        struct V2F {
            float4 pos : SV_POSITION;
            float4 tex : TEXCOORD0;
            float4 posWorld : TEXCOORD1;
        };

        V2F vert(VI v){
            V2F o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.tex = v.tex;
            o.posWorld = mul(_Object2World, v.vertex);
            return o;
        }

        float4 frag(V2F i) : COLOR {
            float3 flatReflection = _LightColor0.xyz *
                (1 / length(_WorldSpaceLightPos0.xyz - i.posWorld.xyz));
            return lerp(
                float4(0,0,0,1),
                tex2D(_LitTex, i.tex.xy * _LitTex_ST.xy + _LitTex_ST.zw),
                clamp((length(flatReflection) - _Pullup + _BlendSize) / (2 * _BlendSize), 0, 1)
            );
        }
        ENDCG

    }
}
FallBack "Diffuse"
}

```

**Update 2**

The same plane and lights rendered using Unity's standard shader, for illustrative purposes.

# Answer
> 1 votes
Turns out, that even though the OpenGL documentation says the Max/Min functions don't take your blend factors into consideration, some quirk in shaderlab means you have to specify them anyway.

As such, the lonely `BlendOp Max` should be have `Blend One One` (or suitable) specified as well.

---
Tags: unity, fragment-shader, shaderlab
---


# Question
Title: Why don't most major game engines use gifs for animated textures?
What is better to use Animation Sheets or Gifs? One advantage Gifs have over Animation Sheets is that you don't have to think about frames going too fast or too slow because of your code and updating in proper ticks.

What are the disadvantages to using Gifs and advantages Animation Sheets have over Gifs?

# Answer
GIF drawbacks:

* very limited color palette, typically 256 colors with ugly dithering (yes, you can have more than 256 colors in animated GIF, but this is uncommon)
* GPUs don't support GIF compression in hardware (means you will have to unpack them on CPU anyway)
* you only get to pick ONE color for transparency (unless implementing custom processing)
* no random access. All preceding GIF frames need to be read and decompressed to access a frame.
* being compressed. You need dedicated decompression function in code. You can't choose different (better) compression algorithms. (yes, uncompressed GIFs exist too, but this is uncommon)

With custom format all these items get resolved very quickly. You have much more control over image format, quality, transparency, random access and compression (including GPU-supported formats alike DXT). Even better, you can prioritize features you need.

> One advantage Gifs have over Animation Sheets is that you don't have to think about frames going too fast or too slow because of your code and updating in proper ticks.

Above statement is misleading. Syncing GIF fps with actual game fps is not much different than syncing custom sprites animation. In both cases you have exactly the same setup - a list of frames, desired framerate and render events. There is no magic powder in GIF - you will have to decompress GIF into spritesheet anyway, which defeats the purpose.

Of course some game engines may hide some of GIF issues behind the curtains, but then, same can be done with spritesheets in a better way.

Said that, there are some few cases where GIFs could *kind of work*. E.g. HTML/CSS GUIs, but these are quite rare and resource-hungry by themselves.
> 90 votes

# Answer
In order to use any image file as a texture in a game, there must be a texture created on the GPU and the pixel data in the image file must be loaded to that texture.

GPUs **do not** support many of the features that image files on CPUs support. They don't support JPG compression, they don't support PNG compression, and with particular reference to GIFs, **they don't support auto-animation**.

So even if you did use a GIF file, you would still have to write your own animation and timing code anyway. GIF gives you nothing.
> 32 votes

# Answer
GIF has a limited color palette. (255) You have to implement parsing and animating the GIF too. So there is not a advancement in time nor in format's technical aspects.
> 13 votes

---
Tags: animation, graphics-programming, spritesheet
---


# Question
Title: glColor3f() 0.0 = no intensity 5.0 = full intensity?
I have a very weird behavior of openGL's glColor right now.

I've wasted hours to detect why my line colors acting so weird until I found out that 0.0 rgb values is zero intensity and 5.0 lead to full intensity (yes NOT 1.0 it's not clamping!)

If I color a line with 1.0, 1.0 1.0 I get very dark grey instead of white. If I color a line with 5.0, 5.0 5.0 I get white. Here is my code:

```
gl.glDisable(GL2.GL_BLEND);
gl.glDisable(GL2.GL_TEXTURE_2D);

/* We need to disable any shaders to get colored lines */
gl.glUseProgramObjectARB(0);

gl.glColorMaterial(GL2.GL_FRONT_AND_BACK, GL2.GL_AMBIENT_AND_DIFFUSE );
gl.glEnable(GL2.GL_COLOR_MATERIAL);

gl.glBegin(GL2.GL_LINES);
for (int lineIndex = 0; lineIndex < lineSegments.getNumberOfLines(); lineIndex++) {
  gl.glColor3d(5, 0, 0);
  //gl.glColor3dv(lineSegments.getLineColor(lineIndex).data(), 0);
  gl.glVertex3fv(lineSegments.getLineStartPoint(lineIndex).floatData(), 0);
  gl.glVertex3fv(lineSegments.getLineEndPoint(lineIndex).floatData(), 0);
}
gl.glEnd();

gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glEnable(GL2.GL_BLEND);

```

Why is OpenGL acting so weird on glColor? Did I miss a gl state or something? I could scale up the colors so I bypass this, but I want to find out whats wrong here.

(The code example leads to a line that ist 100% red)

# Answer
I had to set `gl.glDisable(GL2.GL_LIGHTING);`

Now its working as expected.
> 2 votes

---
Tags: opengl, color
---


# Question
Title: Applying a getButtonDown & getButtonUp on a GUI button for touch input
I have a GUI interface with a button for the character's attack, however I want to implement a defense button where the user can hold the button down to block incoming attacks, when the user stops touching the button then the player goes back to idle.

Right now I have the attack button working correctly, whenever the button gets pressed, it triggers a method where the animator gets called and performs the action. I want to implement the getButtonDown("") and getButtonUp("") used commonly with the keyboard input. How can i implement such fucntions to a GUI button?

# Answer
Attach the following script to your Block button GameObject. Or adapt into your current script.

The boolean 'isMouseDown' will be true while the mouse is held down. I haven't tried this code exactly, but it should work.

```
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class MouseEvents : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
    private bool isMouseDown = false;

    void Update() {
        // Is the mouse still being held down?
        if (isMouseDown) {
            // Keep blocking
        }
    }

    public void OnPointerDown(PointerEventData data) {
        isMouseDown = true;
        // Start blocking
    }

    public void OnPointerUp(PointerEventData data) {
        isMouseDown = false;
        // Stop blocking
    }

}

```
> 0 votes

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


title: How can I make my movement continuous?

text:
# Question
Title: How can I make my movement continuous?
I'm making a game with simple movement code. I don't want the movement to be too complex since it's going to be a small game once it's done.

Right now the character moves 10 units at a time, then stops, then 10 units, then stops, and this looks jerky.

I'd like the character to move continuously, without stopping in between. I tried lowering the `playerSpeed` to make it less jerky, but then the character moved too slowly and players got bored. Instead I want the character to move a little every frame, not a big jump with delays in between.

Here's what I've tried so far:

```
playerSpeed = 10;

document.addEventListener('keydown', function(e){
 if(e.key === 'w' && playerY >= 5){
  playerY-= playerSpeed;
  ctx.clearRect(0, 0, outerWidth, outerHeight);
  drawProtagonistFacingUp();
}
 if(e.key == 'd' && playerX < outerWidth - 50){
  playerX+= playerSpeed;
  ctx.clearRect(0,0,outerWidth, outerHeight);
  drawProtagonistFacingRight();
}

if(e.key == 's' && playerY < outerHeight - 100){
 playerY+= playerSpeed;
 ctx.clearRect(0,0,outerWidth, outerHeight);
 drawProtagonistFacingDown();
}

if(e.key == 'a' && playerX > 5){
  playerX-= playerSpeed;
 ctx.clearRect(0, 0,outerWidth, outerHeight);
 drawProtagonistFacingLeft();
}
});

```

# Answer
The movement isn't smooth because you only move your character when the `keydown` event is emitted which occurs at most a few times per second (I'm not sure how often exactly).

What you want to do instead is, have a boolean variable which tells you whether a key has been pressed (set to true on `keydown`, false on `keyup`). In your main game loop, if the variable is set to on, you would then move the player by `playerSpeed` * `timeDelta` (difference in time between now and the previous iteration, which you can calculate using `getTime`).
> 3 votes

---
Tags: javascript, movement
---