title: How to render in a imGui Window

text:
# Question
Title: How to render in a imGui Window
I am learning OpenGL by glfw3 lib and I am using imgui to make a interesting application.
However, I can not render what I want in a imgui window.

I searched google and get below link:

1. Render in a imGui Window
2. How can I render an OpenGL scene into an ImGui window?

I tried about two days and I have rendered a triangle in a imgui window.
However, when I try to render content as this link(Tutorial and Code) shows me.
The box in my imgui window will not spin! It is a stationary photo.
What's wrong with my code?

`#define __abc__`is a value to test.
Xhader.h just is the header file in the tutorial, also .vs and .fs files.
The only difference is the tutorial uses glad.h and I use glew.h.

```
#define __abc__
#define STB_IMAGE_IMPLEMENTATION
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stb_image.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"

#include "Xhader.h"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);

GLFWwindow* Proinit();
void imguiSetup(GLFWwindow* window);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

int main()
{
    GLFWwindow* window = Proinit();
    imguiSetup(window);

    int view3d_width = 100;
    int view3d_height = 200;

    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);

    // build and compile our shader zprogram
    // ------------------------------------
    Xhader ourShader("shader/vs.txt", "shader/fs.txt");

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float vertices[] = {
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,

            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
            -0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,

            -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,

            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    //---------------------------------------    FBO    -----------------------------//
#ifdef __abc__
    unsigned int fbo;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    GLuint TOF;
    glGenTextures(1, &TOF);
    glBindTexture(GL_TEXTURE_2D, TOF);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 400, 300, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#else
    ;
#endif

    // load and create a texture
    // -------------------------
    unsigned int texture1, texture2;
    // texture 1
    // ---------
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
    std::string s1 = "resources/textures/container.jpg";
    std::string s2 = "resources/textures/awesomeface.png";
    unsigned char* data = stbi_load(s1.c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    // texture 2
    // ---------
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    data = stbi_load(s2.c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);

    // tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
    // -------------------------------------------------------------------------------------------
    ourShader.use();
    ourShader.setInt("texture1", 0);
    ourShader.setInt("texture2", 1);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {

#ifdef __abc__
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, TOF, 0);
#endif
        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
            std::cout << "FRAMEBUFFER SUCCESS" << std::endl;
            glViewport(0, 0, 400, 300);
            // render
            // ------
            glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
            // bind textures on corresponding texture units
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, texture1);
            glActiveTexture(GL_TEXTURE1);
            glBindTexture(GL_TEXTURE_2D, texture2);
            // activate shader
            ourShader.use();
            // create transformations
            glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
            glm::mat4 view = glm::mat4(1.0f);
            glm::mat4 projection = glm::mat4(1.0f);
            float time = (float)glfwGetTime();
            std::cout << time << std::endl;
            model = glm::rotate(model,time , glm::vec3(0.5f, 1.0f, 0.0f));

            view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
            projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
            // retrieve the matrix uniform locations
            unsigned int modelLoc = glGetUniformLocation(ourShader.ID, "model");
            unsigned int viewLoc = glGetUniformLocation(ourShader.ID, "view");
            // pass them to the shaders (3 different ways)
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
            glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &view[0][0]);
            // note: currently we set the projection matrix each frame,
            //but since the projection matrix rarely changes it's often best practice
            //to set it outside the main loop only once.
            ourShader.setMat4("projection", projection);
            // render box
            glBindVertexArray(VAO);
            glDrawArrays(GL_TRIANGLES, 0, 36);

#ifdef __abc__
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
        }
        else {
            std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
        }
#ifdef __abc__
        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();
        bool View_3D = true;
        if (View_3D) {
            ImGui::Begin("3D View", &View_3D);
            view3d_height = ImGui::GetWindowSize().x;
            view3d_width = ImGui::GetWindowSize().y;
            ImVec2 pos = ImGui::GetCursorScreenPos();
            ImGui::GetWindowDrawList()->AddImage(
                (void*)TOF,
                ImVec2(ImGui::GetCursorScreenPos()),
                ImVec2(ImGui::GetCursorScreenPos().x + ImGui::GetWindowSize().x - 15,
                    ImGui::GetCursorScreenPos().y + ImGui::GetWindowSize().y - 35),
                ImVec2(0, 1),
                ImVec2(1, 0)
            );
            ImGui::End();
        }

        // input
        // -----
        processInput(window);

        ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
        // render
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
#endif

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

GLFWwindow* Proinit() {
//glfwSetErrorCallback(glfw_error_callback);
    if (!glfwInit()) return (GLFWwindow*)1;
#ifdef __APPLE__
    // GL 3.2 + GLSL 150
    const char* glsl_version = "#version 150";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // Required on Mac
#else
    const char* glsl_version = "#version 130";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // 3.0+ only
#endif
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Shader3D", NULL, NULL);
    if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return (GLFWwindow*)-1; }
    glfwMakeContextCurrent(window);
    //glfwSwapInterval(1); // Enable vsync
    //glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
#if defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
    bool err = glewInit() != GLEW_OK;
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
    bool err = gladLoadGL() == 0;
#else
    bool err = false;
#endif
    if (err) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return (GLFWwindow*)1; }

    return window;
}

void imguiSetup(GLFWwindow* window) {
    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
    ImGui::StyleColorsDark();
    ImGui_ImplGlfw_InitForOpenGL(window, true);         //Setup Platform bindings
#ifdef __APPLE__
    ImGui_ImplOpenGL3_Init("#version 150");             //Setup Renderer bindings
#else
    ImGui_ImplOpenGL3_Init("#version 130");
#endif

}

```

# Answer
Move these lines inside the while loop.

```
unsigned int fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);

GLuint TOF;
glGenTextures(1, &TOF);
glBindTexture(GL_TEXTURE_2D, TOF);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 400, 300, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

```

Then once all your rendering is done you have to delete the frame buffer and texture object every time inside the loop.

```
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &TOF);

```

The idea is for each and every time inside the loop, the frame buffer needs to be created, utilized and the deleted. Other wise the buffer will not refresh.
> 2 votes

---
Tags: opengl, c++, glfw, imgui
---


# Question
Title: I already have a GameManager script, but need to have a 2nd one
I'm making a Unity game, and I want to use the Unity Distribution Portal.

My problem is that you have to make a script named `GameManager` for this, but I already have another script called `GameManager`, so every time I try to rename the first `GameManager` script, the game stops working.

I don't want to rewrite every script I've used `GameManager` variables in. So the way I've been trying to rename this is by right-clicking on the `GameManager.cs` file in the Unity project window and renaming it there, then typing a 2 in the name inside Visual Studio.

If I call the script for UDP for example something like `GameManager2`, UDP doesn't seem to understand that this is the script it needs for Sandbox Testing.

Can anyone help me with this?

Here is the UDP script I want to add (which is currently called `GameManager2`, but needs to be called `GameManager`):

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UDP;

public class InitListener : MonoBehaviour, IInitListener
{
    public IInitListener listener;
    public void Start()
    {
        StoreService.Initialize(listener);
    }

    public void OnInitialized(UserInfo userInfo)
    {
        Debug.Log("Initialization succeeded");
    }

    public void OnInitializeFailed(string message)
    {
        Debug.Log("Initialization failed: " + message);
    }
}

