title: LWJGL3 shader code doesn't work

text:
# Question
Title: LWJGL3 shader code doesn't work
So I made a program to draw a simple cube with colors at each vertex. The program worked fine until I added shaders. It was using vbos and indicies and it *did* draw a colored cube like it should. So then I went on to add shaders and it all broke. Now all it shows me is a blue screen. When I looked at the lwjglx debug output it didn't show any errors.

I tried making the cube large, so if it was behind the camera, it would still be visible. I also turned off backface culling and made sure the znear and zfar was set correctly. They are. Other than that I can't seem to figure out what the problem is.

Anyway, my question is how can the shader code be fixed to show a cube? I've searched for days trying to find the answer, so any help would be appreciated.

Main.java

```
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.*;
import org.joml.Matrix4f;

public class Main {
    private Thread thread;
    public boolean running = true;

    private long window;

    private int width = 1200, height = 800;
    float angle = 0.0f;

    Matrix4f viewProjMatrix = new Matrix4f();
    FloatBuffer fb = BufferUtils.createFloatBuffer(16);

    int program;
    int viewProjMatrixLocation;
    int colorLocation;

    int indexVBO;
    int cubeVAO;

    public static void main(String args[]) {
        new Main();
    }

    void buildShader() {
        program = glCreateProgram();
        int vs = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vs,
          "#version 420\n" +
          "layout(location=0) in vec3 position;\n" +
          "uniform mat4 viewProjMatrix;\n" +
          "void main() {\n" +
          "    gl_Position = viewProjMatrix * vec4(position, 1.0);\n" +
          "}"
        );
        glCompileShader(vs);
        glAttachShader(program, vs);
        int fs = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fs,
          "#version 420\n" +
          "layout(location=1) in vec3 color;\n" +
          "out vec4 fragColor;\n" +
          "void main() {\n" +
          "    fragColor = vec4(1.0, 0.5, 1.0, 0.5);\n" +
          "}"
        );
        glCompileShader(fs);
        glAttachShader(program, fs);
        glLinkProgram(program);
        glUseProgram(program);

        viewProjMatrixLocation = glGetUniformLocation(program, "viewProjMatrix");
        colorLocation = glGetUniformLocation(program, "color");
        glUseProgram(0);
    }

    void buildCube() {
        float[] colorArray = new float[] {
            1.0f, 0.0f, 0.0f,
            0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 1.0f,
            1.0f, 1.0f, 0.0f,
            0.0f, 1.0f, 1.0f,
            1.0f, 0.0f, 1.0f,
            0.0f, 0.0f, 0.0f,
            1.0f, 1.0f, 1.0f
        };
        float[] vertexArray = new float[] {
            10.0f, 10.0f, 10.0f,    // 0
            -10.0f, 10.0f, 10.0f,   // 1
            -10.0f, -10.0f, 10.0f,  // 2
            10.0f, -10.0f, 10.0f,   // 3
            10.0f, 10.0f, -10.0f,   // 4
            -10.0f, 10.0f, -10.0f,  // 5
            -10.0f, -10.0f, -10.0f, // 6
            10.0f, -10.0f, -10.0f   // 7
        };
        int[] elementArray = new int[] {
            0, 1, 2,
            1, 2, 3,

            4, 5, 6,
            5, 6, 7,

            0, 1, 5,
            1, 5, 4,

            2, 3, 7,
            3, 7, 6,

            0, 4, 7,
            4, 7, 3,

            1, 5, 6,
            5, 6, 2
        };

        FloatBuffer cb = BufferUtils.createFloatBuffer(colorArray.length);
        FloatBuffer vb = BufferUtils.createFloatBuffer(vertexArray.length);

        cb.put(colorArray);
        vb.put(vertexArray);
        vb.flip();
        cb.flip();

        IntBuffer eb = BufferUtils.createIntBuffer(elementArray.length);
        eb.put(elementArray);
        eb.flip();

        // vao
        cubeVAO = glGenVertexArrays();
        glBindVertexArray(cubeVAO);

        // vbo
        int cubeVbo = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, cubeVbo);
        glBufferData(GL_ARRAY_BUFFER, cb, GL_STATIC_DRAW);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 6 * (Float.SIZE / Byte.SIZE) * 3, 0);

        // color
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, false, 6 * (Float.SIZE / Byte.SIZE) * 3, 3 * (Float.SIZE / Byte.SIZE));

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

        // indicies
        indexVBO = glGenBuffers();
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, eb, GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

    public void init() {
        if(!glfwInit()) {
            System.err.println("Could not initialize GLFW");
        }

        glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

        window = glfwCreateWindow(width, height, "Game", NULL, NULL);

        if(window == NULL) {
            System.err.println("Could not create window");
        }

        glfwSetWindowPos(window, 100, 100);

        glfwMakeContextCurrent(window);

        glfwShowWindow(window);

        GL.createCapabilities();

        glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
        glEnable(GL_DEPTH_TEST);
        //glEnable(GL_CULL_FACE);
        glDepthFunc(GL11.GL_LEQUAL);
        //glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
        glDisable(GL_CULL_FACE); // just to test drawing

        buildShader();
        buildCube();
    }

    public void update(int tick) {
        glfwPollEvents();

        angle += 0.01f;
    }

    public void render() {
        glViewport(0, 0, width, height);
        glUseProgram(program);

        viewProjMatrix.setPerspective((float)Math.toRadians(45.0f), (float)width / height, 0.01f, 100.0f).setLookAt(0.0f, 2.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
        glUniformMatrix4fv(viewProjMatrixLocation, false, viewProjMatrix.get(fb));

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBindVertexArray(cubeVAO);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
        glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

        glUseProgram(0);
        glfwSwapBuffers(window);

        int error = glGetError();
        if(error != GL_NO_ERROR) {
            System.out.println("GL ERROR: " + error);
        }
    }

    public Main() {
        init();
        long lastTime = System.nanoTime();
        double delta = 0.0;
        double ns = 1000000000.0 / 6.0;
        long timer = System.currentTimeMillis();
        int updates = 0;
        int frames = 0;

        running = true;
        while(running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            if (delta >= 1.0) {
                update(updates);
                updates++;
                delta--;
            }
            render();
            frames++;
            if(System.currentTimeMillis() - timer > 5000) {
                timer += 5000;
                updates = 0;
                frames = 0;
            }
            if(glfwWindowShouldClose(window)) {
                running = false;
            }
        }
    }
}

```

# Answer
> 1 votes
Your shaders are wrong. Honestly, I'm suprised that it didn't error earlier.

This is your vertex shader:

```
#version 420
layout(location=0) in vec3 position;
uniform mat4 viewProjMatrix;
void main() {
    gl_Position = viewProjMatrix * vec4(position, 1.0);
}

```

The vertex shader is run once per vertex, or once per (position, color) tuple. So it follows that the vertex shader should have as its input position *and* color, not only position. And then, the vertex shader passes the color to the fragment shader, and the fragment shader gets run once per pixel. This means your vertex shader should look like this:

```
#version 420
layout(location=0) in vec3 position;
layout (location=1) in vec3 inColor;

out vec3 color;
uniform mat4 viewProjMatrix;
void main() {
    gl_Position = viewProjMatrix * vec4(position, 1.0);
    color = inColor;
}

```

And your fragment shader, which can't take layout (per-vertex) inputs, should look like this:

```
#version 420
in vec3 color;
out vec4 fragColor;
void main(){
    fragColor=vec4(color,1.0);
}

```

This is all a bit confusing, so I recommend you read https://learnopengl.com/Getting-started/Hello-Triangle.

I'm not entirely sure if your buffer code is correct, but it looks like its fine to me. So fix your shaders, read the article and let me know if it works!

---
Tags: java, lwjgl, lwjgl3
---


# Question
Title: Movement velocity relative to a static object (Vector Maths)
I have a static object. I have a moving player.

If the player is moving directly towards the object then I want to return the value of 1. If the player is moving directly away from the the object then I want to return the value of 0. If the player is moving somewhat between these two directions then I want to return a value proportionally relevant to the two previously mentioned values - between 0 and 1 depending on the direction. The direction that the player is facing is irrelevant, it's the velocity of the player that's important for my situation.

How do I calculate this value?

This is so frustrating, as I know that I've solved this exact problem in the past but I'm currently drawing a blank. It involves some trig and some dot product, but for now I'm clueless and would appreciate any help that's offered.

# Answer
The dot product between two unit vectors is:

* +1 when the vectors are pointing in the same direction
* 0 when the vectors are perpendicular
* -1 when the vectors are pointing in opposite directions

So, we can get this value just by normalizing our two direction vectors and dotting them, and then massaging the output into the 0-1 range.

In Unity-style syntax it would be:

```
float Towardness(Vector3 playerPosition, Vector3 playerVelocity, Vector3 obstaclePosition) {
     Vector3 movementDirection = playerVelocity.normalized;
     Vector3 towardObstacle = (obstaclePosition - playerPosition).normalized;

     float dot = Vector3.Dot(movementDirection, towardObstacle);

     return 0.5f + 0.5f * dot;
}

```

Or, if you want it to vary linearly with the angle between the vectors, we can use the fact that the dot product of two unit vectors is the cosine of that angle, and get the angle itself (in radians) via the arc-cosine function:

```
 return 1f - Mathf.Acos(dot)/Mathf.PI;

```
> 3 votes

---
Tags: mathematics, movement, vector, direction
---


# Question
Title: Why are my screenshots created through a RenderTexture too small?
Current render result:

When I am rendering image in Unity and saving as file(*.png*), quality of those files are reduced. They become tiny and very poor.

How can I enhance that?

Dimension of the image file is 269\*168.

Code to save image :

```
using UnityEngine;
using System.IO;
using System;

//getty code
public class Capture : MonoBehaviour
{
    private static int resWidth = 3840;
    private static int resHeight = 2160;
    private static GameObject camObj = null;

    public static string ScreenShotName()
    {
        return string.Format("{0}/screenshots/{1}.png",
                             Application.dataPath,
                             Util.name_);
    }

    void Start()
    {
        camObj = gameObject;
        Directory.CreateDirectory(Application.dataPath + "/screenshots");
        resHeight=GetComponent<Camera>().pixelHeight;
        resWidth=GetComponent<Camera>().pixelWidth;
        //Util.everyThingHot = true;
    }

    public static void TakeHiResShot()
    {
        try
        {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camObj.GetComponent<Camera>().targetTexture = rt;

            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camObj.GetComponent<Camera>().Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camObj.GetComponent<Camera>().targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName();
            File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            bytes = null;
        }
        catch(Exception e)
        {
            Debug.Log("Error");
        }

    }

}

```

