title: LibGDX simple button with image

text:
# Question
Title: LibGDX simple button with image
I want to make two image buttons (play, restart) in my main menu screen but I dont know how to do it. I tried this:

```
Texture playTexture = new Texture(...)
Image playImage = new Image(playTexture)
ImageButton playButton = new ImageButton(drawable?)

```

but I have no idea what is drawable.

# Answer
> 9 votes
A drawable has information about its size and how to draw itself. It's used to determine size and position by ui components. Since you are using a texture, you can use a TextureRegionDrawable.

```
Drawable drawable = new TextureRegionDrawable(new TextureRegion(playTexture);
ImageButton playButton = new ImageButton(drawable);

```

# Answer
> 7 votes
Something like this should work;

```
public class MyGame extends Game
{
    private Stage stage;
    private Texture myTexture;
    private TextureRegion myTextureRegion;
    private TextureRegionDrawable myTexRegionDrawable;
    private ImageButton button;

    @Override
    public void create()
    {
        myTexture = new Texture(Gdx.files.internal("myTexture.png"));
        myTextureRegion = new TextureRegion(myTexture);
        myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
        button = new ImageButton(myTexRegionDrawable); //Set the button up

        stage = new Stage(new ScreenViewport()); //Set up a stage for the ui
        stage.addActor(button); //Add the button to the stage to perform rendering and take input.
        Gdx.input.setInputProcessor(stage); //Start taking input from the ui
    }

    @Override
    public void render()
    {
        //Clear the screen, set the clear color, yada, yada

        stage.act(Gdx.graphics.getDeltaTime()); //Perform ui logic
        stage.draw(); //Draw the ui
    }
}

```

ImageButton and other ui elements all extend `Actor`. You can add an `EventListener` to each actor to handle input. An example;

```
button.addListener(new EventListener()
    {
        @Override
        public boolean handle(Event event)
        {
            //Handle the input event.
        }
    });

```

# Answer
> 1 votes
1. Create a stage
2. Create image Button
3. Write the action we required in the addListner method
4. Add the button into the stage
5. Draw the button in your render method.

Following is an example of this:

```
public class MenuScreen extends Game {

public GameScreen gameScreen;
public TextureAtlas butonAtlas;

private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
public Stage stage;
public TextButton newGameButton

public Skin skin;

public MenuScreen(Game game) {
    super(game);

}

@Override
public void render(float deltaTime) {

    batch.begin();
    sprite.draw(batch);

    batch.end();
    stage.draw();

}

@Override
public void resize(int width, int height) {
}

@Override
public void show() {

    gameScreen = new GameScreen(game);
    butonAtlas = new TextureAtlas(
            Gdx.files.internal("buttons/buttons.pack"));
    stage = new Stage();
    skin = new Skin();
    skin.addRegions(butonAtlas);

    Gdx.input.setInputProcessor(stage);

    newGameButton.addListener(new EventListener() {

        @Override
        public boolean handle(Event event) {
            // TODO Auto-generated method stub
            // do some actions
            return false;
        }
    });

    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

}

@Override
public void hide() {

    batch.dispose();
    butonAtlas.dispose();

    skin.dispose();
}

@Override
public void pause() {
}
}

```

# Answer
> -1 votes
Here is a simple tutorial on how to create Button, ImageButton and TextButton with LibGDX. Let me know if you have questions or comments.

https://libgdx.info/buttons-scene2d/

I hope it helps

---
Tags: java, android, libgdx, game-design, game-mechanics
---


# Question
Title: OpenGL geometry shader 2d rectangle extrusion has weird angles
I have a geometry shader that extrudes lines to rectangles in 2d (by outputting triangle strips). When the lines are not parallel to the X or Y axis, I'm getting parallelograms instead. Also, when the line is parallel to the X axis, it appears thinner.

Here's what my result looks like, drawing 4 lines at different angles:

Here's the geometry shader:

```
#version 150 core

layout(lines) in;
layout(triangle_strip, max_vertices = 4) out;
in vec3 Color[];
smooth out vec3 FColor;

void main() {
  vec3 g1 = gl_in[0].gl_Position.xyz;
  vec3 g2 = gl_in[1].gl_Position.xyz;
  vec3 v1 = normalize(g1 - g2) * 0.1;
  vec3 v2 = normalize(g2 - g1) * 0.1;

  FColor = Color[0];
  gl_Position = vec4(-v2.y + g1.x, v2.x + g1.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(v1.y + g2.x, -v1.x + g2.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(v2.y + g1.x, -v2.x + g1.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(-v1.y + g2.x, v1.x + g2.y, 0.0, 1.0);
  EmitVertex();

  EndPrimitive();
}

```

To test out the calculation, I ran the same set of vertices through the same calculation in GLM, took the results times 10.0 and plotted them using a web tool. Here's what I got:

So it looks to me like the basic calculation is correct. Can anyone help me understand what I'm doing wrong?

# Answer
> 2 votes
I am the world's biggest moron. My window is 800x600. That means that the X-axis from -1 to 1 is 800 pixels and the Y-axis from -1 to 1 is 600 pixels. If I use a square window, everything is... square.

---
Tags: opengl, shaders, geometry-shader
---


# Question
Title: How to make a tile that can be stretched out
I was playing angry birds and I saw that the elastic used to throw the birds is a texture that expands well when you push it with your finger.

How can textures like this be made in java with libgdx? What are the techniques used in cases like this?

I am asking this because it is obvious that in this situation they did not used a bunch of tiles to make an animation and I have no idea how it is made.

Thanks

# Answer
There are some different options. You could just change the size of a regular sprite:

```
sprite.setSize(float width, float height);

```

The problem is that it will be stretched, so that doesn't really help if your sprite is anything but a solid colour.

For some cases like health-bars consisting of hearts I used a tiled drawable. A tiled drawable repeats itself rather than stretching.

You could also use a ninepatch, which is a drawable that has the extendable parts defined. Basically think of an image that consists of 9 areas where you define where the image can stretch.

This is often used for stuff like UI and other things that need to be able to change size depending on content.

```
NinePatch patch = new NinePatch(new Texture(Gdx.files.internal("t.png")), 12, 12, 12, 12);

```

There are different ways to define the areas, this uses pixel size of the texture, but some versions use black pixels on the edges of the image.
> 2 votes

---
Tags: java, libgdx, sprites
---


# Question
Title: Game Maker (and others): what data type is colour and how can I compare them?
In Game Maker, and I imagine other engines, one can "make colour" by defining either the red-green-blue values of the colour or its hue-value-saturation.

I want to create a program that can compare how similar two given colours are, but without built-in functions that detects the "components" (red-value, saturation etc.) of colours, this is kind of hard.

So, I am asking what data type (compound? integer? real number?) is a colour represented in Game Maker and how I can compare them.

# Answer
Colours in GameMaker is just integers in format $BBGGRR. Some examples:

```
draw_set_colour($FFFFFF); // white
draw_set_colour($0000FF); // red
draw_set_colour($FF0000); // blue

```

Also you can use next functons for get components:

```
colour_get_red
colour_get_green
colour_get_blue
colour_get_hue
colour_get_saturation
colour_get_value

```

See documentation for details.
> 0 votes

---
Tags: software-engineering, game-maker, color
---


title: Server logic on client side?

text:
# Question
Title: Server logic on client side?
I am very confused by the PUN implementation of the Photon networking engine. It looks like I don't have to write a separate server so I'm very curious how this works. I have done quite some KryoNet developing and fiddled around with LidGren, these libraries require you to create a server and client.

* The client sends minimum data to the server.
* The server verifies this data and runs the gameplay logic from it.
* The server sends back minimum data so the client can update to the current server state.

Since PUN does not allow me to write my own server how does PUN work? I believe there is a server behind PUN but if it's the clients job of verifying the data this is a vulnerability.

So whats the deal with Photon? Can a competitive game make use of PUN?

# Answer
Alright, since this question seems like it was answered in the comments, let's turn that into an actual answer shall we?

Photon Unity 3D Networking (PUN) works by connecting people to each other instead of to a server for gameplay implementation. So, in short, it works with P2P networking. The most popular example I can think of is Call of Duty Modern Warfare series that uses this sort of (P2P) networking.

The biggest issue with this implementation is that the server is actually a player and should they cheat, it would be really hard to catch them (a reporting system would be necessary but since they have the server on their machine now, chances are, they could mask their username to something else).

The solution that Photon Engine offers is the Photon Server although this sort of P2P method could be used with other kinds of servers but it would take a bigger effort than using their own server implementation. Time versus money kind of deal.

Quote from the asker because these comments are also relevant to the answer itself:

> You have to install Photon and run the server with it using the binaries. I guess these binaries get uploaded and started on the Photon cloud. They even seem to have a Unity api for this but the link to the documentation does not work.
>
> Well, it does seem like PUN is not useful for a competitive game. It's an amazing framework to create something like Wordfeud or Hangman to play with your FB friends. But nothing that is even really competitive. I got Photon server working currently and it seems to have potential. But the price is kinda high if you compare it to something like KryoNet or Lidgren and pay to host it. I also dislike the development, on each change I need to build the server, put the binaries in a folder, restart photon and start the server again. Normally you would just run the server from your IDE.
> 1 votes

---
Tags: unity, networking, photon
---


# Question
Title: LineRenderer sorting order - lines always in front of everything
I have 3 cameras and 3 canvases.

1. Back Camera: depth = -5, Back Canvas: Sorting layer - BackLayer,
2. Camera: depth = 0, Middle Canvas: Sorting layer - MiddleLayer,
3. Camera: depth = 10, Front Canvas: Sorting layer - FrontLayer,

Orders in canvases are also set (for `SpriteRenderers`, images, ui etc.)

*Back* is for a background image and stars, *middle* for mountains and *front* for the UI. Everything is working perfectly with one exception:

**No matter where I draw lines with a `LineRenderer` \- they're always at the front of everything (each canvas).**

The one situation where the line moves deeper is when I set it's points Z to some huge values like 30000 and then - they're just behind everything.

My goal is to place these lines along with the background image and stars on the BackLayer or BackCanvas.

What I've already tried:

* Setting `LineRenderer` sorting layer and it's order from the code. I read somewhere on Unity forums that lineRenderer has to have a special material for this to work but I tried most of them - not working.
* I also tried setting their positions manually, from the inspector, from the code, incrementally in the `Update()` method - they're always in front or complately hidden (with huge numbers mentioned above).
* I tried assigning them to different canvases (back, middle, front) as children didn't work too.