```

# Answer
When you just type a new name in a class, that doesn't change all the other code files that are trying to refer to that class's name. So you'll get all kinds of compiler errors because they're now referring to a name that doesn't exist.

Instead, you should right-click on the identifier you want to change, and select Rename (or press F2 as a shortcut)

Instances of that name will be highlighted in green, and will all be updated in-sync as you modify the name. A box in the corner will tell you how many references in how many files are going to be changed (and warn you of any conflicts).

When you're happy with the new name, click Apply or press Enter to accept the change and save all the files modified in the process.

Do this before adding the Unity Distribution Portal content to your project, to be sure you don't accidentally mess up any of its references to its own Game Manager script.

I'd also recommend choosing a more informative name than `GameManager2` \- maybe `LocalGameManager` or `PongGameManager` (if you're making a "Pong" game), etc. Something that will remind you in 6 months which file is "your" version of the game manager and which one you got from the distribution portal guide.
> 1 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: Math question: How to move/extrude a cube's face in Unity?
The short question is: What's the math to move the face of a cube? I.e. how to stretch (or shrink) a cube in the direction of one of its faces?

Here's a picture:

The camera shows a cube (left). When the user clicks and drags on one of the faces (yellow), the face (it's vertices) should follow the mouse and as a result expand (or shrink) the cube in the given direction (like the right cuboid in the picture above).

Please note that this should be done ingame, by moving the vertices, not by scaling the object.

Now, I already have the selected face and all the vertices of its four corners. Further, the distance how far it should be moved is also known. The question is, what needs to be done with the vertices to pull the face out (or push it in)? Whats the math?

Your help is very much welcome. Thank you.

# Answer
You said you know the distance, then you just need to figure out the direction too. You simply move each of those vertexes that distance in that direction.

To move it “outwards” and “inwards”, what you’re talking about is moving it along the face’s normal vector.

Not sure if unity has any built in functions for this, but basically 3 of the vertices are enough to define a plane. You need the normal of this plane, convert it to a unit vector (magnitude 1) then you can multiply it by the distance, with negative numbers being inwards, and positive numbers outwards.

I suspect meshes in unity already have a normal vector saved that is associated with each face since these normals are required for materials and textures applied to meshes.
> 1 votes

---
Tags: unity, mathematics
---


# Question
Title: How to properly copy/paste object between folder?
I'm new to unity and found some simple task can't be done here. For example in projects tab, i want to copy/paste a script from script folder to other folder. I should be able to simply select the script, press ctrl C , go to target folder , press ctrl V to paste but nothing happen. So for now , i have to duplicate it then move it to new folder then rename it. But why can't i do simply copy and paste ?

# Answer
> 1 votes
Select the assets you want to copy and paste. Press Control D (for duplicate), or whatever the Mac equivalent is. Then drag these to your new folder (optional), and rename them as needed (also optional).

# Answer
> 0 votes
Unity does not support copying of assets, but it allows you to use drag&drop to move them between directories. It even updates references to these assets in any objects you have.

Alternatively, you can also open the assets directory with the file explorer of your operating system and move assets around, but this might result in some gameObjects in your scenes losing their scripts.

---
Tags: unity
---


# Question
Title: Need a little more help with rotating sword around player (Unity 2D)
this question is somewhat similar to my last question (found here). This time, I **have upgraded to the new Input Manager** and updated the script that uses the controller, but now I'm having trouble with having the sword rotate around the player and towards the mouse. The image below might help visualize this better.  Here's my current code:

```
public void Update()
{
    var gamepad = Gamepad.current;
    var mouse = Mouse.current;
    if (controllerControl)
    {
        x = gamepad.rightStick.ReadValue().x;
        y = gamepad.rightStick.ReadValue().y;
    }
    else
    {
        x = mouse.position.ReadValue().x; //Here's where I think the problem is
        y = mouse.position.ReadValue().y;
    }

    //convert the input into an angle in radians, and convert that into degrees
    float rads = Mathf.Atan2(y, x);
    float degrees = rads * Mathf.Rad2Deg;

    //use trig to position sword
    sword.localPosition = new Vector3(Mathf.Cos(rads) * distance, Mathf.Sin(rads) * distance, 0);
    //rotate to face away from center. note that the angle atan gives us is
    //oriented differently than unity's rotation, so we have to reverse it
    //and add 90.
    sword.localEulerAngles = new Vector3(0, 0, degrees - 90);
}

```

The boolean "controllerControl" will change based on which input device the player chooses. The sword is a child of a box object. If someone could point me in the right direction, that would be much appreciated.

# Answer
> 0 votes
I found the answer by myself, but if this is not best practice then please let me know.

```
var gamepad = Gamepad.current;
    var mouse = Mouse.current;
    if (controllerControl)
    {
        x = gamepad.rightStick.ReadValue().x;
        y = gamepad.rightStick.ReadValue().y;
    }
    else
    {
        Vector3 v2 = cam.ScreenToWorldPoint(new Vector3(mouse.position.ReadValue().x, mouse.position.ReadValue().y, cam.nearClipPlane));
        x = v2.x - box.transform.position.x;
        y = v2.y - box.transform.position.y;

    }

```

This solution requires a new Camera 'cam' if someone else wants to use this.

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


# Question
Title: Supercover line algorithm from corners instead of the square's center?
I need to check whether a cell in a 2D grid is visible to the starting cell. I'm currently using amit's supercover line algorithm, this one https://www.redblobgames.com/grids/line-drawing.html#supercover

The algorithm works but I need the cells that are intersected by the top-left corner-to-corner line instead of the center-to-center.

This shows what I mean:

* The green square is the start point and red is the end point
* The white dots represents the cells that are visited by the line drawing algorithm I'm using
* I want to get the cells that are intersected by the blue line. It's drew from the top-left corner of the start cell to the top-left corner of the end cell.

This is my implementation of the amit's algorithm in gdscript

```
func _line_of_sight(p0, p1):
    var dx = p1.x - p0.x
    var dy = p1.y - p0.y

    var sx = 1 if dx > 0 else -1
    var sy = 1 if dy > 0 else -1

    var p = Vector2(p0.x, p0.y)
    _points.append(p)

    var x = 0
    var y = 0
    var nx = abs(dx)
    var ny = abs(dy)

    var result = true
    var blocked_cells = _tilemap.get_used_cells()

    while x < nx or y < ny:
        var px = (1+2*x) * ny
        var py = (1+2*y) * nx

        if px == py:
            p.x += sx
            p.y += sy
            x += 1
            y += 1

        elif px < py:
            p.x += sx
            x += 1
        else:
            p.y += sy
            y += 1

        if blocked_cells.has(p):
            result = false

        _points.append(p)

    return result

```

I've also tried Bresenham's line algorithm and the Bresenham supercover modification, this and this, as well as this, but none did the trick

Any insight would be appreciated - thanks in advance!

# Answer
The solution was to use "A Fast Voxel Traversal Algorithm for Ray Tracing", as suggested by DMGregor, to trace a ray from/to "world" position instead of a grid cell's coordinate. I implemented the algorithm based on this site: https://www.flipcode.com/archives/Raytracing\_Topics\_Techniques-Part\_4\_Spatial\_Subdivisions.shtml

Some of the other links I visited during my research:
> 3 votes

---
Tags: 2d, algorithm, grid, line-of-sight
---


# Question
Title: Describe a 'seam' of material within Voronoi map
This is my first foray into game programming. I am using Monogame (XNA replacement).

I have begun playing around with a 2d map generator (Think Terraria) and have started off with generating the initial map using the Voronoi method. This is working successfully so far as a prototype. I'm currently just outputting the map as an array of ASCII characters to represent a material or biome type. Example: % = Granite, @ = Dirt etc.

I now want to be able to randomly create 'seams' of different material in this map, given a start and endpoint (x,y), magnitude, and a varying thickness of the material and to make the line of material change direction to a certain degree, especially if it is quite long.

Example map. What I am trying to achieve is represented by the letter 'G', 'S' and 'E' are start and endpoints (*You may have to scroll the code view to the right*)

```
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGEG%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGG%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGGGG%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGGG%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGG%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GGG%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GG%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%S%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$oooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$oooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ooooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ooooooooooooooo%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

```

Setting the start and endpoints is easy enough but doing the rest eludes me. I've had disappointing results when writing code that simply decrements the y value by one, and then randomly decreasing/increasing x by 1 (*With bias on a direction based on if the end position is left or right of start point*) and changing the material at that point.

The above method I am using also doesn't work if the start and end are horizontal.

The aim is to pre-generate as much of the map as possible using a large 2-dimensional array which will then be used for placing the correct block material. The array will only be used at the start of the game world.

P.S. If anyone also has advice regarding the way I am going about generating a starting map please feel free to let me know if I'm to avoid generating the map as an array of ASCII chars :-)

# Answer
I think looking up the math and algorithms behind “random walks” would solve your problem. You basically select a range of angles and a range of step lengths, and the probability to change direction. Each iteration it walks forward by the step length and then decides whether it changes direction.

https://en.wikipedia.org/wiki/L%C3%A9vy\_flight

For your use case, you’ll need to add a width to this so it can affect surrounding tiles. You’ll also need some way to deal with map edges.
> 0 votes

---
Tags: maps
---


# Question
Title: Efficient 2D grid overlay on tiles without each cell being its own GameObject
So for my game I need the ability to add a grid overlay over my tilemap. Now I don't think that making the grid with each cell being its own GameObject with some SpriteRenderer would be hard to do but I know it would be extremely inefficient. I was thinking about using a LineRenderer to draw the grid lines but I don't know how to make the cells have their own traits since they wouldn't be their own individual instance and more of a product of the grid lines. In my case, the cells need their own color and should all have the ability to be accessed individually and that's where I need your help. Do you guys have an idea on how to make this efficient?

# Answer
> 0 votes
You could make an array of structs with a struct for each cell, that includes the cell's grid coordinates and color. Then copy this into a vertex array for rendering so you have a vertex for each cell, and use a geometry shader to turn each vertex into a quad with its own color, and draw the whole grid as 1 object.

# Answer
> 0 votes
You want a grid of size N. Apply a custom shader to your tilemap. In that shader, set every pixel at (x mod N, ?) And (?, y mod N) to your desired color. (In world coordinates) The (x mod N, y mod N) gives you the current relative cell coordinates, allowing you to change drawing properties as desired.

Of course, you can easily blend with the existing texture color rather than outright replacing it, if you so choose.

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


title: String hashing design

text:
# Question
Title: String hashing design
I'm in the process of developing a game engine and I would like to refer to game objects and assets by an integer id rather than by their string name. This should avoid any string comparisons at runtime. As a result I'm trying to implement the string hashing approach that Jason Gregory describes in Game Engine Architecture.

I've got the actual hashing working, using FNV-1a in my case, but there are some parts of the design from the book that I don't understand.

```
static StringId sid_foo = internString("foo");
static StringId sid_bar = internString("bar");
...
[stringid.h]