Sample:

What I see during saving shot:

*It's taking a lot CPU,GPU resources, renders correctly but doesn't give me what I want as a file*

# Answer
The problem was I was changing the value of `resHeight` and `resWidth` as @DMGregory mentioned. So it was rendering in poor quality.

Now,

```
using UnityEngine;
using System.IO;
using System;

//getty code
public class Capture : MonoBehaviour
{
private static int resWidth = 3840;
private static int resHeight = 2160;
private static GameObject camObj = null;

public static string ScreenShotName()
{
    return string.Format("{0}/screenshots/{1}.png",
                         Application.dataPath,
                         Util.name_);
}

void Start()
{
    camObj = gameObject;
    Directory.CreateDirectory(Application.dataPath + "/screenshots");
    //resHeight=GetComponent<Camera>().pixelHeight; *Line changed*
    //resWidth=GetComponent<Camera>().pixelWidth; *Line changed*
    //Util.everyThingHot = true;
}

public static void TakeHiResShot()
{
    try
    {
        RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
        camObj.GetComponent<Camera>().targetTexture = rt;

        Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
        camObj.GetComponent<Camera>().Render();
        RenderTexture.active = rt;
        screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
        camObj.GetComponent<Camera>().targetTexture = null;
        RenderTexture.active = null;
        Destroy(rt);
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = ScreenShotName();
        File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("Took screenshot to: {0}", filename));
        bytes = null;
    }
    catch(Exception e)
    {
        Debug.Log("Error");
    }

}

}

```

Now everything renders perfectly in 4K.
> 0 votes

---
Tags: unity, c#, rendering, image
---


title: 2D AABB Collision

text:
# Question
Title: 2D AABB Collision
Detecting a 2d collision is easy, but after that, I'm having trouble fixing the AABB position to where it should be. I think it would be something like `e.x=obj.x-aabb.x1`. but this obviously won't work for sliding on the ground, as the position will put to the front of the object. You could subtract the prev pos, but that is garbage in a lot of ways.

How can I make sure that the AABBs line up normally, and allow sliding on both axes?

```
for y=0; y<rows;
    for x=0; x<row;
        info = map[y][x]
        if(info.solid && p.aabb.offset(p.x,p.y).intersects(x,y,x+1,y+1)
            ???

```

# Answer
Collision detection in games comprises of the following phases:

1. Broad phase (which we will not go into here) culling.
2. Narrow phase (which you have implemented) detection.
3. Collision feature identification.
4. Collision response.

Collision response, in your case, is correcting the position of intersecting AABBs, based on some metric, which is computed within step 3, which you are missing.

The features of a collision you are interested in, is the **collision normal**, and **penetration depth**.

But to compute these, you will need to redo your collision code again, but in more detail, but first, let me explain a few points.

An AABB is comprised of 4 edges, each of which has a normal vector:

(0,1), (1,0), (-1,0) & (0,-1) As shown below:

Now that we know this, we can use that information to measure the axis of **minimum penetration** :

```
function findMinAxis(in: pointsA, in: pointsB, out: min_penetration, out: normal) begin

    float maxA = min_possible_value
    float maxB = min_possible_value
    float minA = max_possible_value
    float minB = max_possible_value

    min_penetration = max_possible_value
    for each axis in axes loop
        for each point in pointsA loop
            if maxA < dot_product( point, axis)
                maxA = dot_product( point, axis)
            end if
            if minA > dot_product( point, axis)
                minA = dot_product( point, axis)
            end if
        end loop

        for each point in pointsB loop
            if maxA < dot_product( point, axis)
                maxA = dot_product( point, axis)
            end if
            if minA > dot_product( point, axis)
                minA = dot_product( point, axis)
            end if
        end loop

        float penetration = maxA - minB

        if penetration < min_penetration AND penetration > 0
            min_penetration = penetration
            normal = axis
        end if
    end loop
end function

```

Ok, that was a lot of pseudocode, so let's summarise it:

What this code does, is iterate through each axis, and **project** each of the corners of the box onto that axis (via the dot product). This allows us to know how far along the axis each point in, and thus, we can measure the overlap.

We can then compare this overlap to the previous value, and if it is both positive, and smaller, then it is our current best feature. Once the loops complete, then we have our minimum, and the axis that minimum resides upon.

Now that we have identified the axis of minimum penetration, we can now respond to it(see stage 4).

We can do this by moving one or more of the boxes so they don't overlap any more, or do something cooler, like use physics. It's entirely up to you.
> 2 votes

---
Tags: 2d, collision-resolution, aabb
---


# Question
Title: Unreasonably large memory use with high-res screenshot script
I'm using this piece of code to save renders and I'm saving renders in every frame inside `Update()`.

Code:

```
using UnityEngine;
using System.IO;
using System;

//getty code
public class Capture : MonoBehaviour
{
    private static int resWidth = 3840;
    private static int resHeight = 2160;
    private static GameObject camObj = null;

    public static string ScreenShotName()
    {
        return string.Format("{0}/screenshots/{1}.png",
                             Application.dataPath,
                             Util.name_);
    }

    void Start()
    {
        camObj = gameObject;
        Directory.CreateDirectory(Application.dataPath + "/screenshots");
        resHeight=GetComponent<Camera>().pixelHeight;
        resWidth=GetComponent<Camera>().pixelWidth;
        //Util.everyThingHot = true;
    }

    public static void TakeHiResShot()
    {
        try
        {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camObj.GetComponent<Camera>().targetTexture = rt;

            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camObj.GetComponent<Camera>().Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camObj.GetComponent<Camera>().targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName();
            File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            bytes = null;
        }
        catch(Exception e)
        {
            Debug.Log("Error");
        }

    }

}

```

This is giving me 4K images.

But the problem is, it's taking a lot of memory. I have 8 Gigs and it's using 95% of it.

I'm quite sure that it shouldn't take this much memory. I should free up the memory. How can I achieve that. I know *.Net* has it's own garbage collector, but before it works, it takes so much memory.

**So how to do it manually?**

I added `GC.Collect()`, but no good and it even hangs. Previously it used to take like 2-3 minutes to occupy 95%, now it takes only 30 seconds or less.

I used this code :

```
RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
        camObj.GetComponent<Camera>().targetTexture = rt;

        Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
        camObj.GetComponent<Camera>().Render();
        RenderTexture.active = rt;
        screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
        camObj.GetComponent<Camera>().targetTexture = null;
        RenderTexture.active = null;
        rt = null;

        Destroy(rt);
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = ScreenShotName();
        File.WriteAllBytes(filename, bytes);
        bytes = null;
        screenShot = null;

        GC.Collect();

```

I also added after calling this method:

```
Capture.TakeHiResShot();
GC.Collect();

```

After changing :

```
using UnityEngine;
using System.IO;
using System;

public class Capture : MonoBehaviour
{
    private static int resWidth = 3840;
    private static int resHeight = 2160;
    private static GameObject camObj = null;
    private static RenderTexture rt;
    private static Texture2D screenShot;
    private static byte[] bytes;

    public static string ScreenShotName()
    {
        return string.Format("{0}/screenshots/{1}.png",
                             Application.dataPath,
                             Util.name_);
    }

    void Start()
    {
        camObj = gameObject;
        Directory.CreateDirectory(Application.dataPath + "/screenshots");
        rt = new RenderTexture(resWidth, resHeight, 24);
        screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
    }

    public static void TakeHiResShot()
    {
        try
        {
            camObj.GetComponent<Camera>().targetTexture = rt;
            camObj.GetComponent<Camera>().Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camObj.GetComponent<Camera>().targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);
            bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName();
            File.WriteAllBytes(filename, bytes);
        }
        catch(Exception e)
        {
            Debug.Log(e.Data);
        }

    }

}

```

Now its like this :

Profiler :

# Answer
`Textures`, `RenderTextures`, and `Materials` use memory outside of C#'s managed heap (including GPU memory), so the regular C# garbage collector alone can't fully clean them up.

You need to manually `Destroy()` them once you no longer need them.

