title: SDL Multiple keyboard support

text:
# Question
Title: SDL Multiple keyboard support
I am making a game with multiplayer split screen mode using SDL. Basically, I like the idea of having each player plug in his own keyboard to the PC, set custom controls via options and being able to play it with controls that he likes.

However, there's a problem. This code gets the keyboard event:

```
SDL_Event event;
SDL_PollEvent(&event);

```

SDL\_Event has member SDL\_KeyboardEvent key, which has member Uint8 which. In short:

```
event.key.which;

```

According to this, it should represent keyboard device index, however, I've tried connecting three keyboards to my PC and press the buttons at the same time and the result wasn't satisfying: they all had same keyboard indexes. Is there a solution to this? Or am I missing something?

# Answer
I'm assuming you're using Windows so I did some digging and I found this answer on a question on the Microsoft forums about if it is possible to discern multiple keyboards:

> No, this is dealt with at the device driver level. Beyond those, it can no longer tell where the keystroke came from.

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/de8f3244-d4ae-4c23-85d7-b6a7a365b3ec/

I know this question was asked on a .NET related forum, not an SDL forum, but since he's talking about driver level I assume that SDL can't detect it either and that it's merely an artifact of SDL's multi-platform support.

(Please note that I do make a lot of assumptions here so this might not be the definitive answer)
> 4 votes

# Answer
Better later than never answer:
SDL is still blind to this, even though, it was promised to be implemented in v1.3 -after Windows XP came out with supporting multiple keyboard/mice-.
FYI when I write this we are at SDL 2.0.3. Found only some puffing comments that say "SDL will not support this!". It's a shame as (e.g.) openFL uses SDL too (in Haxe lang).
The feature, though, is still available in Windows (and it hopefully will remain like that) through Raw Input API.
> 2 votes

# Answer
Sorry to contribute a bit late right now, but I'm looking for something similar, and since the topic is less than a year old I figured I should not create a new one, correct me if I'm wrong. Anyway, They're clearly wrong, for a simple reason, Serious Sam 3 does it, on Windows, Linux and Mac, but I still didn't find out how... But it's possible then! If anyone has any news about multiple keyboards and mice support, go along :D

PS : I realize that the goal is to it with SDL but unfortunately, it seems they have gave up on this feature 1 or 2 versions ago, it was a WIP but it's impossible to find any "concrete" help on this feature anywhere, and some posts on the official SDL forum stated this feature as incomplete, and apparently not in the works =/

Well I may have found an alternative solution, which specifically adresses the issue expressed by Microsoft (aren't they programmers in the first place, and try to figure out that kind of things? anyway...).

So the thing is you have to communicate with the HID(Humain Interface Device) directly, this way you interact at a level lower than the driver level, and on top of this, each device has its own unique ID (all issues adressed ;) ). The only problem will be that you'll have to rewrite input classes yourself, because HIDs send raw inputs, as signals and codes, so you'll have to find a table of standard keyboard and mouse signals anAd IDs. Other than that, I think it's a viable solution. What do you guys think?
> 1 votes

---
Tags: sdl, keyboard, support
---


title: OpenGL segfault in DrawElements

text:
# Question
Title: OpenGL segfault in DrawElements
I've asked this question on regular StackOverflow but without much success yet. The below program produces a segfault on the call to `glDrawElements`. I've looked at my max and min index values and they do not go over the length of `GLushort` and match up to the size of my vertex array. I don't get the segfault if I use a smaller number of rings and sectors for my sphere; but I don't think this has much to do with it.

As far as I can tell I've loaded by buffers correctly; however I'm new to OpenGL and this is such a simple program that I must be doing something simple wrong.

I've tried using GLIntercept but it doesn't give me anything additional

```
#include <exception>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <string>
#include <algorithm>
#include <functional>

#include <utilities.hpp>

#include <GL/glew.h>
#include <SDL2/sdl.h>
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>

struct VertexData
{
    GLdouble position[4];
    GLfloat color[3];
    GLfloat normal[3];
    GLfloat tcoords[2];
};

int main(int argc, char* argv[])
{
    try
    {
        SDL_Window* window;
        SDL_GLContext context;
        if(SDL_Init(SDL_INIT_VIDEO) < 0)
            throw std::runtime_error("unable to initialise video");

        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);

        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

        window = SDL_CreateWindow("SpaceEngine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        800, 800, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
        if(!window)
            throw std::runtime_error("unable to create window");

        context = SDL_GL_CreateContext(window);

        SDL_GL_SetSwapInterval(1);

        GLenum glewErr = glewInit();
        if(glewErr != GLEW_OK)
        {
            SDL_GL_DeleteContext(context);
            SDL_DestroyWindow(window);
            SDL_Quit();
            throw std::runtime_error(reinterpret_cast<const char*>(glewGetErrorString(glewErr)));
        }

        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LESS);

        std::vector<VertexData> vertices;
        std::vector<GLushort> indices;
        int rings = 200;
        int sectors = 200;
        float radius = 1.0;

        if(rings < 2)
            rings = 2;
        if(sectors < 2)
            sectors = 2;
        while(rings * sectors >= std::numeric_limits<GLushort>::max())
        {
            rings /= 2;
            sectors /= 2;
        }

        const GLuint polyCountXPitch = rings+1;

        GLuint level = 0;

        for(GLuint p1 = 0; p1 < sectors-1; ++p1)
        {
            for(GLuint p2 = 0; p2 < rings-1; ++p2)
            {
                GLuint curr = level + p2;
                indices.push_back(curr + polyCountXPitch);
                indices.push_back(curr);
                indices.push_back(curr + 1);
                indices.push_back(curr + polyCountXPitch);
                indices.push_back(curr + 1);
                indices.push_back(curr + 1 + polyCountXPitch);
            }

            indices.push_back(level + rings - 1 + polyCountXPitch);
            indices.push_back(level + rings - 1);
            indices.push_back(level + rings);

            indices.push_back(level + rings - 1 + polyCountXPitch);
            indices.push_back(level + rings);
            indices.push_back(level + rings + polyCountXPitch);

            level += polyCountXPitch;
        }

        const GLuint polyCountSq = polyCountXPitch * sectors;           //top point
        const GLuint polyCountSq1 = polyCountSq + 1;                    //bottom point
        const GLuint polyCountSqM1 = (sectors - 1) * polyCountXPitch;   //last rows first index

        for(GLuint p2 = 0; p2 < rings - 1; ++p2)
        {
            indices.push_back(polyCountSq);
            indices.push_back(p2 + 1);
            indices.push_back(p2);

            indices.push_back(polyCountSqM1 + p2);
            indices.push_back(polyCountSqM1 + p2 + 1);
            indices.push_back(polyCountSq1);
        }

        indices.push_back(polyCountSq);
        indices.push_back(rings);
        indices.push_back(rings - 1);

        indices.push_back(polyCountSqM1 + rings - 1);
        indices.push_back(polyCountSqM1);
        indices.push_back(polyCountSq1);

        const GLdouble angleX = 2 * pi() / rings;
        const GLdouble angleY = pi() / sectors;

        GLuint i = 0;
        GLdouble axz;
        GLdouble ay = 0;

        vertices.resize(polyCountXPitch * sectors + 2);
        for(GLuint y = 0; y < sectors; ++y)
        {
            ay += angleY;
            const GLdouble sinay = std::sin(ay);
            axz = 0;

            for(GLuint xz = 0; xz < rings; ++xz)
            {
                const glm::vec3 pos((radius * std::cos(axz) * sinay),radius * std::cos(ay), radius * std::sin(axz) * sinay);
                glm::vec3 normal = pos;
                normal = glm::normalize(normal);

                GLuint tu = 0.5f;
                if(y == 0)
                {
                    if(normal.y != -1.0f && normal.y != 1.0f)
                        tu = std::acos(glm::clamp<GLdouble>(normal.x/sinay, -1.0f, 1.0f)) * 0.5 * (1.0f/pi());
                    if(normal.z < 0.0f)
                        tu = 1 - tu;
                }
                else
                    tu = vertices[i-polyCountXPitch].tcoords[0];

                VertexData v;
                v.color[0] = 1;
                v.color[1] = 1;
                v.color[2] = 1;
                v.position[0] = pos.x;
                v.position[1] = pos.y;
                v.position[2] = pos.z;
                v.position[3] = 1.0f;
                v.normal[0] = normal.x;
                v.normal[1] = normal.y;
                v.normal[2] = normal.z;
                v.tcoords[0] = tu;
                v.tcoords[1] = ay * (1.0f/pi());
                vertices.at(i) = v;

                ++i;
                axz += angleX;
            }

            vertices.at(i) = vertices.at(i - rings);
            vertices.at(i).tcoords[0] = 1.0f;
            ++i;
        }

        VertexData v;
        v.color[0] = 1;
        v.color[1] = 1;
        v.color[2] = 1;
        v.position[0] = 0;
        v.position[1] = radius;
        v.position[2] = 0;
        v.position[3] = 1.0f;
        v.normal[0] = 0;
        v.normal[1] = 1;
        v.normal[2] = 0;
        v.tcoords[0] = 0.5f;
        v.tcoords[1] = 0.0f;
        vertices.at(i) = v;
        ++i;
        v.position[1] = -radius;
        v.normal[1] = -1.0f;
        v.tcoords[1] = 1.0f;
        vertices.at(i) = v;

        GLuint vao;
        glGenVertexArrays(1,&vao);
        glBindVertexArray(vao);

        GLuint vbo;
        glGenBuffers(1, &vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, sizeof(struct VertexData) * vertices.size(), vertices.data(), GL_STATIC_DRAW);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 4, GL_DOUBLE, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, position));
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, color));
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, normal));
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, tcoords));

        GLuint ibo;
        glGenBuffers(1, &ibo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indices.size(), indices.data(), GL_STATIC_DRAW);

        glBindVertexArray(0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        GLuint shader1,shader2;
        std::ifstream file("tutorial2.vert");
        if(!file)
            throw std::runtime_error("The file tutorial2.vert was not opened");
        else
        {
            std::string fileContents((std::istreambuf_iterator<char>(file)),std::istreambuf_iterator<char>());

            shader1 = glCreateShader(GL_VERTEX_SHADER);
            std::string fail = "glCreateShader failed using " + GL_VERTEX_SHADER;

            if(!shader1)
                throw std::runtime_error(fail.c_str());

            const GLchar* contents[1];
            contents[0] = fileContents.c_str();
            glShaderSource(shader1, 1, contents, NULL);

            glCompileShader(shader1);
            int compiled;
            glGetShaderiv(shader1, GL_COMPILE_STATUS, &compiled);
            if(compiled == 0)
            {
                int maxLength;
                glGetShaderiv(shader1, GL_INFO_LOG_LENGTH, &maxLength);
                char* vertexInfoLog = new char[maxLength];
                glGetShaderInfoLog(shader1, maxLength, &maxLength, vertexInfoLog);
                throw std::runtime_error("Shader failed to compile:\n>\t" + std::string(vertexInfoLog));
            }
        }
        std::ifstream file2("tutorial2.frag");
        if(!file2)
            throw std::runtime_error("The file tutorial2.frag was not opened");
        else
        {
            std::string fileContents((std::istreambuf_iterator<char>(file2)),std::istreambuf_iterator<char>());

            shader2 = glCreateShader(GL_FRAGMENT_SHADER);
            std::string fail = "glCreateShader failed using " + GL_FRAGMENT_SHADER;
            if(!shader2)
                throw std::runtime_error(fail.c_str());

            const GLchar* contents[1];
            contents[0] = fileContents.c_str();
            glShaderSource(shader2, 1, contents, NULL);

            glCompileShader(shader2);
            int compiled;
            glGetShaderiv(shader2, GL_COMPILE_STATUS, &compiled);
            if(compiled == 0)
            {
                int maxLength;
                glGetShaderiv(shader2, GL_INFO_LOG_LENGTH, &maxLength);
                char* vertexInfoLog = new char[maxLength];
                glGetShaderInfoLog(shader2, maxLength, &maxLength, vertexInfoLog);
                throw std::runtime_error("Shader failed to compile:\n>\t" + std::string(vertexInfoLog));
            }
        }

        GLuint program = glCreateProgram();
        if(!program)
            throw std::runtime_error("glCreateProgram failed");

        glAttachShader(program, shader1);
        glAttachShader(program, shader2);

        glBindAttribLocation(program, 0, "in_Position");
        glBindAttribLocation(program, 1, "in_Color");
        glBindAttribLocation(program, 2, "in_Normal");
        glBindAttribLocation(program, 3, "in_UV");

        glLinkProgram(program);
        int IsLinked;
        glGetProgramiv(program, GL_LINK_STATUS, (int *)&IsLinked);
        if(IsLinked == 0)
        {
           int maxLength;
           glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
           char* shaderProgramInfoLog = new char[maxLength];
           glGetProgramInfoLog(program, maxLength, &maxLength, shaderProgramInfoLog);
           throw std::runtime_error("Program failed to link:\n>\t" + std::string(shaderProgramInfoLog) + "");
        }

        glDetachShader(program, shader1);
        glDetachShader(program, shader2);

        bool done = false;

        while(!done)
        {
            SDL_Event event;
            while(SDL_PollEvent(&event))
            {
                switch(event.type)
                {
                case SDL_WINDOWEVENT:
                    switch(event.window.event)
                    {
                    case SDL_WINDOWEVENT_CLOSE:
                        done = true;
                        break;
                    }
                    break;
                }
            }

            glClearColor(0.0, 0.0, 0.0, 1.0);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            glUseProgram(program);

            glBindVertexArray(vao);

            glDrawElements(GL_TRIANGLES,indices.size(),GL_UNSIGNED_SHORT,0);

            glBindVertexArray(0);

            glUseProgram(0);

            SDL_GL_SwapWindow(window);
            }

        glUseProgram(0);
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);

        glDeleteProgram(program);
        glDeleteBuffers(1, &vbo);
        glDeleteVertexArrays(1, &vao);

        SDL_GL_DeleteContext(context);
        SDL_DestroyWindow(window);
        SDL_Quit();

        std::cout << "all good in the hood" << std::endl;
    }
    catch(const std::exception& e)
    {
        std::cout << "ERROR:\t" << e.what() << std::endl;
    }
    catch(...)
    {
        std::cout << "ERROR" << std::endl;
    }
    exit(EXIT_SUCCESS);
}

```