typedef U32 StringId;
extern StringId internString(const char* str);

[stringid.cpp]

static HashTable<StringId, const char*> gStringIdTable;

StringId internString(const char* str)
{
    StringId sid = hashCrc32(str);
    HashTable<StringId, const char*>::iterator it
        = gStringIdTable.find(sid);

    if (it == gStringTable.end())
    {
        // This string has not yet been added to the
        // table. Add it, being sure to copy it in case
        // the original was dynamically allocated and
        // might later be freed.
        gStringTable[sid] = strdup(str);
    }
    return sid;
}

```
1. Presumably HashTable is a custom hash table implementation as no such class exists in C++? Is there any problem with my current setup of storing the hashed strings in a `std::unordered_map<StringID, const char*>`?
2. From my research, making the hash table static means that it is only accessible inside this translation unit. a) Why is it defined this way, and how would you then access the hash table in the rest of the game engine? b) Or do you call `internString` for every string and store the returned hash in a header #included in every file that needs access?
3. What is the purpose of making `externString` `extern`?

Thanks.

# Answer
> 4 votes
In the book, the subsection 5.4.3 you took the example from is about "ideas". It doesn't seem like the code snippet is meant to be great C++, just good enough to serve as an example that explains the concept.

Yes, you can substitute any hash map.

> "how would you then access the hash table in the rest of the game engine?"

From the book, below the example:

> When using string ids, the strings themselves are only kept around for human consumption. When you ship your game, you almost certainly won’t need the strings—the game itself should only ever use the ids.

In the book, the topic of that section is unique string identifiers for internal use. You will want to access the map for debugging only, and how you do so is up to you.

The book also mentions looking at FName as a working implementation of a similar concept.\*

Strings that are presented to the player need to be handled differently - here you have to look into localization first, because that's where most of the constraints come from.

---

PS: As a bit of unsolicited advice, this introduces a level of complexity that is unnecessary for a home-built first game engine. Just make a class that looks like FName, only declare the parts you currently need (constructor and comparison), but implement it with std::string and operator== as a first draft. When you later need the additional performance you can then change the implementation to one that uses integer comparisons.

---
Tags: c++, architecture
---


# Question
Title: Alternatives for publishing code for a game I'm going to sell?
I'm developing a game. I want to publish the source code (e.g. on GitHub) for others to review and get ideas from. But I want to sell the game at a later point. That might be much later though.

What are my alternatives here? The game will likely not have a lot of graphical assets, so just leaving them out won't do much good.

Or can I license it with a somewhat restrictive open source license and then simply unpublish it as soon as I am getting close to start selling it? What open source license would then be most restrictive?

Are there perhaps any other good examples of this?

# Answer
A software license which prohibits people from forking and monetizing your project would not be an open source license according to the open source initiative. Also, unpublishing an open source project does not revoke the license to those people who already have a copy of it. So you could close future versions of the software (assuming you didn't incorporate any user contributions without securing the copyright to them), but that doesn't prevent people from still redistributing and building upon the last version you released as open source (if someone made a backup).

What you actually seem to want to do is not *open source*, it's **source available**. This is a model where your sourcecode is public for people to view, but your retain all rights to it, so others can not (legally) fork or redistribute it. Keep in mind that you can't *technically* prevent people from doing that, only *legally* by sending your lawyer after them when they violate your terms.

If you decide to go for a source-available model, then Github might not be the right platform for you. While you don't *have* to add an open source license to a Github project (even though they encourage it), many people will (falsely) assume that when it's on Github, it got to be open source and they can do whatever they want with it. Also, the whole Github platform is designed around bazaar-style open source collaboration. This includes the ability to fork your project with one click, which you can not switch off or prohibit (Section D5 of the terms of service). It might be better to host the sourcecode on your own website where you retain control over how it's presented.
> 2 votes

---
Tags: licensing, open-source
---


# Question
Title: How do i instantiate the ball back to its original position once it got destroyed?
```
private void LockBallToPaddle()
{
    Vector2 paddlePos = new Vector2(Paddle.transform.position.x, Paddle.transform.position.y);
    transform.position = paddlePos + paddleToBall;   //For the ball to stick to the paddle
}

```

this is my coding for the ball stick to the paddle.

do i just instantiate as per normal? like instantiate("gameobject", transform.position) ?

# Answer
There are several ways to do that, and which one is the best for you depends on how you built your game and what features you consider to add later.

Making the ball responsible for reinstating itself when destroyed might be possible by having it remember its original position in `Start()`, implementing its OnDestroy event and creating a clone of itself with `Instantiate(gameObject, startPosition)`. But I would not recommend it. The reason is that it is now difficult to *really* destroy the ball when you *actually* want to get rid of it. You can do it by first disabling the script which causes the ball to respawn itself, but that's easy to forget. And you might also find yourself in circumstances where that's hard to do.

What I would prefer instead is to work with a separate gameObject with a separate script "BallSpawner". This object serves the following purposes:

1. Represent the point in your scene where you want the ball to spawn. Having an invisible gameObject for that is useful, because you can now place it visually in your scene and even move it during the game.
2. Spawn a ball when the game starts
3. Check if the ball still exists (hint: variables pointing to destroyed gameObjects are considered equal to `null` in comparisons)
4. Spawn another ball when it doesn't.

Untested code:

```
class BallSpawner : MonoBehaviour {
    public GameObject ballPrefab;
    private GameObject currentBall;

    void Update() {
        // check if the ball does not exist yet or got destroyed
        if (currentBall == null) {
             // create a new ball at the position of the BallSpawner
             currentBall = Instantiate(ballPrefab, transform.position);
        }
    }
}

```

Another option would be to make the scripts which destroy the ball responsible for reinstantiating it. You can do that by just creating another instance of the ball you are just about to destroy. I assume you have some trigger-area behind each paddle which destroys the ball? Then I think it should look something like this (again, untested code):

```
class BallDestroyer : MonoBehaviour {

    public Vector3 ballRespawnPosition;

    void OnTriggerEnter(Collider other) {
        if (other.tag == "Ball") { // <-- always verify that the object is the one you expect!
            Instantiate(other.gameObject, ballRespawnPosition);
            Destroy(other.gameObject)
        }
    }
}

```
> 1 votes

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


# Question
Title: Fixed timestep game loop, why interpolation
This is a very standard way of doing a fixed timestep game loop, where you just accumulate time from the previous frame and consume it in discrete steps with the physics engine:

```
    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