Your current code does this for the `RenderTexture` `rt` (though it doesn't call Release first - I'm not sure if that's necessary) but it never destroys the `Texture2D` `screenshot`.

Since `screenshot` is readable CPU-side, that means it may be in memory twice: once in VRAM and once in main RAM. So every time you take a screenshot you're allocating something like:

```
(3840 x 2160) pixels x 3 bytes per pixel x 2 copies = 47.5 MiB

```

47.5 megs of memory that you never use again and never free. (We made this same mistake in one of the early prototypes on the Starlink project - it'd be nice to get better warnings about this!)

You can clean this up by remembering to `Destroy()` this texture too, but an even better solution is to "Reduce, Reuse, Recycle": if you're taking screenshots frequently, allocate the screenshot buffer once on start-up or lazily on first use, and keep re-using the same one. Something like this:

```
[RequireComponent(typeof(Camera))]
public class Capture {

    // Let's give this a proper singleton implementation
    // if you want global access.
    static Capture instance;
    public static Capture instance {
        get {
            if(instance == null) {
                Debug.LogWarning("No Capture instance in this scene. Adding one to the default camera...");
                Camera.main.AddComponent<Capture>();
            }

            return instance;
        }
    }

    public Vector2Int resolution = new Vector2Int(3840, 2160);

    Camera camera;
    Texture2D screenshot;

    // Singleton implementation - remember where the current instance is.
    void Awake() {
        if(instance != null) {
            Debug.LogWarning("More than one Capture instance currently present. Destroying later one.");
            Destroy(this);
            return;
        }

        instance = this;
    }

    public void TakeScreenshot() {
        // Do this only once, the first time we take a screenshot.
        if(screenshot == null) {
            camera = GetComponent<Camera>();
            screenshot = new Texture2D(resolution.x, resolution.y, TextureFormat.RGB24, false);
        }

        // Get a temporary render texture from Unity's pool, rather than allocate our own.
        // This allows it to be re-used for other features when we're not using it.
        var rt = RenderTexture.GetTemporary(resolution.x, resolution.y, 24);

        // Draw the frame into our render texture.
        camera.targetTexture = rt;
        camera.Render();

        // Copy the render texture into our persistent CPU-side buffer.
        RenderTexture.active = rt;
        screenshot.ReadPixels(new Rect(0, 0, resolution.x, resolution.y), 0, 0);

        // Put the camera/rendering state back the way we found it.
        camera.targetTexture = null;
        RenderTexture.active = null;

        // Done with this! Let someone else use it, or clean it up if it goes unused.
        RenderTexture.ReleaseTemporary(rt);

        byte[] bytes = screenshot.EncodeToPNG();
        string filename = ScreenShotName();
        File.WriteAllBytes(filename, bytes);
    }

    // Clean up after ourselves when destroying this instance.
    void OnDestroy() {
        Destroy(screenshot);
    }
}

```

Summarizing my changes:

* I don't like mixing instance members like `camObject.GetComponent()` in a `static` context where `camObject` could be `null`, so I made this a singleton with `TakeScreenshot()` as a non-static method. This gives us better guarantees that everything runs sensibly, and better warnings when we make a mistake.

You can still call this without knowing where the instance is by first asking for it:

`Capture.instance.TakeScreenshot()`
* One `Texture2D` is created lazily when taking the first screenshot (so in runs where you take no screenshots, no memory needs to be allocated), and is re-used for the life of this camera. When the capture script is destroyed (eg. on scene unload), it destroys the texture properly.

If you want, you could re-use the texture between scenes too, particularly if you fix your resolution as a constant that can't change between scenes.
* Instead of creating our own `RenderTexture`, we ask Unity's rendering system to furnish us with a temporary one, then release the temporary when we're done.

This can be a good habit to get into with render targets - especially if you have a bunch of effects using the screen's resolution - because it lets the same memory be re-used by multiple operations.

Unity will handle allocating the memory if it doesn't have a spare temporary of the requested size/format, and de-allocating it once the target goes unused for a little while.
> 4 votes

# Answer
I finally used this code :

```
using UnityEngine;
using System.IO;
using System;

public class Capture : MonoBehaviour
{
    private static int resWidth = 3840;
    private static int resHeight = 2160;
    private static GameObject camObj = null;

    private static RenderTexture rt;

    private static Texture2D screenShot;

    public static string ScreenShotName()
    {
        return string.Format("{0}/screenshots/{1}.png",
                             Application.dataPath.Substring(0,Application.dataPath.LastIndexOf('/')),
                             Util.name_);
    }

    void Start()
    {
        camObj = gameObject;
        Directory.CreateDirectory(Application.dataPath.Substring(0,Application.dataPath.LastIndexOf('/')) + "/screenshots");
        rt = new RenderTexture(resWidth, resHeight, 24);

        screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
    }

    public static void TakeHiResShot()
    {
        try
        {
            camObj.GetComponent<Camera>().targetTexture = rt;

            camObj.GetComponent<Camera>().Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camObj.GetComponent<Camera>().targetTexture = null;
            RenderTexture.active = null;
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName();
            File.WriteAllBytes(filename, bytes);
            bytes = null;
        }
        catch (Exception e)
        {

            Debug.Log(e.Data);
        }

    }

    void OnDestroy()
    {
        Destroy(rt);
        Destroy(screenShot);
    }

}

```

And everything was cool less than 150 MB of RAM was used, although it had a spike of 300 MB at first.

Thanks to all who helped.
> 2 votes

---
Tags: unity, c#, memory-efficiency, memory, screenshot
---


# Question
Title: Performance of BabylonJS and other browser based software vs traditional software on a low end rig
I would have thought that browser based programs like BabylonJS allowed anyone with a pc powerful enough to load a webpage to be able to utilize extremely powerful software that you'd otherwise needs an expensive rig to do so. That is, you simply ping an extremely powerful rig through the web and it pings back the output of each command as a still image of sorts to display on yours.

I'm confused though, cause while using BabylonJS it throttles my CPU from 10-100% depending on what I'm doing. Is it loading components of a traditional 3d software application and then making my CPU do the work? Or is it some kind of 50/50 give and take relationship?

Similar to Google Stadia, I was just really excited by the idea of being able to use 3d editing software without any hardware limitations. Is this what BabylonJS offers or am I missing something?

# Answer
As Therarot commented above, you seem to have misunderstood what BabylonJS does.

> you simply ping an extremely powerful rig through the web and it pings back the output of each command as a still image of sorts to display on yours.

BabylonJS is *not* a streaming service like Stadia that runs software on a powerful server elsewhere on the net and streams the video output to a thin client in your browser.

BabylonJS is a WebGL graphics engine. What that means:

* WebGL is a Javascript API that lets code running in your browser, on your local machine, communicate with your GPU to render hardware-accelerated graphics, using a dialect of OpenGL.

So it's still using your local device's hardware, it just opens the door to making *better* use of that hardware by offloading highly parallel workloads to a specialized graphics card / chip that can blaze through them more efficiently than doing the same operation on the CPU.
* A graphics engine is a code library that makes it easier to create applications with graphical features.

Writing low-level WebGL / OpenGL code directly can be a bit of a slog, and very error prone. An engine like BabylonJS provides abstractions and shortcuts for common things you might want to do, so your app can focus on the high level of what it wants to draw, and let the library code muck with the details of how to draw it.

BabylonJS will not itself improve the rendering / 3D editing performace of your device. What it can do is make it easier to write apps that achieve good performance for the device you're running them on.

Because this is all still running in Javascript inside your browser - with all the JIT compilation, security sandboxing, and overhead that entails, you should not expect performance to be competitive with dedicated native programs for 3D graphics.
> 2 votes

---
Tags: babylonjs
---


# Question
Title: GameObject not destroyed in ExecuteInEditMode and spooky Instantiating
I was trying to get familiar with Unity's *ExecuteInEditMode*

Everything is fine it keeps the old object although I have deleted them.

And one more thing, although every-thing (cube) is instantiated is set as child of GameObject script is attached to, they where the other cubes come from?

I have this code:

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

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    private int count = 0;
    void Start()
    {}
    void Update()
    {
        if(count!=points.Count)
        {
            count = points.Count;
            foreach(GameObject g in gameObjects)
            {
                DestroyImmediate(g);
            }
            gameObjects.Clear();
            int i = 0;
            foreach (Vector3 point in points)
            {
                Debug.Log(++i + "  " + point);
                GameObject tem = Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), point, Quaternion.identity);
                tem.transform.parent = gameObject.transform;
                gameObjects.Add(tem);
            }
        }
    }
}

```

Here is a snap:

# Answer
Silly mistake :

```
            GameObject tem = GameObject.CreatePrimitive(PrimitiveType.Cube);
            tem.transform.position = point;

```

added replacing

```
GameObject tem = Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), point, Quaternion.identity);

```

2 Cubes were created on that line every time.
> 1 votes

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


# Question
Title: How can I parent an object whilst animating?
Much like in Blender where you can parent an object to another, or the Armature, is it possible to parent an object to another, so when animating, the child object moves with the parent?

I've tried dropping the object I want influenced onto the character's parent object in the hierarchy and accessed it via the Animation tab. I added the object as a property and adjusted it's position, but the results have been pretty mixed.

How can I have an object automatically follow the animation without manually adjusting its curves for each frame?

# Answer
> 1 votes
In Unity, your Armature which was imported from Blender should be modeled as a hierarchy of GameObjects. You can make GameObjects children of these bones to have them move with the bone during an animation, just like you would in Blender. No further animation changes are needed unless you need the objects to reposition beyond just following the parent.

In the following image (taken from another answer), the wrench is a GameObject which is not a part of the imported model/animation. Its parent is the hand. Whenever an animation plays, the wrench will follow the hand.

---
Tags: unity, animation
---


# Question
Title: Unity Anima2D - IK Limb for leg not working
I'm having an issue getting an IK limb to work using Anima2D in Unity. If I place a limb IK for the neck joint, the head moves as expected, however trying to place one for the leg seems to have no effect.

A CCD IK seems to work, but only moving one bone of the leg, whereas I need both bones to move, like a real limb with a knee joint.

Is there anything obvious I'm doing wrong?

Thanks!

# Answer
> 1 votes
Figured out the answer: The lower bone (in my example the Left\_Leg and Right\_Leg) were not set as a child of the higher bone (Left\_Thigh, Right\_Thigh). Setting the lower bone as the child of the higher bone fixed the issue.

---
Tags: unity, animation, skeletal-animation
---


# Question
Title: Keep world changes in sync in client/server architecture
Imagine having a big room (4000w x 4000h) which contains players and items (world objects). The room is spatially partitioned in a 10 x 10 grid for collision detection and changes in the viewport of the player.

* Green rectangle: Item
* Red rectangle: Player viewport

**At the moment**, on the server, every player contains a list of all world objects in his current viewport. When the player changes his position, new items are found in the viewport, compared with his current list of visible objects and the changes are send to the client. His current visible list is updated with the new found objects

```
HashSet<WorldObject> changes = new HashSet<>(foundObjects);
changes.removeAll(player.getVisibleObjects());