My Vertex shader:

```
#version 150

precision highp float;

in vec4 in_Position;
in vec3 in_Color;
in vec3 in_Normal;
in vec2 in_UV;

uniform mat4 mvpmatrix;

out vec3 ex_Color;
void main(void)
{
    gl_Position = in_Position;

    ex_Color = in_Color;
}

```

And my Frag shader:

```
#version 150

precision highp float;

in  vec3 ex_Color;
out vec4 gl_FragColor;

void main(void)
{
    gl_FragColor = vec4(ex_Color,1.0);
}

```

# **EDIT**

I believe the problem is in the way the element array is being setup for the indices.

```
GLuint vao;
glGenVertexArrays(1,&vao);
glBindVertexArray(vao);

GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(struct VertexData) * vertices.size(), vertices.data(), GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_DOUBLE, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, position));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, color));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, normal));
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(struct VertexData), (const GLvoid*)offsetof(struct VertexData, tcoords));

GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indices.size(), indices.data(), GL_STATIC_DRAW);

glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

# **EDIT2**

I've even tried outputing a line of text to a file and iterate through each triangle in my indices 1 by 1. If I run it a few times I find the segfault happens at different points in the indices array. The vertex that the index is looking up is within bounds of my vertices array.

```
for(int i = 0; i < tt; i+=3)
{
    file << "attempting " << i/3 << std::endl;
    glDrawElements(GL_TRIANGLES,i,GL_UNSIGNED_SHORT,0);
    SDL_GL_SwapWindow(sdlglHandler);
}

```

So this tells me that I'm trying to access a index that is outside of the bounds from what I sent to the `GL_ELEMENT_ARRAY_BUFFER` but again, I cannot see the problem.

# Answer
The issue was in using GL\_DOUBLE for the vertices. Changing to GL\_FLOAT seems to have done the trick.

You need to use `glVertexAttribLPointer` when using double.

**EDIT** That is not completely accurate. glVertexAttribLPointer (...) is for double and dvecN vertex attributes, which your shader is not using. To use glVertexAttribLPointer meaningfully would require you to re-write a line in your shader (in dvec4 in\_Position)
> 1 votes

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


# Question
Title: Box2d bodies that are really close together, are getting “stuck”
I'm using a tiled tmx map, and I created a class that adds bodies to each tile within a certain layer. This has been working great so far except for when a character or an enemy moves around on the screen, its body gets stuck on an edge between two tiles.

This seems to happen "sometimes" and in certain spots. Jumping makes you unstuck but it's annoying when it happens, and I tried increasing the position iterations, but the problem keeps reoccurring.

Here's what my game looks like:

# Answer
I ended up redoing to algorithm for building the map. This seems to be working really really well

I wrote this to build it, this basically makes a body for each tile, if there are tiles next to each other, horizontally, it will group them together and create a single body for those tiles

```
 private static void buildCollision(Map map, World world){
        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get("collisionlayer");
        BodyDef bDef = new BodyDef();
        PolygonShape shape = new PolygonShape();
        FixtureDef fDef = new FixtureDef();
        fDef.density = 2.5f;
        fDef.isSensor = false;
        fDef.friction = 0;
        fDef.restitution = 0;

        bDef.type = BodyType.StaticBody;
        Body tileBody = world.createBody(bDef);
        tileBody.setUserData("ground");
        int cellcounter = 0;
        TiledMapTileLayer.Cell cell, nextCell, prevCell;
        int firstCellIndexX = 0, firstCellIndexY = 0;

        for(int j = 0; j < layer.getHeight(); j++){
            for(int i = 0; i < layer.getWidth(); i++){
                cell = layer.getCell(i, j);
                prevCell = layer.getCell(i-1, j);
                nextCell = layer.getCell(i+1, j);

                if(cell != null){
                    cellcounter++;

                    if(prevCell == null){
                        firstCellIndexX = i;
                        firstCellIndexY = j;
                    }

                    if(nextCell == null){
                        float width = layer.getTileWidth() * cellcounter * scaledRatio;
                        float height = layer.getTileHeight() * scaledRatio;

                        shape.setAsBox(width/2, height/2, new Vector2((firstCellIndexX * layer.getTileWidth() * scaledRatio) + (width/2), (firstCellIndexY * layer.getTileHeight() * scaledRatio) + (height/2)), 0);
                        fDef.shape = shape;
                        tileBody.createFixture(fDef);
                        cellcounter = 0;
                    }
                }
            }
        }
        shape.dispose();

    }