```

A lot of articles suggest that with the residual lag we should do an interpolation between the previous update and the current one, BUT it does not make any sense to me!

If you have residual lag it means that you still have some time to catch and you should ***EXTRAPOLATE*** the current state. Why would you ever do an interpolation with the previous state?

# Answer
> 34 votes
Some games do indeed extrapolate.

An advantage of extrapolation is that you can do it with just the single most recent state and a rate of change (like velocity, angular velocity, etc.) rather than two complete states. So it is simpler to implement and compute.

The main disadvantage of extrapolation is that it's a prediction about the future, and like most such predictions, it can be wrong.

Say the player has just started changing directions or slowing to a stop, but their current velocity is still pointing in their old travel direction. With extrapolation, they'll see themselves overshoot, then snap back to a different course when the next simulation step factors in the change in velocity, resulting in a jerky appearance that can look a bit like a bad framerate or network lag (even when both those systems are running smoothly).

Since you're generally not running a full simulation step for the extrapolated state, systems like collision detection don't run on these in-between frames. So your extrapolated velocity might take you partway into a wall or floor, or over-extend a physics joint beyond its correct range of motion, before the next simulation step correctly resolves this situation.

These artifacts usually aren't game-breaking, but they can be quite unsightly.

In contrast, by interpolating two previous simulation steps, we have a strong guarantee that we'll have continuous motion: the end of one interpolated interval is guaranteed to match the start of the next one, unlike with extrapolation. And because we're blending between two known-good states, the chances we do something ridiculous in-between like pass through a solid object or rip apart a physics joint are greatly reduced.

The cost is that the state we're displaying is technically a tiny fraction of a second older.

But "older than *what*?" is the question. The player's perception of what constitutes "now" in the game is informed by the visible, audible, and tactile feedback we present. If the numbers inside the computer memory representing the most recent state we simulated are technically a tiny fraction of a second ahead of the displayed state, it's difficult for the player to observe that directly.

The one place it can be perceived is in input latency. The player knows "I pressed this button now" so if it takes a few frames for visible/audible/tactile reactions to that button press, that can reveal the time mismatch.

Fortunately, as I explain in more depth in this answer, this input latency is often much less than you might expect, and by eagerly presenting fresh input feedback immediately, even on an interpolated frame, we can shrink the perceived latency down to the resolution of our display framerate.

So we can make a game that feels just as responsive as one that's extrapolating, but without the juddery errors of mis-prediction, and that's why we usually prefer to interpolate.

# Answer
> 0 votes
Interpolation with the last two known simulation states also makes little sense to me. You do want some smoothing to gloss over the situation where your simulation and render "frame time" are not full dividers. Some frames will get either an extra simulation tick or one less.

IMHO the sensible solutions are:

**Use simulation values unfiltered.**

If your simulation dt is sufficiently small this may actually be an option. This means the simulation is "as close" as possible to the rendered frame as possible. This only works well when your simulation frame rate is high. This becomes a real problem if your simulation frame rate is slower than your render frame rate.

**Extrapolate simulated values.**

You can extrapolate the simulated values and will try to replicated the missing time. The down side to this is if done blindly you will get additional stutter as the extrapolated values update. (Temporal moiré and extrapolation inaccuracy.)

**Interpolate view values with simulation values.**

This is almost what you alluded to, but not the last two values of the simulation, but the last value of the view and the current simulation. The last view value is not the last simulation as that contains all previous interpolations. This results is a smooth motion, but drags by somewhat of a frame.

**Interpolate view values with extrapolated simulation values.**

This takes both previous approaches, you take the last view values and interpolate them with extrapolated simulation values. This soothes the motion but also tries to compensate for lagging a frame behind.

---

If you can guarantee high tick rate of the simulation and preferably the rendering, I would not bother with interpolation as it just introduced more noise as necessary. But in my experience this is never a given. I have reasonably good experience with the two last options. But as DMGregory writes, latency generally is not so much of an issue, the smoothness of the motion is what you tend to notice.

# Answer
> 0 votes
The code you posted looks a lot like Glenn Fiedler explaining why you should interpolate. Let me add additional clarification to his writing:

> Any remainder in the accumulator is effectively a measure of just how much more time is required before another whole physics step can be taken. For example, a remainder of dt/2 means that we are currently halfway between the current physics step and the next.

After you've produced your new `currentState` and your `accumulator` is greater than zero but less than `dt`, you have a state that is in the future.

If a car was travelling at 10 m/s, you may have simulated 0.02 s of it's movement, but you only wanted 0.01666 s of it's movement to match your 60 fps render speed.

> We can use this remainder value to get a blending factor between the previous and current physics state simply by dividing by dt. This gives an alpha value in the range \[0,1\] which is used to perform a linear interpolation between the two physics states to get the current state to render.

Use interpolation to determine the current state as a point between the past and the future states. Note how `previousState` is overwritten each time in the accumulator loop so it's the state right before the last time we ran a simulate step.

---

I think some confusion may come from assuming you could pass `accumulator` into `integrate(currentState, t, dt)` instead of `dt`, but that's covered in the "Variable delta time" section of Fiedler's post:

> The problem is that the behavior of your physics simulation depends on the delta time you pass in. The effect could be subtle as your game having a slightly different “feel” depending on framerate or it could be as extreme as your spring simulation exploding to infinity, fast moving objects tunneling through walls and players falling through the floor!

Possibly, you could solve this by changing your simulation to handle variable delta time values but Fielder is doubtful:

> One thing is for certain though and that is that it’s utterly unrealistic to expect your simulation to correctly handle any delta time passed into it. To understand why, consider what would happen if you passed in 1/10th of a second as delta time? How about one second? 10 seconds? 100? Eventually you’ll find a breaking point.

Likely, you'd have to introduce a lot of iterations into your logic. It's easy to imagine it working for any delta time if there's only one object, but when you have 10 balls dropped in a pile, how do you handle updating each one of them with any size delta time? You'd have to run many small step iterations to ensure balls that would collide actually collide and then you've just replicated the post's final solution.

---
Tags: physics, game-loop, fixed-timestep
---


# Question
Title: My object just automatically "launch" or do stuff without me clicking on my mouse when it respawn?
I've already set the ball (my object) initially at the start where I have to click for the ball to launch from the paddle (it's a ping pong game).

```
private void LockBallToPaddle() {
    Vector2 paddlePos = new Vector2(Paddle.transform.position.x,
        Paddle.transform.position.y);
    transform.position = paddlePos + paddleToBall; //For the ball to stick to the paddle
}

```

Launch the Ball:

```
private void LaunchBall() {
    if (Input.GetMouseButtonDown(0)) {
        hasStarted = true;
        rbBall.velocity = new Vector2(Random.Range(-2f, 2f),speedVelocity);
    }
}

```

Both of which I put under Update()

```
private void LaunchBall() {
    if (Input.GetMouseButtonDown(0)) {
        hasStarted = true;
        rbBall.velocity = new Vector2(Random.Range(-2f, 2f),speedVelocity);
    }
}

```

Now the problem is when my ball hits a certain collider, I want it to respawn the position back to the paddle. So instead of Destroy the game object, I just copy and paste those same methods under collision

```
if (collision.gameObject.tag == "bottom") {
    LockBallToPaddle();
    LaunchBalls();
}

```

But now it just launches straight away from the paddle when hit the collision without me clicking anything like what "Launchballs()" intended to. What should I do?

# Answer
If one piece of code was working and the other is not, you can try to figure out the difference between it. In this case it is destroy();

The old code was creating a new ball at your launchpad. Your new code just takes the ball and teleports it at the launchpad BUT by doing so, it keeps the velocity it has before and your ball flies gladly in the direction it did before.

You could set the velocity inside your LockBallToPaddle since it handles already the teleport. You probably want to reset your hasStarted to false as well, whatever it does.
> 1 votes

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


# Question
Title: Need help with gravity simulation in 2D game engine
I'm writing a 2D game engine using C++ and SDL2 and started implementing a `rigidbody` component similar to that of unity to my game objects. I have a method in the `rigidbody` class called `AddForce` which takes a 2D vector force as a parameter and calculates the velocity vector using \\$F = MA\\$.

I use this function to move the character left and right using the keyboard arrows. Now my question is, how do I manage the gravity with this and how do I calculate the resultant force of the gravity and the force applied when pressing either keyboard arrows.

Here is the `rigidbody` class:

```
#ifndef RIGIDBODY_H
#define RIGIDBODY_H

//Game engine libraries
#include "gameEngine/Game.h"
#include "gameEngine/GameObject.h"
#include "gameEngine/Component.h"
#include "gameEngine/components/Transform.h"

//GlM library
#include "glm/glm.hpp"

class RigidBody : public Component
{
private:
    Transform* m_transfrom;
private:
    float m_mass;
    float m_acceleration;
    glm::vec2 m_forceApplied;
    glm::vec2 m_velocity;
private:
    float m_deltaTime;

public:
    RigidBody(float mass)
    {
        m_name = "RigidBody";
        m_mass = mass;
        m_acceleration = 0;
        m_forceApplied = glm::vec2(0,0);
        m_velocity = glm::vec2(0,0);
     }
public:
     void AddForce(glm::vec2 force, float deltaTime)
     {
        float forceMagnitude;
        m_deltaTime = deltaTime;
        m_forceApplied = force;

        forceMagnitude = glm::length(force);
        m_acceleration = forceMagnitude / m_mass;
      }
 private:
     glm::vec2 CalculateVelocity()
     {
         float velocityMagnitude;
         static glm::vec2 newVelocity = glm::vec2(0,0);

         velocityMagnitude = m_acceleration * m_deltaTime;

         if(m_forceApplied.x != 0 || m_forceApplied.y != 0)
             newVelocity = glm::normalize(m_forceApplied);
         else
           newVelocity = glm::vec2(0,0);

         newVelocity = newVelocity * velocityMagnitude;

         return newVelocity;
      }

 public:
    void Initialize() override
    {
        m_transfrom = m_owner->GetComponent<Transform>("Transform");
    }
    void Update(Game instance, float deltaTime) override
    {
        m_velocity += CalculateVelocity();
        m_transfrom->position.x += m_velocity.x * deltaTime;
        m_transfrom->position.y += m_velocity.y * deltaTime;
    }
    void Render() override
    {

    }
 };

 #endif

```

# Answer
Have a look at semi-implicit Euler integration - there's an example at the end for an 1D spring. This is what you're basically doing. Also, you have no need for working with magnitudes and normalized directions. Just add the applied forces times the delta time to the velocity. That's all you need to do.

Now, to answer your question, you need a force accumulator. See this course for more details. It could be `m_forceApplied` in your case. And every time you call `AddForce` you just add force to it. And in `CalculateVelocity` you just do `m_velocity += m_forceApplied * deltaTime / m_mass`. And you can add gravity using `AddForce` and the `m * g formula` as Sascha was saying. Or you can hardcode it directly: `m_velocity += (m_forceApplied / m_mass + gravity) * deltaTime`.

Update: I corrected myself, I realized I used the mass wrong in the integration, it was not adding up.
> 0 votes

# Answer
If you're using a physics model which takes only forces as input, weight is simply the product of the object's mass with a gravity constant. If the object's mass is constant then you can simplify the weight to also be a constant.

If the object is lying on the ground or another surface, you also have to add the reaction force.

The resultant of the forces is the sum of all forces acting on the object : gravity, reaction force if any, force resulting to user input if any.
> 0 votes

---
Tags: c++, physics, sdl2
---


# Question
Title: Rotate object relative to camera position
I am trying to write code that is able to rotate object, based on camera position. So far I ended up with a code posted below. Moving mouse up and down (y input) caused to rotate object in y axis, instead of x. That's why I used cross product.

Achieved result is working not exactly as I expected. Rotation is different for every object, dependent on their pivot. I am not exactly sure how it fix it properly.

```
public class DragRotate : MonoBehaviour
{
    public Camera camera;
    public float rotationSpeed = 1;