```

The client maintains a list of all entities that it has seen, renders them in the world and waits for new input.

Now my problem arise **when another player** picks up an item, it notifies the surrounding players, update the local list of items accordingly and stops rendering the item. This works fine. But players outside the viewport are not notified about these changes, so once they are in the grid, they will still see the item being rendered.

How are these kind of problems commonly solved? Is my approach good?

# Answer
> 2 votes
One way you can solve this is to store a "last modified" timestamp for each block on the server, and a "last seen" timestamp for each block in a client's local cache.

When someone makes a change in a block, the server records the timestamp at which that change occurred, and sends it to each nearby player as part of the update telling them what changed. The clients record that timestamp as their last seen modification for that block.

When a client tells the server that it intends to move into range of a new set of blocks, it sends its "last seen" timestamp for each of those blocks. (You can reserve a prehistoric timestamp value to represent "I've never seen this block / it's been evicted from my cache")

The server can then compare those against its "last modified" timestamp to determine whether anything has changed in that block in the meantime, and send back only data for blocks that have changed. The other blocks are safe to load from cache without modification, since they haven't changed since the client's last visit.

---
Tags: java, networking, synchronization
---


# Question
Title: Blender Cycles materials not showing in Second Life
I ran into a problem after trying to import my own creation into second life. While I am not new to 3D modelling with Blender and other programs, I have always only created things for fun. Now I have decided to import few of those creations into Second Life but the materials I have used do not display in the preview at all. I have used the Cycles Render.

How do I solve my issue with Materials not displaying in Second Life after Exporting a Collada file from Blender Rendered in Cycles?

# Answer
> 1 votes
Blenders cycles render engine uses a node based material that does not export to other applications.

To match the cycles material you can bake the cycles material to an image and then use the image texture elsewhere.

---
Tags: blender, materials
---


# Question
Title: Why is my coroutines not working with in the if statement?
Isn't it possible to start co-routines under certain conditions? Or, it should only be started at the initial steps only?

There is an enemy which will be de-activated after certain condition which works fine. After that, a panel shows up which also works perfectly but in that panel there is a text which will be printed from the above code. When I wrote this exact code in at the start of my game without any condition it worked fine. But now, when I have if statement, it doesn't work.

This code currently prints out the words of my sentences. After `typingSpeed` seconds, it will print another word and so on. This is a system that we see in our day to day game but I can't seem to get it work the way I want it to.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LastDIalog : MonoBehaviour {
    public TextMeshProUGUI textDisplay;
    public string[] sentences;
    public int index;
    public GameObject MaxyMory;
    public float typingSpeed;
    // Use this for initialization
    void Start () {
            StartCoroutine (type ());
    }

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

    }

    IEnumerator type () {
        if (MaxyMory.activeInHierarchy == false) {
            foreach (char letters in sentences[index]) {
                textDisplay.text += letters;
                yield return new WaitForSeconds (typingSpeed);
            }
        }
    }
}

```

This particular code is not working. Why?

# Answer
> 1 votes
The `if`-statement you seem to be writing about is inside the coroutine. At that point the coroutine has already started. The `if` just decides whether or not the coroutine actually does something.

What you need to do instead is move the `if` section around the `StartCoroutine`, so the coroutine is only started under a certain condition. But if you do that in `Start`, it will only get checked when the game object this script is on is created. If you constantly want to monitor the state of another GameObject and do something when it changes (which seems to be the "MaxyMory" in this case), then you should do so in `Update`:

```
void Update () {
    if (MaxyMory.activeInHierarchy == false) {
        StartCoroutine (type ());
    }
}

IEnumerator type () {
        foreach (char letters in sentences[index]) {
            textDisplay.text += letters;
            yield return new WaitForSeconds (typingSpeed);
        }
    }
}

```

But now you will see a different problem: The coroutine will get started over and over again while the MaxyMory is inactive. You will end up with lots and lots of concurrently running routines. This is likely not what you want. So you need to make sure that the coroutine isn't already running. One way to do that is by adding another private variable `isTyping`:

```
private bool isTyping = false;

void Update () {
    if (MaxyMory.activeInHierarchy == false && isTyping == false) {
        isTyping = true;
        StartCoroutine (type ());
    }
}

IEnumerator type () {
        foreach (char letters in sentences[index]) {
            textDisplay.text += letters;
            yield return new WaitForSeconds (typingSpeed);
        }
        isTyping = false;
    }
}

```

Another solution could be to not trigger the coroutine from an `Update` script of an unrelated game object, but actually trigger it from the code section which also deactivates the MaxyMory.

---
Tags: unity, coroutines
---


# Question
Title: Procedurally generating non tile based top down 2d game worlds
I’ve been fascinated by procedural generation for over two years now. I have played around with many types of noise generation and even wrote some myself. I’ve been looking into water erosion and procedurally generated biomes and during this time I’ve managed to build some nifty little map generators. Something that has always escaped me, however was generating a procedural map that is not “tile based”. So far, all the procedural map generators I have built relied on one axiom - the map is represented as a 2d matrix containing some sort of information about the terrain that is to be found there. This means that I, by definition, can’t build anything that is not tile based.

And this is why I come here asking for your help. I am curious about how one could render a procedurally generated map in a non tile-based fashion. My end result is the image I posted.

The solution that immediately jumped to my mind is drawing each end every pixel individually, thus making the map look essentially non tile based. This, however would require enormous memory and is unfeasible.

So I am turning to the masters - how can I procedurally generate (and more importantly render) such a map? How would I go about representing the sprites to be drawn? Where do I even get started? This feat is so much out of my grasp that I do not even understand where I should be looking

Note - I know about marching squares and wang tiles. These approaches are however not something I’m fond of because of the huge workload that would go into drawing the resources. I am looking for something more in the realm of algorithms

Thank you!

# Answer
I'm not a master, nor do I do much with procedural content, but this is how I would create such an image:

If you're not using tiles, I would think the next most basic element is line (which you can define as an array of points). Take the river in your reference image for example. That's simply two parallel lines, with random points along each line randomly offset to the left or right via your favorite noise algorithm.

If you want a specific river shape, just start with a single, low-resolution center line, maybe with just a few randomly shifted points to set the initial flow. From the center line you can basically extrude your left and right edges, and just add more randomly shifted points along each edge line for more detail. Once you've got your lines represented in memory, just use a flood fill algorithm to texture the overall river shape.

You could just as easily work with shapes instead of lines. If you were to generate a smooth noise image, you could use an algorithm to group values/colors into shapes. Once you know the bounds of a certain shape, pick a random point within that shape to place your sprite. If your sprite doesn't fit within the bounds of the shape, pick another point inside the shape until you find one that works (but only do that a few times; If you can't find a valid point in a reasonable amount of time, skip it and move on).
> 2 votes

---
Tags: procedural-generation, terrain
---


# Question
Title: Why is that when I use Rigidbody the object falls through the floor?
It keeps falling through the floor.

On the object I added a Rigidbody and it already has a box collider.

And the floor:

I want to make a bouncing ball effect. I'm using the official unity tutorial:

Tutorial

However, my object falls through the floor.

# Answer
> 2 votes
Check the floor collider. Add a box collider to the floor, remove the mesh collider, and check the result. The floor may have wrong mesh orientation. Or just try turning the floor 180 degrees along the relevant axis.

# Answer
> 0 votes
There can be issue to the layers.

Here you can check out edit-\>Project settings-\>physics. See there which layer is colliding and which is not.

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


# Question
Title: Destroy physics triggered GameObject in Unity ExecuteInEditMode
To destroy GameObjects I'm using this code :

```
try
        {
            DestroyImmediate(g);
        }
        catch (Exception e)
        {
            Destroy(g);
        }

```

It is giving me error, something like this :

Full code :

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

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    void Start()
    {

    }
    void OnValidate()
    {
        foreach(GameObject g in gameObjects)
        {
            try
            {
                DestroyImmediate(g);
            }
            catch (Exception e)
            {
                Destroy(g);
            }
        }
        gameObjects.Clear();
        foreach (Vector3 point in points)
        {
            GameObject tem = GameObject.CreatePrimitive(PrimitiveType.Cube);
            tem.transform.position = point;
            tem.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            tem.transform.parent = gameObject.transform;
            gameObjects.Add(tem);
        }
    }
}

```

# Answer
> 4 votes
The red you see in your console is not an exception, it's an internal unity error. so that try catch doesn't help. You can't destroy gameObjects in that frame. You have to delay your call until the next frame. you can achieve this with coroutines.

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

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    void Start()
    {

    }
    void OnValidate()
    {
        foreach(GameObject g in gameObjects)
        {
            StartCoroutine(DestroyGameObject(g));
        }
        gameObjects.Clear();
        foreach (Vector3 point in points)
        {
            GameObject tem = GameObject.CreatePrimitive(PrimitiveType.Cube);
            tem.transform.position = point;
            tem.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            tem.transform.parent = gameObject.transform;
            gameObjects.Add(tem);
        }
    }

    IEnumerator DestroyGameObject(GameObject g)
    {
        yield return null;
        DestroyImmediate(g,true);
    }
}

```

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


# Question
Title: How do I calculate vehicle rotation when two car wheels are on the ground to simulate gravity?
I'm writing some code to simulate a vehicle (tank or car) driving over a heightmap terrain. I'm not using a full physics engine, and just simply checking the height of the terrain at the 4 bottom corners of the vehicle bounding box for collision. The vehicle has a quaternion to represent rotation, and a 3D position.

I have orientation working if there are at least 3 wheels touching the ground (I can define a plane and determine the orientation from the normal), but what I'd like to do is react pseudo-realistically rotate the car if two wheels are touching the ground.

For example, if the rear two wheels hit the ground, I'd like to calculate a rotation to make the front of the vehicle drop until 3+ wheels touch the ground.

Obviously if I have two wheels intersection points, I have an axis, but I'm not sure how to manipulate the rotation and position to rotate around that axis when it's not central to the body.

# Answer
> 3 votes
I'd be inclined to simulate each corner of the vehicle as a point mass on a spring suspension.

Each integration step, you accumulate several vectors that nudge these points around:

* gravity pulling it down
* the suspension spring pushing it away from the terrain, according to its current proximity along your vehicle's vertical axis
* dampening from the suspension to keep it from bouncing / oscillating too much
* the vehicle's momentum / grip from the wheel pushing it forward

Left alone, these influences could cause the corners to all wander off in their own directions, so as a final step you enforce the constraint that all four corners form a planar rectangle with your vehicle's dimensions.

One simple way to do this is with Verlet integration, where you just calculate adjusted positions for each corner and that will implicitly adjust the velocity without the need to compute restoring impulses & torques.

You can compute the average of the four corners to get the vehicle center, the average of the front corners minus the rear to get its average forward direction, and the average of the right corners minus the left, minus the projection onto the forward to get the average right direction. With that basis you can set the corner points back into a perfectly rigid planar rectangle.

That rectangle will naturally try to settle into positions where each suspension spring is similarly depressed, finding its level on uneven terrain. When only two wheels are close enough to provide a push on the suspension springs, the momentum and mass of the remaining two corners will cause it to rotate smoothly along the axis between the supporting wheels until a third wheel touches down.

---
Tags: physics, rotation
---


# Question
Title: Recursive backtracking sometimes missing a tile?
I have a basic recursive backtracking algorithm for a maze. It pretty much works but occasionally leaves some tiles in the corners untouched. This is the recursive function:

