title: OpenGL texture won't draw

text:
# Question
Title: OpenGL texture won't draw
I'm sorry for asking such a common question, yet all of the other answers have not been very applicable to my problem. In short, I have begun learning OpenGL, and have started trying to draw the mandelbrot set as a small exercise. All of the pixel data is stored in a vector (I checked with GDB), yet for some reason when I transfer it into a texture and then draw it it does not work. To draw the texture I created a class called DrawBuffer, which handles all the OpenGL.

Any insight onto why this may be happening would be appreciated.

# Fragment Shader

```
#version 150

in vec2 Tex_coord;

out vec4 outColor;

uniform sampler2D tex;

void main() {
    outColor = texture(tex, Tex_coord);
}

```

# Vertex Shader

```
#version 150

in vec2 position;
in vec2 tex_coord;

out vec2 Tex_coord;

void main() {
    gl_Position = vec4(position, 0.0, 1.0);
    Tex_coord = tex_coord;
}

```

# DrawBuffer.cpp

```
#include "Draw_Buffer.h"
#include <memory>
#include <algorithm>
#include <stdexcept>
#include <vector>
#include <sstream>
#include <fstream>
#include <string>

// Util function to compile a shader from source
void compile_shader(GLuint &shader, const std::string &src) {
    std::ifstream is(src);
    std::string code;

    std::string temp_str;
    while (std::getline(is, temp_str)) {
        code += temp_str + '\n';
    }

    const char *c_code = code.c_str();
    glShaderSource(shader, 1, &c_code, NULL);
    glCompileShader(shader);
}

Draw_Buffer::Draw_Buffer(Window<int> *win, const std::string &vertex_shader_src, const std::string &frag_shader_src) :
        window(win), buffer(std::vector<RGB>(window->size())), pos_iter(buffer.begin()) {
// Initialise GLFW
    if (!glfwInit()) {
        throw std::runtime_error("error: GLFW unable to initialise");
    }

// Set up the window
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    screen.reset(glfwCreateWindow(win->width(), win->height(), "Mandelbrot Fractal", nullptr, nullptr));

    make_current();

// Initialise glew
    glewExperimental = GL_TRUE;
    GLenum glewinit = glewInit();

    if (glewinit != GLEW_OK) {
        std::ostringstream ss;
        ss << "error: Glew unable to initialise" << glewinit;
        throw std::runtime_error(ss.str());
    }

// Clear
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

// Generate shaders
    GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    GLuint frag_shader = glCreateShader(GL_VERTEX_SHADER);

    GLint compile_status;
    compile_shader(vertex_shader, vertex_shader_src);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &compile_status);
    if (compile_status != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(vertex_shader, 512, NULL, buffer);
        throw std::runtime_error(buffer);
    }

    compile_shader(frag_shader, frag_shader_src);
    glGetShaderiv(frag_shader, GL_COMPILE_STATUS, &compile_status);
    if (compile_status != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(frag_shader, 512, NULL, buffer);
        throw std::runtime_error(buffer);
    }

// Put shaders into shader program
    shader_prog = glCreateProgram();
    glAttachShader(shader_prog, vertex_shader);
    glAttachShader(shader_prog, frag_shader);
    glBindFragDataLocation(shader_prog, 0, "outColor");
    glLinkProgram(shader_prog);
    glUseProgram(shader_prog);

// Set shader attributes
    GLint pos_attrib = glGetAttribLocation(shader_prog, "position");
    glVertexAttribPointer(pos_attrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(pos_attrib);

    GLint tex_coord_attrib = glGetAttribLocation(shader_prog, "tex_coord");
    glEnableVertexAttribArray(tex_coord_attrib);
    glVertexAttribPointer(tex_coord_attrib, 2, GL_FLOAT, GL_FALSE,
                        4 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

// Generate texture
    glGenTextures(1, &mandelbrot_tex);
}

Draw_Buffer::~Draw_Buffer() {

// Terminate GLFW
    glfwTerminate();
}

void Draw_Buffer::flush() {

// Render pixels to image
    glBindTexture(GL_TEXTURE_2D, mandelbrot_tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, window->width(), window->height(), 0, GL_RGB, GL_FLOAT, &buffer[0]);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

// Draw a rectangle
    const static GLfloat vertices[] = {
            // Position   Tex-coords
            -1.0f,  1.0f, 0.0f, 0.0f, // Top-left
             1.0f,  1.0f, 1.0f, 0.0f, // Top-right
             1.0f, -1.0f, 1.0f, 1.0f, // Bottom-right
            -1.0f, -1.0f, 0.0f, 1.0f  // Bottom-left
    };

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STREAM_DRAW);

    const static GLuint elements[] = {
            0, 1, 2,
            2, 3, 0
    };

    GLuint ebo;
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STREAM_DRAW);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    glfwSwapBuffers(screen.get());
}

void Draw_Buffer::keep_window_open() {
    while(!glfwWindowShouldClose(screen.get())) {
        glfwPollEvents();
    }
}

Draw_Buffer &operator<<(Draw_Buffer &db, const RGB &pixel) {
    if (db.pos_iter != db.buffer.end()) {
        *(db.pos_iter) = pixel;
        ++db.pos_iter;
        return db;
    }
    else {
        throw std::runtime_error("error: Cannot append past end of buffer : Remember to flush the buffer");
        return db;
    }
}

```

# DrawBuffer.h

```
#include "Window.h"
#include "Cleanup.h"

struct RGB {
    float r;
    float g;
    float b;
};

class Draw_Buffer {
friend Draw_Buffer &operator<<(Draw_Buffer &db, const RGB &pixel);
    std::unique_ptr<Window<int>> window;

    std::unique_ptr<GLFWwindow, Cleaner> screen;

    std::vector<RGB> buffer;

    // Tracks position of appending in buffer
    std::vector<RGB>::iterator pos_iter;

    // Texture where pixels are written to
    GLuint mandelbrot_tex;

    // GLSL Shader program
    GLuint shader_prog;
public:
    Draw_Buffer(Window<int> *, const std::string &, const std::string &);
    ~Draw_Buffer();

    void make_current() {
        glfwMakeContextCurrent(screen.get());
    }

    void flush();

    void keep_window_open();
};

Draw_Buffer &operator<<(Draw_Buffer &db, const RGB &pixel);

#endif //MANDELBROT_FRACTAL_DRAWER_DRAW_BUFFER_H

```

# Answer
> 1 votes
First of all, there's a typo. You're making 2 vertex shaders.

```
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint frag_shader = glCreateShader(GL_VERTEX_SHADER); // Should be GL_FRAGMENT_SHADER

```

Also from the code you have supplied, it seems like you're not creating a vertex array. So prior to `glGenBuffers(1, &vbo)` add:

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

```

Note that the above vertex array must be bound before calling `glEnableVertexAttribArray()` and `glVertexAttribPointer()`.

Also given that `glDrawElements()` and `glfwSwapBuffers()` is in `Draw_Buffer::flush()`. I'm assuming this method is called to draw the rectangle. The extremely bad thing about this is that you're calling `glGenBuffers()`, etc. each frame. But you're never calling `glDeleteBuffers()`. The best thing would be to move all that into `Draw_Buffer::Draw_Buffer()`.

Then inside `Draw_Buffer::flush()` simply have:

```
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

glfwSwapBuffers(screen.get());

```

Also your driver is most likely clever enough to catch this. But as mentioned in the comments, you need to do this as well:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shader_prog, "tex"), 0);

```

Last but not least, since your geometry is static you can replace `GL_STREAM_DRAW` with `GL_STATIC_DRAW`.

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


title: How does mass work in Box2D

text:
# Question
Title: How does mass work in Box2D
I'm making a 2D platformer, shooter type game in LibGDX, and I'm wondering about Box2D's mass system. I'ven't used mass for anything in the game so far, and everything has worked ok. We move the player, enemies, and bullets around by `body.applyLinierImpulse(new Vector2(impulseX, impulseY), body.getWorldCenter)` and even have a variable jump height system, and it all works fine. To change the speed or impact of objects, we just change the impulse. I've tried using `aplyForce()` but it won't move the body. Everything is usually just a simple polygon, but when I'm creating fixtures there's an option to set the density, and bodies have the option to set the massData, but I don't know what either of these properties does. The gravity of the world is around 11. Can anyone tell me how I should be handling mass with my objects in the game? Thanks.

# Answer
> 3 votes
As Bálint explained, mass in Box2D basically works according to Newton's laws of motion.

Sounds like what you're really after though is how mass works in Box2D in practical programmatic terms. As you're suspecting, that's related to fixtures' densities and bodies' mass data.

Insights on density and mass can be found throughout the Box2D version 2.3.0 User Manual.

For example, in Section 2.2 of the manual, where it's talking about the second parameter to the create-fixture method:

> The second parameter is the shape density in kilograms per meter squared. A static body has zero mass by definition, so the density is not used in this case.

Meanwhile, in Section 6.1, it states:

> b2\_staticBody A static body does not move under simulation and behaves as if it has infinite mass. Internally, Box2D stores zero for the mass and the inverse mass.

And a little later:

> b2\_dynamicBody A dynamic body is fully simulated. They can be moved manually by the user, but normally they move according to forces... A dynamic body always has finite, non-zero mass. If you try to set the mass of a dynamic body to zero, it will automatically acquire a mass of one kilogram and it won’t rotate.

Essentially, to summarize, you'll need to use dynamic bodies with greater than zero masses to see mass related physical effects. And you'll probably prefer to use their fixtures' density settings to establish those masses where these densities are the areal mass densities for the shape associated with the fixture. Body masses are then calculated as the sum of the masses of all the shapes associated with the dynamic body where the mass of each shape is this areal mass density times the area of the shape.

# Answer
> 2 votes
Mass defines how easily something can be moved.

Imagine this: you have 2 boulder in front of you, they are the same size, but one of them is out of lead, the other is pure aluminium. Which one's easier to get to a certain velocity? The aluminium one of course.

The formula for force is `F = m * a`, where `F` is the force, `m` is the mass, `a` is acceleration. You can reorder the formula to get `a = F / m`. This means, that the heavier an object is, the smaller it's acceleration is if the force stays the same, and smaller acceleration means slower speed.