    private void Update ()
    {
        float x = Input.mousePosition.x * rotationSpeed;
        float y = Input.mousePosition.y * rotationSpeed;

        var rot = camera.transform.TransformDirection (new Vector3 (x, y));
        rot = Vector3.Cross(rot, camera.transform.forward);

        transform.rotation *= Quaternion.Euler (rot);
    }
}

```

This script will be primarily used with one axis rotation, this feature is not implemented in code yet, but it's shown in the use case. According to attachment, I want to rotate selected cube (visible pivot is set to global). It's worth to say, that in this examples padlock has always same position and rotation, the only thing that changes is position and rotation of the camera:

1. a) Swipe from bottom to top - negative rotation on X axis.b) Top to bottom positive on X axis. c) Other axes should be locked, but for example swipe from right bottom to left top should rotate like example a), but taking into consideration only y (vertical) input.
2. This should behave exactly like example 1, but taking camera rotation into account. So 1a is 1b, 1b is 1a etc.
3. Swipe from left to right should result in 1a rotation, swipe from right to left should result in 1b rotation. Bottom to top or top to bottom should have no effect at all.

# Answer
If I understand your problem correctly, all you need to do is rotate the object around its *local* X axis, regardless of how the mouse moves on the X-Y plane of the camera. What I would do is look at Transform.localRotation first and then, depending on whether the local X axis is aligned with the world X axis or is perpendicular to it, I would use the mouse position of either Y or X respectively and perform a local rotation accordingly, depending on the magnitude of Y or X.
> 1 votes

---
Tags: unity, mathematics, transformation
---


# Question
Title: The farther I move my character, the more its projectiles fire in the wrong direction
I'm making a top down shooter, and the movement is working fine.

However, I'm having trouble getting my Fire function to work correctly. When I run the game, it kind of fires in the right direction, but the more I move, the more off the shooting becomes. Anyone have any idea why?

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private float _horizontalInput = 0;
    private float _verticalInput = 0;

    public int movementSpeed = 2;
    public int rotationSpeed = 2;

    Rigidbody2D rb2d;

    float coolDown = 0;

    public Rigidbody2D bulletPrefab;
    public float attackSpeed = 0.5f;
    public float bulletSpeed = 500;
    public float yValue = 1f; // Used to make it look like it's shot from the gun itself (offset)
    public float xValue = 1f; // Same as above

    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {

        MovePlayer();
        RotatePlayer();
    }

    void Update()
    {
        GetPlayerInput();

        // Determines if the player can fire
        if (Time.time >= coolDown)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                Fire();
            }
        }
    }

    private void GetPlayerInput()
    {
        _horizontalInput = Input.GetAxisRaw("Horizontal");
        _verticalInput = Input.GetAxisRaw("Vertical");

    }

    public void MovePlayer()
    {
        rb2d.velocity = transform.right * Mathf.Clamp01(_verticalInput) * movementSpeed;
    }

    private void RotatePlayer()
    {
        float rotation = -_horizontalInput * rotationSpeed;
        transform.Rotate(Vector3.forward * rotation);
    }

    private void Fire()
    {
        Rigidbody2D bPrefab = Instantiate(bulletPrefab, new Vector3(transform.position.x + xValue, transform.position.y + yValue, transform.position.z), transform.rotation) as Rigidbody2D;

        bPrefab.GetComponent<Rigidbody2D>().AddForce(transform.position * bulletSpeed);
        coolDown = Time.time + attackSpeed;
    }
}

```

# Answer
> 1 votes
Two mistakes on this line:

```
bPrefab.GetComponent<Rigidbody2D>().AddForce(transform.position * bulletSpeed);

```
1. You're passing a *position* where it looks like you want to pass a *direction*.

Try `transform.right` to fire along the object's x (red) axis, or `transform.up` to fire along the object's y (green) axis. If you need a different direction, edit your question to include a diagram.
2. You're passing a *velocity* to a function that expects a *force*.

Try `Vector2 velocity = transform.right * bulletSpeed;` then either...

`bullet.GetComponent<Rigidbody2D>().velocity = velocity;`

or

```
var body = bullet.GetComponent<Rigidbody2D>();
body.AddForce(body.mass * velocity, ForceMode2D.Impulse);

```

Also, don't name your instance variable `bPrefab` with "prefab" in the name - it's *not* a prefab, it's an *instance of* the prefab, which is a different object. Misleading variable names eventually come back to bite us in confusion down the line, so keep them well-matched to their actual meaning.

---
Tags: unity, 2d, projectile-physics
---


# Question
Title: Clipping speed when turning without using aggressive drag
I have a Unity project in which I want to control a player in a similar way to Source games, and so far I am clipping each input to the speed in the player's coordinates, by using

```
transform.InverseTransformDirection( GetComponent<Rigidbody>().velocity )

```

after which I pass each of the player's input vector direction through this function:

```
private float FLSMF ( float aInputVelocity, float aMaximumVelocityOnAxis, float aSpeedOnAxis ) {
    if ( Mod( aSpeedOnAxis ) >= aMaximumVelocityOnAxis ) {
        if( Sign( aSpeedOnAxis ) != Sign ( aInputVelocity ) ) {
            if ( Mod( aSpeedOnAxis + aInputVelocity ) > aMaximumVelocityOnAxis ) {
                return Sign ( aInputVelocity ) * ( aMaximumVelocityOnAxis + Mod( aSpeedOnAxis ) );
            }
            return aInputVelocity;
        }
        return 0;
    }
    if( Mod( aSpeedOnAxis + aInputVelocity ) > aMaximumVelocityOnAxis ) {
        return Sign( aInputVelocity ) * ( aMaximumVelocityOnAxis - Mod( aSpeedOnAxis ) );
    }
    return aInputVelocity;
}

```

There is only one problem: whenever I turn and strafe and walk forwards or backwards, the speed increases dramatically. I tried solving it by comparing each processed velocity axis to the velocity rotated by the difference in the rotations between the last 2 FixedUpdate's. So far nothing worked, aside from driving the drag factor through the roof.

My best guess is that when turning, the unclipped X axis of the vector bleeds into the Z axis when turning, which can't add anything, but cant stop the X axis from interfering because the forward key is pressed.

There is no issue when only one of the input axis are used, the speed remaining consistent when turning.

I tried to implement this function especially so I don't have to use any drag, to allow the player to be flung by other things, like grapples and explosions (this issue is present irrespective of said external factors).

If you want to, I will share the entire code, but it's messy and I don't think it would help.

Any ideas how to solve it?

Edit: yes, I have normalized the input vector. The speed increases to more than triple of the maximum, in as few as 2 turns.

# Answer
The usual pattern I use for this is something like...

```
void FixedUpdate()
{
    var movementInput = new Vector2(
                                 Input.GetAxis("Horizontal"),
                                 Input.GetAxis("Vertical")
                            );

    // Ensure our movement input never exceeds a radius of 1.
    var movementInput = Vector2.ClampMagnitude(movementInput, 1f);

    var movementFrame = Quaternion.LookRotation(-groundNormal, camera.forward);

    // Accelerate up to, but not past, our max speed.
    var desiredVelocity = movementFrame * (Vector3)(movementInput * maxSpeed);
    AccelerateTo(desiredVelocity);
}

void AccelerateTo(Vector3 desiredVelocity) {
    // Compute the desired change in velocity.
    var deltaV = desiredVelocity - body.velocity;

    // Enforce our maximum acceleration limits when speeding up or slowing down.
    float limit = maxAcceleration;
    if (Vector3.Dot(body.velocity, desiredVelocity) <= 0f)
        limit = maxDeceleration;

    deltaV = Vector2.ClampMagnitude(deltaV, limit * Time.deltaTime);

    body.AddForce(deltaV, ForceMode.VelocityChange);
}

```

This ensures the player can never push themselves to go faster than `maxSpeed` in any direction, and propels themselves with only a finite acceleration or deceleration.

I usually keep the `maxAcceleration` quite high for tight controls, and the `maxDeceleration` even higher so you stop quickly when you let go. But you can vary these two variables depending on the game state - dropping them when the player is on slippery terrain or in a knockback state where you want them to keep moving inertially.
> 0 votes

---
Tags: unity, c#, movement, rigidbody
---


# Question
Title: How can I handle input in C without halting the main loop?
I want my C program to update the console every second, and it was working fine until I tried to handle input. Now the program halts since it waits an input from the user. How can I do this?

```
while(true) {
    ShowConsole();  //Show
    Sleep(1000);        //Wait
    scanf("%s",&a)      //Handle Input
    Update();
    ClearScreen();      //Clear
}

```

# Answer
> 1 votes
I took the liberty to try and tackle this myself.

Solely based on the question text, it's not super clear what kind of game you're trying to do, so I took the approach of a kind of *snake* game, where the snake will move, whatever the player is doing (or not doing).