On Unity forums I also read a post which says that we shouldn't use sorting layers with linerenderer and use only Z positions.

If someone has any experience with this, I would be grateful. I really have no idea if I'm doing something wrong or what.

# Answer
First of all - `SpriteRenderer` and `LineRenderer` don't cooperate, as they say on `Unity` forums.

There are two ways of changing the `LineRenderer`'s draw order:

* By changing the position in the line's material's `Render Queue` to lower:
* Creating a complately new layer (normal, not sorting) named for example LineLayer and creating a new camera for it. Set the camera's culling mask to view only this layer and turn it off in other cameras.

I hope that will help someone in the future.
> 1 votes

---
Tags: unity, draw-order, lines
---


# Question
Title: Unity is crashing without leaving a message at the start of my "game"
So. I like to code. I like to play Paradox Interactive games. One thing that I always wondered about was how exactly their implementation of their trigger evaluation/event evaluation system looked like. So I decided I would write myself an implementation and find out!

Now, I didn't want to manually parse their text files out. I could, but it would be an insane waste of time since other people have already developed efficient libraries for it. So I downloaded and set up this nice little library that handles the nasty little details.

I tested the parser to make sure it works. Worked like a charm. Then I started coding. A full day of planning, trial, and error later, I had a very early version ready.

Then I created a C# script with a basic implementation of my new library. I created a basic spherical mesh and dragged it onto my scene. I dragged said C# MonoBehaviour onto my object. I created a country class implementing my 'IScope' interface. I set the "scope chain" up.

I created a text file with the following contents:

```
trigger = {
    id = 5
    vassal = {
        id = 6
    }
}

```

It worked in the parser before. I then wrote the following code in my Start method:

```
void Start()
{
    ScriptBinding.Instance.ReserveTrigger("id", new CheckIDTrigger());
    ScriptBinding.Instance.ReserveScopeName("vassal");
    string path = Application.dataPath + "/ParadoxScriptingEngine/Tests/test_trigger.txt";
    Debug.Log(path);
    FileStream stream = File.OpenRead(path);
    c = new Country(5); //Declared as a class member. Implements IScope.
    tb = new TriggerBlock();
    ParadoxParser.Parse(test_script, tb);
    scope_chain = new IScope[10];
    scope_chain[0] = c; //ROOT
    scope_chain[1] = c; //THIS
}

```

And in Update:

```
void Update()
{
    Debug.Log("The trigger has evaluated to " + tb.Eval(scope_chain));
}

```

When I deactivate the script that launches the parser, the project runs. When I reactivate it and try to run it, the editor instantly crashes.

I have riddled my project with debug statements, but this is just starting to get ridiculous. I have traced through the entire program in my mind, but it is 17 files long all told, and without any data on the error I cannot possibly hope to debug it. The log files are empty as well.

Is there a way to get Unity to print ALL information on errors?

I know that the problem has to be related to my program, so perhaps the better question would be; what kind of problem will cause Unity to not print the error out? I know infinite loops will do it, but there is no way it is an infinite loop is causing this problem - I only used for each loops.

# Answer
> 1 votes
It looks like you may not be closing the filestream once you have opened it, this could be causing the problems you're having.

Try `stream.Close()` at the end of your `Start()` function

You should also wrap a try/catch statement around this so that Unity can handle the errors correctly.

```
try
{
    //file opening code
}
catch (FileNotFoundException e)
{
    // FileNotFoundExceptions are handled here.
}
catch (IOException e)
{
    // Extract some information from this exception, and then
    // throw it to the parent method.
    whenDo not initialize (e.Source != null)
        Console.WriteLine("IOException source: {0}", e.Source);
    throw;
}

```

You can usually find more information about why Unity has crashed without an error by checking the editor logs.

This may give you some clarification, and if you're still stuck you can post the error log for us to look at so that we can advise you further.

https://docs.unity3d.com/Manual/LogFiles.html

# Answer
> 0 votes
That crash is caused because your computer cannot handle too much stuff in one time , example to do :

```
Debug.Log("The trigger has evaluated to " + tb.Eval(scope_chain));

```

In

```
Update()

```

need to do Eval() function each frame , and how about just to do the function take 0.1 second and each second need 60 frame ? what i mean here don't run the function without delay , your computer also have limit .

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


title: storing array of pixels for sprites

text:
# Question
Title: storing array of pixels for sprites
I am trying to write some code in Java for drawing sprites on a BufferedImage.

As of now I have each sprite in a single dimension array. However this is not good for my game because each sprite would only have one image for their sprite.

I would like each sprite to be animated meaning there would be more images to be stored. I have tried using two dimensional arrays for this but I keep running into the same issue with only one frame being stored.

What would be the proper way to solve this?

```
int[][] pxArry;
this.pxArry = new int[][]{
    new int [pxArry.length],
    new int [pxArry[1].length]
};
for(int i = 0; i < pxArry[0].length; i++)
    for(int i2 = 0; i2 < pxArry[1].length; i2++){
        this.pxArry[1][i2] = pxArry[1][i2];
    }

```

# Answer
I do not really understand how your code works, especially the initialisation of the `this.pxArray`, but I can see that you never use the iterator `i` of the first loop in the inner loop.

Try with this :

```
for(int i = 0; i < pxArry[0].length; i++)
{
    for(int i2 = 0; i2 < pxArry[i].length; i2++){
        this.pxArry[i][i2] = pxArry[i][i2];
    }
}

```
> 0 votes

---
Tags: java
---


# Question
Title: Should chunks be procedurally generated client-side or server-side?
I'm developing a game with a friend that involves a procedurally generated map. My question is... Should the client generate the chunks, or should the client make a request to the server, and the server responds with the procedurally generated chunks? I can think of some advantages to both sides.

If it is generated client-side:

* there will be a whole lot less load on the server
* perhaps some game performance improvements too?

If it is generated server-side:

* I can implement anti-cheating algorithms a whole lot more easily and efficiently
* chunks can be "dynamically modified" by the server. Meaning the server can modify chunks for the clients before sending them if needed.

Another option would be for them to work together. The client would generate the chunks on-the-go, but would make a request to the server for modified tiles. I still can't implement the anti-cheating algorithms in this method though. But the advantages to this method are:

* not much load on the server
* server can dynamically modify chunks
* moderate game performance

What is the best option, if any? And what do people usually do? Are there any advantages to any of these methods I'm missing?

**EDIT:** I know Minecraft chose the server-side method. I wonder what their reasons were?

# Answer
> 1 votes
When in doubt, do it server-sided.

If you try to prevent cheating through heuristic means on the server, those heuristic algorithms will have to constantly evolve to keep up with the tricks the cheaters come up with. This is a ton of work for you post-release and will sooner or later result in these algorithms becoming even more resource-intense than the generation algorithms. That means you will sooner or later lose the performance improvements you wanted to achieve.

Having as much logic as possible server-sided also has other advantages.

* If you host your server centrally, you can make updates on the server-side without going through the hassle of rolling out a new client version.
* If you let the community host their own servers, the server admins have a far easier time doing modding than when they need their players to install a mod for everything.

---
Tags: performance, procedural-generation, server, client-server, security
---


title: Why is my texture wrong?

text:
# Question
Title: Why is my texture wrong?
So I am creating an AR app using Vuforia, and I have found a way to read obj files and index them. But now that I finally got my model to show up, there must be something wrong with my UVs/texture coordinates, as I am getting this:

While in Blender it looks like this:

I think there is something wrong with the way I am indexing it, but I can't seem to figure it out. I am pretty new to all this. It could also be that I am using the texture data in the wrong way somehow.

I am using this code to load the `.obj`:

```
bool loadOBJ(
    const char * path,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals
){
    printf("Loading OBJ file %s...\n", path);

    std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
    std::vector<glm::vec3> temp_vertices;
    std::vector<glm::vec2> temp_uvs;
    std::vector<glm::vec3> temp_normals;

    FILE * file = fopen(path, "r");
    if( file == NULL ){
        printf("Impossible to open the file ! Are you in the right path ? See Tutorial 1 for details\n");
        getchar();
        return false;
    }

    while( 1 ){

        char lineHeader[128];
        // read the first word of the line
        int res = fscanf(file, "%s", lineHeader);
        if (res == EOF)
            break; // EOF = End Of File. Quit the loop.

        // else : parse lineHeader

        if ( strcmp( lineHeader, "v" ) == 0 ){
            glm::vec3 vertex;
            fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
            temp_vertices.push_back(vertex);
        }else if ( strcmp( lineHeader, "vt" ) == 0 ){
            glm::vec2 uv;
            fscanf(file, "%f %f\n", &uv.x, &uv.y );
            uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders.
            temp_uvs.push_back(uv);
        }else if ( strcmp( lineHeader, "vn" ) == 0 ){
            glm::vec3 normal;
            fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
            temp_normals.push_back(normal);
        }else if ( strcmp( lineHeader, "f" ) == 0 ){
            std::string vertex1, vertex2, vertex3;
            unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
            int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );
            if (matches != 9){
                printf("File can't be read by our simple parser :-( Try exporting with other options\n");
                fclose(file);
                return false;
            }
            vertexIndices.push_back(vertexIndex[0]);
            vertexIndices.push_back(vertexIndex[1]);
            vertexIndices.push_back(vertexIndex[2]);
            uvIndices    .push_back(uvIndex[0]);
            uvIndices    .push_back(uvIndex[1]);
            uvIndices    .push_back(uvIndex[2]);
            normalIndices.push_back(normalIndex[0]);
            normalIndices.push_back(normalIndex[1]);
            normalIndices.push_back(normalIndex[2]);
        }else{
            // Probably a comment, eat up the rest of the line
            char stupidBuffer[1000];
            fgets(stupidBuffer, 1000, file);
        }

    }

    // For each vertex of each triangle
    for( unsigned int i=0; i<vertexIndices.size(); i++ ){

        // Get the indices of its attributes
        unsigned int vertexIndex = vertexIndices[i];
        unsigned int uvIndex = uvIndices[i];
        unsigned int normalIndex = normalIndices[i];

        // Get the attributes thanks to the index
        glm::vec3 vertex = temp_vertices[ vertexIndex-1 ];
        glm::vec2 uv = temp_uvs[ uvIndex-1 ];
        glm::vec3 normal = temp_normals[ normalIndex-1 ];

        // Put the attributes in buffers
        out_vertices.push_back(vertex);
        out_uvs     .push_back(uv);
        out_normals .push_back(normal);

    }
    fclose(file);
    printf("File can be read by our simple parser :-)\n");
    return true;
}

```