The mass also affects many many other aspects, like momentum (aka: how hard is it to move or stop something), but the main factor is acceleration.

Using force instead of pure acceleration or velocity makes the player actually "feel" how heavy an object is and it doesn't allow the player to push around everything with an ease.

It also makes the interaction between objects more realistic. Going back to the original boulder example, if I put a boulder as big as you in front of you and you start hitting it with pellets, then it won't move. However if you start throwing equally big boulders at it, it will fly away very easily (and I'll be scared of you).

---
Tags: libgdx, physics, box2d
---


# Question
Title: Using Unity and MonoBehavior for UI only?
I've made a turn-based game (think xcom) in Unity, and because I don't need real-time, asynchronous elements, or physics calculations I decided to make a pure c# Model (in the sense of Model, View, Controller) which everything is based on. I use Unity and a MonoBehavior based game loop to handle rendering, camera, UI and input, but stuff like a character attacking another and then calculating a counterattack, or player equipment and spells, are all pure c#.

Am I missing some capabilities of Unity that I should be looking at or is this a basically reasonable approach?

# Answer
> 1 votes
The two are not mutually exclusive. It's a reasonable approach as long as your comfortable working that way. I assume when you say pure C# you're still using MeshRenderer components, gameObjects, etc.

I've worked this way before in Unity, especially early on as I came from Objective C and had written a bespoke 2D Sprite system, and instinctively wanted to work the same way and have a lot of manual control.

I realised though, and this applies to your situation, that there is a certain fundamental design in Unity that can be difficult to work outside of without constantly wrestling with those paradigms. Then add to that the fact that there's a lot of functionally there that can speed up a workflow that you might be ignoring.

User input you mentioned is a good example. If you're not using camera-sourced raycasts and component lookups on the hit results, you might be instead doing it an unnecessarily harder way (I can only speculate).

I'm still code heavy in approach myself, and slightly more OOP than the recommended dosage. I use quite a feature-full boilerplate framework filled with convenience methods and shortcuts, but I also use and respect all of Unity's component based approaches, and editor features. I still get annoyed how so much "magic" process goes on behind a curtain, but I live with it.

Bottom line is I have benefitted greatly from adapting to and appreciating Unity's flow, design, and systems.

---
Tags: unity, turn-based, mvc
---


title: OpenGL large tile map rendering

text:
# Question
Title: OpenGL large tile map rendering
I want to be able to have a big tilemap (e.g. like Terraria, or an infinite procedural generated one), with only a handful of tiles on my screen.

This means that I have a texture atlas (i.e. spritesheet) which contains the textures for the tiles. For the sake of simplicity, let's assume that I have a huge internal 2D array, containing the tileIDs and a lookup tablel/hasmap for the UV coords for each tile type. All the tiles have the same dimension (the texture AND the onscreen tiles). I know a couple of methods to render such a 2D grid/tilemap, but I don't know which one of them is a solid foundation for a game which heavily relies on modifiable tiles.

Additionally, I want to be able to dynamically change the tilesize (i.e. zooming in/out), modifying the tiles/tilemap (e.g. destroying, building) and fast loading (fast paced player actions).

1. Using a single draw call. I create a VBO with all the quads to fill the screen (multiple overlapping vertices, because each quad needs a different texture) and have a persistent buffer to modify the texture buffer object. As soon as the camera moves, I update the UV coordinates in the TBO.
2. I can use attributeless rendering. I make a glDrawArrays call on an empty VAO, and use gl\_VertexID%6 and gl\_VertexID/6 to get the vertex ID and the tileID. To map the UV coordinates, I pass a TBO, which is updated at every camera move. I don't know how expensive this calculation is for the GPU.
3. Hoping on the train of attributeless rendering, I can pass a uniform or create a const array to hold the UV offsets of every tile type, and only pass at every camera move the updated tile type IDs to the shader (with a uniform?). With gl\_VertexID/6 I know which index holds the current tiles type information, and then with this type, I can access my constant array to lookup the UV coordinates.
4. Either using triangle strips, or indices to reduce the vertex count, and use provoking vertices to correctly map the UV coordinates (this can be combined with attributeless rendering). The vertices are all fixed for the window, and only the textures change. Here, once again, I have to map the TBO to a persistent buffer and update it at every camera move.
5. Every tile gets a separate draw call (thus a separate VBO, IBO, TBO) and I can therefore render only the tiles which are seen by the camera. Because of the low amount of onscreen tiles, those separate draw calls shouldn't be too expensive.
6. I put the whole map at the start of the game in the VAO and TBO, and modify the indices buffer, to only render the onscreen tiles (the IBO only holds enough indices to render the onscreen quads). My problem here is that I send too much data to the GPU every frame, and I have a really bad cache locality, because the information has to be accessed from different parts of the buffer objects.
7. There might also be a way to use a geometric shader, although I have never used one.

My concrete question is, is there a "state of the art" method to render big tilemaps, is any of my above mentioned ideas a good solution, and, does it really matter which option I use?

Thank you!

# Answer
> does it really matter which option I use

Use the simplest method which is fast enough. Such method is described below.

> is any of my above mentioned ideas a good solution

The **#1** is unnecessarily slow.

The **#5** is very slow too, probably a lot slower than you think.

Assume you have a 1920x1080 window, filled with 16x16 tiles. (These numbers are similar to what Terraria deals with.) It means that there are approximately 8000 visible tiles. You need at least two draw calls for each one: `glUniform*` and `glDraw*`. It means 16000 draw calls. It's *a lot* of draw calls. Not to mention the enormous amount of needed VBOs.

And honestly saying, all other solutions seem too complicated for my taste, especially since there is a much simpler option: **Chunk-based rendering**.

It means following:

* Divide your map into chunks.
(Small sized squares of tiles; something like 32x32 tiles would work.)
* Make a separate VBO (possibly IBO) for each chunk.
* Only draw visible chunks.
* When a chunk is modified, update it's VBO accordingly.
* If you want an infinite map, you'll have to create and destroy chunks on the fly. Otherwise it shouldn't be necessary.
> 3 votes

---
Tags: opengl, tilemap
---


# Question
Title: Proper way to load assets with a FSM transition between menus and actual game
So far I am making a game in C++ and SDL, and the way to switch between the different menus and the actual game is via a Finite State Machine, AKA a stack where I put each state (MenuState, GameState...) on top, and only render and update the top of said stack.

Now I need to load assets such as images, and I am thinking of creating a class for each state which will hold all the address of the textures, sound, etc and pass it to each state so that it can render, play sound, etc, properly.

Something like a GameAsset class that I pass to `GameState(GameAsset ga)` when I create one, so that `GameState::render()` can do its work fast.

Is there any better way (easier to implement, faster, whatever) to do this ? It seem like it's stretched out for me, as I haven't made games on this scale before. Will this become unmaintainable or whatever ?

Thanks.

# Answer
> 1 votes
First consideration: as retrieving the `GameAssets` inside `GameState::render` will be done only once per frame, there's no consideration of efficiency to be had -- no sensible solution will have any impact.

That aside, let's consider our options. `GameState::render` is a member function, so there are three ways it can retrieve an object:

## Global variable

The usual one. You'd have a global `GameAssets *gGameAssets;`, that is assigned to the `GameAssets` instance once constructed. This is technically the simplest solution, but global variables are usually frown upon because maintenance is an issue: that simplicity means that absolutely no dependency is visible from the outside, so you don't know that `GameState::render` needs and uses `gGameAssets`. Moving on.

## Member variable

`GameState` would hold a `GameAssets *` as a member variable. The pattern you've shown, providing the `GameState` with its `GameAssets` upon construction, is known as Dependency Injection. It's pretty good maintenance-wise: the caller governs which `GameAssets` goes to which `GameState`, and the dependency is visible.

## Function parameter

This one is not always practical, but it should be in this case. There's a good chance that `GameState::render` is the only function from `GameState` that needs the `GameAssets`, and that the function calling `GameState::render` also has access to the `GameAssets`. How about just passing a parameter, i.e. `GameState::render(GameAssets &assets)`? Now the dependency is both explicit *and* tightly localized to the `render` call.

## The choice

It's simple: from bottom to top, pick the first practical solution :)

---
Tags: c++, sdl, fsm
---


# Question
Title: Difference between GUILayout and EditorGUILayout?
Is it matter if I use GUILayout or EditorGUILayout for my custom editor? I need to use one of them in the OnInspectorGUI function.

which one should I use? What are the differences between the two?

Thank you in advance.

# Answer
The EditorGUILayout class gives us a number of additional methods for setting up widgets we often want in custom inspectors for configuring GameObjects/Components/etc:

* Typed numeric inputs - float, double, int, or long
* Siders for integer values, or with user-customizable min & max
* "Delayed" versions of text & numeric input fields that don't update their value until the user presses "Enter" or changes focus
* Layer mask and Tag selection
* Object reference fields (eg. for assigning references to GameObjects, Materials, Textures, other Components, etc.)
* 2, 3, and 4-component vector widgets
* Colour-selection widget
* Titlebars and foldout groups for organizing inspectors

So if you want any of these features, the choice is pretty clear.

Even if you don't need these features immediately, it's not a bad idea to use EditorGUILayout in your inspectors anyway, that way they'll be consistent with other code you might write in the future that does need these features, or custom inspectors you import from a third party like Asset Store content.
> 5 votes

---
Tags: unity
---


title: How to change the size of a draw GUI?

text:
# Question
Title: How to change the size of a draw GUI?
I tried to create a HUD button with a sprite of dimensions 1200x1200 to decrease it by code, but I could not.

Code:

```
draw_sprite(spr_btnBig,0,100,100);
image_xscale=0.05;
image_yscale=0.05;
```

I tried also to modify the scale of the object in the options in the room, but did not obtain the expected result.

Result:

I would not want to have to decrease its size in a program other than the game maker, because the quality of a sprite resized in the game maker gets much higher than a resized in image editors like GIMP or Photoshop:

How could he do that?

# Answer
> 1 votes
`draw_sprite()` ignores `image_xscale` and `image_yscale`. Use `draw_sprite_ext()` instead.