I used `Sleep` to pace the input polling and the redraw rate, and `_kbhit()` to *maybe* read a character, and the `clock_t`/`clock()` to update the game once per second.

Now I'm not a `c` programmer, so I don't know if this `c` code is "elegant" (it's probably not), but it worked on my machine (Windows, Visual Studio).

```
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <ctype.h>
#include <windows.h>

typedef int BOOL;
#define FALSE ((int)0)
#define TRUE ((int)1)

void ClearScreen()
{
  // code here that clears the screen, see https://stackoverflow.com/a/42500322
}

int main( void )
{
  BOOL run = TRUE;

  clock_t lastTickClock = clock();
  int position = 0;

  char registeredCommand = 'd'; // Command that will be effective at the next game tick.
  while ( run )
  {
    char currentCharIfAny = 0; // The char that is read this loop.
    if ( _kbhit() )
      currentCharIfAny = _getch();

    if ( currentCharIfAny == 'a' || currentCharIfAny == 'd' )
      registeredCommand = currentCharIfAny; // We only respond to 'a' or 'd'.

    clock_t newClock = clock();
    if ( ( newClock - lastTickClock ) > CLOCKS_PER_SEC )
    {
      // This is the command handling/the game tick
      if ( registeredCommand == 'a' )
        position = max( --position, 0 );
      else if ( registeredCommand == 'd' )
        position = min( ++position, 24 );

      lastTickClock = newClock;
    }

    char buffer[1024];
    buffer[0] = 0;

    for ( int i = 0; i < position; ++i )
      strcat_s( buffer, 1024, " " );
    strcat_s( buffer, 1024, "_\n" ); // This underscore represents our "agent" or "game token" or "paddle".

    // The following is only for debugging purpose; it prints the character we're currently handling.
    if ( currentCharIfAny >= 'a' && currentCharIfAny <= 'z' )
    {
      char lbuff[2]; lbuff[0] = 0;
      sprintf_s( lbuff, 2, "%c", currentCharIfAny );
      strcat_s( buffer, 1024, lbuff );
    }

    ClearScreen();
    printf( "%s\n", buffer );
    Sleep( 1000 / 60 );
    if ( currentCharIfAny == 'q' )
      run = FALSE;
  }

  printf( "\ndone. press a key to quit." );
  _getch();
  return 0;
}

```

A couple of things to note:

* there are probably other (better) ways to achieve this: for now, when I refresh (ClearScreen), the screen "flickers" a bit.
* on Windows, the OS will "pace" the repeat rate of the character it sends to the apps, so when you hit `d` for instance, the program will show that you're hitting `d`, then it will show that you're hitting no key, then it will show you're hitting `d` again, until you release the key.
* like your own implementation, it's not portable due to the nature of the functions used.

# Answer
> 0 votes
Although I had to use non-portable code, I got it to work without a need of a third-party library. Also it turns out \_kbhit() function delays buffer so you do not need to wait for 1 second to enter the full string. However the written string was being cut if it is not written in a second. So I also showed it in ShowConsole() function.

Note: This is a non-standart, non-portable code. Works in my OS (Windows).

```
char key;
    if(_kbhit()){
        key = _getch();
        if(key == 13){                  //If Enter key is pressed
            HandleInput(moveInput);     //handle the input string
            memset(moveInput, 0, 6);    //clear input string
            moveIndex=0;                //reset string index to 0
        }
        moveInput[moveIndex] = key;     //If any other key is pressed, add the hit character to string input
        moveIndex++;
    }

```

In ShowConsole() Function:

```
ShowConsole(){
    .
    .
    .
    printf("%s", moveInput); // At the end of showing the graphics, also show the input that is being written.
}

```

---
Tags: input, game-loop, c, text-based
---


# Question
Title: Recommendations to protect music and sound effects
I can make some very basic music and sound effects, but prefer to have some actual real audio happening. There are some audio that does support game development - Artlist for one. They state that the music and audio is fine to include in a game, as long as you don't offer them as a jukebox style where the player can select tracks. They also stated that the license is not transferrable, so I would need to ensure to prevent anyone from extracting the assets and grabbing the sounds/songs directly.

I am using MonoGame for my project with .NET Standard and .NET Core. Is there really a perfect way to prevent someone from accessing the files? Would encryption be recommended? Should I instead have my game download audio assets on startup from a website?

# Answer
There are no perfect ways to protect content. If your game can read it, then somebody else who reverse engineers your game code can potentially read it.

It is possible to make it harder and harder for somebody to directly read the assets, or reverse engineer your code, but it is not possible to make it completely impossible.

Even if you made it really really hard to do so, somebody with a microphone pointed at the speakers when the game reproduces the sound can pick it up and steal it. This is called the analog hole.

IMPORTANT: I AM NOT A LAWYER. THE TEXT BELOW IS MY AMATEUR ANALYSIS, AND IS NOT ANY KIND OF LEGAL ADVICE.

That said, the restriction is on sublicensing the content. Somebody stealing your content doesn't mean that you sublicensed it to them. In other words, the one breaking the law is the person who stole the content, not you, since you didn't sublicense it.

In general, the idea behind these licenses is that the creators of the contents are okay with you putting it inside a large project, and as long as the content is not trivially re-offered (for example, as a jukebox), they're okay with it.

If you're concerned, you could consult a lawyer to interpret the specific licensing terms, and explain to you what you can and can't do. At the very least, you could contact the owners of the content and ask for a clarification.

All in all, I'm not sure how common it is for people to try to steal individual sound effects from a game. Sound effects by themselves are not very useful to a potential hacker, so the incentives for stealing them are not very high. Also, sound effects are really cheap to make or license, so I find it really hard to think a case of somebody going all the way to reverse engineer your game just to steal some sound effects, just because.
> 1 votes

---
Tags: assets, asset-management
---


# Question
Title: Swept 3d capsule intersection with AABB, what am I actually supposed to use to accomplish this?
I'm trying to figure out how to do continuous collision with a capsule (which would represent a collision volume for a player for example).

Given how common the *capsule* is in many game engines, and the fact it is merely a circle swept along a line, I would assume that even just normal collision between it any boxes, triangles/arbitrary facets would be abundant, however, I'm having a hard time finding *anything* on capsule collision.

Somehow I guess I could figure out the swept volume/object intersection (box + 4 capsule collision detection), and binary search my way down to an approximate collision, but this seems far from ideal, especially given the simple shapes involved. I feel given the shapes I should be able to intersect directly and receive the results. I'm not sure how to figure out "where" something intersected along with a swept series with other methods (like GJK).

For my case, I'm currently focused on just AABB collisions and vertically oriented swept 3D capsules, which I hope to resolve (move capsule appropriately back with AABB collision).

# Answer
There is no one-size fits all answer to help you here, it really depends on how you want your game to feel and what abilities you want your player to have. Starting with a capsule is a great start, from here Ray cast a vector downwards from the capsules feet to test how far the capsule is from an AABB. then if that distance is less than how far the entity would fall on the next frame, you can set a flag that the entity is on top of something and snap it to the ground position returned from the ray cast.

This can be expanded to ray cast out from the feet at 45 degree angles in a ring to test if the player is approaching a slope. If one of these side rings hits an aabb figure out what surface geometry the player is actually hitting with a narrow phase collision with that mesh, then from this mesh you can figure out the normal of the triangle that you actually hit, if this normal is less steep than the max incline you want the player to be able to walk up move the player in the direction they are walking and let the downwards raycast slide them up the mesh.

This is a good start that you can expand upon!

Here is a video trying to convey these concepts farther. Specifically this part of the video https://youtu.be/LTlBElDPDDM?t=1164
> 1 votes

---
Tags: collision-detection, physics, 3d, collision-resolution, aabb
---


# Question
Title: Why does my material look blotchy on this mesh?
This is a generative mesh - wireframe looks like this

Here's the material

But the shaded object looks like a tie dye tshirt

I've no idea what settings are causing it to look like this. These are the settings of the mesh renderer

# Answer
> 1 votes
It appears like you generated the mesh vertices, but did not generate any texture coordinates (aka uv map) for them. Texture coordinates are important, because they tell the renderer which part of the texture should be visible on which polygon of your 3d mesh.

So when you generate a mesh using the Mesh class, make sure that you don't just fill the `.vertices` array but also the `.uv` array with one `Vector2` for each `Vector3` in your vertices array.

---
Tags: unity, 3d, mesh, materials
---


title: World position into local position

text:
# Question
Title: World position into local position
I want to understand how I can convert world position of an object into local position. Especially how to deal with a rotation of objects.

I'm testing transform.InverseTransform(...) methods. When parent and child has 0 rotation, this methods easily convert world into local position. I don't know how to deal with a situation, when one of the objects has not zero rotation.

In the example below my parent object has (0,0,10) position and (0,0,0) rotation. Child position (0,0,0) and rotation (90,0,0).

```
Debug.Log (string.Format ("World position: {0}\nLocalPosition: {1}\nInverseTransformPoint: {2}\nInverseTransformVector: {3}\nInverseTransformDirection: {4}\nTransformPoint: {5}\nTransformVector: {6}\nTransformDirection: {7}",
transform.position.ToString (),
transform.localPosition.ToString (),
transform.InverseTransformPoint (transform.position).ToString (),
transform.InverseTransformVector (transform.position).ToString (),
transform.InverseTransformDirection (transform.position).ToString (),
transform.TransformPoint (transform.localPosition).ToString (),
transform.TransformVector (transform.localPosition).ToString (),
transform.TransformDirection (transform.localPosition).ToString ()));

```

The example debug result:

```
World position: (-1.0, -0.7, 10.0)
LocalPosition: (-1.0, -0.7, 0.0)
InverseTransformPoint: (0.0, 0.0, 0.0)
InverseTransformVector: (-1.0, 10.0, 0.7)
InverseTransformDirection: (-1.0, 10.0, 0.7)
TransformPoint: (-2.1, -0.7, 9.3)
TransformVector: (-1.0, 0.0, -0.7)
TransformDirection: (-1.0, 0.0, -0.7)

```

What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition?

# Answer
> 3 votes
> What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition?

Add `parent`:

```
transform.parent.InverseTransformPoint(transform.position) == transform.localPosition

```

`transform.localPosition` is the position of this object in its *parent's* coordinate system.

`transform.InverseTransformPoint()` transforms a position from world space into *this* object's coordinate system. So naturally when you take the worldspace position of this object's origin and transform it into *its own* coordinate system, you get zero - that's what "origin" means.

---
Tags: unity, mathematics, rotation, position
---


# Question
Title: How to put trees on procedural generated world created using Perlin noise
I have been new to game programming but I knew little bit about Perlin noise. So I have created a infinite world using Perlin noise but I don't be able to understand how I put trees in my world like it is put in game Factorio. My game is a 2d top down.

# Answer
I assume you already created a Perlin noise which is supposed to represent the tree density and now you wonder how to feed this noise map into your tree spawning system.

The simplest approach is to place a tree on every position where the amplitude of the Perlin noise exceeds a specific level. That will give you islands of dense grids of trees separated by oceans completely devoid of trees. Or a dense forest grid with occasional clearings, depending on the chosen cutoff level.

Sometimes that's exactly what you want, like in RTS games like *Warcraft* or *Age of Empires* where forests are both resources and obstacles. But in other cases you usually want a more organic look with trees placed a lot more randomly and with varying density.

If you are looking for a more natual look, then it's a good way to treat the amplitude of the noise as a tree *probability*. A simple way to do that is to roll a random number for every possible tree position and place a tree if that number is smaller than the amplitude of the tree-noise at that position. So areas with a high amplitude will statistically generate more trees than areas with a low amplitude.

As usual with procedural generation, you might have to experiment a lot to get the results you find both aesthetically pleasing and good for gameplay. Possible tweaks are a cutoff value under which no trees are generated at all, make tree probability a logarithmic or quadratic function of density, play around with placing trees not exactly on the coordinates but with a slight offset to avoid visible grids in high-density areas and many more.
> 4 votes

# Answer
Philipp's answer is great, but if you want your trees to spawn based on a world seed; so you don't have to save locations to disk or hold them in memory, there are extra steps.

Calculate a tile seed using the `x` and `y` coordinates of the tile like so.

`tile_seed = WORLD_SEED + int(x * 2) + int(y / 2)`

Set an RNG instance's seed to the `tile_seed` for the given tile's `x/y` before doing your probability checks on a tile with that RNG object and the tree will always spawn in the same location for the same world seed. you can do additional rolls with the same tile seed to get randomized properties for the objects as well.

This can be used to spawn anything into the game with randomized properties, in a repeatable way based on tile location and world seed.

Here is an example of this method in action: https://gfycat.com/obesewanhummingbird

I use godot engine, and godot engine wraps around on 64 bit integers if they exceed the bounds, so in theory it should be perfectly safe for pretty much any coordinate.
> 1 votes

---
Tags: unity, c#, procedural-generation, pixel-art
---


# Question
Title: is unity DOTS mature enough to build a whole project on it?
maybe you assume this question opinion based but its not. please read the whole question.

the question has 2 aspects.

1. are all features implemented? just better say, can i do everything or any gameplay i did on monobehaviours, on the DOTS? all are needed features implemented? including Ai, navigation, physics, animations and...
2. the bigger problem about DOTS and ECS is software engineering. DOTS gives us much better performance in memory and performance and parallel processing but it takes all good OOP practices from us.

as you may know, DOTS is not OO and uses its own architectures. most of references values are gone in dots to make data more compact. so there is no solid principles. dependency injections and all those OO design patterns. instead we have a hardly coupled code and entities.

the question is: does DOTS and ECS really lacks software engineering or its just we dont know enough about it and there are standards about it?

many people say that you should make all project on old monobehaviours and you can migrate section that are expensive to DOTS.

im not really sure what is the right approach for using with new technology.

# Answer
> 1 votes
Looks like many DOTS-related features are still in Preview or even Experimental. As of December 2020:

* **Entities**: Preview
* **Physics**: Preview
* **Netcode**: Preview
* **DSPGraph** (audio): Experimental
* **Animation**: Experimental
* **DOTS Runtime**: Preview

You should probably start making your game with regular MonoBehaviours and only use DOTS if you find that there are performance bottlenecks.

I have not worked with DOTS, but it sounds like the development tools/libraries/coding style are so drastically different that it's almost better to think of it as a separate engine. My impression is that DOTS will be best suited for large teams/AAA projects.

# Answer
> 1 votes
I’m currently building a dots project and I’m using the new netcode too. It’s definitely ready, but by no means easy. And once in a while you’ll have to deal with breaking changes or bugs. But I would stay it’s stable enough to build a prototype from. Maybe not if you plan on releasing in the very near future. But maybe if you’re looking at mid-late next year.

As for it not being OO, on the contrary. Once my brain figured out the new patterns I’m actually finding it extremely clean and object oriented. Think of the objects more as message objects, tag objects, and data objects. The systems are objects that do a single behaviour of your program. There’s definitely way more abstraction. So you won’t have the same mapping of real world object to code object that you sometimes find in traditional unity code. But maybe that’s a good thing.

Edit: this is more of the composition vs inheritance approach. It follows a similar idea. But still OO.

There’s definitely a learning curve.

---
Tags: unity, multithreading, entity-component-system
---


title: Flexible Animation Tooling

text:
# Question
Title: Flexible Animation Tooling
I'm looking to find tools for building and exporting animations into my game. I'm not using any of the popular engines like Unity or Unreal; for the most part, I've building most of it from scratch in WebGL.

In my case, I'm building a card game, so I don't have complex character animations but I *do* have a couple of things I'd like achieve:

* Movement animations (perhaps as the cards are dealt onto the board)
* Probably rotation
* Some parameterized "highlight" effect to signal things to the player
* Maybe triggering particle effects

That sort of thing. My gut reaction is to use Blender for this and write custom exporters, but I'm wondering if there's any other tooling out there I should consider instead. I'm also curious if there's just a better workflow altogether.

# Answer
If it's 2D, Spine http://en.esotericsoftware.com/ if it's 3D, dealer's choice. Probably Blender as you mentioned, or Maya.

The better question to ask, is can you simply use math to produce those effects? Since you're building it from scratch, hooking up the API and a pipeline might just be overkill for the features you're implementing.

A spline is like a swiss-army knife in games. Same goes for interpolation. They can be used to create and pan cameras for cinematics, they can blend colors and interpolate rainbows, they can be used to create a path for your cards to travel without ever needing to animate a single thing in another program.

To be honest, your use cases are so trivial that I highly recommend implementing spline utilities and just using that. If you want a card to fly from the deck to a location, make a spline (or even just linear interpolate) from one point to another. Want the card to spin in a circle? Interpolate the angles from 0 to 2pi.

The highlight effect can be achieved with a shader quite easily. Especially considering you're already using WebGL, it should be a simple task to implement pixel-picking and a shader (or just the shader).

When I make a custom game engine from scratch or if I start working in a new environment, I always make sure to implement interpolation and splines first. So often, that I have them on my github so I don't need to do it repeatedly. Here are two examples, in C++ and in C#.

Here is a video example of someone doing precisely what I mentioned above **in WebGL** (using the fantastic three.js library) to animate a box along a path.

Here's some examples of entire games in 3D and 2D implemented in nothing but shader code and math, playable in your browser
> 0 votes

---
Tags: animation
---


# Question
Title: How to do game dev without downloading binaries?
I am trying to start a student club for game development. My initial plan was to have students start by modifying an existing Open Source game, such as Sauerbraten, Tux Racer, or SuperTux. The students all have Windows computers, the problem is they're locked from installing any binaries such as these games, which would be needed to get started. So is there some option for creating a collaborative project that wouldn't require downloading of binaries to do?

# Answer
It sounds like you're working under a very restrictive environment.

If you really can't run any non-whitelisted executables at all, then your safest bet might be to teach HTML5 game development.

You can author these games with as little as a text editor (though if you can work with the school's IT folks to pre-install an IDE on the machines, that's a much better experience for the students and offers more power in what they can do).

And you can run and debug these games in a standard web browser, with no new executables to download or run.

Modern JavaScript is much more powerful and better-performing than it used to be, and you can even teach conventional game 3D rendering and shaders via WebGL if you're so inclined. (This will likely require an IDE though, due to some complications in loading textures for use in WebGL - you need a web server running locally to appease browsers' security restrictions)
> 3 votes