```
void GenerateMaze(Coordinate tilePos)
    {
        Debug.Log("MazeGen");
        tileMap[tilePos.x, tilePos.y].visited = true;
        Shuffle<Coordinate>(directions);
        foreach(Coordinate d in directions)
        {
            if (tilePos.x + d.x >= 0 &&
            tilePos.x + d.x < mapWidth &&
            tilePos.y + d.y >= 0 &&
            tilePos.y + d.y < mapHeight)
            {
                if (!tileMap[tilePos.x + d.x, tilePos.y + d.y].visited)
                {
                    Carve(tilePos, d);
                    GenerateMaze(new Coordinate(tilePos.x + d.x, tilePos.y + d.y));
                }
            }
        }
    }

```

This is how the Carve method looks like:

```
private void Carve(Coordinate position, Coordinate direction)
    {
        if (direction.Equals(new Coordinate(-1, 0)))
        {
            tileMap[position.x, position.y].west = true;
            tileMap[position.x + direction.x, position.y + direction.y].east = true;
        }
        else if (direction.Equals(new Coordinate(1, 0)))
        {
            tileMap[position.x, position.y].east = true;
            tileMap[position.x + direction.x, position.y + direction.y].west = true;
        }
        else if (direction.Equals(new Coordinate(0, -1)))
        {
            tileMap[position.x, position.y].south = true;
            tileMap[position.x + direction.x, position.y + direction.y].north = true;
        }
        else if (direction.Equals(new Coordinate(0, 1)))
        {
            tileMap[position.x, position.y].north = true;
            tileMap[position.x + direction.x, position.y + direction.y].south = true;
        }
    }

```

I'm betting on a typo or stupid mistake somewhere but I cannot find it. In my last result `tileMap[4,4]` stayed untouched without any walls. But the algorithm does backtrack as I often end up with dead ends. It does not happen often and up till now only on the sides.

Below is an example where two `tiles` on the bottom right have not been carved in too.

Here is another one without walls, this time 3 unconnected `tiles` in another corner of the maze.

Anyone can find whats wrong?

# Answer
Old question, but looking at it this morning I noticed that the `directions` collection isn't defined in the body of the method, nor passed as an argument. That means, unless its iterator is defined in an unusual way, that every recursive call is using *the same* collection of directions, re-shuffling it on every recursion.

This is a problem because this maze generation algorithm relies on exhaustively trying every direction from the each cell, to ensure we haven't missed visiting any of them.

We do this exhaustive check in a random order to make the maze non-uniform, but for this to work, the random order we choose for a cell has to be *fixed* at the time we start exploring that cell.

Imagine we start exploring a cell and randomly shuffle the `directions` collection into the order \[North, East, South, West\]. We check North first and find it unvisited, so we carve Northward and recurse and recurse and recurse, re-shuffling our directions each time.

By the time the stack unrolls back to the cell we started from, let's say the `directions` collection is in the order \[East, North, South, West\]. If we carry trying the second, third, and fourth directions in this list, we'll have completely skipped checking the East direction, since it got swapped into a slot that our local iterator state thinks it already checked!

So, if we're solving this recursively, we need to fix the permuted order we'll check the directions as a local variable that can persist its value in the stack until we resume. That doesn't mean we need to copy arrays all over the place. There are only 24 permutations of four elements into four slots, and we can pack them into a collection of 24 integers:

```
27
30
39
45
54
57
75
78
99
108
114
120
135
141
147
156
177
180
198
201
210
216
225
228

```

You can store this list as a constant, and instead of your shuffle routine, select one random integer from the list, then peel it out into a permutation of the directions like so:

```
int order = orders[Random.Range(0, orders.Length)];

for(int i = 0; i < 4; i++) {
    // Peel one value 0-3 off the bottom.
    var direction = directions[order & 3];
    // Chop off the direction we read,
    // to bring the next one to the bottom.
    order >>= 2;

    // ... now use the direction.
}

```
> 2 votes

---
Tags: c#, algorithm, ai, procedural-generation
---


# Question
Title: How to make an object track another object's exact movements
This script below helps me to to tell the follower object to copy exact movements of the leader object, I found this script in Unity forums and it works pretty well.

My question is how can I add some kind speed variable to it; how can I tell the follower object to move at lower speed?

```
 public class delayTracker : MonoBehaviour
 {
     float progress;
     const int MAX_FPS = 60;

     public Transform leader;
     public float lagSeconds = 0.5f;

     Vector3[] _positionBuffer;
     float[] _timeBuffer;
     int _oldestIndex;
     int _newestIndex;

     // Use this for initialization
     void Start()
     {
         int bufferLength = Mathf.CeilToInt(lagSeconds * MAX_FPS);
         _positionBuffer = new Vector3[bufferLength];
         _timeBuffer = new float[bufferLength];

         _positionBuffer[0] = _positionBuffer[1] = leader.position;
         _timeBuffer[0] = _timeBuffer[1] = Time.time;

         _oldestIndex = 0;
         _newestIndex = 1;
     }

     void LateUpdate()
     {
         // Insert newest position into our cache.
         // If the cache is full, overwrite the latest sample.
         int newIndex = (_newestIndex + 1) % _positionBuffer.Length;
         if (newIndex != _oldestIndex)
             _newestIndex = newIndex;

         _positionBuffer[_newestIndex] = leader.position;
         _timeBuffer[_newestIndex] = Time.time;

         // Skip ahead in the buffer to the segment containing our target time.
         float targetTime = Time.time - lagSeconds;
         int nextIndex;
         while (_timeBuffer[nextIndex = (_oldestIndex + 1) % _timeBuffer.Length] < targetTime)
             _oldestIndex = nextIndex;

         // Interpolate between the two samples on either side of our target time.
         float span = _timeBuffer[nextIndex] - _timeBuffer[_oldestIndex];
         float progress = 0f;
         if (span > 0f)
         {
             progress = (targetTime - _timeBuffer[_oldestIndex]) / span;
         }

         transform.position = Vector3.Lerp(_positionBuffer[_oldestIndex], _positionBuffer[nextIndex], progress );
     }

     void OnDrawGizmos()
     {
         if (_positionBuffer == null || _positionBuffer.Length == 0)
             return;

         Gizmos.color = Color.grey;

         Vector3 oldPosition = _positionBuffer[_oldestIndex];
         int next;
         for (int i = _oldestIndex; i != _newestIndex; i = next)
         {
             next = (i + 1) % _positionBuffer.Length;
             Vector3 newPosition = _positionBuffer[next];
             Gizmos.DrawLine(oldPosition, newPosition);
             oldPosition = newPosition;
         }
     }
 }

```

# Answer
I created a tiny project for you, h00man13 !

It doesn't use timers; instead, uses distance to determine how far the follower can be to "forget" the leader. It is smart enough to keep cpu overhead low (using sqrmagnitude, for example).

You can also set different speeds for the followers, and they also rotate towards the target (if you want). In the example, you have 3 different followers, with != speeds.

Hope it helps. The code is simple, you'll get the idea when you read it, but feel free to ask for more, if you want.

Here you have it: https://github.com/burkard/FollowTheLeader

If you prefer, use the following 2 scripts:

**LeaderObject.cs**

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

public class LeaderObject : MonoBehaviour
{
    [Tooltip("when objects reach this distance, they stop")]
    public float stayAwayDistance;

    [Tooltip("when objects are inside this range, they follow me")]
    public float startFollowingDistance;

    [Tooltip("Minimum travelled distance to record position, in meters -- lower values are more precise, but use MUCH MORE memory, and create more jaggy movements! ")]
    public float moveThreshold; // the followers will keep it's own records

    void Start()
    {
        if (stayAwayDistance == 0f || startFollowingDistance == 0f || moveThreshold == 0f) Debug.LogWarning("If you don't set a startFollowingDistance (and stayAway) for " + this.gameObject.name + ", the followers will start to follow IMEDIATELLY! Is this what you want?");
    }

    void Update()
    {

    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, stayAwayDistance);

        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, startFollowingDistance);
    }
}

```

**FollowerObject.cs**

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

public enum WhatToLook{ target, nextPosition }

public class FollowerObject : MonoBehaviour
{
    public GameObject target;

    [Tooltip("Moving speed, in meters per second")]
    public float movingSpeed;
    [Tooltip("The higher the speed, the quicker they turn to the target")]
    public float turningSpeed;

    [Tooltip("The delay, in seconds, until it starts to follow the target")]
    public float startDelay = 0f;

    [Tooltip("Should I stop when reach the target, or follow the whole path?")]
    public bool stopWhenReachedTarget;

    [Header("Buffer size")]
    [Tooltip("The higher the number, the bigger the path will be - but more memory will be used! It will use the last X positions (the prior ones will be discarded)")]
    public int bufferSize = 100;

    [Header("What should I look at while I'm moving?")]
    public WhatToLook lookAt;

    private float startTime = 0f;

    private Vector3 relativePos;
    private Quaternion rotation;

    private List<Vector3> desiredPositions;
    private bool isFollowing;

    private static float startFollowingSqrDistance, stayAwaySqrDistance, currentSqrDistance, sqrMoveThreshold;

    void Start()
    {
        if (target == null || movingSpeed <= 0f || turningSpeed == 0f) Debug.LogError("Error - please set target and speed for " + this.name);
        desiredPositions = new List<Vector3>();
        isFollowing = false;

        if (startFollowingSqrDistance == 0f) startFollowingSqrDistance = Vector3.SqrMagnitude(
                new Vector3(target.GetComponent<LeaderObject>().startFollowingDistance, 0f, 0f)
            );

        if (stayAwaySqrDistance == 0f) stayAwaySqrDistance = Vector3.SqrMagnitude(
                new Vector3(target.GetComponent<LeaderObject>().stayAwayDistance, 0f, 0f)
            );

        if (sqrMoveThreshold == 0f) sqrMoveThreshold = Vector3.SqrMagnitude(
                new Vector3(target.GetComponent<LeaderObject>().moveThreshold, 0f, 0f)
            );
    }

    void Update()
    {
        currentSqrDistance = Vector3.SqrMagnitude(target.transform.position - transform.position);
        if (currentSqrDistance <= startFollowingSqrDistance)
        {
            RecordTargetPosition();

            if (!isFollowing) startTime = Time.time + startDelay;
            isFollowing = true;
            if (currentSqrDistance > stayAwaySqrDistance || !stopWhenReachedTarget) MoveToTarget();
            else isFollowing = false;
        }
        else
        {
            if (currentSqrDistance > stayAwaySqrDistance || !stopWhenReachedTarget) MoveToTarget();
        }

        if (isFollowing)
        {
            LookToTarget();
        }
        else
        {
            if (desiredPositions.Count > bufferSize) desiredPositions.RemoveAt(0);
        }
        if (desiredPositions.Count == 0) isFollowing = false;
    }

    void RecordTargetPosition()
    {
        // record target's position ONLY IF target has moved beyond its threshold:
        if (desiredPositions.Count == 0) desiredPositions.Add(target.transform.position);

        if (desiredPositions.Count > 0 && Vector3.SqrMagnitude(desiredPositions[desiredPositions.Count - 1] - target.transform.position) >= sqrMoveThreshold)
            desiredPositions.Add(target.transform.position);
    }

    void LookToTarget()
    {
        if (lookAt == WhatToLook.target || desiredPositions.Count == 0)
            relativePos = target.transform.position - transform.position;
        else
            relativePos = desiredPositions[0] - transform.position;

        transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(relativePos, Vector3.up), turningSpeed * Time.deltaTime);
    }

    void MoveToTarget()
    {
        if (Time.time > startTime && desiredPositions.Count > 0)
        {
            relativePos = desiredPositions[0] - transform.position;

            if (relativePos.sqrMagnitude <= 0.1f)
            {
                desiredPositions.RemoveAt(0);
            }

            transform.position += relativePos.normalized * movingSpeed * Time.deltaTime;
        }
    }
}

```
> 3 votes