P.S. Are you really need so high resolutions? It's very bad for memory. It won't work on most part of mobile devices, it won't work (or will work very slow) on big part of old desktops and laptops.

> the game maker gets much higher than a resized in image editors like GIMP or Photoshop

I'm sure you're wrong. Photoshop has many algorithms for resizing. I think you tried a wrong one of them.

# Answer
> 1 votes
First of all, make sure you are drawing your button in the `Draw GUI` event, since you want it to be drawn relative to the display coordinates instead of world coordinates: this is for you may want to have different viewport size and GUI size (respectively modifiable via the `view_wview[]` and `view_hview[]` variables, and the `display_set_gui_size()` function.

That said, in the `Draw GUI` event of your button, you can gain more control on how to draw the button sprite by using some of the extended drawing functions, such as:

* `draw_sprite_ext()`, to use horizontal and vertical scaling factors for the sprite (most commonly used imho);
* `draw_sprite_stretched()`, to force explicit values for width and height of the sprite to be drawn.

Also, when drawing in the *Draw GUI* event, coordinates are always relative to the GUI canvas, having origin in the top-left corner of the game window and having size equal to the viewport, unless you set it to other values.

---
Tags: gui, game-maker, hud
---


title: How do I make a high score in Unity?

text:
# Question
Title: How do I make a high score in Unity?
I want to make a GUI box displaying a high score, but I have no idea how to do it. How do I make a high score in Unity?

Here is what I have done so far:

```
using UnityEngine;

public class Highscore : Tap
{
    public static int HighScore;

    void Update()
    {
        if (HighScore > counter)
        {
            HighScore = counter;
            HighScore = PlayerPrefs.GetInt("Highscore", HighScore);
            PlayerPrefs.Save();
        }
    }

    void OnGUI()
    {
        GUIStyle customButton = new GUIStyle("button");
        customButton.fontSize = 75;
        GUI.Box(new Rect(550, 200, 500, 90), "Highscore:" + HighScore, customButton);
    }
}

```

# Answer
I'm afraid I can't directly help with the OnGUI method as I haven't used it directly, though I can tell you that the unity UI system is excellent at such tasks and I have made such things successfully in the past using a canvas, a text field and code that alters the value in the text field dynamically. I don't know how much better or easier this would be in comparison to OnGUI, though building a canvas and a text field only take literally 30 seconds to do simply by going to 'Create \> UI \> Canvas' and then 'Create \> UI \> Text' from the hierarchy pane within Unity.

If you haven't used the Unity UI system before, the Canvas is essentially the board you can pin things to for viewing by the user. The weird thing is that by default it appears absolutely massive in your scene view, and the text field will also appear quite large in comparison to your scene. This is normal, and what will happen when you play the game is that this canvas will resize to the player's screen size and display over the top of whatever is happening. If you parent the text field to the canvas (in the hierarchy pane just drag the text field onto the canvas, it should then parent to the canvas), the text field will appear wherever you place it in front of anything else in view.

In your code there's a few ways you can then set the high score value to your field, but a simple and flexible way (if you change things later) is creating an empty variable then setting it to be your high score in a similar fashion as below:

```
public UnityEngine.UI.Text ScoreToUpdate;

void Update (){
    ScoreToUpdate.text = HighScore; // Whatever variable you use to store/pass your high score after the = here
}

```

The final step is then just to attach the script to the canvas, then with the canvas selected drag the text object from your hierarchy into the 'ScoreToUpdate' field of the script on the canvas object, then that should be it. Your high score should then be displayed on screen at all times in the place you set it.

Apologies if some of these things aren't perfect - i'm a relative noob to unity and programming in general, and i'm away from my unity dev pc to check this fully. This should be fairly close to what you need if it's not exact though.
> 0 votes

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


# Question
Title: What is the best way to store Vertex Buffer Object data?
Until now, I have been using a `vertexData` structure to store data for a Vertex Buffer Object (VBO); `vertexData` holds a static array of 6 vertices (2 triangles). I then save them to a `vector` of the `vertexData` type, before finally using this `vertexData` in the buffering method:

```
struct vertexData {

    Vertex vertices[6]; // position, color, UVs
};

std::vector<vertexData> _DATA;

void SpriteBatch::createVBO() {

    glBindBuffer(GL_ARRAY_BUFFER,_VBO);

    glBufferData(GL_ARRAY_BUFFER,_DATA.size()*sizeof(vertexData),nullptr,GL_DYNAMIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER,0,_DATA.size()*sizeof(vertexData),_DATA.data());

    glBindBuffer(GL_ARRAY_BUFFER,0);
}

```

---

This works good, as everything in my vector is contiguous. However, I want to work with other vertex sizes, for different shapes. I tried a `vector` of `vector` types, in oder to work with dynamically allocated arrays, but it did not work, as it was not contiguous.

At first, I thought about using a polymorphic class to be stored as a `vector`, where every child would have a different array size; but then I recognized that this vertex buffer does not work with pointers

The second idea was to create a generic `SpriteBatch`. For example, a batch for 6 vertices, and then a batch for 2 vertices, etc. etc.

What is the best way to store Vertex Buffer Object data?

# Answer
> 1 votes
My knee jerk (operative work jerk?) reaction:

Leave your contiguous vector as it is but make it just 3 or 1 vertices (depending on the rest of your code), store all your different shapes into the same contiguous space as you do now. Then use an index (map) to record the offset of each polygon/shape.

Then when you use the VBO, just remember to offset your pointers by the index depending on what shape you want.

Example (warning, haven't touched C++ in years)...

```
std::map<int,int> _shapeOffsets;
_shapeOffsets[_myPolygonsCustomIdentifier] = _theOffsetOfMyPolygonInTheVertexData;
MyPolygonDrawingFunc(_DATA.data() + _shapeOffsets[_myPolygonsCustomIdentifier]);

```

**Pro:** Not much of a change from what you're doing now **Con:** Could have complications if you wanted to 'delete' a shape and remove vertices. If this is an issue, we can brainstorm an alternative solution.

Hope that was clear enough, hope I didn't miss the point somewhere :)

---
Tags: opengl
---


# Question
Title: How would you handle different level-types in an entity-component-system?
Im currently developing a game with the entity-component system of Ashley in Libgdx (Java).

In the game you would be able to walk on planets (2D not 3D), fly in the star system and traverse between systems. These are all different types of levels that all need to be handled and rendered differently.

So my question is, how would you differentiate between these types (for example in the renderer), should I add a case for every type in the renderer or split it up somehow?

# Answer
> 2 votes
I don't think there is a completely correct answer to a question like this, but I'll take my best shot at it.

As I'm sure you know, one of the key ideas behind the entity-component architecture is that entities have data but not functionality, and systems contain functionality but not data. There are exceptions of course, but this is the general rule of thumb. As such, let's think of this in terms of data, then functionality.

The way you describe "types of levels", it sounds like these aren't levels in say a platformer sense (i.e. different locations) so much as different levels of abstraction (When I walk on the planet, I'm concerned with the terrain and features of that planet; when I take off, I don't care about the things on each individual planet as much as the relationships between the other stellar bodies).

What this means then is that from a data perspective, you're working with the same set of planet entities at each level of abstraction, you just care about different levels of depth. For example, when I'm walking on the planet, I need to know a lot of detail about that particular entity, and almost no information about the other planet entities (maybe you can see them on the horizon or something). When I take off, I'm concerned with the NameComponent and the IconComponent (or equivalents) associated with each entity.

As such, I would argue that whatever we do, we *don't* put level-type information in the planet entities themselves. Instead, you'll probably want to include some sort of state information like location (e.g. "Hoth VI", "Hoth System", "The Galaxy") or location type ("Planet", "System", "Galaxy").

Now from a functionality perspective, it sounds like you want to render the world differently depending on the "level-type" the player is in (i.e. you render a 2D side view when they're jumping around on the planet, a top-down view when they're navigating the system)- in an ECS this implies that you have separate rendering systems for each view type (or if they are 80% similar, a case statement in your rendering system).

I tend to use Artemis rather than Ashley, but I think one way you could solve for this issue would be to add a listener that fires whenever the player entity changes level types and adds/removes renderers from the world.

Alternatively you could have the renderers look up the player entity and check its location to see whether they should be rendering anything or not.

---
Tags: java, libgdx, entity-system
---


# Question
Title: mobile: Is every position in percentages when you support multiple screen sizes (different aspect ratios)?
Is every position in percentages when you support different aspect ratios? Or do you do if-else statements for each aspect ratio and put absolute positions? What are the pros and cons of each?

# Answer
No, it isn't. Two reasons:

1. You have to deal with different aspect ratios, so percentages would lead to stretched images.
2. On low resolutions, pixel perfect alignment is necessary to avoid blur.

Unless you program specifically for a very limited number of devices, the if-else approach you suggested simply won't work, because there are dozens of resolutions today and there will be more in the future.\*

So what we're doing is the percentage approach, except way more complicated. If you look at modern frameworks for UI development, they allow you to specify margins and padding in terms of percent, pixels, and inches on screen (which occasionally doesn't work). They also allow relative spacing i.e. "place this element exactly between those two elements".

On top of this you use the if/else approach to switch between a few layouts depending on the aspect ratio (horizontal and vertical being two big ones).

\*In gaming specifically, the fixed if/else approach is unfortunately still very common.
> 0 votes

---
Tags: mobile, screen, support
---


title: Scaling a UI bar for progress in Unity

text:
# Question
Title: Scaling a UI bar for progress in Unity
I have created a progress bar inside Unity for one of my energy systems. The bar progression works fine. Its just a plane pivoted on one of the faces so scaling it in x axis makes it progress further as seen in the image below Now I am trying to implement a feature where when the bar stops progressing I would want to show a red bar indicating that it has stopped like in the image below

To implement this I would need to know somehow that the bar has stopped scaling and not progressing any further so that I can put the red bar at the position where it stops scaling.

But how do I know when the yellow progress bar stops progressing as its position stays the same throughout and its just scaling in the x direction.

I hope my question makes sense. Please help me out if it does. Thanks :)

# Answer
Take a look at Renderer Bounds

Which gives you a world space AABB that you can use to determine the scale along the axis.

Now if you have a rotated loading bar you can just use the transform's lossyscale to do a similar thing but the rotation will make it slightly inaccurate.