---
Tags: teaching
---


# Question
Title: Unity: What does the green line gizmo signify?
When I place a point light it shows this green gizmo that ends in the terrain.
What's the name of this gizmo?
What does it signify?

# Answer
> 2 votes
I suspect it’s just to show you what location “above” the terrain the object currently is, to help you place it accurately. Small objects are notoriously hard to place correctly in 3D, since it’s hard to tell if they are near or far.

---
Tags: unity, lighting
---


# Question
Title: Should UI systems update naively with events and data from outside, or should they be coupled to some game state/singleton to know to change itself?
I'm making a game in Unity for my game dev course in uni. I hope the question isn't too confusing but I have bolded sort of like a TLDR at the bottom.

My level currently has a pregame UI panel, to set number of players and lives, and that panel gets hidden in midgame. When a winner is found, the midgame UI is hidden, and I unhide an endgame UI panel which shows the name of the last survivor, and the LevelManager emits these events that tell my UI to do that, along with data about who won, the player object that won, etc.

I have an EventManager singleton that I currently use that the UIManager can use to subscribe to the LevelManager emitting a game end event. I pass through data or params using CustomEventArgs, and the UI can use that data to update itself. So essentially, I'm using the **former method in my title,** where a UIManager just hides or shows panels based on its own method calls that it receives through events from the LevelManager, and has no idea whether or not the game is over, or done, or is started, it just does its own method calls based on the events it's subscribed to and I manually show and hide pregame/postgame panels in these methods.