And this code to index the `.obj`:

```
void indexVBO(
    std::vector<glm::vec3> & in_vertices,
    std::vector<glm::vec2> & in_uvs,
    std::vector<glm::vec3> & in_normals,

    std::vector<unsigned int> & out_indices,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals
){
    std::map<PackedVertex,unsigned int> VertexToOutIndex;

    // For each input vertex
    for ( unsigned int i=0; i<in_vertices.size(); i++ ){

        PackedVertex packed = {in_vertices[i], in_uvs[i], in_normals[i]};

        std::map<PackedVertex,unsigned int>::iterator it = VertexToOutIndex.find(packed);
        if ( it == VertexToOutIndex.end() ){
            out_vertices.push_back( in_vertices[i]);
            out_uvs     .push_back( in_uvs[i]);
            out_normals .push_back( in_normals[i]);
            unsigned int newindex = (unsigned int)out_vertices.size() - 1;
            out_indices .push_back( newindex );
            VertexToOutIndex[ packed ] = newindex;
        }else{
            unsigned int index = it->second;
            out_indices.push_back( index );
        }
    }
}

```

Here is my rendering code for the model (Warning: this contains Objective-C):

```
// Clear colour and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Render video background
[appRenderer renderVideoBackground];

glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);

glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)(&(object->vertices)[0]));
glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)(&(object->normals)[0]));
glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)(&(object->uvs)[0]));

glEnableVertexAttribArray(vertexHandle);
glEnableVertexAttribArray(normalHandle);
glEnableVertexAttribArray(textureCoordHandle);

glActiveTexture(GL_TEXTURE0);

int targetIndex = [[self.vuforiaTrackCaller textureIndexForTarget:name] intValue];

glBindTexture(GL_TEXTURE_2D, [augmentationTexture objectAtIndex:targetIndex].textureID);
glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);
glUniform1i(texSampler2DHandle, 0 /*GL_TEXTURE0*/);

glDrawElements(GL_TRIANGLES, object->indices.size(), GL_UNSIGNED_INT, (const GLvoid*)(&(object->indices)[0]));

glDisableVertexAttribArray(vertexHandle);
glDisableVertexAttribArray(normalHandle);
glDisableVertexAttribArray(textureCoordHandle);

glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);

```