Once you know the scale along an axis you can use an origin point to define an offset from the origin point where your red bar should appear.

I have included this poorly drawn image to help.
> 1 votes

# Answer
If I understand your problem correctly, it is as follows:

**Problem:** You have no way of knowing when your progress bar stops scaling/progressing in x value. You would like to position a red bar (for player feedback) at the end of the progress bar only if it stops scaling/progressing.

If this is correct, I think that I may be able to help.

**Answer:** It seems as though you are in need of a "status bool". Status bools are very important when you are trying to record and communicate binary states (Ex. on/off) to other scripts. I am not sure if you have a separate script that controls the function of the red bar, but the method should be similar:

```
private bool isScaling = false; // Assuming that the bar defaults with no scaling.

void Update () { // Update function is used in this example for testing purposes only.
    if (isScaling) {
        // The red bar is not visible.
    } else {
        // The red bar is visible.
    }
};

```

That line of thinking will work for knowing when to show or hide the red bar. The other problem that you will face is *actually setting the 'isScaling' bool to the correct value* at the appropriate times. For that, you will probably need to create (or modify) a function that sets 'isScaling' to 'true' when you are scaling the bar and to false when you are not. I hope this helps!
> 0 votes

# Answer
As Jackoftraes said you want to have a bool for displaying if the bar should be displayed.

So you don't know if it moves by the position but you **do** know if the scale changes. So every frame check if the scale is the same as last frame (or the past few frames), then once the scale has been the same for enough frames show the red bar.