But I was wondering whether or not a better way would be to add some sort of state machine to the LevelManager and just have the UIManager change based on tracking state changes of the LevelManager. If the LevelManager changes its own state, the UIManager would just receive information about the LevelManager's change in state and hide/show its own panels automatically depending on the current game state? I feel like since the UI is so near the LevelManager in terms of having to use the LevelManager's information, I should be having the UIManager ask for and receive data from the LevelManager directly, instead of changing UI naively with event calls and data passed in params from ouside.

What do you all think? **Should a UI system stay sort of uncoupled from a game manager and only change itself based on method calls and passing in data with params, or should the UI system just keep a reference to some global game state and know when and what to change through changes in this global state?**

# Answer
As a project gets bigger tighter coupling starts becoming a bigger problem since it leads to any small changes becoming nightmares. This is because if classes depend on each other, changing one class will affect many other classes. As a project grows it’s good to try to decouple classes where you find this starting to occur. As @DMGregory mentioned, it’s good to keep things as is until you notice a problem.

As for UI, with direct references, you may start to find that any small changes to your managers completely break your entire UI. This might slow down your development considerably in a larger project. Moving to an event system, or an observer pattern can help decouple and reduce such breakage.

You need to balance getting things done quickly with helping future you’s quality of life. If you’re building a quick prototype, don’t bother. If you expect to reuse the code, or use it in a long term project, it might be worthwhile to engineer it a bit more carefully.

Myself, I usually get things working quick and dirty, then every week or two take a pass on some things that seem like they might be an issue in the future. But I don’t go over all the code, just code I’ve ended up working on a lot or things that bother me.
> 1 votes

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


# Question
Title: Unity - Renderer "raycasts" from top down?
I'm trying to have objects in a game be selectable only from a **top down orthographic camera view**. I think having physics colliders might be overkill for that - especially because this only needs to be in 2D and not 3D. Is there another method that might be better, such as something like a renderer "raycasts", but perhaps even more performant as it is just from the orthographic 2D top down view

# Answer
> 1 votes
If you build your "top down" view on the XY plane, you can use 2D colliders and `Physics2D.OverlapPoint`.

This is about as efficient as you will get. A 2D collider is using exactly the same math you'd need to write in your C# code to test for a hit anyway. And if you're using Kinematic bodies on a physics layer that doesn't interact with anything, they won't burn any cycles on unneeded collision detection and resolution.

# Answer
> -1 votes
you can use quadtree algorithm to detect which object under the mouse position

you can use octree algorithm in 3d space

---
Tags: unity, 2d, raycasting
---


# Question
Title: Calculate min number of moves (no path involved)
I'm looking to implement an algorithm that will calculate the minimum number of moves based on the rules below.

Let's say that we have a grid (NxM), as exampled in the image below.

Each cell will be the sum based on the row and column and I can subtract 1 unit from one cell and add it to a neighbour. For example, on the image above, the minimum number of moves on **Initial** will be *2* and on **Initial - 2** will be *4*.

# Answer
> 0 votes
Aha! Here's another angle on solving this:

Your problem is isomorphic to the Minimum Weighted Edge Cover problem on a bipartite graph.

To build some intuition: imagine your grid is initially at its resolved value, then we've scattered onto it a bunch of charged particles, like electrons (-1) and positrons (+1). Each electron or positron needs to make its way to its opposite to annihilate. Once all electron-positron pairs have annihilated, we've returned to the resolved value of the grid and found a solution.

So our problem becomes: how do we pair up the positive and negative charges ("computing a *matching*" between them), so that the total travel distance (number of swaps) is minimized?

To translate this into a graph: take each cell whose initial value is different from its resolved value. For every +1 value it has above its resolved value, create a "positive" node. For every -1 below, create a "negative" node.

Then form a bipartite graph by joining an edge from each positive node to every negative node. The length of the edge is the Manhattan distance between the two nodes' cells. (The number of moves it would take to bring the excess 1 to the cell with the deficit, or vice versa, or to make them meet somewhere in the middle)

We want to find a subset of these edges such that:

* Every node is connected to exactly one chosen edge.
* The total weight of all chosen edges is minimized.

The minimum weighted edge cover on a bipartite graph with a single assignment to each node is also called The Assignment Problem (specifically the linear balanced assignment problem).

The Wikipedia link has an overview of algorithms for solving it, including "The Hungarian Algorithm". Now you have several algorithms to choose from to do the heavy lifting.

# Answer
> 0 votes
An under-appreciated fact about the A\* pathfinding algorithm is that it's not restricted to finding shortest paths in the spatial sense. It finds the shortest sequence of moves to solve *any* problem that can be expressed as walk on a graph.

And your problem is a walk on a graph.

* Each node of the graph is one particular assignment of n x m numbers to the cells in the grid.
* Each node has an edge leading to every other node that can be formed by subtracting 1 from one of its cells and adding 1 to a neighbouring cell.

So now you have a starting node (your "initial" state), a goal node (your "resolved" state), and a procedure to enumerate the nodes reachable from the current node (for each cell, subtract 1 from its value and try adding it to each of the cell's neighbours in turn).

All we need to add to use A\* is a heuristic, to estimate how many swaps remain to be done. A good heuristic lets us focus our search on the most promising parts of the graph, and save time by not exploring "bad" moves.

We could just use a heuristic of 0 - that's admissible (it never over-estimates the remaining work), but it doesn't help us distinguish promising moves from useless / harmful ones. With this, A\* effectively falls back to Djikstra's algorithm, exploring equally in all directions until it happens across the solution.

But we can do better. Iterate over all your cells, and for each one take the absolute value of the difference between its current value and its resolved value. Sum up those absolute differences to get the total amount of value we need to shunt around, and divide by 2 (since each step could potentially move 2 cells closer to their correct value).

This is also an admissible estimate (never over-estimates), and while it can under-estimate the distance, it's a lot more accurate - it gives the correct move count for all three of your examples, for instance.

You could probably do even better than this, by factoring in some spatial information. Like if a cell is 1 above its resolved value, and the closest cell below its own resolved value is 5 units away, you know you need to do at least 5 swaps to transport the excess to a suitable sink. But this is more complicated to compute, so there's a trade-off between choosing an accurate heuristic that lets you evaluate a minimal number of nodes, and choosing a cheap heuristic that you can evaluate quickly, so evaluating a few more nodes isn't a problem. Especially for small problem sizes, the options above might be all you need.

Once A\* has found found its way to a solution, guided by this heuristic, it will report back the number of steps on the path from the initial state to the goal. This count is guaranteed to be the smallest possible, as long as you use an admissible heuristic.

# Answer
> 0 votes
This can be expressed as a maximum flow problem where the sources are the cells with values higher than desired and the sinks are cells with values lower than desired and each source points to every sink with infinite capacity.

The only difference from a traditional maximum flow problem is we also have to assign each path a length equal to the Manhattan distance and we must pick a solution that minimizes the distance of the pipes.

The most straightforward way to do this is brute force every possible solution to the maximum flow problem. But I suspect this problem can be solved greedily.

To do this pick the source that is farthest from any sink and distribute as much flow as you can from that source to the nearest sink. Then repeat until solved. I'm not 100% sure if this algorithm is correct but it appears to work.

---
Tags: algorithm, grid
---