And how I load the textures (I don't think the problem is here):

```
// Generate the OpenGL ES texture and upload the texture data for use
// when rendering the augmentation
for (int i = 0; i < [augmentationTexture count]; ++i) {
    GLuint textureID;
    glGenTextures(1, &textureID);
    [[augmentationTexture objectAtIndex:i] setTextureID:textureID];
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, [[augmentationTexture objectAtIndex:i] width], [[augmentationTexture objectAtIndex:i] height], 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)[[augmentationTexture objectAtIndex:i] pngData]);
}

```

# Answer
> 4 votes
See if you can fix this by flipping V coordinate of the UV map:

```
 V = 1 - V

```

It is very common that UV gets vertically flipped in different programs/engines. Also note that different image formats (and loaders) could also store/flip images vertically.

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


title: On button click wait

text:
# Question
Title: On button click wait
I have a button I got from google material design asset pack which has a ripple animation when pressed. I'm using the button's click option in the inspector that calls a method that switches scenes. But when I tap the button it switches the scene immediately and feels unnatural since the animation hasn't finished the button ripples animation.

I tried using co-routines. Made the button call a method in which I call a IEnumerator method (since the button can't directly call a co-routine) and then switch the scene. But that doesn't work since it starts the co-routine and switches the scene, the co-routine never pauses the code and never finishes (probably because I loaded a new scene and the object that carries the script isn't transferred).

Code example:

The method that gets called when I tap a button:

```
 public void OnButtonTap()
 {
     StartCoroutine(Wait(0.2f));
     SceneManager.LoadScene("OnePlayerGameIntro");
 }

```

The wait coroutine:

```
 public IEnumerator Wait(float seconds)
 {
     yield return new WaitForSeconds(seconds);
 }

```

# Answer
> 0 votes
Here is the method with the coroutines.

```
 public void OnButtonTap()
 {
     StartCoroutine(LoadSceneAfterDelay("OnePlayerGameIntro", 0.2f));
 }

 public IEnumerator LoadSceneAfterDelay(string sceneName, float seconds)
 {
     yield return new WaitForSeconds(seconds);
     SceneManager.LoadScene(sceneName);
 }

```

Coroutines can't pause the "main thread" of Unity. A coroutine is a parallel execution of a piece of code and runs "independently" of the main thread.

# Answer
> 0 votes
Use the `Invoke` method. `Invoke` is used to trigger *another* method, but it allows us to pass a `float` value, representing a "wait" before the method runs.

Note that `Invoke` takes a `string` for the method name. Simple type out the *name* of the method with *no enclosing brackets* inside *double quotation marks*, as shown, in the example. Also note that you can not call methods that take parameters, in this way.

---

```
///<summary>Opens the scene immediately.</summary>
public void OpenScene
{
    // put your logic to open the scene here
}

///<summary>Opens the scene after a 0.3 second delay.</summary>
public void OpenSceneWithWait()
{
    Invoke("OpenScene", 0.3f);
}

```

# Answer
> 0 votes
If you're using Unity animations you could take advantage of Animation Events. This will allow you to trigger code at a specific point in an animation. This should allow you to be more accurate than using a co-routine or invoke method.

https://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

---
Tags: unity, android, scene, coroutines
---


# Question
Title: Rendering perspective independent polygons in perspective view
I am creating an editor where I have "grabhandles" that can be dragged to transform a primitive object.

My problem is that I can't find the correct solution to show these grabhandles in a perspective view.

They need to have the correct position AND same size independent of where they are,how far away they are on the perspective viewport and independent of what the viewport dimensions are.

In orthographic mode I do not have this problem as I create the handle polygons by multiplying it with a zoom factor.

# Answer
> 1 votes
You could project the 3D points to screen and then do a 2D rendering of the points and paste those over the main image. The size would be consistent then.

Another option would be billboarding, where you could make the object always face the camera and you can fix the size of the objects by manipulating the transforms. Here is a good article on billboarding that includes fixed sizing.

---
Tags: opengl, matrix, perspective
---


# Question
Title: Libgdx: touchup fired even when figure not on texture
I've implemented a touchup listener for an actor in stage. Now what happens is that when user touch downs the sprite and releases finger, its all good. The problem is when user touch downs the finger, and drag it somewhere else (possibly to cancel the touch) and releases, it still fires the touch up event as if nothing ever happened. How do I stop that? Here's my code:

```
voiceToggle.addListener(new InputListener() {
    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        System.out.println("touched");
        return true;
    }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        System.out.println(event); // still fires even if not on original touchdown element
    }
});

```

# Answer
I actually found that ClickListener class contains another method clicked which fires just like I want it to (if the figure is on actor).

```
voiceToggle.addListener(new ClickListener() {
    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        System.out.println("touched");
        return true;
    }

           @Override
            public void clicked(InputEvent event, float x, float y) {
                // all the stuff
                super.clicked(event, x, y);
            }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        System.out.println(event); // still fires even if not on original touchdown element
    }
});

```
> 0 votes

# Answer
Oddly enough, the documentation for InputListener appears to be a little different than the source. If you look at the source for InputListener, it's actually behaving as it's supposed to:

```
/** Called when a mouse button or a finger touch goes down on the actor. If true is returned, this listener will receive all
 * touchDragged and touchUp events, even those not over this actor, until touchUp is received. Also when true is returned, the
 * event is {@link Event#handle() handled}.
 * @see InputEvent */
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
    return false;
}

/** Called when a mouse button or a finger touch goes up anywhere, but only if touchDown previously returned true for the mouse
 * button or touch. The touchUp event is always {@link Event#handle() handled}.
 * @see InputEvent */
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
}

```

A simple way to solve this would be to put a check in your `touchUp()` method that checks to see if x and y are still on top of the actor. If they're not, don't do anything.

I suspect the reason they built it this way was to give you the option of choosing whether you want to do anything or not (while there is a separate `onDragged` method, you might want to do something special with the new position).
> 0 votes

---
Tags: libgdx
---


# Question
Title: In MySQL, how would I model moves that Pokemon can learn?
I'm making a Pokemon MMO Game with Unity + SmartFoxServer/MySQL. At the moment I'm creating the base structure for the database.

If you are not familiar with Pokemon Games, every Pokemon can learn only a fixed set of moves. I want to represent this in my database. **How should I do it?**

---

Currently I have a *pokemon\_base* table that is storing all the base data of the Pokemon, like name, elemental types, base stats, etc, and a Unique Identifier. I need for every Pokemon inside this table to have a list of learnable moves.

I have these ideas to continue:

* Have a field on the Pokemon table containing comma-separated IDs of learnable moves
* Have a field on the Moves table containing comma-separated IDs of Pokemon that can learn this move, or
* Have another Table with a Field for Pokemon ID and boolean fields for each move

The first one to me seems the better because once I have a Pokemon ID I can get all the moves in a string, which I can split by commas and do my checks. Have I missed something?

# Answer
> 7 votes
Create an intermediary table that maps Pokemon to learnable skills:

Now you can select all the learnables for a Pokemon by name:

```
SELECT LearnableSkills.ID FROM LearnableSkills, PokemonLearnables, Pokemon
WHERE LearnableSkills.ID = PokemonLearnables.LearnableID
AND PokemonLearnables.PokemonID = Pokemon.ID
AND Pokemon.Name = 'byte56'

```

Or by ID:

```
SELECT LearnableSkills.ID FROM LearnableSkills, PokemonLearnables
WHERE LearnableSkills.ID = PokemonLearnables.LearnableID
AND PokemonLearnables.PokemonID = 56

```

# Answer
> -2 votes
I don't have time at the moment to create a visio diagram showing this in practice, but in within the Pokemon games the move sets have an elemental type that determines which Pokemon can learn those moves. As such, I don't know if it's best to keep a table listing all of the available moves each Pokemon can learn as answered above.

For instance, ThunderShock is an electric type move that electric type Pokemon can learn.

The elemental types include:

* Water
* Grass
* Fire
* Ice
* Electric
* Psychic
* Dragon
* Dark
* etc. (and more I believe)

Within your database, I'd suggest the following tables:

ElementalType (primary key ID, Name)

Pokemon (primary key ID/#, Name, foreign key ElementalType.id as TypeID)

Moves (primary key ID, Name, Damage, PowerPointsRequired, foreign key ElementalType.id as TypeID)

To store moves known, an association table LearnedMoves (foreign key Pokemon.id as PokemonID, foreign key Moves.ID as MoveID)

Then to show the moves a Pokemon could learn, you could run the following query:

```
    SELECT * from Moves m
    INNER JOIN ElementalType t ON m.TypeID = t.ID
    INNER JOIN Pokemon p ON p.TypeID = t.ID
    WHERE p.ID = @PokemonID

```

---
Tags: data-structure, mysql
---


# Question
Title: How to deal with two different axes on isometric game?
Hi! Above is a visual of the problem I am having. My game has two different coordinate systems. You have the client, or the canvas, where the game is rendered - a standard coordinate plane; however, I also have the game coordinate plane where it is rotated due to the isometric nature of the game.

*Note: The server only feeds chunks of tiles to the game at a time, which makes it impossible for me to just translate the canvas. I have to calculate the drag amount and in what direction, and request the new chunk of tiles to be displayed from the server.*

**My problem:** I can't figure out how to calculate the # of tiles moved (so I can send that data to the server), because I don't know how to determine how many tiles and in what direction the user moves the map. Because if they move to the left, it's not only change the game's x position, but also the game's y position because both new columns and rows would have to be loaded due to the nature of the isometric map.

I hope this made sense, I tried my best to explain the problem and I'm not too sure I explained it correctly.

# Answer
I hope this is the answer to your problem, not something obvious you already know. If it is, sorry!

You can keep the track of the last loaded tiles in each direction in blue dimensions and the movement of camera in red ones. For example, when the user starts, if it starts from the center, mathematically, the tiles will be loaded based on this formula:

```
|y| = n - |x|

```

Now, you can get the dimensions of the display port. If there are variations in screen sizes, does the objects get scaled up in bigger screens or the bigger screens can see more tiles all at once? based on the answer, whether you have to pass a fixed number or a dynamic formula that gets the actual space a tile takes on the screen (in your screenshot each tile has taken 12% x 10.5% of your display) It's isometric display, and 45 degrees so it's quite easy (only depends on your camera's vertical angles) when you had this "projected" height and width of the tiles in pixels, if the player moved the camera more than the projected width or height of a tile, a new row or column of tiles would be requested, again based on tiles' dimensions on the screen.
> 0 votes

# Answer
I agree that its a big optimization to avoid attempting to draw tiles that aren't visible to the client. I suggest drawing the client screen area using a staggered approach. **Refer to the image you've provided in your question to make sense of the following algorithm.** It has a nicely visible grid to figure out the row and column movements in the server tilemap data structure. I assume you want as much of the client screen area covered as possible.

Here are some output examples for the code I've provided.

* The *top-left* image shows how the top left corner of the server's tilemap gets drawn in a staggered fashion without adequate border padding tiles. The black spaces can be seen along the outer edges of the client screen area.
* The *bottom-left* shows the same inadequate padding near the center of the server's tilemap data.
* The *top-right* and *bottom-right* images show staggered isometric drawing with betting border padding tiles to allow for the illusion of a more continuous area.

Note that I removed the grass tiles from the "insufficient padding" example on the left to highlight the missing tiles against the back background. The orange square is my programmer art for my player sprite.

---

Here is the general algorithm:

1. Get the top left point of the visible window, meaning the position of the camera in server space.
2. Convert this point to Cartesian coordinates on the assumption that its already an isometric coordinate, even if you never explicitly converted the camera movement or position to isometric. Here is a useful link for coordinate conversion and isometric tilemaps in general
3. Calculate the tilemap cell (aka tile) using that Cartesian point, meaning the index in your tilemap array. I use a 2D array, so I directly index tiles by row and column.
4. Decrease the row by 1 or 2 to find a cell that will start drawing at a wider point beyond the client screen area.
5. Continue from there by querying and drawing tiles "diagonally" through the server tilemap data structure. This will result in a visibly horizontal line of tiles across the client screen area. Meaning, from the staring \[row\]\[column\] go to \[row++\]\[column--\].
6. The number of cells to draw across is just the ratio of isometric cell width to client screen area width. EG: `screenWidth == 800`, `isometric cell width == 64`, so the number of cells to draw horizontally is `(int)(800 / 64) == 12` loops. You'll probably have to add some extra loops, say + 5, depending on whatever offset your floor tile images have.
7. Once a line is complete, *toggle* an odd/even line boolean, meaning if its false make it true, and vis versa.
8. If odd/even boolean is true, increment the starting column, then set your indexing row and column back the the starting row and column (using the modified starting column).
9. If odd/even boolean is false, increment the starting row, then set your indexing row and column back the the starting row and column (using the modified starting row).
10. Continue in this odd/even *staggered* movement down the client screen area according to *twice* the ratio of isometric cell height to client screen area height. EG: `screenHeight == 600`, `isometric cell height == 32`, so the number of horizontal lines to draw is `(2 * (int)(600 / 32)) == 37` loops. Again, you'll probably have to add some extra loops, say + 5, to ensure the client screen area is fully covered.

---

## My Solution

I am using SDL and C++ but the principles are the same for Java. Note that my tile origins have been pre-calculated and saved as isometric values. I am aware that the following code may be difficult to understand without knowing what all the function calls I'm making are; however, the idea here is that you should look into *staggered* isometric drawing instead of diamond isometric drawing because it maps much better to client screen area (even if it is more confusing than diamond drawing methods) and the relative draw order is preserved.

```
void eMap::Draw() {
    // DEBUG: these constants assume a cell is square, and that its isometric projection
    // is twice as wide as it is tall, the invIsoCellHeight is halved to account for the
    // staggered isometric cell alignment
    static const float invIsoCellWidth = 1.0f / (float)(tileMap.CellWidth() << 1);
    static const float invIsoCellHeight = 1.0f / (float)(tileMap.CellHeight() >> 1);

    // DEBUG: the extra '+ 5' is on both of these to ensure enough tiles are drawn to cover the screen
    int maxHorizCells = (int)(game.GetRenderer().ViewArea().w * invIsoCellWidth) + 5;
    int maxVertCells = (int)(game.GetRenderer().ViewArea().h * invIsoCellHeight) + 5;

    eVec2 camTopLeft = eVec2(game.GetCamera().GetAbsBounds().x, game.GetCamera().GetAbsBounds().y);
    eMath::IsometricToCartesian(camTopLeft.x, camTopLeft.y);

    int startRow, startCol;
    int row, column;
    tileMap.Index(camTopLeft, startRow, startCol);      // DEBUG: this tile has isometric coordinates
    // DEBUG: also note that the startRow and startCol may be negative if the top left corner of the camera is negative.

    startRow -= 2;                                      // DEBUG: ensure enough rows cover the screen area
    row = startRow;
    column = startCol;

    bool oddLine = false;
    for (int vertCount = 0; vertCount < maxVertCells; vertCount++) {
        for (int horizCount = 0; horizCount < maxHorizCells; horizCount++) {
            // DEBUG: ensure the tilemap row and column about to be queried are valid
            if (row < tileMap.Rows() && row >= 0 && column < tileMap.Columns() && column >= 0) {
                eTile & tile = tileMap.Index(row, column);
                eVec2 screenPoint = eVec2(
                    eMath::NearestFloat(tile.Origin().x - game.GetCamera().GetAbsBounds().x),
                    eMath::NearestFloat(tile.Origin().y - game.GetCamera().GetAbsBounds().y)
                    );
                game.GetRenderer().AddToRenderQueue(renderImage_t(screenPoint, tile.Image(), tile.Layer()));
            }
            row++; column--;
        }
        oddLine = !oddLine;
        oddLine ? startCol++ : startRow++;
        row = startRow;
        column = startCol;
    }
}

```

I hope all this gets you thinking and ideally helps solve some problems. Here's another useful answer to staggered drawing
> 1 votes

---
Tags: 2d, javascript, isometric
---


# Question
Title: Why are symbols placed in front of UI texts?
I've been to play testing sessions from both large and indie studios, and I often see a symbol in front of UI texts during development builds. It most commonly appear in buttons texts, but can also be seen in NPC names and etc.

The symbols are typically a dollar sign ($) or a exclamation sign (!).

A game at Ubisoft for example had exclamation marks in front of every UI text:

```
!Start
!Load

```

When someone breaks Skyrim by modding, a dollar sign could be seen as well:

What do these symbols mean / are used for? Placeholder? To be localized? Do the symbols used vary from studio to studio or is there a notation standard of some sort and different symbol mean different things?

Are there any reasons at all for the rest of us to adopt this?

# Answer
These are pre-localized strings, most likely.

For localization, there will be a primary identifier (like `$Spells`) that is used to look-up the correct text in a big translation table loaded depending on the active language.

These identifiers are also often used to help find the correct voice or texture for in-world elements. For instance, if a wall is supposed to show a sign texture, the wall might be painted with the texture identifier `$sign_1` which is then looked up in the translation table. If the table is set to French then `$sign_1` possibly maps to a resource path string like `/textures/localized/fr/route_dangereuse.dds` while in the English table it might map to `/texture/localized/en/dangerous_road.dds`. (Games these days are perhaps more likely to dynamically generate the text to avoid texture pack explosion, but you get the idea.)

Using the special symbols may be part of the tooling the engine uses. For instance, if the translation for `Inventory` is requested but no translation is found, the system might return a marked-up result like `##Inventory##` (or `$Inventory`) as this will make the game more usable during development but still makes untranslated text "obvious". It may also just help for any search-and-replace the developers might do for hard-coded UI strings, though that's hopefully a very rare problem in most games; this then might imply that the weird character is convention rather than a technological artifact.

Building off of @AminePaleo's answer, it's also possible that the engine has a text substitution engine that looks for certain patterns and performs the translation. e.g. `Go to $location now.` might parse out `location` as the name of an entry in the current quest. This will generally be done *after* localization though, since grammatical structure will be different between languages. So the game might have a string like `!go_to_location` which is looked up in the localization table and is `Go to $location now` in English, and then `location` is the quest's target location, whose localized English name is `Seattle`, so the final output after all stages of translation would be `Go to Seattle now.`.

Most games will keep any kind of two-stage lookup like that to a minimum, though, due to the extreme difficulty in composing natural-sounding English (much less French, German, etc.) from sentence fragments (getting the English articles - *a*, *the*, *an*, etc. - right is itself surprisingly difficult, given that the correct article changes based on both the sentence structure and the noun in question, e.g. whether it's proper, plural, definite, uncountable, etc.).
> 5 votes

# Answer
They are probably storing all String values in a single place, so to access a value by its variable name, you need to indicate that it is a variable and not the actual value.

---

You can do this by adding the sign `$`, `@` or `!`. For example, consider the following:

```
$name = "someone";
$text = "some speech";

```

We would say `"this guy" + $name + " says" + $text`, as the strings have not been implemented, yet. The output would look `"this guy someone says that speech some speech"`.

---

Note that this answer is based in theory.
> 1 votes

---
Tags: text
---


title: Make Enemies Walk Next to the Player

text:
# Question
Title: Make Enemies Walk Next to the Player
I know the A\* algorithm but if I have a long range (firing) enemy 20 metres away in 2D-land and I want it be about 3 metres away from its target (aka the player).

Is there an algorithm for choosing an appropriate path and square?

# Answer
> 3 votes
Try pathfinding to the target using A\*, then walking along the path until you are within distance.

Alternatively you could check the distance to the target as the pathfinding goal, but this might be slow due to too many distance calculations.

# Answer
> 1 votes
You could write a function that checks all tiles within the desired range of the player to see if they are moveable, then cache that tile's position. So, some pseudo code:

```
/* This SHOULD perform a backwards check
*   from the specified tile to return all walkable tiles between
*   the specified tile and all tiles the specified distance away.
*/
function GetTilesWithinDistanceOf(Tile tile, int distance) {
    var m_neighbors = new List();
    foreach(Tile neighbor in tile.neighbors) {
        if(neighbor.IsWalkable()) {
            if(distance > 1) {
                m_neighbors.AddAll(GetTilesWithinDistanceOf(neighbor, distance--));

            } else {
                m_neighbors.Add(neighbor);
            }
        }
    }
    return m_neighbors;
}

```

Then you could run a simple algorithm to determine which of those tiles has the closest location:

```
function GetClosestInList(List list, Tile closest_to){
    Tile cached = nil;
    foreach(Tile tile in list){
        if(cached == nil){
            cached = tile;
        } else if (tile.DistanceTo(closest_to) < cached.DistanceTo(closest_to)){
            cached = tile;
        }
    }
    return cached;
}

```

Then perform your main A\* pathfinding algorithm on the position:

```
AStarPathFinder finder = new AStarPathFinder(GetMap());
List tiles_near_target = GetTilesWithinDistanceOf(target, 3);
Tile optimal_tile = GetClosestInList(tiles_near_target);
List path = finder.ComputePath(GetEnemyTiles(), GetPlayerTile());

```

---
Tags: path-finding
---


title: Get width of a 2D GameObject in Unity

text:
# Question
Title: Get width of a 2D GameObject in Unity
I'm trying to get the width and height of a 2D GameObject. My GameObject is simply a prefab created using sprite.

I have tried solutions from other posts but they don't work for me:

```
Vector2 size = myGameObject.GetComponent<CircleCollider2D>().bounds.size;
float width = size.x;
float height = size.y;

```

and

```
Vector2 size = myGameObject.GetComponent<Collider2D>().bounds.size;
float width = size.x;
float height = size.y;

```

My prefab has a `Circle Collider 2D` but `x` and `y` always returns `0`

I'm using Unity 5.5.0f3, not sure if previous solutions apply to this version.

# Answer
> 3 votes
I think you should use CircleCollider2D.radius

So get the radius and multiply it by 2.

```
var size = GetComponent<CircleCollider2D>().radius;
Debug.Log(2 * size);

```

---
Tags: unity
---


# Question
Title: How to draw connecting lines in plain color?
Since there is no option for flat shading in OpenGL ES2, is there a workaround to disable the color interpolation when different color is being passed to each of the vertices?

**Update:**
I'm working with OpengGL ES 2.0 in android. I'm given with these vertices which I used to draw shapes by connecting them with lines. Now I need to change color of each of these lines individually. I tried passing a color matrix for each vertex through vertex shader to fragment shader but the color gets interpolated (which actually makes sense, since I'm giving different color to two vertices). I did some googling about that and found out glSmoothShader cannot be disabled in OpengGL ES.

Is there a way to color those lines without the colors getting interpolated?

Or is there a way to use multiple triangles to draw a line between two vertices that way i can flat color each of those triangles.

# Answer
OpenGL ES does not support the `flat` keyword that is designed for that. There is currently no way to stop interpolating the fragments other than change your vertices to just use the same values on each vertex. That doesn't really stop the interpolation, but does achieve what you want for the end result.

You are not specifying how you are rendering your lines. If you are rendering them as GL\_LINES then just apply the same color value on each line vertex. If you are using GL\_LINESTRIP or GL\_LINELOOP and are stuck with that, just add additional vertex to where you want the color gradient not happen.
> 1 votes

---
Tags: shaders, opengl-es2, fragment-shader
---


# Question
Title: How to determine contact bodies when multiple bodies overlap and a third makes contact with both at the same time
I understand how the below DidBeginConact function works, but how do you detect which categories make contact when you have multiple colored bars (in the example code) or a friend category and enemy category when an enemy overlaps a friend or two enemies overlap and a projectile category intersects both at the same time?

func didBeginContact(contact: SKPhysicsContact) {

```
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
    firstBody = contact.bodyA
    secondBody = contact.bodyB
} else {
    firstBody = contact.bodyB
    secondBody = contact.bodyA
}

if firstBody.categoryBitMask == RedBallCategory &&
   secondBody.categoryBitMask == GreenBarCategory {

    (secondBody.node!.removeFromParent())
    score++
    scoreLabel.text = "\(score)"
} else if firstBody.categoryBitMask == GreenBallCategory &&
          secondBody.categoryBitMask == RedBarCategory {

    (secondBody.node!.removeFromParent())
    score++
    scoreLabel.text = "\(score)"
}

```

I've tried so many different combinations I can't keep them all straight or remember what I've tried and what I haven't.

Thanks in advance for help and suggestions in this.

# Answer
I'm not really a fan of this :

```
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
    firstBody = contact.bodyA
    secondBody = contact.bodyB
} else {
    firstBody = contact.bodyB
    secondBody = contact.bodyA
}

```

and prefer to do the following:

```
        let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch contactMask {
        // Redball and GreenBar have contacted
        case RedBallCategory | GreenBarCategory :
           score += 1       // ++ is deprecated
           scoreLabel.text = "\(score)"

           // Remove GreenBar
           let GreenBar = contact.bodyA.categoryBitMask == GreenBarCategory ? contact.bodyA.node! : contact.bodyB.node!
           GreenBar.removeFromParent

        // Greenball and RedBar have contacted
        case GreenBallCategory | RedBarCategory :
           score += 1       // ++ is deprecated
           scoreLabel.text = "\(score)"

           // Remove RedBar
           let RedBar = contact.bodyA.categoryBitMask == RedBarCategory ? contact.bodyA.node! : contact.bodyB.node!
           RedBar.removeFromParent

       default :
         //Some other contact has occurred
       }

```

You can just add as many `RedBallCategory | GreenBarCategory` cases as you need for all the contacts that you have to take action for in your game. Code each potential contact individually and you won't loose yourself in if...then...else
> 3 votes

# Answer
Here is what worked best for my latest project based on Steve's answer, please note though this is using c++ and the cocos2dx framework:

```
PhysicsBody *a = contact.getShapeA()->getBody();
PhysicsBody *b = contact.getShapeB()->getBody();

int contactMask = a->getCategoryBitmask() | b->getCategoryBitmask();
switch (contactMask)
{
case PhysicsMasks::kInvaderCategory | PhysicsMasks::kShipFiredBulletCategory:
{
    Invader* invader = dynamic_cast<Invader*>(a->getNode()) ?
        dynamic_cast<Invader*>(a->getNode()) : dynamic_cast<Invader*>(b->getNode());

    Bullet* bullet = dynamic_cast<Bullet*>(a->getNode()) ?
        dynamic_cast<Bullet*>(a->getNode()) : dynamic_cast<Bullet*>(b->getNode());

    if (bullet && invader) {
        invaderDied(invader, bullet);
    }
}
break;
default:
    break;
}

```

Where the PhysicsMask are declared like this:

```
struct PhysicsMasks {
    static const int kInvaderCategory = 0x0001;
    static const int kShipFiredBulletCategory = 0x0002;
};

const PhysicsMasks physicsMasks{};

```
> 1 votes

---
Tags: collision-detection, ios, spritekit
---


# Question
Title: Please help me find the error in a pygame code for Tetris?
I am creating a Tetris game using Pygame. However, instead of calling a single shape, but code calls all the functions for the shapes randomly one after the other. I tried calling `NewShape` at different places, but nothings working. If it calls a single shape, then the keyboard control does not work.

```
x=50
y=50
def ShapeL(screen,x,y):
    pygame.draw.rect(screen, Cyan, [x,y-50,50,150])
    pygame.draw.line (screen,Cyan, [x, y], [x+50,y])
    pygame.draw.line (screen,Cyan, [x, y+50], [x+50,y+50])
    pygame.draw.line (screen,Cyan, [x, y+100], [x+50,y+100])
    pygame.draw.rect(screen, Cyan, [x+50,y+50 ,50,50])

ShapeChosen=False
def NewShape(screen,x,y):
    ListShapes=[ShapeS, ShapeT, ShapeL, ShapeI, ShapeSquare]
    Shape=random.choice(ListShapes)(screen,x,y)#chooses random shape
    ShapeChosen=True

def BasicGame(x,y):
    Done=False
    while not Done and y!=500 and ShapeChosen!=True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Done=True
            elif event.type == pygame.KEYDOWN:
                if event.key ==pygame.K_LEFT:
                    x=x-50
                elif event.key==pygame.K_RIGHT:
                    x=x+50
                elif event.key==pygame.K_DOWN:
                    y=y+50
                elif event.key==pygame.K_SPACE:
                    y=500
            if x==0:#Borders so the shape doesn't leave the screen.
                x=50
            elif x==400:
                x=350
            if y==550:
                y=500
    screen.fill(White)
    NewShape(screen,x,y)

```

I tried passing the parameter `ShapeChosen` to the function, however, it did not work as well. I tried passing `global ShapeChosen`, but it prevents the keyboard functions from working.

# Answer
> 1 votes
You definitely want to modify your `NewShape` function so that it modifies the global variable `ShapeChosen` instead of creating a new global one.

```
ShapeChosen=False
def NewShape(screen,x,y):
    global ShapeChosen
    ListShapes=[ShapeS, ShapeT, ShapeL, ShapeI, ShapeSquare]
    Shape=random.choice(ListShapes)(screen,x,y)#chooses random shape
    ShapeChosen=True

```

Now, you mentioned that if you do so, the keyboard input stops working. I'm not really sure how you've planned your code to work here, but the line

```
while not Done and y!=500 and ShapeChosen!=True:

```

is obviously the issue, because the while-loop should stop as soon as `ShapeChosen` becomes true. I can't tell what your intention here is, but perhaps you would like to move the `ShapeChosen`-condition just above the call to `NewShape`? Something along the lines of

```
if not ShapeChosen:
    NewShape(screen, x, y)

```

---
Tags: python, pygame
---


# Question
Title: TLS Allocator ALLOC_TEMP_THREAD error using "Fireworks" and "Explosion" particle systems in Unity 5.5
I receive a `TLS Allocator ALLOC_TEMP_THREAD` error whenever I add certain prefab particle system assets, such as "Fireworks" and "Explosion", to my scene.

---

It also generates a huge amount of log messages, such as

> Allocation of 752 bytes at 0524a60f
> Allocation of 22960 bytes at 0542a6f0
> ...

It also creates a huge amount of lag and, severely drops the frame rate.

---

Particle systems like "Flare", "Dust Storm" and "AfterBurner" work as expected. The individual simulation of the child particle systems in the "Explosion" and "Fire" prefabs worked perfectly in the scene view, but the same prefabs simulate weirdly in the game.

---

I am using Unity 5.5, and this error should have been fixed in 5.4.0 b23, but apparently it has not. How do I fix these issues?

# Answer
> 1 votes
We are working on a fix for this issue. You can track it here: https://issuetracker.unity3d.com/issues/tls-allocator-alloc-temp-thread-error-caused-by-particle-systems

Having the same sub emitter used at 2 or more different levels of the hierarchy causes it.

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


# Question
Title: Raycast will not hit generated box colliders at initialization
In my map class I have an algorithm that is generating and merging box colliders together. These belong to the layer "Ground".

After that, in some places on my map I'm generating some new cubes on-the-fly, and some of these cubes I don't want to generate at all. So, I'm doing a raycast to determine if they should be added or not.

I'm doing these raycasts to check if the position they should be generated at have free space to the left and right. For both rays I'm checking if they hit a collider beloning to the layer "Ground".

But I don't get a hit at all!

I've tried to create two cubes in the editor and assign them to the layer "Ground". If I run the game then I get a hit between these two cubes. But I will never get a hit checking against my generated colliders.

I do this logic in the Start-method, is there any certain method in the life cycle when I can start to use my generated box colliders?

# Answer
Assuming you're trying to coordinate the `Start()` method of various scripts, you can ensure they execute in the order you want by going into the menu at `Edit > Project Settings > Script Execution Order`.

Just make sure your box collider script is running before the raycast script and you should be good to go!

From Unity's official documentation:

> Scripts can be added to the inspector using the Plus “+” button and dragged to change their relative order. Note that it is possible to drag a script either above or below the Default Time bar; those above will execute ahead of the default time while those below will execute after. The ordering of scripts in the dialog from top to bottom determines their execution order. All scripts not in the dialog execute in the default time slot in arbitrary order.
>
> The numbers shown for each script are the values the scripts are actually ordered by. When a script is dragged to a new position, the number for the script is automatically changed accordingly. When a number is changed, either manually or automatically, it changes the meta file for that script. For this reason it’s best if as few of the numbers as possible change when the order is changed. This is why, when possible, only the script that is dragged has its number changed, rather than assigning new numbers to all the scripts.
> 1 votes

# Answer
I had the same problem with a character collider; it used to miss collisions with objects. I found out that it was caused by a bug that has not been fixed, as of Unity 5.5.

---

The fix was simple. I added a capsule collider, and continuously checked for collision using `OnTriggerStay()`.
> 0 votes

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


# Question
Title: (Pacman) Loading 151 dots (picturebox) in form. What's the easy way?
I'm making pacman clone for school project and I'm having a bit of a struggle with loading dots into the map. I want to put 151 dots (`picturebox`) onto a map to a specific location, so that later on I could check if there is collision between Pacman and dots using function `intersectWith`.

I feel like this isn't really the most friendly way of doing it, but currently I don't have any other idea.

So, how does one put many `picturebox` on a form (if there is a way), and put them in array where I could check for intersection.

This is just some brief, probably wrong code, how I'm imagining this to work:

```
for(int i = 0; i < 151; ++i)
{
    dot[i] = Resources.dot;
    drawingArea.Load(dot[i]);
}

```

Thank you all!

# Answer
> 1 votes
The short answer is that I think your code is on the right track, although knowing PACMAN I don't think you'll be able to set the positions in a loop because they're not based on a predictable pattern- you'll probably need to set them individually. One way to handle this would be to store the "level" information in a file and then loop through it to create the dots. C# isn't my first language, but the pseudo-code would look something like this:

Imagine our file looks like this: (Super small level for this example)

```
0000000
0223220
1200021
0224220
0000000

```

0 = wall, 1 = clear path, 2 = dot, 3 = ghost start, 4 = PACMAN start. You could then create your map based on the following pseudo-code:

```
string rawRows = System.file.io.ReadAllLines("some/path/to/file"); // See Article #1
for(int row = 0; row < rawRows.length; row++) { // Loop row by row (line by line)
  for(int column = 0; column < rawRows[row].length; column++) {
    switch(rawRows[row][column]) {
      case 0:
        // Add wall
      case 1:
        // Add Clear Path Image
      case 2:
        // Add Clear Path Image
        // Add Dot Image on Top
      case 3:
        // Add Clear Path Image
        // Add Ghost
      case 4:
        // Add Clear Path Image
        // Add PACMAN
      }
    }
  }
}

```

Article #1

When you add a Dot to your game, you could put them in an array like you said, so that you can loop through it and see how many dots are remaining.

---

The better answer is that you probably shouldn't be trying to use forms and pictureboxes at all to make a game- they're not intended for this purpose, and they'll be clunky (My first game was "Checkers" using VB Forms). If your class permits it, and you're willing to put in the time and effort to learn, I recommend you look into a game framework (like MonoGame) to create your game with. It'll have a steeper learning curve, but it will allow you to make a much better game overall.

---
Tags: c#
---


# Question
Title: How PhysicsBodyLoader.SCALE of overlap2d runtime works?
What is the purpose of that method is and when I have to use it? Really I have no idea. I also found the source code but that didn't help me much.

# Answer
From looking at the source code, it appears to be used to help translate between "pixel units" and "world units".

\[EDIT\] \[Xoppa's article\] explains it rather well, but "pixel units" is the number of pixels in your viewport. "world units" is what your game is actually measured in.

For example, suppose you have a table that is 1 meter (world unit) high. If it's far away, you may render it 10 pixels high; if you are closer it may be 100 pixels high. Moving closer changed how big you *perceived it to be*, and thus changed its pixel size, but didn't change how big it really was (its world unit size).

By default in vanilla libGDX these values are 1:1, but it is useful to keep them logically separate because that way you can change your display size without worrying about messing up your game height. If I know the chair is 1m high, I know a character who can jump 2m can jump over it regardless of how big I draw the character and the chair.

There are occasions where you might need to convert between the two (e.g. raycasting), and I imagine that is when scale would come in handy.
> 1 votes

---
Tags: java, libgdx, overlap2d
---


# Question
Title: Best way to draw a textfield in OpenGL, when performance really matters?
I'am creating my own GUI library in LWJGL (opengl for Java). I already managed in creating buttons and panels, and I've also got the *hover* and *active* states of the components implemented. This question is about finding a fast way to render a complex component. **The library should be very performant**!

So I pre-render everything I can, before the gameloop starts. I also want to decrease the use of VBO's, triangles, and textures to render a single component. My approach for creating a button is: pre-render the button appearance using a java Graphics object and put the drawing in a *Power Of Two* sized BufferedImage. That image is the texture.

Then I've got a *FilledRectangle* class. That class gets a BufferedImage (the texture) and an x, y, width and height. The class creates a VBO that just renders the Button. For the *hover* state and *active* state, I really do the exact same thing, except that there is another drawing made with the Graphics object. So I just create another VBO for each state.

When it comes to rendering components that change their appearance, I can't pre-render too much. I want to create a *TextField*. Now I pre-render the background (the box of the textfield). And I also pre-render the cursor. The text has to be rendered during the game, and I have the following options:

* Rendering the text using a Graphics object from the java graphics.
* Pre-render a spritesheet (a character map) with all characters on it in a specific font, and then use that texture to create a new VBO for every time the text changes. Note that the box of the component and the cursor are seperate VBO's so, when the text changes, I only have to deal with text rendering in a fast way.

My questions

* It's very easy for me to draw things using a java Graphics object, but isn't this too slow when I have to use this during the gameloop?
* Is it OK to recreate a VBO for every visible change?

# Answer
> Is it OK to recreate a VBO for every visible change?

No, this is never OK.

Creating (and destroying) GPU objects at runtime will absolutely kill your performance, and that's on top of the huge amount of state changes you'll need with your current approach. I do understand the appeal of having everything you need to draw nicely encapsulated, but that's not how you're going to run fast.

Drawing text (or other 2D GUI widgets) is a well-understood and long-solved problem; you need to do some research on **sprite batching**. Some quick Googling turns up this, for example, which may be a useful place to start.
> 1 votes

---
Tags: opengl, performance, lwjgl, gui, vbo
---


# Question
Title: Using Unity as a front-end GUI for a non-unity application?
I'm working on a game right now that is 2D, and grid based, and for a variety of reasons have decided making it in Unity wouldn't be worth the hassle I'd have fighting the engine.

That said, I want to possibly add in VR support at some point, and Unity seems the easiest way to make that happen. Right now, the game is structured so that part of the code takes in a grid from the game-core, and that grid tells it what sprite(s) to stick in each spot on said grid.

My thought was that it might be possible to replace the "take grid array, render sprite-grid" portion of my game with a Unity front-end. For example, perhaps this would be like a board game sitting on a table, and rather than a 2D grid, the "sprites" would be simple models on the grid-board, with the user looking down at it in VR.

Is this a thing that is possible? Essentially, all I would need is for my Unity program to take inputs, and send trigger signals to the game-core, then receive an updated grid-array and respond accordingly. I've not been able to find any information on this kind of thing, interfacing Unity with an external program in this way. The game is turn based, so 2-3 updates per second would be the absolute max I'd need, performance-wise, and the game core could run on a potato.

In specific: can Unity send triggers to and receive a data array from an external binary (written in c#), and how would I do this?

I really hope this is possible.

# Answer
Some real games actually take this game logic and render separation approach that you are mentioning. I know that the ARMA games do it. You can always communicate via TCP with your 'game logic server' if its on the same PC it might be fast enough for board games.

Of course this is quite a convoluted approach. You might wish to make a small prototype to see if its worth it.

(Also the term GUI might not really apply here)
> 2 votes

# Answer
I don't know whether or not this is possible, but regardless this wouldn't really address your use case anyway. VR is a hell of a lot more than just the GUI, so using Unity just for the GUI wouldn't help you any as far as converting the game to VR. If that is at all likely to happen in the future, you are best building your game in Unity from the start, since there isn't really a distinction between 2D and 3D graphics in Unity.
> 0 votes

---
Tags: unity, c#, software-engineering
---


# Question
Title: Unity Navigation & Pathfinding and A star algorithm
I just tried to follow a tough **tutorial about A\* path finding in Unity C#**. I have also tried Unity own Navigation & Pathfinding system which is actually quite easy to understand and implement. I am willing to know it that how NavMesh system of unity actually works. Do it also implement the A\* algorithm. Further I want to ask that how does A\* algorith will work with slope. I implement A\* with plane where is no slope.

# Answer
> 1 votes
Here is how a computer will see an a star path find:

As you see, it is just a graph of nodes with certain neighbors. Between each neighbor, there is a "distance", or weight, that connects the two nodes. The algorithm finds a rout between nodes that will have, when all of the path lengths are added up, the smallest possible number.

If you look at a navmesh, all it does is separate the map into a lot of triangles. Every touching triangle represents a neighbor, and the dist between the two neighbors is most likely the distance between each triangle's center point, but there might be other algorithms. And, using this graph, it probably uses a star, maybe with performance optimizations. See here for more info.

On a grid, like the ones you saw in the video, the nodes are the tiles, and the distance is just 1 unit for adjacent and about 1.4 units for diagonal.

Going back to your slope, if you want the agent to be slower on it, then artificially make the number between the nodes larger like:

```
if (nieghbor has to much of a y-value difference):
    neighbor_cost *= 5

```

For more info on artificially changing the distance between nodes, click here.

Hope this helps. Ask me if you need any more info! =D

---
Tags: unity, c#, path-finding
---


# Question
Title: Creating a space game. Need help with a solution for creating dynamic spiral graphics
My friend and I are working on a web based game where we want to have a blackhole-like thing rendered in some form of an engine or 3D program for us to freely manipulate adding more "arms" making it smaller or bigger and playing around with its light.

Here's a picture of our concept of the graphic element:

(smaller black hole:)

(larger black hole:)

We want help to find the best possible solution for this, and possible also some kind on guide to create these elements. So far everything is designed in photoshop but if we want the hole to be dynamic we can't use pictures.

# Answer
> 1 votes
Arcane Engineer mentions using a pixel shader to create this type of spiral effect. That would be how I'd approach it too. You could either run the shader once and output the result to a texture, or simply use the shader to render your black hole quads at runtime.

Here's an example of a pixel shader that performs this kind of spiral effect:

```
fixed4 spiral (v2f i) : SV_Target
{
    // Convert UV coordinates from range (0...1)
    // to (-1...1) with (0, 0) in the center.
    i.uv = i.uv * 2.0f - 1.0f;

    // Convert to polar coordinates.
    float angle = atan2(i.uv.y, i.uv.x);
    float radius = length(i.uv);

    // Create a value that varies from 1 (normal falloff in the arms)
    // to 2 * _ArmSharpness (accelerated falloff in the gaps between).
    float armBias = (sin(angle * _ArmCount + radius * _Twist) + 1.0f) * _ArmSharpness;

    // Use this to bias our lookup value, which falls off with radius.
    float lookup = saturate(1.0f - radius * (armBias + 1.0f));

    // You could use this lookup to sample a gradient texture...
    // fixed4 col = tex2D(_MainTex, lookup);

    // But here I'll just use it to calculate a purple-ish gradient:
    return float4(lookup * lookup, 3.0f * lookup - 2.0f, lookup, 1.0);
}

```

This exposes three parameters to control the look:

You can perform a second processing step to overlay the dark hole in the center, or build it into the same formula, whichever you prefer. I've left that part out to focus on the spiral aspect here.

If you're not using a 3D graphics API, you can also manually construct a texture by running a function like the one above to compute each pixel's colour value.

# Answer
> 0 votes
Create a circle with say 2 triangular arms pointing straight outward. Say this sits exactly inside a 256x256 texture (i.e. outer radius 128, and inner radius - i.e. radius of the solid disc - of 64). This you can do in code very easily so I will not go into it, here.

Now to create a spiral effect. If you google images of a water vortex, you will note that the area of least transformation is at the outer edge, because the force applied is lowest there. As you get in toward the centre, there is more torsion and thus more deformation.

```
texDimensions = (256, 256)
centre = texDimensions / 2
rMax = outer radius //128 to start, for a 256x256 image as noted above
rMin = disc radius //the radius of your galactic disc without arms, say 64

for each pixel
    dist = maxRadius - currentPixelRadius
    apply a 2D [rotation transform][1] dist * k radians.

```

So, depending on the exact radial distance of current pixel from centre, we rotate by some amount; this is more toward the centre, less toward the outer edge.

You can adapt the arm count, amount of rotation (via `k`) etc. How much torsion you want may be influenced by the number of arms, from a "looks good" perspective.

P.S. As this is a once-off process and you likely cache the result for all future use, don't worry over cost, just do it in the loading phase. Else use a pixel or compute shader to do it on the fly / in realtime.

---
Tags: graphic-effects
---


# Question
Title: Unity - Easier way to resize group of buttons to the same size
I have a canvas with buttons, with a script attached to each button. This script creates an array for buttons and resizes every button to the same size as the longest one in that array (the button with the longest line of text in it). Everything works, but I was wondering: is there is an easier, more automatic way for this instead of having to drag every button in every array in the Inspector tab?

Any ideas would be greatly appreciated

UnityPackage: https://transfer.sh/6BCDG/buttonwidth.unitypackage

```
public Image[] otherbutton;

void Start () {

    for(int i = 0; i < otherbutton.Length; i++)
    {

        if (otherbutton[i].rectTransform.sizeDelta.x > gameObject.GetComponent<Image>().rectTransform.sizeDelta.x)
        {
            gameObject.GetComponent<ContentSizeFitter> ().enabled = false;

            gameObject.GetComponent<Image>().rectTransform.sizeDelta = new Vector2( otherbutton[i].rectTransform.sizeDelta.x, otherbutton[i].rectTransform.sizeDelta.y);

        }
    }
}

```

# Answer
> 1 votes
Using a layout group would be ideal, but if for some reason that doesn't work with what you're doing you can populate your button array by simply creating a public variable that you place the parent of the buttons in, using the inspector, and then getting the children on start. The code would look something like this:

```
public Transform parentOfButtons;

private Image[] otherbutton;

void Start()
{
    otherbutton = new Image[parentOfButtons.childCount];
    for (int i = 0; i < parentOfButtons.childCount; i++)
    {
        otherbutton[i] = parentOfButtons.GetChild(i).GetComponent<Image>();
        if (otherbutton[i].rectTransform.sizeDelta.x > gameObject.GetComponent<Image>().rectTransform.sizeDelta.x)
        {
            gameObject.GetComponent<ContentSizeFitter>().enabled = false;

            gameObject.GetComponent<Image>().rectTransform.sizeDelta = new Vector2(otherbutton[i].rectTransform.sizeDelta.x, otherbutton[i].rectTransform.sizeDelta.y);

        }
    }
}

```

# Answer
> 0 votes
*Maybe more a long comment than an answer*

I would improve your code by first creating all the buttons, then search for the maxWidth, store it, and resize all the buttons accordingly.

It seems to me than now you are resizing your buttons too many times, for example if you have 4 buttons, sizing {100px, 120px, 140px, 80px}, when you create the 4th button now you are resizing it 3 times.

# Answer
> 0 votes
Are the buttons supposed to appear right below each other?

Then put your buttons into a Vertical Layout Group and switch on "Child Force Expand". They will then be automatically enlarged to fit the layout group. No scripting required.

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


# Question
Title: How do professional games avoid showing pixel seams in adjacent mesh boundaries due to decimal imprecision?
Graphics cards are mathematically imprecise.

So when some meshes are joined by their borders, the graphics card often makes mistakes and decides that some pixels at the seam represent neither object, and unwanted pixels appear.

It's a natural behaviour on all graphics cards. How are such worries avoided in Pro Games? Batching? Shaders? Different tangent vectors? Merging? Overlaping seams? Dark backgrounds? Extra vertices at borders? Z precision? Camera distance tweaks?

Screencap of a fix that ended up not working:

# Answer
Modern graphics APIs are very careful about specifying how rasterization of triangles that share edges will be done in order to avoid overlapping fragments and missing fragments.

Fabien Giesen mentions one of these rules in his article series on the graphics pipeline, cited here:

> you need to have tie-breaking rules to ensure that for any pair of triangles sharing an edge, no pixel near that edge will ever be skipped or rasterized twice. D3D and OpenGL both use the so-called “top-left” fill rule; the details are explained in the respective manuals. I won’t talk about it here except to note that with this kind of integer rasterizer, it boils down to subtracting 1 from the constant term on some edges during triangle setup. That makes it guaranteed watertight, no fuss at all

An example is Direct3D 10's Rasterization Rules documented in public on MSDN.

This requires that your vertices (and thus edges) are exactly coinciding which is not a problem inside individual meshes and terrain chunks.

When it comes to the XZ grid of terrain chunks, you can often organize your computation of grid positions such that they perfectly agree when you move chunks around. When transitioning between LoD levels, most techniques apply skirts or a spreading-out pattern along the edges to avoid T-junctions and the interpolation differences those have.

You may want to reconsider the use of terms like 'mistakes' and 'imprecise'. They do exactly what they're told, and floating point arithmetic rules are deterministic. Misuse, operation ordering or misspecification of what you tolerate is what causes problems, not spurious cosmic rays that mutate results.
> 11 votes

# Answer
In my case the seam imprecision increased with distance from origin.

Because the further an object is from origin, the bigger mistakes occur in single precision floating point maths, obj positions are rounded and sent to graphics card, and their vertices are different in graphics card, even if they are whole numers and mathematically and logically the same...

If you keep all objects on origin, and instead you reassign the VERTEX POSITIONS to new positions, all the vertices in the graphics card will be the same because no different roundings from different obj positions: all obj positions and mesh positions to the graphics will be the same and there will be no errors.
> 0 votes

---
Tags: vertex, gpu, mesh, seams
---


title: Why does a unit vector show direction?

text:
# Question
Title: Why does a unit vector show direction?
If I have two objects, Person A and Person B, and I want to know if Person B is facing the same direction as Person A; once I have the vectors, how do I use the normalized vector to show direction?

---

I've read the math on vectors, but I'm still learning, and I am not understanding how the unit vector shows direction. I know it does, but I don't know why.

One person said they imagine it on the unit circle. I understand how that can show a direction, but what I don't understand is how the normalized vector shows me a direction.

I have seen "What is a direction vector and why should it be normalized?", but I am still missing it.

# Answer
> 11 votes
First we get a vector from B to A, as in the following picture:

Now we have a vector that tells us how to get exactly from B to A. In code it looks something along these lines:

```
var BtoA = A - B;

```

In the above image's case, the resulting vector is `X:15` `Y:-20`. At this point we actually already know the direction, as it is included in the information of how to get from B to A. Then if we need to know just the direction, we get that by normalizing the vector we have:

```
var direction = normalize(BtoA);

```

Normalizing a vector does this to it:

```
vec2 normalize(vec2 v)
{
    return v / sqrt(v.x * v.x + v.y * v.y);
}

```

To break it down, first we get the length (aka magnitude) of the vector by Pythagorean theorem which you probably have learned at school. After we have the length of the vector, we divide the original vector by it's own length to make it a unit vector. In other words, we reduce the length of `BtoA` into just one, which makes it an unit vector.

Now we have a direction vector that looks like this:

And the resulting unit vector is `X:0.6` `Y:-0.8`. If you want to make sure, you can check it's length, which should be 1:

```
var v = vec2(0.6, -0.8);
var length = sqrt(v.x * v.x + v.y * v.y);
print(length); // Should print 1

```

Now at this point, the unit vector we got from normalizing the BtoA vector is now just pointing at the direction of A from the point of B.

**Basically we have only reduced the length of the BtoA vector to 1, which is why it is just pointing at the direction of A from the viewpoint of B.**

And then as you asked, how to figure out if person B is facing at the same direction of person A, you need to know the orientation of person B and A. You don't get that just by calculating the direction to A from B.

The orientation is found by first figuring out the orientation vector of B, which you can calculate if you have the rotation angle of B:

```
var rotation = 1.5708; // 90 degrees in radians, radians are easier in code
var orientationVec = vec2(sin(rotation), cos(rotation));

```

Now the orientation vector should be `X:0` `Y:1`, because it is in 90 degree angle. Now that we have the orientation of B, we can check if it is facing A by checking the dot product:

```
var facing = dot(direction, orientationVec);
if(facing > 0)
    print("Yes, the B vector is roughly facing A");

```

What is a dot product then? It looks like this:

```
float dot(vec2 a, vec2 b)
{
    return a.x * b.x + a.y * b.y;
}

```

The dot product has a property of telling if two unit vectors are in parallel, and if not how much they differ. If the dot product is 1, the two unit vectors are pointing exactly at the same direction. If it is 0, the unit vectors are perpendicular to each other. So any values above 0 means that the unit vectors are going in roughly the same direction.

Of course using 0 as a threshold for determining if B is facing A is a bit wrong here, as you are talking about a person. If you define that a person is facing the other when the orientation towards the other is in 90 degree range, you can just check if the facing value is more than 0.5, which probably gives better results. You can also define that a person is facing another only when they are exactly looking at the other, which then requires you to use a value very close to 1.

So to put it all together:

```
bool IsBFacingA(vec2 A, vec2 B, float bRotation, float tolerance)
{
    var BtoA = A - B;
    var dir = normalize(BtoA);
    var orientation = vec2(sin(bRotation), cos(bRotation));
    var facing = dot(dir, orientation);
    return facing >= tolerance;
}

```

Now you can tell if B is facing A. It requires a bit more than just the normalized direction from B to A.

But this still does not answer your question.

You can use all that information to determine if A and B are facing the same direction, by getting the orientation of both A and B and comparing them with the dot product. Like this:

```
bool IsBFacingTheSameDirectionAsA(float aRotation, float bRotation, float tolerance)
{
    var aOrientation = vec2(sin(aRotation), cos(aRotation));
    var bOrientation = vec2(sin(bRotation), cos(bRotation));
    var facing = dot(aOrientation , bOrientation );
    return facing >= tolerance;
}

```

And there you go, that is how you determine if A and B are facing the same direction.

---
Tags: vector, linear-algebra, direction
---


title: Binding tiles with Rect

text:
# Question
Title: Binding tiles with Rect
I'm having trouble binding tiles with `Rect`. I've successfully bound other objects (such as the player, trees, etc) in my game with rectangles but I'm unable to do the same with the tiles and I don't know where I'm going wrong. Here's my tile class:

```
public class Tile {
    private float x, y;
    private int type;
    private static int VelX;
    private static int tileSpeed = -200;
    private static Rect tileRect;
    public Bitmap tileImage;

    public Tile (float x, float y, int typeInt) {
        this.x = x * 50;
        this.y = y * 50;
        type = typeInt;
        tileRect = new Rect();

        if (type == 2) {
            tileImage = Assets.grass;
        } else if (type == 1) {
            tileImage = Assets.dirt;
        }
    }

    public void update(float delta) {
        x += VelX * delta;
        tileRect.set((int) x, (int) y, (int) x + 50, (int) y + 50);
    }

    public static void accel() {
        VelX = tileSpeed;
    }

    public static void stop() {
        VelX = 0;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

    public int getType() {
        return type;
    }

    public static Rect getTileRect() {
        return tileRect;
    }

    public Bitmap getTileImage() {
        return tileImage;
    }
}

```

# Answer
Try it using as **non-static** variable:

```
private Rect tileRect;
//...
public Rect getTileRect()
{
    return tileRect;
}

```
> 0 votes

# Answer
I see two things which are probably causing you trouble here.

When you call .set on the rectangle the numbers you enter are used as X position, Y position, width and height. Right now it looks like you are using them like they would represent the other corner of the rectangle.

```
tileRect.set(x, y, 50, 50);

```

This is probably what you are meaning to do.

It's also possible to do this right as you create the rectangle.

```
    tileRect = new Rect(x, y, 50, 50);

```

Also, the rectangle in your code is static, which means that every instance of the class Tile that you make, share the same rectangle. Obviously this will cause problem if you are going to use the class to display several tiles.

You might also not want to set the tiles size in the update method, since that will probably be called every frame, unless you intend to move the tile, in which case you can use:

```
tileRect.setPosition(x, y);

```

That way you don't have to set the size, but only the position.
> 0 votes

---
Tags: java, android
---


title: GLFW3 multiple windows

text:
# Question
Title: GLFW3 multiple windows
I'm trying to use GLFW3 to develop VJing application. So basic idea is use two windows:

1st window for fullscreen projection on secondary monitor (basically projector)

2nd window for (hopefully) fullscreen GUI.

It does not have to share context, as GUI window will be just using libRocket for controlling content, recieving MIDI & OSC commands, etc.

Problem is that so far, when I switch projection window on second monitor to fullscreen, it runs, but as soon as I move mouse to primary monitor and click somewhere, projection window gets minimized. Also, GUI window gets a poor framerate.

```
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <GLFW/glfw3.h>

using namespace std;

void errorCallback(int error, const char *description){
fputs(description, stderr);
}

static void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods){
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
{
    glfwSetWindowShouldClose(window, GL_TRUE);
}
}

int main(){

glfwSetErrorCallback(errorCallback);
if (!glfwInit())
{
    exit(EXIT_FAILURE);
}

int MonitorCount;
GLFWmonitor ** monitors = glfwGetMonitors(&MonitorCount);

//GLFWvidmode* modes = glfwGetVideoModes(monitors, &MonitorCount);

GLFWwindow *window;
window = glfwCreateWindow(1024, 768,"Projection", monitors[0], NULL);
GLFWwindow *controls;
controls = glfwCreateWindow(1024, 768, "Controls", glfwGetPrimaryMonitor(), NULL);

glfwSetKeyCallback(window, keyCallback);
while(!glfwWindowShouldClose(window)){

     //// PROJECTION WINDOW
    glfwMakeContextCurrent(window);

    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    ratio = width / (float) height;
    glViewport(0,0, width, height);
    glClear(GL_COLOR_BUFFER_BIT);

      glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
    glBegin(GL_TRIANGLES);
    glColor3f(1.f, 0.f, 0.f);
    glVertex3f(-0.6f, -0.4f, 0.f);
    glColor3f(0.f, 1.f, 0.f);
    glVertex3f(0.6f, -0.4f, 0.f);
    glColor3f(0.f, 0.f, 1.f);
    glVertex3f(0.f, 0.6f, 0.f);
    glEnd();

    //// ---- CONTROL WINDOW ----
    glfwMakeContextCurrent(controls);
    glfwGetFramebufferSize(controls, &width, &height);
    ratio = width / (float) height;
    glViewport(0,0, width, height);
    glClear(GL_COLOR_BUFFER_BIT);

          glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef((float) glfwGetTime() * 100.f, 0.f, 0.f, 1.f);
    glBegin(GL_TRIANGLES);
    glColor3f(0.f, 0.f, 0.f);
    glVertex3f(-0.6f, -0.4f, 0.f);
    glColor3f(0.f, 1.f, 0.f);
    glVertex3f(0.6f, -0.4f, 0.f);
    glColor3f(0.f, 0.f, 1.f);
    glVertex3f(0.f, 0.6f, 0.f);
    glEnd();

    glfwSwapBuffers(controls);
    glfwSwapBuffers(window);

    glfwPollEvents();
}

glfwDestroyWindow(controls);
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);

}

```

I'm on Win7 / VS2012 using nVidia 680m

# Answer
> 1 votes
Set the GLFW\_AUTO\_ICONIFY window hint to false to disable automatic iconification of full screen windows.

---
Tags: glfw, window-management
---