```
> 1 votes

# Answer
The way Box2D resolves collisions results in it working very poorly with tiles maps where the tiles are converted into square bodies. It is best to have a separate layer for specifying objects to use for collision which is completely separate from the graphical information for the tile map. You can then use this object layer to generate the Box2D bodies needed for your game.

## Creating an Object Layer for Specifying the Collision Layer.

Excerpt from a gamedevelopment.tutsplus.com Tutorial

Now if we wanted to specify collisions there are a few ways we can do that too. I'm going to use an object layer since they can be used for just about anything, so it will be a nice introduction.

Select Layer \> Add Object Layer. With the object layer selected, select the "Insert Object" at the top of the menu. Now you can click and drag a box around the trunk of the tree to define the collision box.

## Converting that Object Layer to Box2D Bodies

This is a solved problem. See this question for an implementation using the same technologies you are.
> 1 votes

# Answer
Change your actor body so the lower part is an arc. Like this it should be able to get over small steps and or walking up/down diagonal slopes.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: Trying to implement bounding box collision
I've been trying to do collision detection using the Intersects() function with two rectangles.

I've got a player and multiple enemy's. When the player intersects with an enemy a bool var is set to true and the enemy is removed, the next time the player intersects with an enemy I wan't some thing else to happen.

Here is the code:

```
private void HandleCollision()
        {
            bool hasBlock = false;

            List<int> bulletsToRemove = new List<int> ();
            List<int> enemysToRemove = new List<int> ();

            for (int i = 0; i < Enemys.Count; i++)
            {
                if ( hasBlock == false && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
                {
                    enemysToRemove.Add (i);
                    Bullets.Add (new BulletEntity(EnemyBox, Player.Position));
                    hasBlock = true;
                    Console.WriteLine ("has block == false");
                }
                else if ( hasBlock == true && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
                {
                    Console.WriteLine ("has block == true");
                }
            }

            for (int i = 0; i < bulletsToRemove.Count; ++i)
            {
                Bullets.RemoveAt (bulletsToRemove[i]);
                i++;
            }
            for (int i = 0; i < enemysToRemove.Count; i++)
            {
                Enemys.RemoveAt (enemysToRemove [i]);
                i++;
            }
        }

```

My problem is the every time the player intersects with the enemy the code after "if ( hasBlock == false && Enemys \[i\].EnemyBounds.Intersects (Player.PlayerBounds))" get executed. I can't for the life of me figure out what I am doing wrong. I would love some help.

In my mind when hasBlock is set to false the next enemy should pass through the player and not be removed.

# Answer
Everytime you call this fonction you set `hasBlock` to false.

`Console.WriteLine ("has block == true");` will be executed only if the player collides with two enemies on the same frame.

The solution could be to use a static or a global variable.
> 1 votes

---
Tags: xna, collision-detection, monogame
---


# Question
Title: Communication pattern in Entity Component System
I'm putting together a ECS for my game with another two main components: an event bus for communication and a Lua interpreter to load scripts.

Now, the parent element is a framework/game object with references to all this three components. My question is, what is the best communication pattern: drill the interpreter and any other orchestration objects down to every system or centralize all those calls in a subscriptor for the eventbus, and make everything from there.

Example:

// Plan A

```
   public class CollisionEntitySystem extends EntityProcessingSystem {

   LuaEngine mEngine;

   EventBus mBus;

   MoreThings mThings;

   public CollisionEntitySystem(LuaEngine engine, EventBus bus, MoreThings things){
       mEngine = engine;
       mBus = bus;
       mThings = things;
   }

    @Override
    protected void process(Entity e) {
        //Something wonderful happened here
        mEngine.load("onCollision.lua", parameters);
    }
};

```

// Plan B

```
   public class CollisionEntitySystem extends EntityProcessingSystem {

   Bus mEventBus;

   public CollisionEntitySystem(Bus bus){
       mEventBus= bus;
   }

    @Override
    protected void process(Entity e) {
        //Something wonderful happened here
        mEventBus.post(EventScriptCall.create("OnCollision", paremeters))
    }
};

```

Given that the event bus post is synch the results are the same, so it all boils down to architectural differences: centralized logic and hundreds of event objects or disperse logic with less objects.

# Answer
There is no right answer to your question and a lot of it comes from personal taste and out of need.

Most engines often need the ability to deliver both asynchronous and synchronous events because certain situations are easier handled in one fashion than others. Secondly, in the case where you are using systems to update your entities in your example, you will need a means to dispatch events between systems specifying single entity for delivery, collection of entities, or all depending on the scenario.

Next, I generally prefer to keep scripting centralized in a script system. If other systems want to trigger some *ScriptEvent*, I prefer they raise an event and I have the script system capable of listening for that case and dispatching it to the appropriate script handler. This has the benefit that it allows other parts of the system to intercept and handle the same event and keeps the implementation of the script system abstracted so if I change internals or perhaps the language of choice, the engine is unaffected.

In the case of your collision example, when the system detects a collision has occured between two entities, simply send a *CollisionEvent* with source entity and the colliding entity as parameters. The scripting system sees this event and dispatches it to your script.

In my specific solution, my script system looks for a specific method definition called *OnEvent* and if found, it automatically hooks the script into the event system. It is worth noting that a single logic component is linked to an entity enabling scripting behavior. The script can require and include any composition of behavior needed.

This allows the script system to delegate default event dispatch into the scripts logic. Additionally, if the script wants to be notified of other events perhaps from other systems, I just call *RegisterEvent(eventName)* inside the script during it's loading and the script system links that script instance to that event name. When that event fires, the scripting system is responsible for taking the event parameters, packaging them into a lua method call and then calling *OnEvent* with the event name and the arguments.

In the corner cases perhaps where system A needs to call into the script system and invoke a particular behavior and you'd rather not involve the event system for it, you could always expose a method on the scripting system like *RaiseEvent(EventObject)* and allow the scripting system to again decompose the event into the scripting language's needs and dispatch the handler.

This is my own preference, but there is nothing that prevents scripting from being a fundamental part of the entire engine where each system can call into it. I've seen some component frameworks where any component can be ammended with a script to alter it's base behavior.

Either approach relies on a specific amount of abstraction to keep details from leaking into other parts of the engine so that refactoring and extending can be done easily without signfiicant time and costs.
> 1 votes

---
Tags: architecture, entity-system
---


title: Inventory implementation in Java RPG

text:
# Question
Title: Inventory implementation in Java RPG
In my game (simple RPG with Java) there will be an abstract class Creature.

Critter, Beast, Vampire... will inherit from Creature. But not ALL classes that inherit from Creature will have an inventory.

Should I

a) make another abstract class such as CreatureWithInventory and inherit from it?

or

b) make an interface such as Inventory and make stuff as (Vampire implements Inventory)?

Is there a reason to prefer one over the other? Any considerable trade-offs?

Should Inventory itself be a class and let some Creatures have a field for it? If so, how would I test if Creature foo has Inventory? Is that even possible?

# Answer
An Inventory class with a matching field on the abstract class Creature seems best.

You can perform a null check against this field to see if a creature has an inventory.

This also allows you to reuse the inventory class as a field of non-creatures like bags, chests, rooms or anything else that suits your game.
> 3 votes

# Answer
In general you should prefer *composition* over *inheritance* if answer to question "A is a B?" is "No". E.g. `Inventory` is a `Creature`? No, then it should be a component. But `Vampire` is a `Creature`, so it's logically inherited.

My other answer to similar question can also be useful.
> 3 votes

# Answer
As others have pointer out, you should generally prefer composition over inheritance(is-a vs. has-a):

```
public class Creature {
    private Inventory mInventory;

    public boolean hasInventory() {
        return mInventory != null;
    }

    public Inventory getInventory() {
        return mInventory;
    }

    public void setInventory(Inventory inventory) {
        mInventory = inventory;
    }
}

```

This makes a much more flexible architecture in cases where you might want to make an exception for some specific creature. Consider the famous mudcrab merchant in Morrowind for example.

This approach lends itself well to data-drivenness as well. For example, if you would load all your creatures from JSON-files, you could specify a default creature with no inventory and specialize from that if needed:

vampire.json

```
{
  "type": "vampire",
  ...
}

```

frank.json

```
{
  "type": "vampire",
  "name": "Frank",
  "inventory": [
    { "item": "sword", "count": 1 },
    { "item": "gold", "count": 75 },
    ...
  ]
}

```

Then while reading the creature definitions you could just check if a creature has the `inventory`-field and set it accordingly:

```
public Creature parseCreature(JsonObject json) {
    Creature creature;
    if (json.getString("type").equals("vampire")) {
        creature = new Vampire();
    } else if (...) {
        ...
    }

    if (json.has("inventory")) {
        creature.setInventory(parseInventory(json.getJsonObject("inventory")));
    }

    return creature;
}

```

As you can see, you can achieve many things that would be quite difficult with inheritance/interfaces.
> 0 votes

# Answer
Create a drop rule:

here are my assuptions:

* you have a round based game
* you have a method that handles input (best case: as a command)
* you have a list for monsters and a currentMap

when will a drop rule apply? at the beginning of the monsters turn:

```
//assuming you have a kind of listener that handles all inputs
public void parseInput(Command cmd){

    //1. do players turn
    player.applyEffects(); //like poison or so
    boolean isDead = player.isDead(); //check life points
    if(!isDead){
       executeCommand(cmd);
    }else{
        ...
    }

    //2. do monsters turn
    for (Monster monster: monsterList){
         monster.applyEffects();
         boolean isDead = monster.isDead(); //check life points again

         if(isDead){
             applyDropRule(monster, currentMap);

             //most important: remove the monster from the map!
             monster.markAsRemoved = true; //but you can't remove the monster right
                                           //now, because you're still iterating
                                           //throug this list (see below)
         }else{
             ...
         }
    }

    //remove dead ones here
    List<Monster> removeList = new ArrayList<Monster>();
    for (Monster monster: monsterList){
        if(monster.markAsRemoved){
            removeList.add(monster);
        }
    }
    monsterList.removeAll(removeList );

    //3. let the environment do something too
    Field f = currentmap.getField(player.getPos() );
    if(f.isTrap() ){
        ...
    }
}

```

ok, as mentioned above this is an assupmtion, no we're coming to the interesting part: the drop rule:

again, i have to make another assumptions

* you know the dropping rules from books or ebooks

ok, then lets see how to do it ^^

```
public void applyDropRule(monster, currentMap){
    Field field = currentMap.getField(monster.getPos() );

    //dropList depending on current monster
    List<Item> dropList = DropCalculator.getDropsForMonster(monster.getType() );

    //another droplist depending on your level - maybe you can combine these two methods
    List<Item> goodyList = DropCalculator.getDropsForMap(currentMap.getType() );

    //adding 'default' items
    for (Item item: dropList){
        field.addItem(item);
    }

    //adding goodies
    for (Item item: dropList){
        field.addItem(item);
    }

    //maybe adding a bloodstain (or a green squishy stain)
    if(monster.leavesStain){
         field.addDeco(...);
    }
}

```

so ok, lets have a closer look at the dropCaluculator:

```
public class DropCalculator {

    //we have static access methods, you don't need an instance of this calculator
    //same as java.lang.Math
    public static List<Item> getDropsForMonster(MonsterType type){
        ArrayList<Item> dropList = new ArrayList();

        //it's always about probability
        //e.g. Sheep.chanceToLeaveCrorpse = 0.9 - most likely
        //e.g. Newt.chanceToLeaveCrorpse = 0.2 - not very likely
        //take these values from your rule book
        if (type.chanceToLeaveCorpse > Math.random() ){
            double nutritionValue = type.getNutrition;
            Item meat = ItemFactory.createItem(ItemType.Meat);
            meat.nutrition = nutritionValue;
            dropList.add(meat);
        }
    }

    return dropList;

}

```

there are a lot of rules that can be applied when a monster dies, so this is just a small impression of what can be done...
> 0 votes

---
Tags: java, rpg
---


title: Directx fbx loader

text:
# Question
Title: Directx fbx loader
I am trying to build a game with animation in c++ with DirectX.

I have some fbx files with animation that I want to integrate in my game.

But I do not want to draw the fbx files as a FbxScene or FbxMesh but to get all the data of the mesh to a primitive data (like array of vertex) so I can easily change some things like convert it to directx mesh.

I searched the internet but I could not find a solution how to read the data from the FbxScene.

Thanks very much.

# Answer
In supplemental to Syntac\_'s example, here's how you could also load some keyframe and skeletal animation data.

For a start, given you have an Fbx scene object initialized, you could pass fbxScene-\>GetRootNode() to a method like this:

```
void MyFbxScene::LoadNode(FbxNode* fbxNode)
{
    int numAttributes = fbxNode->GetNodeAttributeCount();
    for (int i = 0; i < numAttributes; i++)
    {
        FbxNodeAttribute *nodeAttributeFbx = fbxNode->GetNodeAttributeByIndex(i);
        FbxNodeAttribute::EType attributeType = nodeAttributeFbx->GetAttributeType();

        switch (attributeType)
        {
            case FbxNodeAttribute::eMesh:
            {
                // Load keyframe transformations
                this->LoadNodeKeyframeAnimation(fbxNode);

                // Load mesh vertices, texcoords, normals, etc
                this->LoadMesh((FbxMesh*)nodeAttributeFbx);

                // Load mesh skeleton
                this->LoadMesh_Skeleton((FbxMesh*)nodeAttributeFbx);
                break;
            }
        }
    }

    // Load the child nodes
    int numChildren = fbxNode->GetChildCount();
    for(int i = 0; i < numChildren; i++)
    {
        this->LoadNode(fbxNode->GetChild(i));
    }
}

```

Load some mesh data

```
void MyFbxScene::LoadMesh(FbxMesh *fbxMesh)
    // Load Vertices
    int numVertices = fbxMesh->GetControlPointsCount();
    FbxVector4 *verticesFbx = fbxMesh->GetControlPoints();
    for (int vertexIndex = 0; vertexIndex < numVertices; vertexIndex++)
    {
        float x = (float)verticesFbx[vertexIndex][0];
        float y = (float)verticesFbx[vertexIndex][0];
        float z = (float)verticesFbx[vertexIndex][0];
    }
    // You'd probably want to also load at least texture coords. It's a little bit complicated, if you want to take into account the different mapping modes, but you can check it from the reference link i've included below
    // You may also want to load normals, as Syntac_ suggests, as well as tangents, or you could generate them yourself. And you could load any bone weights if you want to perform skinning animation.
}

```

Load keyframes - the data on translation, rotation and scaling for each keyframe of an animation

```
void MyFbxScene::LoadNodeKeyframeAnimation(FbxNode* fbxNode)
{
    bool isAnimated = false;

    // Iterate all animations (for example, walking, running, falling and etc.)
    int numAnimations = this->fbxScene->GetSrcObjectCount(FbxAnimStack::ClassId);
    for (int animationIndex = 0; animationIndex < numAnimations; animationIndex++)
    {
        FbxAnimStack *animStack = (FbxAnimStack*)this->fbxScene->GetSrcObject(FbxAnimStack::ClassId, animationIndex);
        FbxAnimEvaluator *animEvaluator = this->fbxScene->GetAnimationEvaluator();
        animStack->GetName(); // Get the name of the animation if needed

        // Iterate all the transformation layers of the animation. You can have several layers, for example one for translation, one for rotation, one for scaling and each can have keys at different frame numbers.
        int numLayers = animStack->GetMemberCount();
        for (int layerIndex = 0; layerIndex < numLayers; layerIndex++)
        {
            FbxAnimLayer *animLayer = (FbxAnimLayer*)animStack->GetMember(layerIndex);
            animLayer->GetName(); // Get the layer's name if needed

            FbxAnimCurve *translationCurve = fbxNode->LclTranslation.GetCurve(animLayer);
            FbxAnimCurve *rotationCurve = fbxNode->LclRotation.GetCurve(animLayer);
            FbxAnimCurve *scalingCurve = fbxNode->LclScaling.GetCurve(animLayer);

            if (scalingCurve != 0)
            {
                int numKeys = scalingCurve->KeyGetCount();
                for (int keyIndex = 0; keyIndex < numKeys; keyIndex++)
                {
                    FbxTime frameTime = scalingCurve->KeyGetTime(keyIndex);
                    FbxDouble3 scalingVector = fbxNode->EvaluateLocalScaling(frameTime);
                    float x = (float)scalingVector[0];
                    float y = (float)scalingVector[1];
                    float z = (float)scalingVector[2];

                    float frameSeconds = (float)frameTime.GetSecondDouble(); // If needed, get the time of the scaling keyframe, in seconds
                }
            }
            else
            {
                // If this animation layer has no scaling curve, then use the default one, if needed
                FbxDouble3 scalingVector = fbxNode->LclScaling.Get();
                float x = (float)scalingVector[0];
                float y = (float)scalingVector[1];
                float z = (float)scalingVector[2];
            }

            // Analogically, process rotationa and translation
        }
    }
}

```

Load skeletal animation

```
void MyFbxScene::LoadMesh_Skeleton(FbxMesh *fbxMesh)
{
    int numDeformers = fbxMesh->GetDeformerCount();
    FbxSkin* skin = (FbxSkin*)fbxMesh->GetDeformer(0, FbxDeformer::eSkin);
    if (skin != 0)
    {
        int boneCount = skin->GetClusterCount();
        for (int boneIndex = 0; boneIndex < boneCount; boneIndex++)
        {
            FbxCluster* cluster = skin->GetCluster(boneIndex);
            FbxNode* bone = cluster->GetLink(); // Get a reference to the bone's node

            // Get the bind pose
            FbxAMatrix bindPoseMatrix;
            cluster->GetTransformLinkMatrix(bindPoseMatrix);

            int *boneVertexIndices = cluster->GetControlPointIndices();
            double *boneVertexWeights = cluster->GetControlPointWeights();

            // Iterate through all the vertices, which are affected by the bone
            int numBoneVertexIndices = cluster->GetControlPointIndicesCount();
            for (int boneVertexIndex = 0; boneVertexIndex < numBoneVertexIndices; boneVertexIndex++)
            {
                int boneVertexIndex = boneVertexIndices[boneVertexIndex];
                float boneWeight = (float)boneVertexWeights[boneVertexIndex];
            }
        }
    }
}

```

However, it's a bit complicated, because if you want to open the fbx properly, you'd have to consider things like smoothing groups and sub materials. Skinning is also tricky, because of taking the mesh's binding pose and the pile of tranformations affecting the mesh. It's kinda messy.

These examples are adapted cut-offs from Meshwork's MwModuleFbx. For a complete example reference, you can take a look at the full code, but bear in mind that it too has issues with skinning. You can find it at http://morroworks.com/meshwork/source/
> 3 votes

# Answer
Once you have loaded your scene you can do the following to get a reference to all the meshes.

```
FbxNode* pNode = m_pScene->GetRootNode();

if(pNode)
{
    for(int nNode = 0; nNode < pNode->GetChildCount(); nNode++)
    {
        FbxNode* pChildNode = pNode->GetChild(nNode);

        // Search for mesh node
        if(pChildNode->GetNodeAttribute())
        {
            if( pChildNode->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eMesh)
            {
                FbxMesh* pMesh = (FbxMesh*)pChildNode->GetNodeAttribute();

                // return here if you only expect one mesh or store them in an array
            }
        }
    }
}

```

Once you have a valid `FbxMesh` you can then do something like the following to read per-vertex data.

```
unsigned long uPolyCount = pMesh->GetPolygonCount();
unsigned long uVertexCount = 0;
unsigned long uVertexNumber = 0;

for(unsigned long uPoly = 0; uPoly < uPolyCount; ++uPoly)
{
    // Get number of vertices in current poly - is your mesh triangulated?
    uVertexCount = pMesh->GetPolygonSize(uPoly);

    for(unsigned long uVertex = 0; uVertex < uVertexCount; ++uVertex)
    {
         // Get corresponding vertex index for this poly-vertex
         uVertexIndex = m_pMesh->GetPolygonVertex(uPoly, uVertex);
         assert(uVertexIndex != -1 && "Index is out of range");

         // Get vertex position
         FbxVector4 fbxVertex = pMesh->GetControlPointAt(uVertexIndex);

         // Get vertex normal
         FbxVector4 fbxNormal;
         bool bResult = pMesh->GetPolygonVertexNormal(uPoly, uVertex, fbxNormal);

         // etc..
    }
 }

```

Note: This example uses the 2013.3 FBX SDK.
> 1 votes

---
Tags: c++, directx, fbx
---


title: Distort a quad with a World Matrix

text:
# Question
Title: Distort a quad with a World Matrix
Is it possible to distort a quad multiplying its vertices by a specific world matrix? See the picture to understand what kind of distortion I need:

Please note, that the quad is in 3d space and I particularly need it's VERTICES to be distorted and NOT to rotate a perspective camera. The quad is laying on a plane with Z=0, all of the quad's vertices have their Z components equal to 0 and they should have their Z component equal to 0 after the transformation.

I know that it can quite easily be done by moving the vertices in a vertex shader, but the reason why I need to distort the quad using a World matrix is because I am rendering hundreds of such quads with a single draw call. Some of them need to be distorted and some dont. So I need a uniform vertex shader for every case and before doing branching in the shader I would like to know if such distortion can be done with a World matrix.

# Answer
> Please note, that the quad is in 3d space and I particularly need it's VERTICES to be distorted and NOT to rotate a perspective camera. The quad is laying on a plane with Z=0, all of the quad's vertices have their Z components equal to 0 and they should have their Z component equal to 0 after the transformation.

Please note that even though you wish to dismiss a solution, it may still be valid. If you want quad's vertices to have Z=0, there's a scale matrix for that:

```
1 0 0 0
0 1 0 0
0 0 0 0
0 0 0 1

```

So, to sum up: rotate the quad, apply perspective transformation, divide by W (scale with 1/W) and flatten it along the Z axis in the end.
> 1 votes

---
Tags: shaders, matrix, geometry, transformation
---


# Question
Title: Static constants set to default value in HLSL
I'm using dx11 and I'm working on SSAO. I am having wierd results, so I tried debugging it using RenderDoc and stepping through the pixel shader log, all the values of the static array seems to default to 0-vector. For example, look at r3-register in the following screenshot.

Here's the pixel shader I'm using. The global static variable that seems to be all null despite my initialization is the `gSSAOKernel`. Why is this? Isn't this correct?

```
#ifndef SSAO_PIXEL_HLSL
#define SSAO_PIXEL_HLSL

#include "Constants.h"
#include "Common.hlsl"

static const float gKernelSize = 16.0;
static const float gRadius = 1.5;
static const float gSSAOPower = 2.0;
static const float3 gSSAOKernel[gKernelSize] =
{
    float3(-0.0780436, 0.0558389, 0.0281286),
    float3(0.034318, -0.0635879, 0.0741237),
    float3(0.00230821, 0.0807279, 0.0805477),
    float3(0.0124638, 0.117585, 0.0578601),
    float3(0.093943, -0.0944602, 0.0816459),
    float3(0.139348, -0.109816, 0.0618508),
    float3(-0.181872, -0.129649, 0.0380075),
    float3(0.240066, -0.0494057, 0.118559),
    float3(0.115965, -0.0374714, 0.301286),
    float3(-0.294819, -0.100726, 0.225789),
    float3(-0.149652, 0.37459, 0.202967),
    float3(0.261695, -0.292813, 0.349015),
    float3(-0.37944, -0.425145, 0.206921),
    float3(0.628994, -0.189387, 0.224343),
    float3(-0.331257, -0.646864, 0.307335),
    float3(-0.467004, 0.439687, 0.618459),
};

cbuffer SSAOCBuffer : register(CBUFFER_REGISTER_PIXEL)
{
    float4x4 gViewProjMatrix;
    float4x4 gProjMatrix;
    float2 gScreenSize;
};

Texture2D gPositionTexture : register(TEXTURE_REGISTER_POSITION);
Texture2D gNormalTexture : register(TEXTURE_REGISTER_NORMAL);
Texture2D gNoiseTexture : register(TEXTURE_REGISTER_DIFFUSE);
Texture2D gDepthTexture : register(TEXTURE_REGISTER_DEPTH);
SamplerState gPointSampler : register(SAMPLER_REGISTER_POINT);

float linearizeDepth(in float depth, in float4x4 projMatrix) {
    return projMatrix[3][2] / (depth - projMatrix[2][2]);
}

float4 ssao(in float3x3 kernelBasis, in float3 originPos)
{
    float occlusion = 0.0;
    for (int i = 0; i < gKernelSize; i++)
    {
        float3 samplePos = mul(kernelBasis, gSSAOKernel[i]);   <---------------------- this line
        samplePos *= gRadius * originPos;

        float4 offset = mul(gViewProjMatrix, float4(samplePos, 1.0));
        offset.xy /= offset.w;
        offset.xy = offset.xy * 0.5 + 0.5;

        float depth = gDepthTexture.Sample(gPointSampler, offset.xy).r;
        depth = linearizeDepth(depth, gProjMatrix);

        float rangeCheck = abs(originPos.z - depth) < gRadius ? 1.0 : 0.0;
        occlusion += (depth <= samplePos.z ? 1.0 : 0.0) * rangeCheck;

    }
    occlusion = 1.0 - (occlusion / float(gKernelSize));

    return pow(occlusion, gSSAOPower);
}

float4 ps_main(float4 position : SV_Position) : SV_Target0
{
    float2 coords = float2(1920.0, 1080.0) / float2(4.0, 4.0);
    coords *= float2(position.x / gScreenSize.x, position.y / gScreenSize.y);

    float3 originPos = gPositionTexture[uint2(position.xy)].xyz;
    float3 normal = gNormalTexture[uint2(position.xy)].xyz;

    float3 rvec = gNoiseTexture.Sample(gPointSampler, coords).xyz; //texture(uNoiseTex, noiseTexCoords).rgb * 2.0 - 1.0;
    float3 tangent = normalize(rvec - normal * dot(rvec, normal));
    float3 bitangent = cross(tangent, normal);
    float3x3 kernelBasis = CreateMatrixFromCols(tangent, bitangent, normal);

    return ssao(kernelBasis, originPos);// gFinalTexture.Sample(gPointSampler, coords);//float4(1.0, 0.0, 1.0, 1.0);
}

#endif

```

Also - offtopic, but this pixelshader murders my framerate, all the way from solid 450+ to 80-90. I guess with all the texture lookups the technique is simply expensive, but still, I must be doing something wrong in regard to performance.

# Answer
> 3 votes
This is my fault - the 0 values are caused by a bug in RenderDoc v0.20 - the x0\[\] indexable temp register being used there which contains your kernel data wasn't implemented in the shader debugging at the time of that release - I implemented it a few months ago. I'm hoping to get v0.21 with all the latest fixes out this week-ish.

---
Tags: directx, hlsl, directx11
---


# Question
Title: Processing periodical operations on the database
I program MMO strategy game (C# monogame) like Goodgame Empire or Travian for Windows Phone.

The server part of the game will run on Windows Server and MS SQL database.

I'm trying to figure out a way to perform periodical operations over players' data. My point is that, for example farm will produce one piece of food every minute and I need store it to database in real time.

I thought about that when registering a new player would cause the database start new job, but for example at 2000 players on the server I'm not sure if I do not kill performance. I want to find optimal solution and I wanted to ask your opinions on what you think would be the best solution.

# Answer
> 2 votes
Why do you want to start a new job for every single player?

Create a single job that calculates the updates every minute for all players. This should be a lesser performance impact.

**Edit based on comments**

When doing this in a single job then use a single transaction for this job then no player gains an advantage as the new values are visible at the end of the transaction.

# Answer
> 1 votes
Personally if it were me I would separate this for simplicity.

Here's how ...

1. Create an API call on your game server that will handle the saving of player
2. Create a new executable that would simply make an api call to my game server every minute.
3. Schedule that using windows task scheduler

The new exe can then be configurable to call any number of things every minute.

The other way if you don't want the separation is to have something global and static on the server that contains a timer and on every "elapsed" event call the api method talked about above.

I tend to go for separation that way my server can just literally be a bunch of API calls.

---
Tags: xna, c#, monogame, mmo, databases
---


title: Snake game logic

text:
# Question
Title: Snake game logic
So I'm thinking about making snake game. I started thinking about it. I figured out almost everything, but I have found one fundamental problem I can not fix myself and I need your help. The logic here is simplified.

We have a grid 10 by 10. A snake is 3 segment long thing that occupies 3 sectors of the grid. I think of implementing the container for snake body as two-dimensional array. So if the snake is somewhere in the middle horizontally and we calculate position from lower left, it might be in positions array\[5\]\[5\], array\[5\]\[6\], array\[5\]\[7\].

Now, to move snake we need to add another segment at the direction it moves and remove segment from its tail. For that we need int direction that holds 4 possible directions and two Structures each of which contains x and y coordinate of segment in array. We may set the length and coordinates of snake in the init steps. So we have structures preset for us at start. Lets imagine they are

Tail.y = 5, Tail.x = 5; Head.y = 5, Head.y = 7;

And the direction will be some arbitary number that we decided says it is east.

So when we move our snake, we look for head, check direction, and add a segment in that spot, and set our head struct to point at that spot. So our new head is array\[5\]\[8\]. Then we check for tail. Our struct says its array\[5\]\[5\]. We remove it from array. Here comes the problem with my logic. How do we get our struct to point on the last element of our snake that becomes a new tail?

Easy solution seems to check direction and look for segment next after last tail in that direction, but if our snake is not straight line it will fail.

I understand that my question is huge but it is all simple, just need some guidance.

The language I use is Objective-C.

EDIT:

As nobody suggested, I used NSMutableArray of CGPoints (wrapped in NSValue). I can freely add objects to array and remove from it. This way the first object is always head and the last object is always tail. It gets trivial at that point.

# Answer
You could go for a linked list, as others suggested. But basically, a snake is just a FIFO stack (sometimes called a queue) of grid coordinates:

* When the snake grows one bit, you just push an element on top of the stack
* When it moves one square, you push an element on top and pop an element off the bottom

For an implementation of a queue in Objective-C, you can check this answer on SO, it seems OK by looking at all the upvotes.

Also, check this answer for some more snake implementation tips.

\[self-promotion\] Oh, and for an interesting snake implementation, you could check the source code for SnakeDemocracy! \[/self-promotion\]
> 9 votes

# Answer
Instead of implementing the snake as an array, why not implement it as a linked list, where each entry in the list is a point where the snake's body turns? For example, you could have the list {\<5,5\>, \<8,5\>, \<8,10\>, \<12,10\>} with \<5,5\> being the head, \<12,10\> being the tail, and the points in the middle being curves in the snake's body. Then when the player turns the snake, you only have to add a new entry to the front of the list, and when the snake moves you just update the tail until it overlaps the next point, at which time you remove it.
> 2 votes

# Answer
You don't actually need a linked list, nor any other complex data structure (outside of the board array itself) to do a snake game.

You just need certain pieces of information:

The head position, head direction, the tail position, the current length, and the maximum length.

Within each board cell, you must have a way to mark what type of segment is present.

I typically do this with either booleans or bitflags. Either work.

For ease of understanding, consider booleans. One for each of snake body segment present, connection to the north, connection to the east, connection to the west, connection to the south (thinking of a screen in terms of a map).

Next, when moving the head, you know which direction you are moving, so you add that directional connection to that board cell, you move the head, then you add the OPPOSITE direction connection. When you move the head, you add 1 to the length of the snake.

Example:

Head is at (5,5), direction south (+0,+1), snake length 4.

Add SOUTH flag to (5,5), move head to (5,6), add NORTH flag to (5,6).

Snake length ++ to 5.

When the length is greater than the maximum length, you find the tail, and it will have exactly one connection flag to another cell. remove that connection flag, then move the tail that direction, then remove the OPPOSITE direction connection.

Example:

Tail is at (2,3), connection to the west(-1,+0), snake length 5.

Remove WEST connection from (2,3).

Move tail to (1,3).

Remove EAST connection from (1,3).

Snake length -- to 4.

Hope this helps.
> 2 votes

# Answer
What I would do, is have a `SnakeNode class`, and mimic a linked list data structure.

For example:

```
class SnakeNode
{
    SnakeNode next;
    SnakeNode prev;

    public SnakeNode(SnakeNode next, SnakeNode prev)
    {
         this.next = next;
         this.prev = prev;
    }
}

```

You will know you are at the head if prev is null. The tail will be when next is null. Start at the head and move your way down to the tail, using your next/prev objects.

Doing it this way, it becomes trivial. Simply reposition them one by one working your way down the list.
> 1 votes

# Answer
The simple answer is that you need to track all of the snake's body positions, not just the head and tail. If the snake is always going to stay 3 segments long, you can stick to an array of (x,y) positions of length three.

When doing your movement logic, before you update the head with a new position, loop through the array from tail to head. For each position in the array, you need to change it to the next value in the array. So in some pseudo-code:

```
for(int i=snakeArray.length-1; i>0; i--)
    snakeArray[i].x = snakeArray[i-1].x
    snakeArray[i].y = snakeArray[i-1].y

```

You can then find the next position for the snake's head and set snakeArray\[0\] to that.

If you're going to be making the snakes grow and shrink a lot, then consider the linked list answers. Lists will make your life easier, but are not mandatory.
> 0 votes

# Answer
Why not have the value for the array\[x\]\[y\] increment down to zero each update (move) where when you move the head of the snake you place down a value of the length of the snake itself. Using this you could search the board for the value 1 for the snake tail and a defined value for the snake head (-1). Upon an expansion of the snakes length just decide not to decrease the valued for the board that turn.
> 0 votes

---
Tags: objective-c, logic
---


# Question
Title: Can you save a png in XNA larger than the backbuffer width?
I'm looking at using the 'savetopng' method of the texture2D class to draw out custom textures. My problem is that my viewport is quite small (the application runs in a window) and the textures will often times run off the screen up to the maximum texture size of 2048px. If I know the texture size ahead of time am I able to instead create an array larger than the visible screen area. Or will the fact that the pixels are outside the viewport mean that they are not being rendered and as a result won't have the correct values?

# Answer
The easier is to test it... :)

but yes... you can...

the texture maximum size is 2048x2048 or 4096x4096 depends on the profile,

you can use a array in CPU memory to fill it,

```
 Color[] colors = new Color[2048x2048]
 Texture.SetData(colors);

```

and save to png method is no related to viewport.
> 2 votes

# Answer
The savetopng method copies the texture from the graphics card into a specified file in png format. The view port has nothing to do with it. The textures may be smaller or larger than the actual window. So the answer is yes.
> 0 votes

---
Tags: c#, xna-4.0, png
---


title: Map scrolling around the world

text:
# Question
Title: Map scrolling around the world
I am developing an TBS (turn based strategy) game. I have created a simple canvas renderer to render hexagonial map. I already implemented scrolling on the map. My current problem is that I want to make it like in the civilizations games that you can scroll around the world. But I am kind of stuck on how to implement that. I had the idea of checking if a tile was rendered and if there is still space to the left render next sibling and so on, but this would turn out into long loops. My map array (2d) holds all the tiles and every tile has a member which holds all the siblings. How would you solve this?

This is a screenshot from the example. You can check it out on http://civ.minerjs.com. The code is also available to browse on the site using developer tools. Thanks for reading!

# Answer
Hex grids can be treated as square grids with an offset every other column/row (depending on orientation), which means your map can be a 2D array instead of a linked graph of hex cells, then you just need method calls to find the siblings that wrap up a little math to handle converting hex grid coords to square grid coords.. For instance.. given your orientation, East and West are easy... NE/NW/SE/SW need to look at if they are on an even or odd row to decide if the neighbor hex is directly above or below, or offset to to the east or west. But given the next part of my answer, that will only really matter for things that are moving on the map, not for drawing the map.

Considering that there are fixed size steps for each row/column, using a 2D array as the backing store and a bit of math it should not be hard to pre-determine how many cells you can display on a canvas of given size... that makes your draw loop deterministic and MUCH faster than walking a linked graph of hex cells. you may be scanning a 2D map array, but drawing the hex cells with the correct offsets based if the row is even or odd.

Basically what it boils down to is if you store your map in a 2D array, it is wasteful to also store sibling links.. the sibling coords for hex grids are too easy to compute at runtime

As far as wrapping to be able to scroll around the world (I'm assuming in the east/west direction only) all you are doing looping from startpos to startpos+CellCountWidth(canvasWidth) \[ which may extend beyond the end of the array\] and just wrap the position if it goes over the edge (if xpos \>= arraysize { xpos -= arraysize; }) \[x is east west, Y is your row counter the way I'm looking at the coords\]
> 2 votes

---
Tags: javascript, game-mechanics, html-canvas, turn-based-strategy
---


title: Why cap game loop delta-time?

text:
# Question
Title: Why cap game loop delta-time?
I was reading some game's source code on Github and saw this game loop implementation for the first time:

```
var lastTime = 0;
var maxTime = 1/30;

/**
 * @param {DOMHighResTimeStamp} curTime requestAnimationFrame provides this value automatically
 */
this.loop = function(curTime) {
    requestAnimationFrame(Game.loop);

    // Same as division by 1000
    var dt = (curTime - lastTime) * 0.001;

    if(dt > maxTime) {
        dt = maxTime;
    }

    for(var i = 0, len = boards.length; i < len; i++) {
        if(boards[i]) {
           boards[i].step(dt);
           boards[i].draw(Game.ctx);
        }
    }

    lastTime = curTime;
};

```

The key thing: The game updates and draws at every step, but the delta time is capped at the desired maximum delta. That way, if a frame takes too long, the next frame steps with a constant delta.

What are the pros and cons of this approach? I imagine it's useful for preventing huge entity movements caused by a long timestep, but can it cause problems?

**Edit**

Use `curTime` as provided by `window.requestAnimationFrame` in order to simplify stuff and avoid comments that don't deal with my main question.

# Answer
> 1 votes
The practical reason to enforce a maximum delta time is to keep your numerical integration from breaking down. An essential principle of numerical integrators is that the smaller the time delta, the smaller the error delta. A "perfect" integrator would have a time delta of zero and would be indistinguishable from an analytical solution (neglecting floating-point error).

If you have a sudden spike where a frame takes a couple hundred milliseconds to process instead of a dozen or so, the time delta submitted to the integrator is huge and thus you get a huge spatial inconsistency. If you cap the time delta, you get a small temporal inconsistency which is harder for humans to notice.

The real solution is to separate the logic/physics processing from everything else, so you have a consistent time delta while the rendering frame rate is allowed to fluctuate and bear the brunt of whatever lag spikes come up. The fantastic article Fix Your Timestep explains how to implement this.

# Answer
> 1 votes
This is, in general, a bad way to accomplish this goal. Just use the callback `requestAnimationFrame`. Otherwise you run the risk of wasting a ton of power and draining the user's battery faster (remember laptops and mobile are more prevalent than desktops these days, so performance and power usage matters!).

The use of `Date().getTime()` is also wrong. This is not capable of giving you a very accurate time measurement. Always prefer `performance.now()` and fall back only if that's unavailable. The former will return time in milliseconds (too coarse when you're dealing with a time of 16.6ms), is not monotonic (so you can get timing glitches when the clock changes), and is not guaranteed high resolution (so it might return in chunks of 4ms or so instead of the assumed 1ms).

As to the question, yes, capping time is important, though usually I see the caps a bit higher. Otherwise any situation that pauses the app might cause a huge `dt` when it resumes and either break game logic or waste a huge amount of power trying to catch up.

However, it should not break game logic, as your game logic should be as completely divorced from the `dt` as possible. The usual link is Fix Your Timestep! The gist is to handle game logic in a fixed time step (e.g. logic always runs at 60hz) and then just use the measured `dt` to determine how many times you need to iterate over your game logic each frame. To get very smooth display you will need to interpolate on-screen transforms between the current state and a previous state. Overall it's more work, but very much worth it.

# Answer
> 0 votes
The major CON is inconsistency... If you do like most game programmers so and define motion in terms of distance per unit time, capping the delta per frame causes time to magically disappear, slowing down the motion and causing potentially visible artifacts when the render loop most needs to show as close to stable output as it possibly can. Changing the rate of motion of moving entities in the scene is not going to impact your frame rate AT ALL.

The second point to note is that with modern graphics hardware you will likely NEVER hit that cap unless your step method is doing far too much processing. One of our voxel terrain tech demos renders 360K verticies at over 500 fps (1/500th second per frame) on what we consider mid-level graphics hardware (AMD HD7850 GPU)... our step/update methods per object are simple and short (in fact most of the renderable object don't have step/update methods at all.. thats managed elsewhere), so the majority of the overhead in each pass through the rendering loop is pushing draw commands to the GPU...

So instead of munging something that has absolutely no effect on the problem, why not just write the code as though you are going to get sky high frame rates, then when your code fails to meet expectations, profile the code and find out what is really sucking up enough cpu time to cause the sub-normal frame rates. In other words -- don't fix the problem until there IS a problem !! :) And yes -- I'm assuming that cpu load is going to be most of the cause of any low frame rates... it takes a LOT (100s to 1000s) of itty bitty draw calls to get GPU bound during the render loop, but that is a different problem with a different solution (namely make sure your draw calls are at least doing a few thousand verts per draw call so the API is waiting for the GPU to be ready, rather than the GPU waiting for the API to send the next draw call).

---
Tags: javascript, game-loop, timing
---


# Question
Title: Voxel engine/vertexes: how to add more and more different textures during game runtime and change some of the blocks' faces?
It's difficult to ask this, but I'll try. The thing is: I asked before somethings about creating ramps and blocks with vertexes. \[I'm using C#/XNA.\]

---

Explanation: now I got a chunk that has blocks wherever I want, that automatically change "stairs" into ramps. And I love it and I thank all the people that helped me out! But I don't know how to texture it appropriately.

I could add a Texture Atlas and set the coordinates of each texture (I found the example at a project called "TechCraft Engine"), but I'd like to create separate PNG files for each texture, 'cause I'll use transparency later and I'd like that textures can be loaded during game runtime.

I'm newbie in programming, but I'm searching for solutions. All that I got for now is that I have a custom effect (FX file) created that changes colors for each time of the day. But it only has a slot for one texture file loaded. And I still can't implement it because of that.

I can't add more texture samplers to the effect 'cause it can't be done at game runtime (or can it?)

I'm using the VertexBuffers and IndexBuffers, with TriangleList primitive. For now, I can only draw with colors, without textures.

Later in my game I would like that custom textures could be added and placed on some of the block's faces. A example for this can be found in The Sims 3. There you can add textures to the game and paint the walls and objects with it. It's something like that I'd like to create, but with a loader while playing.

---

My question is: should I create a VertexBuffer and a IndexBuffer for each texture and separate the vertexes with each texture between them, creating a List of VertexBuffer and IndexBuffer for placing each?... Then I could draw all the vertexes of one texture at a time, change the effect's texture parameter with a different one (call the pass technique again), and set the graphics device again with the next VertexBuffer and IndexBuffer of the list, for drawing it with the TriangleList primitive.

I'd repeat it for each texture loaded. Does it work or is there any other way to do it?

Should I forget about runtime loading for now, for finding a easier solution?

I'm pretty messed with this, do you have any suggestions? Any information will help. Thank you!

# Answer
> 0 votes
Ok, I found a solution to my problem: ConcurrentDictionary of string, VertexBuffer, ConcurrentDictionary of string, IndexBuffer and ConcurrentDictionary of string, Texture2D.

With them, I can create each VertexBuffer and IndexBuffer for a texture name stored in a string.

Then I can easily access all data I need: loading a Texture 2D, setting a name for it and setting a block to use it.

First I create each VertexBuffer and IndexBuffer for each block type in the map, storing in the ConcurrentDictionary the block's texture name as the string parameter and the data created.

When the drawing function comes, I check every VertexBuffer in the ConcurrentDictionary and decide which texture to use using its name, then get the IndexBuffer and Texture2D for it from each ConcurrentDictionary.

I'll provide more details later, if I can edit the post.

Edit: here are my codes:

First, in my content loader, I make the texture be detected and added to a ConcurrentDictionary in another class:

```
                dynamic XNAobject = Game.Content.Load<dynamic>(path);
                // [...]

                else if (XNAobject is Texture2D && path.Contains("Terrain") && path.EndsWith("Atlas")) {
                    Console.WriteLine(this + " adicionando textura de terreno");
                    TextureManager.AddTerrainTexture((Texture2D)XNAobject, path);
                }

```

Here's the class that contains the ConcurrentDictionary.

```
    #region Texturas do Terreno
    /// <summary>
    ///  Todas as texturas carregadas, classificadas pelo caminho do arquivo (Tag).
    /// </summary>
    internal static ConcurrentDictionary<string, Texture2D> TerrainTextures = new ConcurrentDictionary<string, Texture2D>();
    #endregion
    #endregion

    #region Adicionar Textura
    internal static void AddTerrainTexture(Texture2D texture2DAtlas, object tag) {
        texture2DAtlas.Tag = tag;
        if (!(tag is string)) { return; }
        string stringTag = (string)tag;
        string texture2DName = stringTag.Substring(stringTag.LastIndexOf("\\") + 1, (stringTag.LastIndexOf("Atlas")) - (stringTag.LastIndexOf("\\") + 1));
        //Debug.WriteLine("textura 2D adicionada: " + texture2DName);

        Texture2D oldValue;
        texture2DAtlas.Name = texture2DName;
        if (!TerrainTextures.TryGetValue(texture2DName, out oldValue)) { TerrainTextures.TryAdd(texture2DName, texture2DAtlas); }
    }
    #endregion

```

Here's the process of creating and saving the buffers for each texture. But I didn't show here the vertex creation still.

```
        //  Criar buffers.
        #region Buffers
        lock (chunk) {

            chunk.IndexBuffers.Clear(); chunk.VertexBuffers.Clear();

            //  Adquirir dados finais do chunk.
            foreach (var list in chunk.Vertexes) { string textureName = list.Key;
                IVertexType[] vertexes = list.Value.ToArray();

                short[] indexes = chunk.Indexes[textureName].ToArray();

                if (vertexes.Length > 0) {
                    ////  Buffer de vértices.
                    chunk.VertexBuffers.TryAdd(textureName,
                        new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTextureLight), vertexes.Length, BufferUsage.WriteOnly));

                    //  Converter para o tipo.
                    VertexPositionNormalTextureLight[] vertexesConverted = new VertexPositionNormalTextureLight[vertexes.Length];
                    for (int i = 0; i < vertexes.Length; i ++) {
                        vertexesConverted[i] = (VertexPositionNormalTextureLight)vertexes[i];
                    }

                    chunk.VertexBuffers[textureName].SetData(vertexesConverted);

                    //  Buffer de índices.
                    chunk.IndexBuffers.TryAdd(textureName,
                        new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, indexes.Length, BufferUsage.WriteOnly));

                    chunk.IndexBuffers[textureName].SetData(indexes);
                }
            }

            chunk.NeedsBuild = false;
        }
        #endregion