---
Tags: unity
---


title: Generating a Sprite to cover given area

text:
# Question
Title: Generating a Sprite to cover given area
I have an area say `a x b` of cells. actually I render every single cell in this matrix with a tile representing floor, wall, etc. What I'm trying to achieve it to replace this tiling system with a unique tile covering the whole `a x b` area.

I tried to play with creating a single `GameObject` and then adding a `SpriteRenderer` component with the base idea to stick in a sprite with desired size so that the image (whatever it is) gets stretched to fit it but apparently all the suitable fields which could be involved in this are readonly (I considered the `rect` and the `bounds` attribute).

In other words I feel like I'd need to attach a `SpriteRenderer` with a dynamic size based on given dimensions. How could I reach this goal?

# Answer
> 1 votes
There are multiple ways to achieve that, simple one is:

1. Set scale of the sprite to width = a * tileWidth, height = b * tileHeight
2. Set draw mode to Tiled or Sliced if you have some borders https://docs.unity3d.com/ScriptReference/SpriteRenderer-drawMode.html

# Answer
> 0 votes
You may need to generate your own Mesh dynamically and use a MeshRenderer.

Which may require building your own texture atlas with all the tile textures.

This would give you full control over the shape, size and texture coordinates of your custom sprites.

http://docs.unity3d.com/ScriptReference/Mesh.html

---
Tags: rendering, unity
---


title: Javelin throw projectile motion

text:
# Question
Title: Javelin throw projectile motion
I am trying to simulate throw of javelin using projectile motion. The basic physics of projectile motion of a point was used to position the javelin. For the rotation part, I just assumed that the javelin must be tanget to the projectile path as shown below.

But, if the launch angle was extremely huge, we can see that the projectile range will be extremely small. Now, lets assume, the height of projectile was big, the projectile motion will look as shown below.

The animation looks unnatural because the stick rotates really fast because the curve is extremely steep.

So, I am sure the javelin is not always tangent to the path(of Centre of Gravity of the javelin).

So I thought maybe I need to calculate torque on the javelin. I've also tried this approach but the javelin is extremely shaky. My steps were:

1. $$torque = r \times \vec{F}$$
2. $$\vec{F} = mg + ma$$
3. $$ a = \frac{dv}{dt} $$ v is the velocity of the centre of javelin at any point of time of projectile motion. We integrate the equation to find the change in torque.
4. $$d\vec{Torque} = r \times d\vec{force}$$
5. $$d\vec{Torque} = Id\vec{\omega}$$
6. Now, we obtain the change in angular velocity, which is then integrated to obtain the orientation of javelin.

I must have messed up somewhere because the integration is not working. Its extremely shaky and it works in some cases where launch angle is small, but fails when launch angle is huge.

So can anybody give me some pointers?

# Answer
To align a javelin, you should properly compute all forces.

The reason that a javelin can orient itself into its path, is because of air drag.

Note that the drag is not always asymmetric enough to induce enough torque to align it:

Sometimes a javelin lands with point sticking in the grass, sometimes it lands flat on the ground.

Note that gravity should be applied at the javelin's centre of mass, **which is not** the centre of the javelin.

If you drop a javelin from a tower, horizontally, then a drag force (magnitude scales with square of velocity) works along the whole length, the gravity is off-centre, causing it to nose-down.
> 4 votes

# Answer
Have you ever thrown a javelin straight up? It does actually rotate quickly on top, because the pointy end is heavier. But it does so not when it reaches the top but after the velocity changes to move downward. It's built that way to ensure the pointy end hits the target ...

You can try to model torque but that gets ugly with different weights, lengths, and heads/tails compositions. A full model might produce the most accurate results, but if the goal is to have a projectile that lands pointy-end-first no matter the launch angle, then your original method is what I'd use, but maybe augmented with a small time delay.

E.g. delay the change in orientation a small amount so that it starts to travel downward before fully rotating, much like a real spear or arrow. You can have a decaying delay for best results.

If o(t) is the tangential angle you were using for the projectile at time t, then have it instead be o(t-a). Where *a* is minimum of t or some maximum A.
> 3 votes

# Answer
maybe you should position the javelin in such a way, that the 'nose' of the javelin is where the curve is, not in the middle, that way it might look a little 'more natural'.

or

you can add a turning delta that javelin can turn only by certain degrees that are given to it, that way it goes maybe a little bit out of sync but it will look better ;-)
> 2 votes

---
Tags: projectile-physics, motion, torque
---


title: OpenGL Lines between triangles?

text:
# Question
Title: OpenGL Lines between triangles?
I'm currently using marching cubes to generate a mesh, and have encountered this incredibly weird problem.

Looking from below the terrain, these weird fully lit lines appear between every triangle. And from above, these are black. Moving closer does not remove these lines.

What could be causing these artifacts?

**Marching Cubes**

```
std::vector<glm::vec3> triangles;

glm::vec3 pos(0, 0, 0);
for (int x = 0; x < t_width - 1; x++)
for (int y = 0; y < t_height - 1; y++)
for (int z = 0; z < t_depth - 1; z++)
{
    glm::float4 cubeCorners[8] = {
        m_scalar_field[x][y][z],
        m_scalar_field[x + 1][y][z],
        m_scalar_field[x + 1][y][z + 1],
        m_scalar_field[x][y][z + 1],
        m_scalar_field[x][y + 1][z],
        m_scalar_field[x + 1][y + 1][z],
        m_scalar_field[x + 1][y + 1][z + 1],
        m_scalar_field[x][y + 1][z + 1]
    };

    int cubeindex = 0;
    for (int i = 0; i < 8; i++)
    {
        if (cubeCorners[i].w <= m_scalar_median)
        {
            cubeindex |= 1 << i;
        }
    }

    if (m_edge_table[cubeindex] != 0)
    {
        glm::float3 vertexList[12];
        if (m_edge_table[cubeindex] & 1)
            vertexList[0] =
            linearInterp(m_scalar_median, cubeCorners[0], cubeCorners[1]);
        if (m_edge_table[cubeindex] & 2)
            vertexList[1] =
            linearInterp(m_scalar_median, cubeCorners[1], cubeCorners[2]);
        if (m_edge_table[cubeindex] & 4)
            vertexList[2] =
            linearInterp(m_scalar_median, cubeCorners[2], cubeCorners[3]);
        if (m_edge_table[cubeindex] & 8)
            vertexList[3] =
            linearInterp(m_scalar_median, cubeCorners[3], cubeCorners[0]);
        if (m_edge_table[cubeindex] & 16)
            vertexList[4] =
            linearInterp(m_scalar_median, cubeCorners[4], cubeCorners[5]);
        if (m_edge_table[cubeindex] & 32)
            vertexList[5] =
            linearInterp(m_scalar_median, cubeCorners[5], cubeCorners[6]);
        if (m_edge_table[cubeindex] & 64)
            vertexList[6] =
            linearInterp(m_scalar_median, cubeCorners[6], cubeCorners[7]);
        if (m_edge_table[cubeindex] & 128)
            vertexList[7] =
            linearInterp(m_scalar_median, cubeCorners[7], cubeCorners[4]);
        if (m_edge_table[cubeindex] & 256)
            vertexList[8] =
            linearInterp(m_scalar_median, cubeCorners[0], cubeCorners[4]);
        if (m_edge_table[cubeindex] & 512)
            vertexList[9] =
            linearInterp(m_scalar_median, cubeCorners[1], cubeCorners[5]);
        if (m_edge_table[cubeindex] & 1024)
            vertexList[10] =
            linearInterp(m_scalar_median, cubeCorners[2], cubeCorners[6]);
        if (m_edge_table[cubeindex] & 2048)
            vertexList[11] =
            linearInterp(m_scalar_median, cubeCorners[3], cubeCorners[7]);

        for (int i = 0; m_tri_table[cubeindex][i] != -1; i += 3) {
            triangles.push_back(vertexList[m_tri_table[cubeindex][i]]);
            triangles.push_back(vertexList[m_tri_table[cubeindex][i + 1]]);
            triangles.push_back(vertexList[m_tri_table[cubeindex][i + 2]]);
        }
    }
}

return triangles;

```

**Calculate Normals**

```
std::vector<GLfloat> CubeMarcher::calculateNormals(const std::vector<glm::vec3> t_triangles)
{
    std::vector<GLfloat> normals;
    normals.resize(t_triangles.size() * 3);

    for(int i = 0; i < t_triangles.size(); i+= 3)
    {
        glm::vec3 normal = calulateNormal(
            t_triangles[i],
            t_triangles[i + 1],
            t_triangles[i + 2]
        );

        normals[i * 3] = normal.x;
        normals[i * 3 + 1] = normal.y;
        normals[i * 3 + 2] = normal.z;
    }

    return normals;
}

glm::vec3 CubeMarcher::calulateNormal(const glm::vec3 t_vertex1, const glm::vec3 t_vertex2, const glm::vec3 t_vertex3)
{
    glm::vec3 normal;

    glm::vec3 u = t_vertex2 - t_vertex1;
    glm::vec3 v = t_vertex3 - t_vertex1;

    normal = glm::cross(u, v);

    return normal;
}

```