Hope this helps :) (even though i'm late to the party)
> 0 votes

# Answer
You could use a slider, if you need more option for the sliders then 0.x to 1.x then you can set the max and min value to whatever you like. You can set a bool on this and say if value in changing bool is true, and make an IEnumerator wait x seconds, and then show the slider handle after that time.
> 0 votes

---
Tags: unity, mathematics, gui
---


# Question
Title: How to render in an entity component system?
I am currently working on a game in Java that uses an entity component system. The game currently has two separate `update()` and `render()` methods in the game loop however this does not seem to fit with my entity component system. From what I understand, each system in an ECS has an update method but what about say, a rendering system that draws sprites to the screen? How does rendering work with an ECS? One idea could be to have systems that draw on the screen implement a `RenderSystem` interface so that they are only used in the rendering method but I've never seen anything like this. Is there a certain way of doing this?

# Answer
> 1 votes
A common way to implement rendering in an ECS is to have a `Renderer` component on any entity which is supposed to be visible in the game world. This component would hold all the information which is required by the graphic engine (which you can call `RenderingSystem` if you like) to visualize this entity.

---
Tags: java, entity-system, entity-component
---


# Question
Title: How Do You Handle Timed Events In Prediction/Reconciliation Client Model?
I'm currently designing and implementing a multiplayer game server for a fairly basic 2D tile game (somewhat similar to old Zelda games like LttP). The PvP aspect of this game involves fast paced combat where players will be in close contact/interaction with each other using swords to deal damage.

As such I want the system to be as smooth and as accurate as possible given a range of connection speeds and pings. I've run into one problem using Prediction and Reconciliation on the client-side.

My current implementation works beautifully for movement. The movement looks flawless and smooth for the client and very smooth with almost no delay for other clients.

My player object is currently a finite state machine with the following states: idle, walking, attacking.

My general is approach is this:

1. Sample Input
2. Set the player's state
3. On update read the sampled inputs and apply any changes to player world-state based on these inputs
4. Send the input to the server along with an integer id and queue it
5. On update on the server-side read any queued inputs and apply them one at a time, sending back updates with the player's world state and the packet id after each one (and of course broadcasting this to the other clients)
6. Back on the client-side, when a packet comes back from the server apply it, drop all inputs with lower or equal packet id from the queue and reconcile the remaining ("future") inputs up to the client's present time

As I said, this works flawlessly for movement. However a major part of the design of combat is that the player freezes for a small period (500ms) following an attack.

On the client-side when an attack is initiated, the state is changed to 'attacking', the attack is executed, and the player is frozen. 500ms later the player unfreezes. On update the input is sent to the server following the same process as the movement. The server applies this input, freezes the player and sends back the data, all as expected.

**edit: I've rewritten a large part of the question due to finding the underlying issue after some refactoring and debugging.**

**edit 2: Another problem, again with the timing of reconciliation is described below.**

My issues occur in the reconciliation stage and all of them cause desync between the client and server. My timers are either:

1. Being created multiple times if the reconciliation process replays the attack initiation multiple times because of the timing of the updates from the server.
2. Being decremented for the same inputs multiple times if the same inputs are reconciled multiple times on separate server updates.
3. Finishing and being cleared on the client-side while still counting down on the server-side. Thus when an update comes back and reconciliation replays, there is no timer to count down and the player is not frozen.

The errors occur in the following cases:

**Example 1 (First and second errors)**

Client-side prediction:

1. Inputs 1-15 are all movement packets.
2. On input 16 an attack is initiated.
3. Up to input 20 has been processed and sent but the timer has not reached 0 yet.

Server-side:

1. Inputs 1-12 are processed and the world-state is sent back with a last input value of 12.
2. Inputs 13-15 are processed and the world-state is sent back with a last input value of 15.
3. Inputs 17-19 are processed and the world-state is sent back with a last input value of 19.

Client-side reconciliation:

1. The world-state is received with a last input of 12. Inputs 13-15 are replayed but only contain movement. On input 16 an attack is initiated and the timer is set to 500ms. Inputs 17 to 20 are replayed, the timer has not yet reached zero.
2. The world-state is received with a last input is 15. Input 16 is replayed and a second timer is now created (it shouldn't be). Additionally, the first timer ticks again erroneously. Inputs 17 to 20 are replayed, the first timer has now ticked twice for each of inputs 17 to 20 - it reaches zero and the player moves out of the attack state and begins moving putting the client and server out of sync. The second timer is ticking correctly but should technically not exist.
3. The world-state is received with a last input of 19. The player is out of sync and experiences a warping back to where the prediction and the server said it should be at that point. The player is again in the attack state because this is enforced by the server. Input 20 is replayed and the second timer erroneously ticks again for input 20.

**Example 2 (Third error)**

Client-side prediction:

1. Inputs 1-10 are all movement packets.
2. On input 11 an attack is initiated.
3. Up to input 16 has been processed with the timer finishing at input 15.

Server-side:

1. Inputs 1-12 are processed and the world-state is sent back with a last input value of 12.
2. Inputs 13-14 are processed and the world-state is sent back with a last input value of 14.
3. Input 15-16 is processed and the world-state is sent back with a last input value of 16.

Client-side reconciliation

1. The world-state is received with a last input of 12. On input 11 an attack is initiated and the timer is set to 500ms. Inputs 13-16 are replayed, with the timer reaching 0 at input 14.
2. The world-state is received with a last input of 14. Since the prediction and previous reconciliation step both had the timer complete and the point where the attack is initiated has passed, there is now no timer and the player is not frozen. Packets 15-16 are replayed with the player moving erroneously on packet 15.
3. The world-state is received with a last input of 16. No further input has occurred so reconciliation is not done here.

As you can see there are three distinct conditions that have to be satisfied in reconciliation for this to work properly:

1. Timers should not be created multiple times for the same attack initiation.
2. A timer should not tick for inputs It's already ticked on when inputs are being replayed. E.g. if the reconciliation replays inputs 14-20 and then 17-20, the timer should not tick twice for inputs 17-20.
3. If the server replays from the middle of a timer which already completed on the client, the client should freeze the player for those frames and recreate/retick the timer from that point.

One solution I thought of is to send the time remaining on the timer(s) back from the server and let reconciliation use that to freeze the player & tick down the timer if needed. However this feels messy and could quickly cause problems once multiple timers come into the mix.

**So, my actual question: How can I more effectively deal with timed events on reconciliation to fulfill the above conditions?**

---

Much of my research on this topic included reading the usual recommended articles: Gaffer On Games Networked Physics series, Gabriel Gambetta's Fast-Paced Multiplayer series, and the Source Multiplayer Networking article. While they provided me with very significant help I am still not entirely sure how to apply the knowledge to the timing problem I've described.

There is also a related question I found since I searched again after finding my underlying issue: Client-side-prediction and Server-reconciliation with timing inputs.

I cannot unfortunately provide code at this time, however hopefully my description is enough to get a general idea of my process and give an answer. If not, I will gladly edit this post with more information as needed.

Thanks!

# Answer
I think you're on the right track with your idea about sending time information back from the server. Sending action-specific times doesn't seem necessary, though.

If each input sent to and from the server has a time, and the server sends its time back to the client, you should be able to do the appropriate math to determine when the freeze should end.

An important, if pedantic, detail is that I would not store separate timers for each instance of an action. Instead, I'd keep the last-known time that a freeze should expire. When an attack is triggered/replayed, set the appropriate expiration time.

Side note: You imply in your first example that the player state is directly enforced by the server. If server authority is the rule, then the server could simply force the client into a "frozen-after-attacking" state, with the expiration time as a part of the state information. There's no timer, just an end time attached to the current state. I guess is kind of a shortcut (as in more direct, not less accurate) version of the solution I described above.
> 1 votes

---
Tags: networking, multiplayer, client-server, movement-prediction
---


# Question
Title: How to initialize OpenGL context with PyGame instead of GLUT
I'm trying to start with OpenGL, using Python and PyGame.

I'm going to use PyGame instead of GLUT to do all the initializing, windows opening, input handling, etc.

However, my shaders are failing to compile, unless I specify exactly the version of OpenGL and profile.

They *do* compile with GLUT initialization from the book:

```
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(400, 400)

# this is what I need
glutInitContextVersion(3, 3)
glutInitContextProfile(GLUT_CORE_PROFILE)

glutCreateWindow("main")

```

But, with simple PyGame initialization like this:

```
pygame.init()
display = (400, 400)
pygame.display.set_mode(display, pygame.DOUBLEBUF|pygame.OPENGL)

```

which doesn't specify exact OpenGL version 3.3 and CORE\_PROFILE, the same program would fail when trying to compile shaders:

> RuntimeError: ('Shader compile failure (0): 0:2(10): error: GLSL 3.30 is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES, and 3.00 ES\n', \['\n #version 330 core\n layout(location = 0) in vec4 position;\n void main()\n {\n gl\_Position = position;\n }\n '\], GL\_VERTEX\_SHADER)

My question is: how do I do this initialization with PyGame?

# Answer
Okay I don't think this can be done with standard pygame since it's built on top of SDL 1, and if SDL supports the GL core profile, it's not exposed in pygame from what i can tell.

However, there is a port of pygame to SDL 2 on github which is a drop in replacement which does expose the required attributes so you can specify a specific context.

So basically you will need the below changes, this got me a 3d triangle using 330 shaders on a linux laptop.

```
import pygame_sdl2
pygame_sdl2.init()
pygame_sdl2.display.gl_set_attribute(GL_ALPHA_SIZE, 8)
pygame_sdl2.display.gl_set_attribute(pygame_sdl2.GL_CONTEXT_MAJOR_VERSION, 3)
pygame_sdl2.display.gl_set_attribute(pygame_sdl2.GL_CONTEXT_MINOR_VERSION, 3)

pygame_sdl2.display.set_mode((self.viewport[2], self.viewport[3]), OPENGL|DOUBLEBUF)

```

Hope this helps.
> 1 votes

# Answer
Try the Kivy framework for Python. It's easy. Alternativley, I work on Ubuntu; compile with the command `python main.py` via the terminal source main.

```
    # -*- coding: utf-8 -*-
"""
Created on Thu Jan 15 21:08:24 2015

@author: fmannan
"""
from __future__ import division
import sys
import numpy as np
import scipy.misc
try:
  from OpenGL.GLUT import *
  from OpenGL.GL import *
  from OpenGL.GLU import *
except:
  print '''
ERROR: PyOpenGL not installed properly.
        '''
  sys.exit()

class GLRenderShape:
    def Triangle(self):
        glBegin(GL_TRIANGLES)
        glColor3f(0., 1., 1.)
        glVertex3f(-1, -1, 0.)
        glColor3f(1., 0., 1.)
        glVertex3f(1., -1., 0.)
        glColor3f(1., 1., 1.)
        glVertex3f(0, 1, 0.)
        glEnd()

class Scene:
    def __init__(self):
        self.quadric = gluNewQuadric()
        self.render_shapes = GLRenderShape()
        self.init()
        self.eye = [0.25, .25, -100]
        self.center = [0.2, -.3, 0]
        self.up = [0, 1, 0]

    def display(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glPushMatrix()
        glRotatef(45, 0., 0. , 1.)
        glScalef(0.5, 0.5, 0.5)
        self.render_shapes.Triangle();
        glPopMatrix()

        glPushAttrib(GL_COLOR_BUFFER_BIT)
        glColor3f(0.4, 0.2, 0.2)
        glPushMatrix()
        glTranslatef(0, .25, 0)
        glutSolidTeapot(0.25)
        glPopMatrix()
        glPopAttrib()

        glPushMatrix()
        glColor3f(1., 0., 0.)
        glTranslatef(-.5, -.5, -1)
        gluSphere(self.quadric, 0.5, 32, 32)
        glPopMatrix()

        glutSwapBuffers()

    def reshape(self, width, height):
        self.width = width
        self.height = height
        glViewport(0, 0, self.width, self.height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def keyboard(self, key, x, y ):
        if key == '\033':
            sys.exit()
        elif key == 's' or 'S':
            filename = 'a1.png'
            print('saving screen shot to %s' %filename)
            glReadBuffer(GL_FRONT)
            im = glReadPixels(0, 0, self.width, self.height,
                                   GL_RGBA, GL_UNSIGNED_INT)
            scipy.misc.imsave('a1.png', np.flipud(im))
            im_depth = glReadPixels(0, 0, self.width, self.height, GL_DEPTH_COMPONENT, GL_FLOAT)
            scipy.misc.imsave('test_depth.png', np.flipud(im_depth))

#            import matplotlib.pyplot as plt
#            plt.imshow(np.flipud(im_depth))
#            plt.show()
            print('done')

    def mouse(self, button, state, x, y):
        print(button, state, x, y)

    def motion(self, x, y):
        #print(x, y)
        pass

    def init(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glEnable(GL_DEPTH_TEST)

if __name__ == '__main__':
    glutInit()
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
    w1 = glutCreateWindow('COMP557 Sample')
    glutReshapeWindow(512,512)
    scene = Scene()
    glutReshapeFunc(scene.reshape)
    glutDisplayFunc(scene.display)
    glutKeyboardFunc(scene.keyboard)
    glutMouseFunc(scene.mouse)
    glutMotionFunc(scene.motion)
    scene.init()
    glutMainLoop()

```
> -1 votes

---
Tags: opengl, python, pygame, glut
---


# Question
Title: How do I make a launcher for multiple executables?
I'm trying to make a launcher for a game I like that compiles the vanilla version and the mods into one launcher. I want to make it so I can choose between the versions, maybe with a rudimentary GUI. The original versions of the game are in Java, but I'm converting them to .EXE with Launch4j, and that's working fine.

# Answer
> 1 votes
Okay, I just made a BAT file (Batch program, whatever) and coded it like that. I know Batch is a dying language, but I like it and it's fairly backwards-compatible. Here's the code:

```
@echo off
:beginning
ECHO Minicraft Launcher 1.0
ECHO Coded in Microsoft Batch by Deven Blake
ECHO (C) 2017 Please reproduce with credit to the author.
ECHO.
ECHO    ^>1 Minicraft Vanilla
ECHO    ^>2 Minicraft Flash v1
ECHO    ^>3 Minicraft Flash v2
ECHO    ^>4 Minicraft Flash v3
ECHO    ^>5 Minicraft Flash v4
ECHO    ^>6 Minicraft Plus
ECHO    ^>7 Minicraft Delux
ECHO.
SET /P _inputness= Which Minicraft version would you like to play?
IF "%_inputness%"=="1" GOTO :vanilla-mode
IF "%_inputness%"=="2" GOTO :flashmode-1
IF "%_inputness%"=="3" GOTO :flashmode-2
IF "%_inputness%"=="4" GOTO :flashmode-3
IF "%_inputness%"=="5" GOTO :flashmode-4
IF "%_inputness%"=="6" GOTO :plus-mode
IF "%_inputness%"=="7" GOTO :deluxe-mode
ECHO Option not recognized. Please input a number from one to seven.
GOTO :beginning

:vanilla-mode
minicraft.exe
GOTO :end

:flashmode-1
"minicraft online v1.exe"
GOTO :end

:flashmode-2
"minicraft online v2.exe"
GOTO :end

:flashmode-3
"minicraft online v3.exe"
GOTO :end

:flashmode-4
"minicraft online v4.exe"
GOTO :end

:plus-mode
"minicraft plus.exe"
GOTO :end

:deluxe-mode
"minicraft delux.exe"
GOTO :end

:end

```

That's not the final edit before I release it on Github (with mention that I didn't create the original games, I only made the launcher), but it's a nice start. Thanks, you guys, for trying to help.

**UPDATE: Minicraft Ultimate on GitHub**

---
Tags: java, launcher
---


# Question
Title: D3D/OpenGL: Question about shaders in larger projects
I'm a game dev student and last semester we had a '3D-programming' course, in which we did some basic stuff such as rendering a textured quad spinning around in the "scene". We used quite basic vertex-, geometry-, and fragment-shaders to do this.

My question is, how are shaders "managed" in a larger projects? For example, I might have a sphere in the scene that uses a shader to generate some effect on it, some VS or FS to generate water ripples or waves on a water 'model', etc. How would all these different shaders be combined in the same project? Do we just create new shader programs for the different shaders(as you can do in OpenGL)? Do you use some kind of condition-statement in the shader and use only one program? Some other approach? I've heard you really want to minimize API-calls, especially for realtime apps (Multiple shader programs would need at least 2 calls to set the shader programs, EVERY frame.) I'm really confused about this part, and our next course involves making a small game so this will be quite important I'd imagine. (also im personally very paranoid when it comes to performance; I want to do things right from the start when possible)

Sorry if the question is poorly formulated, hope it makes some sense. ^^'

An example would be great, HLSL/D3D or GLSL/OpenGL doesnt matter, I've fiddled with both.

# Answer
> 1 votes
It depends on your needs.

Most of the time you just have separate shaders for separate effects, like reflections water, post-processing or simple shading. This allows the graphics programmers to work in a much more organized way. How you create the individual shaders is however very inconsistent. A post-processing shader (or shaders) usually have a single purpose (e.g. blur), but stuff like lighting is usually just a very big shader that does things differently based on the values passed to it, so the same shader can be used to create metal and dirt.

The other approach is the uber shader. This is a very broad term, and you won't find a lot about it on the internet either. Usually, uber shaders are massive shader programs meant to deal with a variety of rendering situations (however, post-processing is usually not one of them). They either use compile time (`#define`, `#if`) or runtime (`if (...)`) switches to handle different scenarios. Sometimes even water and other reflecting or refracting surfaces are included in the mix. If you want, you can literally include every shader program in a single file, but it's not advised.

The third and in my opinion the most flexible approach are the modular shaders. These are constructed on the fly, usually when the game starts. Instead of having a single pre-defined shaders, you have a lot of self-contained pieces of code, which you put together to form a shader. This has multiple benefits, first it makes creating shaders easy and fast by sacrificing some load time, and second, it makes shaders only do what they need to do, thus avoiding wasting time on things like specularity on a matt object.

---
Tags: opengl, shaders, directx
---


title: OpenGL 2D Origin in Upper Left Corner

text:
# Question
Title: OpenGL 2D Origin in Upper Left Corner
I got an OpenGL Context Working in SDL, and I'm trying to set it up so I can render with pixel coordinates of the screen. I got this trying to fill the entire screen with a white rectangle:

```
glViewport(0, 0, MonitorWidth, MonitorHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, MonitorWidth, MonitorHeight, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glColor3f(1, 1, 1);

glBegin(GL_QUADS);

glVertex2f(0, 0);
glVertex2f(MonitorWidth, 0);
glVertex2f(MonitorWidth, MonitorHeight);
glVertex2f(0, MonitorHeight);

glEnd();

```

It doesn't work, and the entire screen appears black. What's wrong with this?

# Answer
Aright I fixed it:

```
glViewport(0, 0, MonitorWidth, MonitorHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, MonitorWidth, MonitorHeight, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glColor3f(1, 1, 1);

glBegin(GL_QUADS);

glVertex2i(0, 0);
glVertex2i(MonitorWidth, 0);
glVertex2i(MonitorWidth, MonitorHeight);
glVertex2i(0, MonitorHeight);

glEnd();

```
> -1 votes

---
Tags: opengl, sdl
---


title: How to tween animated sprites?

text:
# Question
Title: How to tween animated sprites?
So I have an animated sprite of 15 frames, needless to say, at 15 frames, it plays jumpy with a low frame rate.

I want to increase that, by somehow tweening or generating intermediates between the authored animation frames.

I found tools that do frame interpolation for video, and I'm wondering whether similar techniques could be applied to sprite sequences.

Do you know any methods I could use to tween my sprites?

# Answer
> 1 votes
Well, in traditional pen and paper animation. tweening is just adding another frame between two frames and drawing it, and doing it over again until when each image is display back to back in short succession it creates the illusion of fluid motion.

one way of artificially tweening is to alpha blend between each frame a extra one. for example, frame 1 and frame 2 have an additional frame placed inbetween which is frame 1 at at 50% opacity/transperency sitting on top of frame 2. your can add more transitions as you like to make it even longer just like regular animation. typically the more frames you add the shorter you want the duration each frame gets displayed.

Rinse repeat for each frames in order.

This will sort of "blend" the frames into one another.

you can hard code this into the animation by manually doing this in your image editor. or you can do it within your game engine. there is alway the option to code it yourself as well.

I think of this like interpolation of the frames.

Now personally. I like to adjust how long each frame is shown(usually in milli-seconds), make it longer or shorter till the animation feels right easier.

I usually make my stuff in PhotoShop. and then code the animation graphics in C++ and SDL2 and SDL\_image.

---
Tags: animation, sprites
---


title: Object look at target direction?

text:
# Question
Title: Object look at target direction?
How to make an object look at the target direction not at the target himself ?

```
public Transform target;

void Update() {

    transform.LookAt(target);
    float step = 2 * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, target.position, step);

}

```

# Answer
If you want one object to look parallel to the sight-direction of another object, you can simply turn it into the same rotation:

```
this.transform.rotation = target.transform.rotation;

```

But if you want one object to look at whatever *thing* another object is looking at, you first need to figure out where that other *thing* is, because the direction would differ depending on if it's something directly in front of the other object or something at the horizon.

One option is to do a raycast from the other object to find the point where its line of sight is broken and then use `LookAt` for that point.

```
RaycastHit hit;
if (Physics.Raycast(target.transform.position, target.transform.rotation.eulerAngles, out hit)) {
     this.transform.LookAt(hit.point);
}

```

Note that Physics.Raycast is only broken by objects with colliders.
> 1 votes

---
Tags: unity
---


title: blocking queue in Unity

text:
# Question
Title: blocking queue in Unity
I want to implement a custom TCP Client in Unity that has separate threads for sending and receiving certain messages. For sending, the Client is supposed to have a **blocking queue**, that

* receives messages from other threads and
* the message-sending thread polls messages from the queue and sends them - but blocks when the queue is empty.

In on .net 3.5 I do not have access to BlockingCollection.

I would have expected that some implementation existed. So far I have found implementation that simply lock on a queue, which from my understanding is not sufficient.

How could I implement this?

# Answer
This implementation shared by Stephen Toub is literally the second Google search result for "blocking queue c#" so don't underestimate the value of doing your own research. ;)

Code reproduced below in case the link ever breaks. Comments are mine:

```
using System.Threading;
using System.Collections.Generic;

class BlockingQueue<T> : IEnumerable<T>
{
    private int _count = 0;

    private Queue<T> _queue = new Queue<T>();

    public T Dequeue()
    {
        lock (_queue)
        {
            // If we have items remaining in the queue, skip over this.
            while (_count <= 0)
            {
                // Release the lock and block on this line until someone
                // adds something to the queue, resuming once they
                // release the lock again.
                Monitor.Wait(_queue);
            }

            _count--;

            return _queue.Dequeue();
        }
    }

    public void Enqueue(T data)
    {
        if (data == null) throw new ArgumentNullException(“data”);

        lock (_queue)
        {
            _queue.Enqueue(data);

            _count++;

            // If the consumer thread is waiting for an item
            // to be added to the queue, this will move it
            // to a waiting list, to resume execution
            // once we release our lock.
            Monitor.Pulse(_queue);
        }
    }

    // Lets the consumer thread consume the queue with a foreach loop.
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        while (true) yield return Dequeue();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<T>)this).GetEnumerator();
    }
}

```
> 1 votes

---
Tags: unity, c#, multithreading, client
---


title: How can i port my OpenGL game to linux?

text:
# Question
Title: How can i port my OpenGL game to linux?
I made a game with OpenGL 4.3(core profile) and C++. I used GLFW3 for window and context management. I am also using bunch of third party library which are also available for linux.

What things do i need to consider if i want to port the game and how can i make it support all windows and linux?

# Answer
What I would do first, is collect the list of libararies you link against for the windows opengl game. I personally stick to 64 bit when given the option since I have 64bit pc.use 32 bit if thats what your computer and operating system support( u can install 32 bit on 64 bit since it is reverse compaitble. just cant install 64 bit onto 32 bit archatecture.)

Opengl is already available for linux via the Mesa libs. if all libararies are already available for linux. download and install them, there is also probably a "*-dev" version of the libraries you want those aswell. make sure u get both versions. "*-dev" contains the source code and or the header files and the debug symbols.

second create a Make or Cmake files to make life easier so you dont have to pass all that to the command line( I prefer cmake, it usually makes better make files than I can). configure the make or cmake file so that you link all of the libraries into your project and then compile your code.

Your code might generate errors and warning that it never gave in windows possibly so you will need to resolve any unforseen issues.

not all versions of linux are the same either. some libararies might not be supported in some versions or even just wont work with all hardware, but recently this has not been such a problem. keep this in mind if u have an issue

Cmake's website can help you get set up. Cmake helps you generate Makefiles and generate Visual Studio solutions.

https://cmake.org/cmake-tutorial/ great point for getting started.

and the last part is if you find anything that was windows only specefic, that will have removed and/or rewritten. first thing to do if this happens is google for a linux library that provides the same functionality.

now for my personal recommendation, I like to use SDL2 and its related libraries. It is multi-platform, mean if you target SDL2 instead of "linux" or "windows" that it will run on anything. it can create a window. it can create and use different renders. such as opengl, or DirectX . and u can just use it. it even has its own renderer's.

If your interested in more about SDL2 :

https://www.libsdl.org/ direct website for download and wiki.

and some videos as well

https://www.youtube.com/watch?v=MeMPCSqQ-34 steamdev days talk about sdl2 and linux game dev

https://www.youtube.com/watch?v=Sd8ie5R4CVE another one

https://www.youtube.com/watch?v=xTmAknUbpB0&t=1433s this one is about debugging on linux.
> 0 votes

---
Tags: opengl, windows, linux, porting, operating-system
---


# Question
Title: Grab reference to static members or functions that has custom attribute attached
I am trying to create a custom attribute that I can attach to either variables or functions, such that I could grab all references somewhere else in code.

Example

```
[Attribute1]                        //custom attribute
public static int speed = 1;        //dummy variable
[Attribute1]                        //custom attribute
public static int acceleration = 1; //dummy variable
[Attribute2]                        //custom attribute
public static int count = 1;        //dummy variable

[Attribute3]
public static void DummyFunction() {...}

```

and from somewhere else, be able to do something along the lines of

```
var allAttributeReferences = GetAllAttributes("Attribute1");
allAttributeReferences[0] = 10;

var allAttributeReferences2 = GetAllAttributes("Attribute2");
foreach (var reference in allAttributeReferences2)
{
    reference = 0;
}

var allAttributeReferences3 = GetAllAttributes("Attribute3")[0];
allAttributeReferences3(); //Assume it is a function, and invoke function.

```

Is this even remotely possible? Could someone point me in the right direction?

# Answer
> 0 votes
using System.Reflection:

```
var assembly = Assembly.GetExecutingAssembly();
var types = assembly.GetTypes();

foreach (var t in types)
{
    var fields = t.GetFields(); //or GetMethods(), etc etc
    foreach (var f in fields)
    {
        if (f.GetCustomAttributes(typeof(ATTRIBUTE), true).Any())
        {
            if (f.IsStatic)
            {
                // do stuff with f
            }
        }
    }
}

```

---
Tags: unity
---


# Question
Title: Creating new static sprites for Warhammer 40K Armageddon Pc Game
I want to create new unit sprites for the Warhammer 40K Armageddon pc game.

Game uses simple 3D static PNG sprites facing 6 different direction for all units. They don't animate in game, just pictures (as shown in link).

If I simply copy already-made sprites and just rename them with my own liking, I can integrate to game easily (with adding strings, sound and animation files etc.). But I want to create my own unique sprites. I know this can be done because other people already did this (I of course tried to contact them through game forums and steam at first but couldn't succeeded, so I wanted to ask here).

How can I make these sprites?

P.S. I don't have any kind of modelling experience, but I'm a coder.

Some of already-made sprites: https://i.stack.imgur.com/3xLdA.jpg

# Answer
You could still use a copy of the original sprites and either edit them by using them as a template (like erasing the sprite's weapon and drawing your own). Or completely erase the sprites and draw new ones and keep the same dimensions. So if the sprite is 32x64 pixels, any image that is that size will be used in place of the original image.

Hope that helps
> 1 votes

# Answer
I've opened another model, cut any section I want, opened an image I want to modify, pasted onto it, did some smoothing/reshaping etc and done. Top is original model, below is sponson (side) mounted heavy bolter. I did same modifying to all 6 directions. Thank you for ideas and answers.
> 0 votes

---
Tags: 3d, rendering, sprites, modding
---


# Question
Title: How to translate the accelerometer input by specific angle?
I have an `orthographic camera` set on `position(0,0,-10)`, `rotation(0,0,0)` and it's parent - `CameraHolder` with a `transform`:

which gives an isometric feel:

Now, I need to move the ball with the accelerometer so here's how the `FixedUpdate()` looks like:

```
   void FixedUpdate ()
     {
         if (SystemInfo.deviceType == DeviceType.Desktop)
         {
             // Player movement in desktop devices
             // Definition of force vector X and Y components
             float moveHorizontal = Input.GetAxis("Horizontal");
             float moveVertical = Input.GetAxis("Vertical");

             // Building of force vector
             Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);
             // Adding force to rigidbody
             rigidbody.AddForce(movement * speed * Time.deltaTime);
         }
         else
         {
             // Player movement in mobile devices
             // Building of force vector
             Vector3 movement = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
             // Adding force to rigidbody
             rigidbody.AddForce(movement * speed * Time.deltaTime);
         }
     }

```

The movement looks like this:

And I want it to move like:

I need to translate the movement by 45 degrees, but I have no idea how.

If anyone has a clue, I'd be grateful for help!

# Answer
> 1 votes
If the movement will always be camera locked, you can compute the movement vectors using the camera transform.

You would use this whenever the camera rotates

```
//Take care to normalize AFTER setting y to 0
Vector3 camFwd = cam.transform.forward;
camFwd.y = 0; camFwd = camFwd.normalized;

Vector3 camRight = cam.transform.right;
camRight.y = 0; camRight = camRight.normalized;

```

and you would use this whenever movement should occur

```
Vector3 acc = Input.acceleration;
Vector3 movmenet = new Vector3(camRight * acc.x,0.0f,camFwd * acc.z);

```

You could also use a Quaternion / Matrix and rotate the vector, but that's way more costly and complicated than necessary.

---
Tags: unity, camera, isometric
---


title: Web Game Resolution

text:
# Question
Title: Web Game Resolution
I'm starting on a new game that I intend to release via the web (HTML + Javascript). I would like to be able to make a reasonable decision about what screen resolution sizes to support, and what percentage of players can comfortably play my game at increasing resolutions.

Any answer is temporal, so I'm looking for a solution that's up-to-date. For example, I looked at the Steam hardware/software survey -- which is what I want, but data is skewed heavily towards desktop gamers (eg. some of the most common resolutions look like they span two screens).

Where can I find constantly updated data about screen resolutions for my in-browser game?

# Answer
With the web you really can't assume anything about the user's resolution.

People browse the web with all kinds of devices. PCs, tablets, smartphones, even smart TVs. Even if you decide to only target PCs, you can not assume that the user maximized their browser window. So it might have any size whatsoever.

To deal with this problem, try to design your game in a way that it can zoom smoothly and its UI so that it adapts well to different resolutions. If you simply can't manage with a variable aspect ratio, your last resort is letterboxing/pillarboxing (keep the game in the aspect ratio, make it as large as possible and add black bars on the side or on top).
> 1 votes

---
Tags: resolution, web
---


# Question
Title: Can I Create A Windows Package to Submit to the Window Store using the Mac Version of Unity 5.3?
Note: New to App Development.

I'm using a Mac for building my three 3D puzzle apps with Unity 5.3.2. I want to create Windows versions to sell in the Windows Store. I attempted to transfer the package for one of our apps to the Windows version of Unity but it was a pure hot mess. A lot of the alignment of text and images was skewed really bad. We have not used Windows in approx. 10 years so for all practical purposes we are brand new Windows users. The last OS we used was XP. The laptop we just purchased runs Windows 10 Home.

I can create a Windows executable (.exe) file from the Mac version of Unity that executes my 3D puzzle app perfectly just like the Mac version. However I found out that I had to submit a special package to the Windows Store. The instructions that I found so far for this assumes that you are using the Windows version of Unity.

I do not plan to be a full time app developer so the idea of trying to learn Visual Studio for me is a waste of my time. I would prefer creating the Windows package for the Windows Store using the Mac version of Unity. Is this possible? I could not find instructions in the manual or from search on what options need to be set to do this. I'm thinking it can be done since I was able to create a Windows exe file using my Mac version of Unity. I would like to create Windows Store packages for both 8.1 and 10.

# Answer
> 1 votes
You cannot convert a .exe to a .appx or related file to submit it to the Windows Store. There is an app called *MakeAppx* that came with Visual Studio for Windows 8, the Windows SDK for Windows 8 and 8.1 and built-in to Windows 10 that does it, but it can't be downloaded.

---
Tags: unity, windows, macos, appstore
---


# Question
Title: Scaling a sphere to give identical result, regardless of rotation
how can I maintain a consistent scaling of a sphere regardless of the rotation of the model? For example, take the following (scaled) sphere:

In this image, we start with a sphere, looking at it directly through the Z-azis. The sphere is scaled by 0.7x on the Y (up/down) axis, giving it a 'squashed' appearance.

A 3D vector that describes the scaling of this sphere is `[1.0, 0.7, 1.0]`. The red dot indicates an arbitrarily chosen point on the surface of the sphere that we will mark as the 'top'.

Now, after the sphere rotates 90 degrees through the Z-axis, the same scaling coefficients `[1.0, 0.7, 1.0]` when applied will produce a result like this:

My question is as follows:

**Given a rotation quaternion `Q` that represents the rotation of the sphere, how can I use `Q` to correctly alter the scaling coefficients vector in order to produce a result like this instead:**

Notice that the eventual 'oriented shape' of the sphere is the same as in the first image, even though a 90-degree-through-Z rotation has been applied. In this instance, a corrected scaling coefficient vector would be something like \[0.7, 1.0, 1.0\].

---

I've tried simply multiplying the scaling coefficients vector by `Q` but this gives an incorrect result. This is actually trivial to see if you imagine rotating \[1.0, 1.0, 1.0\] by 45 degrees through any angle. The answer should always remain as \[1.0, 1.0, 1.0\] but it does not.

# Answer
We can construct a matrix representing this transformation by simply reversing the order in which we normally apply scale and rotation:

```
 Matrix4x4 RotationInvariantScale(Vector3 axisAlignedScaleCoeffs, Quaternion orientation)
 {
     Matrix4x4 scaleMatrix = Matrix4x4.Scale(axisAlignedScaleCoeffs);
     Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, orientation, Vector3.one);
     return scaleMatrix * rotationMatrix;
 }

```

Here I draw a model with this matrix as I change the input rotation:

(Made in Unity, using Graphics.DrawMesh to render using my custom matrix, since Unity won't allow us to set the matrix on a Transform component directly)

Depending on your full setup, you may find this is easier to execute using parenting: place the sphere's visual as the child of an otherwise invisible parent. Apply scaling on the parent object, and rotation on the visible child object. This can avoid hacking in a skewed matrix manually.
> 2 votes

---
Tags: mathematics, linear-algebra
---


# Question
Title: How to smooth jagged pixel edges in Unity?
So I am reading an image from a png file into a 2D sprite. This sprite serves as a "province" in my game. Currently, I am getting this:

If you look closely, you will notice that you are seeing the square corners of each pixel, because I am mapping the image on a 1:1 ratio of pixels:world coordinates.

What I want is a slightly rounded corner in these places. Look at the 2-dimensional provinces in this example:

I have been googling around for algorithms, but most answers simply say "use a shader" and don't describe the techniques used to do this (until now I have not done much with shaders). If you would like to see my working code for the province system, it is posted on my answer to my own question here.

# Answer
> 3 votes
One economical way is to perform tile-based rendering, but have lots of variations in tiles depending on the edge type (straight edge, inner corner, outer corner etc.) Here's an example:

Note that despite the appearance of a very complex coastline, you can pick out variations of coast types, where each variation within a type are interchangeable. For example, here are all the variants where the coast goes from the top-left corner to the bottom-left corner, with the land on the upper diagonal:

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


# Question
Title: Unity or OpenGL for a real time strategy game?
I'm trying to recreate an old game I use to play back in the day called Evony but I'm not sure what would be the best way to accomplish this **graphically**. It was originally written in **Flash** and I'm contemplating whether to do it using **Unity** or **openGL**. I'm not really sure how these types of games are made **graphically**, I looked at *Clash of Clans* but all it said is that they use "C++" so I'm lost. How would I go about making these types of games **graphically** using "C++" as most of these types of games are made for the android platform. I was thinking of using Unity but I'm afraid it would probably be too "bulky" and might make the game run slow, I want to be able to make it in C++ if possible so it can be more efficient. So again, how should I go about this?

# Answer
If you know C++ and already know OpenGL, you should use it. It can be way faster than Unity, but you do have to code **everything** from scratch

If you want a simpler solution that can still be very fast, use Unity. It has a big community that will help you out with your problems if you need help.
> -4 votes

---
Tags: unity, opengl, c++, android
---


# Question
Title: Calculate 2D tile map tiles within a "field of view" cone
I need to calculate which tiles make up a "cone", originating at my player and extending outward for a specific tile distance.

My player can only face North, South, East, West and I'm not sure yet on the angles I'll use for the cone.

I've found several posts/articles already covering this but they're trying to determine visibility and are a lot more complex than I need. I'm not lighting a room or calculating shadows/occlusions.

# Answer
With a combination of Bresenham's algorithm and floodfill, this can be very easily solved (you could use draw a lot of lines instead of floodfill, but that tends to create empty spots).

You need to take your player's angle add ans remove half of the FOV angle from it to get the two boundaries of it.

Next, using trigonometry get the coordinates of the corners of the cone and draw a line from the player to the corners.

```
x = cos(angle) * r
y = sin(angle) * r

```

Where r is the radius of the cone and angle is the corner angles in radians.

Then interpolate between the two angles, each time using the formula above to set the tiles in a circle segment to be inside the fov. This closes the cone. If you want the cone to have a flat end instead of cicular, you could use the line algorithm.

Lastly, use flood fill to fill in the inner part of the cone with the new tile.
> 2 votes

---
Tags: unity, c#, 2d, mathematics, raytracing
---


# Question
Title: Farseer Physics collision detection vs intersection detection with sensors
I'm trying to make a game that uses Farseer physics engine as its main collision detection engine. I have a 2d circle body object that has a matching fixture (I used the CreatCircle method. I did not create the fixtures and bodies separate). When IsSensor is set to false, objects collide with this circle and bounce off. My goal was to have events triggered when other physics enabled bodies move through this field and just use the engine to detect the collisions (or rather intersections) so I set it to IsSensor = true, and now all the other bodies pass right through but I do not get collision events. The be specific, sometimes I do get events but not continuously as I would expect. My intention was to have this collision code fired each time the world re evaluated collisions.

Does anyone know a way to do this. My googling has led me nowhere and I'll be fudging with the limited farseer documentation I can find this weekend to try and get this right.

Thanks ahead of time.

# Answer
Get the Body.ContactList which is populated by all contact resulting from BB collisions. If you want contacts that actually have fixtures touching check to see if Contact.IsTouching() is true.

Edit: There are performance issues with this approach so I suggest setting a flag when the sensor collision event fires and setting the flag to false when none of the items in the ContactList are touching. Only iterate though the contact while this flag it set to true. This would prevent you from iterating every every time a BB intersects with your sensor.
> 0 votes

# Answer
```
//declare variables
private List<Dynamics.Contacts.Contact> contacts;

public int SensorData;
//you need your fixture
//my fixture create by Bayazit
TactSensorTexture = Content.Load<Texture2D>("test_1");
uint[] data1 = new uint[TactSensorTexture.Width * TactSensorTexture.Height];
TactSensorTexture.GetData(data1);
Vertices verts1 = PolygonTools.CreatePolygon(data1, TactSensorTexture.Width);
Vector2 scale = new Vector2(0.07f, 0.07f);
List<Vertices> _list = FarseerPhysics.Common.Decomposition.Triangulate.ConvexPartition(verts1, TriangulationAlgorithm.Bayazit);
foreach (Vertices vertices in _list)
        {
            vertices.Scale(ref scale);
        }
//attach to create body (already have a circle shape)
compaund = FixtureFactory.AttachCompoundPolygon(_list, 0.000f, _circleBody);
//FixtureFactory create two fixture
compaund[1].IsSensor = true;
compaund[0].IsSensor = true;

//in function update i white next construction (insert on right place)
SensorData = 0; //always set zero because you in update funciton
contacts = _world.ContactList; //get list of contacts
foreach(Dynamics.Contacts.Contact contact in contacts)
            {

                if ((contact.FixtureA == compaund[0] && contact.IsTouching) || (contact.FixtureB == compaund[0] && contact.IsTouching)) //check only for one fixture because it's just example
                {
                    SensorData = 1;
                }
                else
                {
                   //dont need do anything
                }

            }
//also you can drow on screen (insert on right place)
_batch.DrawString(_font, System.Convert.ToString(SensorData), new Vector2(14f, 20f), Color.Red);

```
> 0 votes

---
Tags: xna, collision-detection, physics, farseer-physics-engine
---


# Question
Title: How do I set the exact local position of a RectTransform?
I have a game object that creates a keyboard in side of my world canvas. I am working out the offset positions for each key, and appear to be doing that correctly. However, when I set the positions in the actual keys, the values are being offset by anything from 100 - 1000.

---

This is the basic method I am currently using to set the position:

```
public void SetDimensions(Vector2 position)
{
    GetComponent<RectTransform>().localPosition = position;
    Debug.Log(key + ": " + position);
}

```

I have also tried using `.position` and `.anchoredPosition`, as per the somewhat confusing API reference. I have also tried simply referencing `transform.localPosition` and `transform.position`. No matter what, the output is *exactly the same*. The debug output confirms that I am working out the correct local position, but no matter what I do, that is not the value being set to my transform.

As you can see, I have my pivot set to the center; though I think this *may* have an impact, it certainly should not cause an offset of *400-500*.

---

As per request, this is my main canvas:

---

What am I doing wrong, or more specifically, how do I set the exact local position of a game object using a `RectTransform`?

# Answer
First of all, ensure you set the parent before setting local position, then, you have two options according to the type of Rect Transform : non-stretching and stretching ones.

> For a non-stretching Rect Transform, the position is set most easily by setting the anchoredPosition and the sizeDelta properties. The anchoredPosition specifies the position of the pivot relative to the **anchors**. The sizeDelta is just the same as the size when there’s no stretching.

Try to do as follow :

```
RectTransform rt = GetComponent<RectTransform>();
rt.anchoredPosition = position ;
Debug.Log( position + " " + rt.anchoredPosition ) ;

```

I've just tried the previous code with a simple button inside a canvas, it works great. If it doesn't for you, you may have another script changing the position or a parent with a Layout group maybe ?

---

For your information :

> For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right anchor.

```
RectTransform rt = GetComponent<RectTransform>();
rt.offsetMin = rt.offsetMax = Vector2.zero ;

```

Source : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html
> 6 votes

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


# Question
Title: Volume preserving procedural mesh deformation
I'm having difficulties trying to create a procedural mesh that deforms on impact. The deformation is meant to look and feel like metal when it is being forged. Since this is less of an aesthetic feature and more of something that would affect gameplay directly, it needs to be somewhat accurate. This means that volume of the mesh should be preserved (at least visually) such that the mesh does not gradually get too much smaller.

What I have tried:

1) Applying force on every vertex, based on the force and distance from impact point

```
foreach (Vector3 vertexPos in vertexList)
{
    vertexPos += (force / distanceToImpactPoint.sqrMagnitude) * impactDir;
}

```

This led to the entire mesh gradually becoming smaller (as mentioned earlier)

2) Take into account the dot product between the impact direction and vertex normal for each vertex, as well as lerp between impact direction and normal (to simulate sides of objects bulging out when compressed

```
foreach (Vector3 vertexPos in vertexList)
{
    float attenuatedForce = (force / distanceToImpactPoint.sqrMagnitude);
    float nDotD = Vector3.Dot(impactDir, currVertexNormal);
    vertexPos = attenuatedForce * nDotD * Vector3.Lerp(impactDir, currVertexNormal, nDotD);
}

```

This led to mesh completely splitting apart for anything that has hard shading (as there are duplicate vertices where the edges are, and also artifacts on smooth shaded objects.

Hard Shading:

Soft Shading (sort of works, but lots of artefacts and not volume preserving)

Also, both methods break completely if force is applied to an edge.

Does anyone know of a more elegant solution to do this?

# Answer
> 2 votes
Due to the relatively low melting temperature of metals, they act like a fluid (sort of) when you hit them (it' closer to a gel, but gels are also fluids technically). The higher something's temperature is, the more viscose it gets (that's why metal workers heat up metals bars before using them, try heating up honey to test this).

So, you can technically simulate the properties of them with a fluid simulation algorithm (like the Navier-Stokes equations) by using a very very high viscosity.

Most fluid simulators allow you to apply a force at a specific position. You can use this to apply the hit force to the material, which makes a part of the fluid more dense, thus the algorithm dissipates it to the sides. Because fluids are uncompressable (they are, but a higjer compression would create a nuclear reaction), the material won't ever disappear.

Creating a mesh out of the data is very easy too. Most fluid simulators use a grid to store the water. You can just take this grid and process it using an algorithm like marching cubes to produce a mesh out of it.

This mesh can then get rendered and used in a mesh collider.

---
Tags: unity, procedural-generation, procedural, dynamic-mesh
---


# Question
Title: glsl Expected token ')', found 'identifier' with function mix
I have a Fragment shader that contains:

```
[...]
float c = texture2D(tex, tc).a;
float alpha = mix(0.0f, 1.0f, c);
gl_FragColor = vec4(1, 1, 1, alpha) * color;

```

This works fine on my desktop and Nexus 5. However I get an exception while running on a Wiko mobile:

```
0:22: L0001: Expected token ')', found 'identifier'

```

Line 22 is the line containing the mix function.

What I'm doing wrong?

# Answer
> 1 votes
Depending on your driver and GLSL version, the "f" suffix on floats may be illegal. Change to:

```
float alpha = mix(0.0, 1.0, c);

```

As always, OS is irrelevant; you really **need** to say what **hardware** (in particular what **GPU**) you have.

---
Tags: glsl, opengl-es
---


title: Fully decentralized matchmaking?

text:
# Question
Title: Fully decentralized matchmaking?
Most games that I know use a master server to connect players in multiplayer. If it ever gets shut down, without third-party software or master server, the game is effectively unplayable in multiplayer, sometimes not even in LAN. Temporary shutdowns can arguably be worse than permanent, because in the latter case you will likely have a community solution soon, in the former you have to wait for an unknown amount of time.

Assuming good intentions of the game developer, how can such a game be constructed so it remains playable? Can matchmaking be made fully decentralized? Do such solutions already exist?

# Answer
The google keyword you're looking for is peer-to-peer. The problem is that most decent solutions still require a minimal server (to maintain a list of at least one initial peer), and when that server goes down you're back at square one. For this part of the answer I'll refer to stackoverflow: https://stackoverflow.com/questions/310607/peer-to-peer-methods-of-finding-peers

The problem with implementing a peer to peer solution is that the upsides only show at the end of life, when sales are low or nonexistent, yet the downsides show at launch, when the impact on sales is high.

Downsides:

* Without company controlled server, cheating is easier.
* Without company controlled server illegitimate clients can play online
* A complex new framework can crash under heavy load, so there's a risk nobody can play at launch.

Upsides:

* Players can continue to play the game long after they paid for it.
> 1 votes

# Answer
There is really no way to properly do matchmaking without a central server where players looking for a match can report to. The internet is just too large to find someone without knowing their IP address.

But what you can do is to create some workarounds to join a multiplayer game without matchmaking:

* Allow an optional way to connect to other players directly by entering the IP/hostname of the player they want to join.
* Also add a command line parameter to directly connect to a multiplayer game. This allows the community to create an alternative matchmaking application which launches your game application after the player picked a match to join.
* Allow to set the matchmaking server hostname in the game config. At the end-of-life you can then publish the matchmaking server binary so the community can set up their own matchmaking servers. (keep in mind that crafty players might try to reverse-engineer your matchmaking protocol and set up their own matchmaking servers before you want them to do that)
> 1 votes

---
Tags: matchmaking
---