```

And some of the chunk data needed for the buffers:

```
    #region Vértices
    /// <summary>
    ///  Listas de todos os vértices do chunk, para serem desenhados.
    /// </summary>
    public ConcurrentDictionary<string, List<IVertexType>> Vertexes =
        new ConcurrentDictionary<string, List<IVertexType>>();

    public ConcurrentDictionary<string, short> VertexCounts = new ConcurrentDictionary<string, short>();

    /// <summary>
    ///  Listas de todos os índices para a ordem de vértices neste chunk.
    /// </summary>
    public ConcurrentDictionary<string, List<short>> Indexes =
        new ConcurrentDictionary<string, List<short>>();
    #endregion

    #region Buffers
    /// <summary>
    ///  Lista de Buffers de vértices dos blocos do chunk.
    ///  Cada buffer pode ser usado para aplicar determinado efeito.
    /// </summary>
    public ConcurrentDictionary<string, VertexBuffer> VertexBuffers = new ConcurrentDictionary<string, VertexBuffer>();

    /// <summary>
    ///  Lista de Buffers de índices do chunk.
    /// </summary>
    public ConcurrentDictionary<string, IndexBuffer> IndexBuffers = new ConcurrentDictionary<string, IndexBuffer>();
    #endregion

```

Then, after building a VertexBuffer and a IndexBuffer for each texture, and saving in a ConcurrentDictionary with the texture's name, I can access it by the texture's name and draw it:

```
                    lock (chunk) {
                        //  Desenhar vértices dos blocos, com as texturas para eles.
                        foreach (var list in chunk.VertexBuffers) { string textureName = list.Key;
                            Texture2D texture;
                            if (TextureManager.TerrainTextures.TryGetValue(textureName, out texture)) {
                                //  Colocar a textura selecionada da lista.
                                TextureManager.DynamicTexturingEffect.Parameters["Texture1"].SetValue(texture);
                                //Debug.WriteLine(texture.Name);

                                //  Ativar as opções de efeito para o dispositivo gráfico e desenhar com elas.
                                foreach (EffectPass pass in TextureManager.DynamicTexturingEffect.CurrentTechnique.Passes) {
                                    pass.Apply();

                                    VertexBuffer vertexBuffer; IndexBuffer indexBuffer;
                                    if (chunk.IndexBuffers.TryGetValue(textureName, out indexBuffer) && chunk.VertexBuffers.TryGetValue(textureName, out vertexBuffer)) {
                                        if (indexBuffer.IndexCount > 0) {
                                            lock (GraphicsDevice) {
                                                GraphicsDevice.SetVertexBuffer(vertexBuffer);
                                                GraphicsDevice.Indices = indexBuffer;
                                                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount, 0, indexBuffer.IndexCount / 3);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

```

---
Tags: xna, c#, textures, voxels, graphic-effects
---


title: Multiple SpriteSheets break batching

text:
# Question
Title: Multiple SpriteSheets break batching
**The problem:** I can't fit all my 2d animation sprites for all units and environment in 1 spritesheet.

Everything batches fine until I use two spritesheets... I noticed the following : all units from spritesheet A batch fine until something needs to be rendered fom spritesheet B. so lets say from back to camera : 50units - tree -50 units - camera will result in 3 drawcalls... Not that bad but if you have: unit- tree - unit -tree -unit -tree ... like it's probably most of the time... this wil result in 100+ drawcalls even though you have only two spritesheets...

**How can you solve this? Or better, how can i use two spritesheets and have only two drawcalls even though the sprites are at different distances to the camera**

Hope this image helps to understand the problem:

1 : the trees are on spritesheet B and batch fine 2: the batching is broken as the unitsprite sits on spritesheet A and is put in between the trees...

# Answer
Sort the rendering order by the used sprite sheet and not by distance from camera. This works fine if you use z-buffer and don't render transparent objects. I.e. first draw all the trees (and other objects in the same sprite sheet) into the scene and test and write the depth in z-buffer. Then render all units and do the same. This will result in 2 draw calls regardless how many units and trees you have or how they are placed.

Another option is to use array textures if it's supported on your target platform. Here you can store all the atlas textures into a single texture (it's just a stack of 2D textures) and you can render the whole scene with single draw call in any order you want.
> 4 votes

---
Tags: unity, spritesheet, spritebatch, draw-order
---


title: Why should I use getcomponent?

text:
# Question
Title: Why should I use getcomponent?
I have already referred the animator by using the statement,

```
       Animator anim;

```

But,What is the use of getcomponent in awake() function.What happens without it.

# Answer
`Animator anim;` is just a empty reference. If you want to actually access the `Animator` script attached to the object, you'll have to use `GetComponent<Animator>()` and assign it to `anim`.

Your first sentence is incorrect `Animator anim;` does not refer to anything. It's simply a placeholder for referencing an `Animator` object. It doesn't point to anything unless you tell it what to point to.
> 3 votes

# Answer
if you make a public variable like

```
public Animator anim;

```

in a monobehavior script, outside any method, you can drag and drop a gameobject with animator component in inspector when you add this script to a gameobject. it will automatically get the Animator component from the dropped gameobject.

But if you already have a reference to the desired gameobject(g) with a Animator component, you can get a reference to it by

```
anim= g.GetComponent<Animator>();

```
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: touch.phase == TouchPhase.Canceled not worked
i m tired to handle and solve issues related to multitouch. i m use maximume 5 touch simultaneously but when two touches are down on two object and i moved my fingures then that both touches fired TouchPhase.Ended event but not fired TouchedPhase.Canceled.

I want to fired TouchPhase.Canceled when i my fingures out of those objects.

```
if (touch.phase == TouchPhase.Began) { hitObject.GetComponent ().TouchDown (hitObject); }

if (touch.phase == TouchPhase.Ended) { hitObject.GetComponent ().TouchExit (hitObject); }

if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { hitObject.GetComponent ().TouchStay (hitObject); }

if (touch.phase == TouchPhase.Canceled) { print ("Touched canceled...."); hitObject.GetComponent ().TouchExit (hitObject); }

```

# Answer
Normally "touchphase.cancelled" occurs when the user puts more than the maximum number of touches the system can track on the screen. So, it does not get fired as you get fingers off.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: Box2D platformer: Why does horizontal movement stop jumping?
I'm writing my sBox2D game character's movement code, but my implementation of *jumping* is failing:

When I press the Jump key, the character jumps OK. However, when I press jump and another key (like the left arrow key) at the same time, it kind of blocks the jump from happening.

I'm using `applyForceToCenter` and `setLinearVelocity` to move the character.

What could the problem be?

---

Here's how I've bound keys trigger movement:

```
// press W key (aka Up key or BTNup)
if (RHInput.isDown(RHInput.BTNup)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.applyForceToCenter(0, 100, true );
        System.out.println("Toni jumps");
    }
}

// press A key (aka Left key or BTNleft)
if (RHInput.isDown(RHInput.BTNleft)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.setLinearVelocity(-5, 0);
        System.out.println("Toni walks left");
    }
    else {
        toniBody.setLinearVelocity(-1, 0);
    }
}

```

# Answer
> 1 votes
The `setLinearVelocity` method *literally sets* the Box2D body's x- and y-velocities to the given values.

That means if the parameter for **x** is set, the character will begin moving horizontally. However, if the parameter for **y** is zero, the character will stop moving vertically.

To fix this, you could either

* pass the character's current y-velocity in the y-parameter, so it doesn't change to zero, or
* use the `applyForce` (`applyForceToCenter` in jBox2D apparently) method, just as you've done for jumping, which only adds to or subtracts from existing velocities, instead of directly setting them.

The `applyForce` method is probably a better choice here, since Box2D is designed with the assumption that *forces* are what causes dynamic bodies to move. This usually makes collisions stabler. (Directly setting velocities is usually just used for kinematic bodies.)

---
Tags: java, box2d, movement, platformer, control
---


# Question
Title: Is it possible to make windows games using Havok's Project Anarchy?
I'm interrested in Havok's Project Anarchy as I plan to learn how to make 3D Games, so I've done some research and it seems focused on mobile platforms.

So before I engage myself I would like to know if it is possible to make PC Windows games with It since it is not explicitly mentionned.

# Answer
Take a look at the features page. Under "Platform Comparison" it has an entry for `Win32/64`. For `Project Anarchy Free` this is not available, but for `"Pro" Package` it is available.

Therefore, yes, it is possible to make a PC game with it -- provided you have the pro version.

How much is the pro version? Based on the FAQ:

> How much does it cost? For commercial licenses on additional platforms (beyond iOS, Android, and Tizen) you are looking at a cost relative to a small studio of about 5-10 game developers using Unity.

That's on the order of $2k-$4k.
> 3 votes

# Answer
Licensing for Project Anarchy has changed since this question was asked/answered. You can now get a PC exporter license, from the updated FAQ:

> PC Exporter for Project Anarchy allows deployment to PC at a cost of $499 per seat.
> 2 votes

---
Tags: havok
---


title: Efficiently tracking active instances

text:
# Question
Title: Efficiently tracking active instances
I'm creating a game with lots of instances. On each iteration of the game loop, I only want to deal with the ones that are near the player. Currently, I do this by constructing a list of all the existing instances within a rectangle surrounding the player every few iterations. However, this takes far too long. How could I speed it up?

# Answer
## Space Partitioning

> In mathematics, space partitioning is the process of dividing a space (usually a Euclidean space) into two or more disjoint subsets (see also partition of a set). In other words, space partitioning divides a space into non-overlapping regions. Any point in the space can then be identified to lie in exactly one of the regions.

In summary Space Partitioning is the process of breaking a large number of items into non overlapping sets. This will benefit you because you can calculate what set your player is in and only deal with the items in that set.

I would recommend either a Quadtree (2D) or an Octree (3D). One advantage of Quadtrees/Octrees is that because they are evenly divided it easier make the updating more inclusive by simply moving a few nodes up the tree and iterating over everything below that point.

For implementing a Quadtree I would recommend looking at this article.

For implementing a OctreeI would recommend looking at this article.
> 2 votes

---
Tags: python, optimization, pygame
---


# Question
Title: Change DisplayObject's bounds in Flash/AS3
I'm developing some platform-like game using AS3 and Flash CS5 for animations. I've already done most of the mechanics now, and I've starded to drawing characters and animating them. But some problem appeared. I used getBounds(this) for caching all of the collisions, and after changing the placeholders to real images everything sucks. Is there any way to change the bounding box to something more constant? What's the proper way to handle with this problem in AS3? I was thinking about representing each colidable object as a pair of animated object and some constant object that will be my colliding box. But usage of that model will be quite annoying... couse I would need to make two working objects/classes for each object that I would like to have collidable. Every help will be appreciated. Looking for some non-noob ways of dealing with it =\]

# Answer
Ok... What I did exactly to handle it somehow: I've created an object and called it BBox. I filled it red to be seen well. Now I put it in each MotionClip that I want to have constant bounding box. But to have the stage clear I just added 'visible = false' in it's class constructor. Basicaly it is visible in Flash in scene view, but it's hidden in game, so I can easly draw it in scene view. Of course I resize this object each time using it to fit my needs. The only thing to remember is to call bBox.hitTestObject() not this.hitTestObject() in class that is being used. Of course I need to call getChildByName in the class that I want to use this boundingbox and keep its referance also. It's some tricky way of doing this and there must be some easier one. I you have some other way of doing that just let me know.
> 0 votes

---
Tags: animation, flash, actionscript-3
---


# Question
Title: How to implement color changing fragment shader?
I have a background of a given size and filled with a given color. I want to change it with an animation effect, starting from the center and spread out until it extends the whole background. The new color should fade / blend smooth into the existing color from the background. Some kind of radial gradient that changes the color and then spreads out over the whole background.

I am working with SpriteKit on iOS and I am really sure that the best way to implement this is to do this with fragment shaders which are new to iOS 8 SpriteKit SDK. I have done some work with shaders and understand how they work but I am asking for help more on the mathematics behind this.

# Answer
> 11 votes
Here's how I would do this. First, make sure you have the object's UVs or world coords (which you can pass through from your vertex shader) available to you. If it's just a background, you could also just use fragment coords (`gl_FragCoord`).

For instance, let's say we're using UV coords. A fragment shader with only: `gl_FragColor = vec4(vec3(uv.x),1.0);` will look something like:

And similarly, `gl_FragColor = vec4(vec3(uv.y),1.0);` will look like:

If you're using world coords or fragment coords, you can still scale and translate to normalize to (0,0) -\> (1, 1), but we're going to need to scale and translate again anyway so you can skip that step. Make your coords instead range from (-1.0, -1.0) to (1.0, 1.0) to make the next steps easier, like so: `uv = 2.0 * uv - 1.0;`

Now before we go any further, let's make a super plain radial gradient. Recall that the equation of a circle is x² + y² = r². So using the transformed UVs as a coordinate system, a unit circle (r = 1) can be made with `gl_FragColor = vec4(vec3(uv.x * uv.x + uv.y * uv.y),1.0);` and will look something like:

The next step is animation. To do this, you just need to play around with the "r" value and change the radius. You don't need to worry about clamping color values between 0.0 and 1.0 because that happens automatically anyway.

All together it would look something like this:

```
uniform vec2 screenSize;
uniform float time;

void main(void) {
    // Scale to UV space coords
    vec2 uv = gl_FragCoord.xy / screenSize;

    // Transform to [(-1.0, -1.0), (1.0, 1.0)] range
    uv = 2.0 * uv - 1.0;

    // Have something to vary the radius (can also just be a linear counter (time))
    float wave = sin(time);

    // Calculate how near to the center (0.0) or edge (1.0) this fragment is
    float circle = uv.x * uv.x + uv.y * uv.y;

    // Put it all together
    gl_FragColor = vec4(vec3(circle + wave),1.0);
}

```

Of course you can simplify a lot of things and play around much more with the variables and constants. Here's a live demo of me doing just that: https://www.shadertoy.com/view/4sjXWh

## Edit:

If you want to do this with different colors, fortunately there's an easy solution! Pass in your colors as uniforms (or hardcode them in the actual fragment shader) and change the last line to this:

```
gl_FragColor = mix(color1, color2, circle + wave);

```

`color1` and `color2` are both `vec4`s. Here's that in action: https://www.shadertoy.com/view/XsjSW1

# Answer
> 2 votes
Since I am working with SpriteKit on iOS the shader support in SpriteKit is still missing a few things to implement an animated color gradient shader in SpriteKit.

However for those who come up to the same situation I have found a more performant way to make animated gradients with sprite kit. Instead of working with shaders I have created a simple image with a blurred out circle ... Like this:

and with a few lines of SpriteKit-Code you get nice and smooth blended gradient color waves starting from the center and extending all over the screen!

```
// Create a Sprite with Gradient-Texture
SKSpriteNode* gradientSpriteNode = [SKSpriteNode spriteNodeWithImageNamed:@"SSGradientMap.png"];

// Set the color and scale properties
gradientSpriteNode.color = color;
gradientSpriteNode.colorBlendFactor = 1.0;
[gradientSpriteNode setScale:0.1];

// Add it to our parent node
[self addChild:gradientSpriteNode];

// Add it to our container
[self.gradientNodes addObject:gradientSpriteNode];

// Create and configure a scale up action
SKAction* scaleAction = [SKAction scaleTo:3.0 duration:3.0];
scaleAction.timingMode = SKActionTimingEaseInEaseOut;

// Run that action and attach a completion block
[gradientSpriteNode runAction:scaleAction completion:^{

    // Create a random color
    float r = [SSHelper randomWithLowerFloat:0. andUpperFloat:1.];
    float g = [SSHelper randomWithLowerFloat:0. andUpperFloat:1.];
    float b = [SSHelper randomWithLowerFloat:0. andUpperFloat:1.];
    UIColor* randomColor = [UIColor colorWithRed:r green:g blue:b alpha:1.0];

    // Create a new gradient ontop of the last one
    [self addGradientWithColor:randomColor];

    // If more than 2 gradient sprites inside our container the last one can be removed
    if (self.gradientNodes.count > 2) {
        SKSpriteNode* gradientNode_ = [self.gradientNodes firstObject];
        [gradientNode_ removeFromParent];
        [self.gradientNodes removeObject:gradientNode_];
    }
}];

```

The idea is to add the sprite to the screen but scaled down to zero. An animation scales it up until it extends the whole screen. Then you start again but having the sprite blended with a different color.

---
Tags: shaders, ios, graphics-programming, fragment-shader, spritekit
---


# Question
Title: How can I create a contrail effect for a spaceship in motion?
I am curious how I could create an effect similar to the ship's tail in the following picture:

# Answer
> 7 votes
I was about to start an answer going over splines, but realized there was probably already a pretty good explanation in the internet. And here it is. The relevant steps are 1 and 2 (3 isn't directly applicable)

The gist of it is:

* Every so many frames, record where the player is:

```

```

The key here is to make sure you're recording the position at a constant time interval, so when the player goes faster, the trail gets longer (as the old points start to "lag" behind)

* Form a spline and from those points (Steps 1 and 2). The result will be something similar to the wireframe image in that tutorial.

Because you don't have "infinite" resolution in a mesh, you get a bunch of short straight sections gradually curve. Pretend that the width of the segments is constant, (I was drawing with a trackpad). You don't address the fact that the trail gets thinner just yet :

```

```
* Now you get to shading the mesh.

The tutorial I linked to was trying to do something a little different. It has points that stay in the same place, and uses a shader to move the trail (that's Step 3).

You're moving the points, so you use different approaches. One I could see is using a simple shader that interpolates between a color and a texture along the entire mesh. The texture would be combined with a solid base for the mesh. Something like:

```

```

But you should also look at the tools you have access to. Most middleware has some sort of "trail renderer" already implemented, and it's probably well optimized. Unity3D and UDK both do, in fact that tutorial's goal could have been be implemented in Unity without any of that extra work (a properly configured trail renderer could have been animated)

# Answer
> 2 votes
You can implement such effect using *Polyboards*. If you can get yourself a copy of *Mathematics for 3D Game Programming and Computer Graphics*, there is a section in the book dedicated to this technique. (actually, the section for polyboards is available for free here).

This technique is also sometimes called a "LineRenderer" or "TrailRender".

# Answer
> 0 votes
when you have an object you can simply draw line to that object as seen as a red line on my pic ^^

**MY** line is drawn in red but you can tell the computer to not use a plain fill but use a gradient filling... now

now haing such a gradient for filling (using black/white on the alpha channel) will result in beeing a fading tail

after seeing your other picture i must add that you don't need a strict line but can do it with any form!

---
Tags: graphic-effects
---