**Vertex Shader**

```
#version 400 core

in vec3 position;
in vec3 normal;

out vec3 pass_Color;
out vec3 surface_normal;
out vec3 to_light;

uniform mat4 projectionMatrix;
uniform mat4 transformationMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;
uniform vec3 color;

void main()
{
    vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * viewMatrix * worldPosition;
    pass_Color = color;
    surface_normal = (transformationMatrix * vec4(normal, 0.0)).xyz;
    to_light = lightPosition - worldPosition.xyz;
}

```

**Fragment Shader**

```
#version 400 core

in vec3 pass_Color;
in vec3 surface_normal;
in vec3 to_light;

out vec4 out_Color;

void main(void){

    vec3 ambient = vec3(0.1, 0.1, 0.1);
    vec3 normal = normalize(surface_normal);
    vec3 light = normalize(to_light);

    float dotP = dot(normal, light);
    float brightness = max(dotP, 0.0);
    vec3 diffuse = (brightness + ambient) * pass_Color;

    out_Color = vec4(diffuse, 1.0);
}

```

**Above**

**Below**

**EDIT** I decided to render to a flat color as recommended in the comments. But neither looking from above or below the mesh shows any seams.

**EDIT 2** Without glEnable(GL\_CULL\_FACE)

With glEnable(GL\_CULL\_FACE)

# Answer
So, I looked through all my code again and again and noticed missing normals. Then it finally dawned on me:

```
normals[i * 3] = normal.x;
normals[i * 3 + 1] = normal.y;
normals[i * 3 + 2] = normal.z;

```

Had to be:

```
normals[i * 3] = normal.x;
normals[i * 3 + 1] = normal.y;
normals[i * 3 + 2] = normal.z;

normals[i * 3 + 3] = normal.x;
normals[i * 3 + 4] = normal.y;
normals[i * 3 + 5] = normal.z;

normals[i * 3 + 6] = normal.x;
normals[i * 3 + 7] = normal.y;
normals[i * 3 + 8] = normal.z;

```

So the ultimate problem was missing normals.
> 1 votes

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


# Question
Title: Enemy collision detection with movie clips
I have created multiple movieclips with animations within them. It is an obstacle avoidance game and I cannot seem to be able to get my enemies to contact my `playableCharacter`. The enemies I have created are each embedded on certain levels of my game. I have created an array, `enemiesArray` to have each of my enemies placed within it. Here is the code for that:

```
//step 1: make sure array exists
if(enemiesArray!=null && enemiesArray.length!=0)
{
    //step 2: check all enemies against villain
    for(var i:int = 0;i < enemiesArray.length; i++)
    {
        //step 3: check for collision
        if(villain.hitTestObject(enemiesArray[i]))
        {
            //step 4: do stuff
            trace("HIT!");
            removeChild(enemiesArray[i]);
            enemiesArray.splice(i,1);

            removeChild(villain);
            villain = null;
        }
    }
}

```

What I am unsure of is whether or not my `enemiesArray` is actually holding the movieclips I have suggested. If it was, this code would be tracing back a "HIT" for every time I ran into an enemy and would kill my character. It is not doing that however.

I am thinking I have to push my movieclips into my array but I don't know how to do that or where for that matter.

Any and all help would be much appreciated.

# Answer
> 1 votes
If you add the enemies to the stage dynamically, via code, you should add a line of code which pushes the enemy onto the enemiesArray every time you create a new enemy and add it to the stage.

For example,

```
var myEnemy:Enemy = new Enemy();
stage.addChild(myEnemy);
enemiesList.push(myEnemy);

```

# Answer
> -1 votes
I am a noob user, so take this for what it is worth... I had a similar issue on a simple shooter game. I switched these two lines: removeChild(villain); villain = null;

to this: villain = null;
removeChild(villain);

and everything started working correctly.

---
Tags: actionscript-3
---


# Question
Title: Using a sphere collider in combination with FoV
I have a character and some npc's in my game. I want the npc's to look out for my character using a sphere collider. Well it kind of works but of course not as i want. When the npc is looking at me and a colission occurs it should trigger some chasing behaviour, but if the npc look in another direction, it should not trigger that behaviour.

So i need something like a field of view inside the collider. I watched some tutorials like https://www.youtube.com/watch?v=rQG9aUWarwE and https://www.youtube.com/watch?v=mBGUY7EUxXQ but it should be 3 dimensional so not only on the ground like in the tutorial. I added a picture to visualize it

How can i accomplish this?

# Answer
In addition to the approaches using Vector3.Dot or .Angle to check whether the line from the observer to the target fits within a round cone, we could also try an approach like this to get a pyramidal field of view, that can be wider horizontally than vertically for example:

```
[Tooltip("Horizontal & vertical field of view of the agent's vision pyramid, in degrees, measured from the central axis")]
public Vector2 fieldOfView = new Vector2(45, 30);

[Tooltip("Assign a transform here to represent the position of the observer's eyes")]
public Transform eye;

void OnTriggerStay(Collider collider) {
    // Transform the target's (pivot) position into the eye's frame of reference.
    Vector3 inEyeSpace = eye.InverseTransformPoint(collider.transform.position);

    // Dividing by depth gives us the slope of the ray to the target...
    Vector2 tangent = ((Vector2)inEyeSpace) / inEyeSpace.z;

    // ...which we can compare against the limits of our FoV angles.
    Vector2 radians = fieldOfView * Mathf.Deg2Rad;
    bool inHorizontalRange = Mathf.Abs(tangent.x) <= Mathf.Tan(radians.x);
    bool inVerticalRange = Mathf.Abs(tangent.y) <= Mathf.Tan(radians.y);

    // If the target is in front of the eye and not out of range on either axis, we see it!
    if(inEyeSpace.z > 0 && inHorizontalRange && inVerticalRange)
         Detect(collider.gameObject); // Trigger your detection, or confirm with a raycast first.
}

```

By placing a (potentially empty) GameObject where the character's head should be, and assigning its Transform to the `eye` variable, you can control both where the vision pyramid originates, and also its direction - for instance if you wanted to angle it downward so the character sees more of what's below them than above them.

You can add a gizmo method to help visualize the shape of the vision pyramid in the scene view and double-check that detection is occurring as you expect. The far corners aren't quite exact - I'm neglecting here the curvature or center of the sphere collider - but it provides a decent visual aid all the same.

```
void OnDrawGizmos() {
    var sphere = GetComponent<SphereCollider>();
    if(sphere == null || eye == null)
        return;

    Vector2 radians = fieldOfView * Mathf.Deg2Rad;
    Vector3 localCorner = new Vector3(
                                 Mathf.Tan(radians.x),
                                 Mathf.Tan(radians.y),
                                 1
                          ) * sphere.radius;

    Vector3 topRight = eye.TransformPoint(localCorner);
    localCorner.x *= -1f;
    Vector3 topLeft = eye.TransformPoint(localCorner);
    localCorner.y *= -1f;
    Vector3 bottomLeft = eye.TransformPoint(localCorner);
    localCorner.x *= -1f;
    Vector3 bottomRight = eye.TransformPoint(localCorner);

    Gizmos.DrawLine(eye.position, topLeft);
    Gizmos.DrawLine(eye.position, topRight);
    Gizmos.DrawLine(eye.position, bottomLeft);
    Gizmos.DrawLine(eye.position, bottomRight);
    Gizmos.DrawLine(topLeft, topRight);
    Gizmos.DrawLine(topRight, bottomRight);
    Gizmos.DrawLine(bottomRight, bottomLeft);
    Gizmos.DrawLine(bottomLeft, topLeft);
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Black and white textures load as turquoise?
I have some black and white, and some grayscale textures, that are loading in unity as turquoise and white textures. What is causing this and how can I fix this? Also, can somebody verify that I am supposed to load roughness textures into the "Metallic" slot of the Standard shader? That feels so weird. I was using Principled Shader in Blender to make the original materials. \**EDIT: "Autodesk Interactive" shader has a "Roughness" input but most of my roughness textures and some b&w textures are still turquoise, what is happening...

Here is one of the problem textures (the others are too big, \> 6mb):

# Answer
> 1 votes
The problem seems to have been that the bit depth was too high for these images (16 bits per channel, higher for others). resolved by going into Photoshop, going to the Image tab on the menu, and setting the bits per channel to 8 (instead of 16). All textures load normally after doing this. If refreshing the scene doesn't do it, delete the old assets and drag-and-drop the updated textures. Thanks to DMGregory for suggesting this solution.

---
Tags: unity, textures, materials, alpha
---


# Question
Title: Can't get Direct3D11 depth buffer to work
I can't get the depth buffer to work correctly. I am rendering 2 cubes in a single Draw function, and from one angle it looks great

But swing the camera around to view the opposite sides, and I discover it's just Painter's Algorithm.

This is my code to setup the depth stencil buffer:

```
void Graphics::CreateDepthStencilBuffer(ID3D11Texture2D* backBuffer)
{
    D3D11_TEXTURE2D_DESC dsTextureDesc;
    backBuffer->GetDesc(&dsTextureDesc);
    dsTextureDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    dsTextureDesc.Usage = D3D11_USAGE_DEFAULT;
    dsTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    dsTextureDesc.MipLevels = 1;
    dsTextureDesc.ArraySize = 1;
    dsTextureDesc.CPUAccessFlags = 0;
    dsTextureDesc.MiscFlags = 0;
    Microsoft::WRL::ComPtr<ID3D11Texture2D> dsBuffer;
    ASSERT_SUCCEEDED(g_Device->CreateTexture2D(&dsTextureDesc, NULL, dsBuffer.ReleaseAndGetAddressOf()));

    D3D11_DEPTH_STENCIL_DESC dsDesc;
    dsDesc.DepthEnable = true;
    dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
    ... snipped stencil properties ...
    ASSERT_SUCCEEDED(g_Device->CreateDepthStencilState(&dsDesc, g_DepthStencilState.GetAddressOf()));
    g_pDevCon->OMSetDepthStencilState(g_DepthStencilState.Get(), 1);

    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    depthStencilViewDesc.Format = dsTextureDesc.Format;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;
    ASSERT_SUCCEEDED(g_Device->CreateDepthStencilView(dsBuffer.Get(), &depthStencilViewDesc, g_depthStencilView.GetAddressOf()));
}

```

And I'm calling `g_pDevCon->OMSetRenderTargets(1, g_renderTargetView.GetAddressOf(), g_depthStencilView.Get());` after every Present call.

I've been scratching my head for ages wondering what the problem is. Any clues will be much appreciated!

Edit:
I used the graphics debugger, and apparently the output merger is doing its job, as seen in the screenshot below, but that isn't what I am seeing on screen. At the top of the pic is the state of the depth buffer, but I can't make sense of it to determine if it's correct or not.

# Answer
> 0 votes
Well, it turns out I committed the cardinal sin of setting the near Z to zero. (I didn't know this was problem at the time) This resulted in my Z values being the same as the W values, and everything became 1 in the depth buffer.

In general, it pays to push out the near Z as far as is practical. It's highly unlikely you will ever need it to be zero.

---
Tags: directx11, depth-buffer
---


# Question
Title: How to make rhythm game long notes in Unity?
I'm making a rhythm game for a university course and I can't figure out a way to make the long/sustained notes. For reference, this is what I mean taken from Guitar Hero:

I already have a system working for regular notes. The way I do it is that the notes are stored in an external file as numbers which represent the absence or presence of a note as well as what type of note it is, separated into musical bars: 000 010 020 001

There are three lanes for the notes to be, and this means that in this particular bar there are notes wherever it's not 0 (with the numbers being different types of notes). I had thought of using this system to create long/sustained note start and end markers (say 3 and 4) and that create another game object which would be the line between the start and end markers. But the way my note generator works is that the notes are not all generated at once because that'd be pretty heavy. Instead, the notes are generated at a certain time taking into account its speed so that it's instantiated and will reach the player's activator when it's supposed to. The following is a part of my note generator code, put in the Update method:

```
// if current song time - time offset is greater than
// time taken for all executed bars so far
// spawn the next bar's notes
if (songTimer - _timeOffset >= (barExecutedTime - barTime))
{
   StartCoroutine(PlaceBar(noteData.bars[barCount++]));

   barExecutedTime += barTime;
}

```

And here is the PlaceBar coroutine:

```
// go through all notes in a bar
// creates an instance of note prefab
// depending on which note is meant to be spawned
private IEnumerator PlaceBar(List<SongParser.Notes> bar)
{
   for (int i = 0; i < bar.Count; i++)
   {
       if (IsThereNote(bar[i].bottom))
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].bottom, true), new Vector3(bottomLane.transform.position.x + distance, bottomLane.transform.position.y, bottomLane.transform.position.z - 0.3f), Quaternion.identity);
       }
       if (bar[i].middle != 0)
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].middle, false), new Vector3(middleLane.transform.position.x + distance, middleLane.transform.position.y, middleLane.transform.position.z - 0.3f), Quaternion.identity);
       }
       if (bar[i].top != 0)
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].top, true), new Vector3(topLane.transform.position.x + distance, topLane.transform.position.y, topLane.transform.position.z - 0.3f), Quaternion.identity);
       }

       yield return new WaitForSeconds((barTime / bar.Count) - Time.deltaTime);
   }
}

```

So if I were to make start and end markers, the start marker would not know where the end marker is because it doesn't exist. Could anyone help please?

# Answer
It looks like you can solve this by keeping track of the last-placed note in each lane, then stitching the continuation of that note onto it.

Let's assume you have a script on your note representation prefab(s) onto which we can add the concept of a "continuation" like what's below:

```
public class NoteRepresentation : MonoBehaviour {

    public NoteKind kind;
    NoteRepresentation continuation;

    public void AddContinuation(NoteRepresentation note) {
        if(kind != NoteKind.SustainedBegin && kind != NoteKind.SustainedMiddle) {
            Debug.LogWarningFormat("Tried to add a continuation to a note that doesn't support it ({0}). Check your song data.", kind);
            return;
        }
        continuation = note;
        // Here you might want to do things like adjust the size of the middle segment
        // to connect to this note, or extend a line renderer between the notes...
    }
}

```

Then your parser can track the most recent note it spawned in each lane:

```
NoteRepresentation[] latestNote = new NoteRepresentation[LANE_COUNT];

```

And when placing a note, you can check to see if it's a continuation of a previous starting note, and glue them together if so:

```
PlaceNote(NoteRepresentation prefab, int laneIndex) {

    Vector3 position = laneTransforms[laneIndex];
    position.x += distance;
    position.z -= 0.3f;

    // You could also serve these from a pool to reduce allocations/garbage.
    var noteRepresentation = Instantiate(prefab, position, Quaternion.identity);

    if ( noteRepresentation.kind == NoteKind.SustainedMiddle
      || noteRespresentation.kind == NoteKind.SustainedEnd ) {

        if(latestNote[laneIndex] == null) {
            Debug.LogError("Continuation note {0} is first note found in lane {1}", noteRepresentation.kind, laneIndex);
        } else {
            latestNote[laneIndex].AddContinuation(noteRepresentation);
        }
    }

    // Remember this note for future.
    latestNote[laneIndex] = noteRepresentation;
}

```

You can call this `PlaceNote` routine each time you try to place a note (we could go even further with indexing to make this a loop over `n` lanes instead of three separate checks):

```
if (IsThereNote(bar[i].bottom))
   PlaceNote(GetNotePrefab(bar[i].bottom,false), 0);

if (bar[i].middle != 0)
   PlaceNote(GetNotePrefab(bar[i].middle,false), 1);

if (bar[i].top != 0)
   PlaceNote(GetNotePrefab(bar[i].top,false), 2);

```

As long as your parser looks far enough ahead to find the continuation of a note before that note appears on screen,the player shouldn't notice that the long notes are built-up a piece at a time - by the time they come into view they should be fully-formed. If you can't guarantee that with your default approach, you could have the parser check to see if it has any outstanding nodes that need continuation in its `latestNote` array, and parse an extra bar further than normal if so.
> 1 votes

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


# Question
Title: 2D character tips over sideways after collision with platform
This is what happens when my player character jumps and collides with a platform from the side. The player character tilts over or ends up upside-down or sometimes on its back.

How can I prevent this?

# Answer
Inside your character's Rigidbody2D component, expand the "Constraints" fold-out, and tick the "Freeze Rotation Z" box. This will ensure that physics impacts can't cause your character to spin.
> 1 votes

---
Tags: unity, c#, physics, platformer, collision-resolution
---


# Question
Title: Are the sides of a beveled rectangular prism considered "ngons", to be avoided?
Many tutorials I have watched say that everything should be made in 'quads' (ie. no triangles, and no ngons).

I think this is mainly due to getting into this habit so that if I make a complex model, eg. a rigged character face, then there won't be any animation issues like model warping or bad occlusions/shadows/etc. (please do correct me if this is wrong, its just what I've gathered from many videos and some books).

So I tasked myself with making a Glock handgun, thinking this boxy shape might be a good starter project. I noticed the corners of the top piece are curved/beveled, so I beveled it on my model.

This is where I got my first problem though, the bevel process created about 3 new vertices on each corner I applied it to, but then this leaves the side of the piece with more than 4 edges (see picture):

In the pic you can see I highlighted one of the small 'edges' the bevel created. So now I can count something like 12 edges in total surrounding that side part.

Is that an ngon? Will it matter? And if its not OK, how should I do it?

# Answer
> 1 votes
> Is that an ngon?

It is a polygon with more than 4 sides, so yes, by definition, it is an ngon in this sense.

> Will it matter?

Probably not.

As you say, non-quad faces can be troublesome when applying smooth deforming animations, but this is a rigid object that won't need to deform in that way.

Non-quads can also cause trouble if you want to apply subdivision modifiers to smooth an initial control mesh, or to apply surface sculpting & high-res detail through something like Z-Brush/Mudbox. But that doesn't seem to be part of the workflow you have planned for this object.

In gamedev, the most surefire way to know if something is a problem is to try it and see what goes wrong. If nothing's gone wrong yet, then it might very well be good enough for your purposes. ;)

> And if its not OK, how should I do it?

Finding a good edge flow for quads on a mesh that needs animation or subdivision is an art form in itself. An artist-focused site like Polycount might be a better place to get detailed guidance on this front. Check out their forum posts about edge flow, and hard surface topology

---
Tags: 3d, 3d-meshes, maya
---


# Question
Title: Input.GetKey("example") ect. Player Input not working full screen Unity Engine
hopefully this is a simple fix i tried looked for others with the issue but I don't know if I am bad at google or if this is just an issue with me.

When I go into test mode to test player inputs it works if I am still in the main screens with my scene, game display, and all my toolbars and option. but when I press game and click Shift+Space to go full screen and then press play, I lose all access to my Player Inputs. Is there something I need to enable or is it just 2 am tiredness?

# Answer
> 3 votes
Remember to click inside your game window to give it input focus.

For whatever reason, clicking the play button doesn't automatically give the game window input focus in "Maximize On Play" mode.

---
Tags: unity
---


# Question
Title: How does one get sprites to hide/unhide using OnMouseDown() in Unity?
I'm right now using Unity for a school project and I need to be able to hide and unhide sprites for "expansions".

I've looked all over the internet for this and I can't seem to find an answer.

Here is the script so far:

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

[DisallowMultipleComponent]
public class addBlock : MonoBehaviour{

  void OnMouseDown()
  {
     Debug.log(gameObject.name);
  }
}

```

# Answer
> 1 votes
"I looked all over the internet" and somehow completely missed the enabled checkbox? ;)

```
[RequireComponent(typeof(Renderer))]
public class HideShowOnClick : MonoBehaviour {

    Renderer visual;

    void Start() {
        visual = GetComponent<Renderer>();
    }

    void OnMouseDown() {
        // If it was shown, hide it. If it was hidden, show it.
        visual.enabled = !visual.enabled;
    }
}

```

Make sure your object has both a renderer attached (can be a SpriteRenderer, MeshRenderer, etc), and an appropriately-shaped/sized collider to detect whether the mouse click hits it. Because we turn off only the visual, the collider is still there to capture the click to trigger it to turn back on.

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