# Question
Title: How can I switch targets using coroutine each x seconds?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    public FLookAnimator lookAnimator;
    public Transform[] targets;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(WaitSome());
    }

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

    }

    IEnumerator WaitSome()
    {
        lookAnimator.ObjectToFollow = targets[0];

        yield return new WaitForSeconds(10f);

        lookAnimator.ObjectToFollow = targets[1];
    }
}

```

This changes the targets every 10 seconds but it's doing it only once and I don't want to assign the target on my own like targets\[0\] and targets\[1\] in this case I have two targets but if I have 20 targets?

How can I loop in the Update over the targets and then every 10 seconds to change between all the targets. every 10 seconds change the target.

# Answer
It looks like you meant to write something like...

```
IEnumerator SwitchTargetsPeriodically()
{
    for (int i = 0; true; i = (i + 1) % targets.Length) {
        lookAnimator.ObjectToFollow = targets[i];
        yield return new WaitForSeconds(10f);
    }
}

```
> 0 votes

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


# Question
Title: Unity 2D Game: does transparency count as overdraw?
I'm working on a 16:9, 1920x1080, 2.5D point-and-click adventure game and I just today learned the word overdraw. I have a few questions, but first some details about the game:

**Backgrounds**

Backgrounds are hand drawn, and broken up into layers. For instance, if there's a room with a table, some chairs, and a lamp on the table, then I'll have a sprite for each of those objects whenever I want the player to be able to walk in-front of or behind that object.

To make positioning of these objects consistent with what's in photoshop, I've exported each layer as a full HD image with huge swaths of transparency. These images have a very small memory footprint because only a small portion of image is populated with non-transparency.

**Animation**

Animation is hand drawn. To make character position consistent across all characters, each animation is exported as full HD images with huge swaths of transparency. The characters reside at the bottom center of frame. I call it the anchor point. In point of fact, it's where I put the pivot.

I've got all animations and backgrounds in sprite atlases to save on video memory. So far, it's low.

MY QUESTION:

Am I a huge idiot? Are these full screen images with lots of transparency going to be a big problem for me? The game is for mobile and PC and Switch.

# Answer
> 0 votes
So. I think the answer to this is NO, I'm not a huge idiot. So long as my sprites are set to Mesh Type: "Tight" instead of "Full Rect," the alpha regions shouldn't be rendered.

Also of note, in order for Image objects to use the tight mesh, you have to specifically check the box that says "Use Sprite Mesh"

---
Tags: unity
---


# Question
Title: In a 3D grid of cubes, how to calculate index of a cube if we only know it's coordinates and the way cubes are generated?
I have a code that generates a grid of equally sized cubes in a cubic volume of given limited size, intended to be used for 3d path finding. Let's say cubes are objects stored in an array called `Grid[]`. I need to mathematically retrieve an index of the cube in that array, when knowing only it's X, Y and Z coordinates.

As an example, imagine a volume that can fit 6 cubes in length (**X**), 4 cubes in width (**Y**), and 3 cubes in height (**Z**). That's a total of 72 cubes. That means every cube has it's unique X, Y and Z coordinates; `{0, 0, 0}` for the first cube (`Grid[0]`), all the way to the `{5, 3, 2}` for the last cube (`Grid[71]`).

The cubes are generated by filling the Z axis upwards, than the Y axis, and lastly the X. Here's a drawing to explain it better:

**What mathematical formula can I use to calculate the *i* by using cube's X, Y and Z coordinates, and the volume's maximum X, Y and Z values?**

I am not allowed to have a separate HashMap to look through it. I am also not supposed to loop through all of the array members and compare the stored values with the given coordinates - the grid could contain millions of cubes.

# Answer
> 1 votes
It's a geometric progression. Here's a working formula:

```
i = z + y * maxZ + x * maxY * maxZ

```

# Answer
> 0 votes
```
i = z + y * CubesPerColumn + x * CubesPerSlice

```

In your diagram,

```
CubesPerColumn = 3

```

and

```
CubesPerSlice = CubesPerColumn * ColumnsPerSlice = 3 * 4 = 12

```

---
Tags: 3d, vector
---


title: FBO not rendering or changing anything

text:
# Question
Title: FBO not rendering or changing anything
Recently, I am making a 3D game. I want to do special post processing effects, like pixelization. I used this to load do everything with FBOS, but it's kindof weird...

In some code for the initialization of the FBO, it stops, and errors out with the error code `1280`, which aparently means `GL_INVALID_ENUM`, and it all started when I put in this code in my `FBO` class:

```
GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, renderTex, 0, GL11.GL_TEXTURE_2D);

```

It errors out, then closes (by if statement). If I don't close it, it renders black, like this:

If I change `glFramebufferTexture2D` to `glFramebufferTexture`, it just turns black and no error outputs.

I seriously have no idea how.

maybe it's by the classes that's causing this, so here they are:

Main Class:

```
package me.pale.main;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.opengl.Texture;

import me.pale.model.Voxel;
import me.pale.postprocess.FBO;
import me.pale.postprocess.PostProcessQuad;
import me.pale.shader.Shader;

public class BlockGame {

    float fac = 16;

    float t = 16;

    Texture testtex;

    float rot;

    Shader shader;
    Shader postprocess;

    PostProcessQuad ppq = new PostProcessQuad();

    Voxel test = new Voxel();

    public void window(String name, int width, int height) throws LWJGLException, FileNotFoundException, IOException {

        Display.setDisplayMode(new DisplayMode(width, height));
        Display.create();

        FBO fbo = new FBO();

        shader = new Shader("res/fragment.glsl", "res/vertex.glsl");
        postprocess = new Shader("res/ppfrag.glsl", "res/ppvert.glsl");

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
        GL11.glClearColor(0, 0, 0, 0);
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GLU.gluPerspective(90.0f, 1.333f, 0.1f, 650.0f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glEnable(GL11.GL_DEPTH_TEST);
        GL11.glDepthMask(true);

        GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac);

        GL11.glTranslated(0.0f, 0.0f, -5.0f);

        while (!Display.isCloseRequested()) {

            if (fac < 0) {

                fac = 0;
                t = 0;

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {

                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac -= 0.025f);
                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "t"), t -= 0.025f);

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {

                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac += 0.025f);
                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "t"), t += 0.025f);

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_R)) {

                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), 16);
                GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "t"), 16);

            }

            rot += 0.05f;

            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
            GL11.glClearColor(1.0f, 1.0f, 0.2f, 1.0f);
            //GL11.glBindTexture(GL11.GL_TEXTURE_2D, testtex.getTextureID());

            // shader.start();
            GL11.glPushMatrix();
            GL11.glTranslatef(-4.0f, 0.0f, 0.0f);
            GL11.glBegin(GL11.GL_QUADS);
            GL11.glBindTexture(0, fbo.getRenderTex());
            GL11.glTexCoord2f(0, 0);
            GL11.glVertex3f(-1, 1, -1);
            GL11.glTexCoord2f(1, 0);
            GL11.glVertex3f(1, 1, -1);
            GL11.glTexCoord2f(1, 1);
            GL11.glVertex3f(1, -1, -1);
            GL11.glTexCoord2f(0, 1);
            GL11.glVertex3f(-1, -1, -1);
            GL11.glEnd();
            GL11.glPopMatrix();

            fbo.bindFBOS();
            postprocess.start();
            GL11.glPushMatrix();
            GL11.glTranslatef(-4.0f, 0.0f, 0.0f);
            ppq.draw();
            GL11.glPopMatrix();
            fbo.unbind();

            postprocess.halt();

            shader.start();

            GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "f"), rot/10);

            GL11.glPushMatrix();

                GL11.glRotatef(rot, 1, 1, 1);

                test.draw();

            GL11.glPopMatrix();

            shader.halt();
            // shader.halt();

            Display.update();

        }

        fbo.wash();
        postprocess.wash();
        shader.wash();
        Display.destroy();
        System.exit(0);

    }

    public static void main(String[] args) throws LWJGLException, FileNotFoundException, IOException {

        BlockGame bg = new BlockGame();
        bg.window("Game", 640, 480);

    }

}

```

FBO Class:

```
package me.pale.postprocess;

import java.nio.ByteBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;

public class FBO {

    int defaultFBO;
    int defaultTEX;
    int defaultDEPTH;

    public FBO() {

        init();

    }

    public int createFBO() {

        int fbo = GL30.glGenFramebuffers();
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
        // GL11.glViewport(0, 0, 640, 480);
        GL11.glDrawBuffer(GL30.GL_COLOR_ATTACHMENT0);

        return fbo;

    }

    public int createRenderTexture() {

        int renderTex = GL11.glGenTextures();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, renderTex);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, 640, 480, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);

        GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, renderTex, 0, GL11.GL_TEXTURE_2D);

        int drawBuffer = GL30.GL_COLOR_ATTACHMENT0;

        GL20.glDrawBuffers(drawBuffer);

        if (GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE) {

            System.out.println("ERR: error occurred making FBO " + GL11.glGetError());
            System.exit(-1);

        }
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);

        return renderTex;

    }

    public void bind(int fbo) {

        // GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
        GL11.glViewport(0, 0, 640, 480);

    }

    public void unbind() {

        // GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
        GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());

    }

    public void render() {

        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
        GL11.glViewport(0, 0, 640, 480);

    }

    private int createDepthBuffer() {

        int depthRenderBuffer = GL30.glGenRenderbuffers();
        GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depthRenderBuffer);
        GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL11.GL_DEPTH_COMPONENT, 640, 480);
        GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER, depthRenderBuffer);

        return depthRenderBuffer;

    }

    public void bindFBOS() {

        bind(defaultFBO);

    }

    public void init() {

        defaultFBO = createFBO();
        defaultTEX = createRenderTexture();
        defaultDEPTH = createDepthBuffer();
        unbind();

    }

    public void wash() {

        GL30.glDeleteFramebuffers(defaultFBO);
        GL11.glDeleteTextures(defaultTEX);

    }

    public int getRenderTex() {
        return defaultTEX;
    }

    public int getFbo() {
        return defaultFBO;
    }
}

```

Be in mind that I used this link and ThinMatrix's water tutorial, episode 2.

Any help appreciated!

# Answer
Here, you used the wrong order of parameters:

```
glFramebufferTexture2D(
    GL30.GL_FRAMEBUFFER,
    GL30.GL_COLOR_ATTACHMENT0,
    renderTex,
    0,
    GL11.GL_TEXTURE_2D);

```

As specified by the documentation, it should have been:

```
glFramebufferTexture2D(
    GL30.GL_FRAMEBUFFER,
    GL30.GL_COLOR_ATTACHMENT0,
    GL11.GL_TEXTURE_2D,
    renderTex,
    0);

```

Also in Java, I think you can use something like this:

```
import static org.lwjgl.opengl.GL30.*;

```

which allows you to write

```
public void render() {

    glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
    glViewport(0, 0, 640, 480);

}

```

See! No need to write `GL11` or `GL30`.
> 1 votes

---
Tags: opengl, java, lwjgl, fbo
---


# Question
Title: What is a correct approach to gamma correction in OpenGL?
I'm currently reading about the topic of gamma correction and am a bit confused about what should I, as a game developer, do about it. There seem to be a few options here:

1. Don't do anything at all and let OS, driver, monitor and user figure it out. Doesn't seem to be the right one to me, but I may be wrong.
2. Explicitly request sRGB framebuffer and enable `GL_FRAMEBUFFER_SRGB` while doing rendering to display, leaving details to driver once again.
3. Explicitly request sRGB framebuffer and manually apply gamma correction in shader, potentially exposing slider to user.

In addition to above, there's an idea to "uncorrect" textures, which assumes that they were made in sRGB color space to begin with, which seems pretty dubious to me: wouldn't good textures already be properly using RGB colorspace instead of sRGB? Even if they weren't, why not correct them on disk instead of doing extra calculations in runtime?

So, what approach should I take?

# Answer
> 1 votes
Ask OpenGL driver if it has extensions for framebuffer and texture sRGB conversions. And implement fallback gamma correction with `#ifdef` in shader code.

You must also notice that not every texture is in sRGB space, for example normal maps. And if you do postprocessing of your image, you should convert from linear space to sRGB only on last stage.

---
Tags: opengl, srgb
---


# Question
Title: opengl (lwjgl) - only white triangle gets rendered, vertex and fragment shader not responsive
Currently my program can only render my vertices as white and changes in my vertex and fragment shader don't change what gets rendered for some reason i.e: (`gl_Position = vec4(position+0.5,1);` doesn't shift my triangle).

I'm not getting `GL_FALSE` from the `glGetShaderi` and `glGetProgrami` functions and I know my fragment shader and vertex shader are being read as `glGetShaderi(shader,GL_COMPILE_STATUS)` == `GL_FALSE` when I forget my semi-colon.

Anyone know how to solve this?

Vertex Shader:

```
#version 330

layout (location = 0) in vec3 position;

void main(){
    gl_Position = vec4(position+0.5,1);
}

```

Fragment Shader:

```
#version 330

out vec4 fragColor;

void main(){
    fragColor = vec4(1,1,0,1);
}

```

Main.java:

```
public class Main {
    static long window;
    private static int WIN_WIDTH = 500;
    private static int WIN_HEIGHT = 500;

    public static void main(String[] args) {
        // glfwInit
        if (!glfwInit()) {
            throw new IllegalStateException("Error for glfwInit");
        }

        // Hint
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,2);

        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GLFW_TRUE);

        glfwWindowHint(GLFW_VISIBLE,GLFW_FALSE);

        // Window
        // window create
        window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "warmulfollowalong", 0, 0);
        // window check
        if  (window == 0) {
            throw new IllegalStateException("Error creating window");
        }

        // CONTEXT
        glfwMakeContextCurrent(window);
        GL.createCapabilities();

        // window position

        GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        glfwSetWindowPos(window, videoMode.width()/2-WIN_WIDTH/2, videoMode.height()/2-WIN_HEIGHT/2);

        // window display
        glfwShowWindow(window);

        // CREATE MESH
        Mesh testMesh = new Mesh();
        testMesh.create(new float[] {
                -1, -1, 0,
                0,1,0,
                1,-1,-1,
        });

        //
        Shader shader = new Shader();
        shader.create("shader");

        // LOOP
        while(!glfwWindowShouldClose(window)) {
            glfwPollEvents();

            // clear
            glClearColor(1, 0, 0, 1);
            glClear(GL_COLOR_BUFFER_BIT);

            // shader
            shader.useShader();

            // DRAW
            testMesh.draw();

            glfwSwapBuffers(window);
        }

        // destroy
        testMesh.destroy();
        shader.destroy();

        // close
        glfwTerminate();
    }
}

```

Mesh.java:

```
public class Mesh {
    private int vao;
    private int vbo;

    private int vertexCount;

    public void Mesh() {

    }

    public boolean create(float[] vertices) {
        // Create VAO and bind it
        vao = glGenVertexArrays();
        glBindVertexArray(vao);

        // Create empty buffer and bind it and bufferData
        vbo = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER,vertices,GL_STATIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0,0);

        // Unbind VAO
        glBindVertexArray(0);

        // Set vertexCount
        vertexCount = vertices.length / 3;

        return true;
    }

    public void destroy() {
        // delete vao & vbo
        glDeleteVertexArrays(vao);
        glDeleteBuffers(vbo);
    }

    public void draw() {    // Seems very inefficient
        // bind VAO
        glBindVertexArray(vao);
        // enable VBO (essentially) / enable vertex Attribute Array
        glEnableVertexAttribArray(0);   // !@$!@#!@# when to use???

        // DRAW
        glDrawArrays(GL_TRIANGLES, 0, vertexCount);

        // disable VBO (essentially) / enable vertex Attribute Array
        glDisableVertexAttribArray(0);
        // unbind VAO
        glBindVertexArray(0);
    }
}

```

Shader.java:

public class Shader {
    // stores int handle
    private int vertexShader, fragmentShader, program;

    public Shader(){

    }

    public boolean create(String shader) {
        // Create vertex shader
        int vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, readSource(shader+".vs"));
        glCompileShader(vertexShader);

        if(glGetShaderi(vertexShader, GL_COMPILE_STATUS) == GL_FALSE) {
            throw new Error("ERROR: compiling vertex shader. Info: "+glGetShaderInfoLog(vertexShader));
        }

        // Create fragment shader
        int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragmentShader,readSource(shader+".fs"));
        glCompileShader(fragmentShader);

        if(glGetShaderi(fragmentShader,GL_COMPILE_STATUS) == GL_FALSE) {
            throw new Error("ERROR: compiling fragment shader. Info: "+glGetShaderInfoLog(fragmentShader));
        }

        // Program
        int program = glCreateProgram();
        glAttachShader(program, vertexShader);  // !@#!@#!@#
        glAttachShader(program, fragmentShader);

        // Program check
        glLinkProgram(program);
        if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) {
            throw new Error("ERROR: linking program. Info: "+glGetProgramInfoLog(program));
        }
        glValidateProgram(program);
        if (glGetProgrami(program,GL_VALIDATE_STATUS) == GL_FALSE) {
            throw new Error("ERROR: validating program. Info: "+glGetProgramInfoLog(program));
        }

        return true;    // !@#!@# Shouldn't you be passing down the program? Isn't this like an anti pattern?

    }

    public void destroy() {
        // detach
        glDetachShader(program, vertexShader);
        glDetachShader(program, fragmentShader);

        // delete shaders
        glDeleteShader(vertexShader);
        glDeleteShader(fragmentShader);

        // delete program
        glDeleteProgram(program);
    }

    public void useShader() {
        glUseProgram(program);
    }

    public String readSource(String file) {
        BufferedReader reader = null;
        StringBuilder sourceBuilder = new StringBuilder();

        try {
            reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/shaders/"+file)));

            String line;

            while((line = reader.readLine()) != null) {
                sourceBuilder.append(line+"\n");    //<= remember to add new line
            }
        }catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                //MY
                if(reader != null){
                    reader.close();
                }
            }catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        return sourceBuilder.toString();
    }

}

```
</code></pre>

# Answer
The culprit was the `int` in `int program = glCreateProgram();`.

Using the below code ultimately helped solve this problem:

<pre><code>glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE );

// Place the below two after you've run `glfwMakeContextCurrent(window);` & `GL.createCapabilities();` and before the GL code
glEnable(org.lwjgl.opengl.KHRDebug.GL_DEBUG_OUTPUT_SYNCHRONOUS);
// store this in a field somewhere so it doesn't gets GC'd
Callback callbackA = GLUtil.setupDebugMessageCallback();
```

> 0 votes

---
Tags: java, shaders, lwjgl
---


# Question
Title: Deriving multiple properties from a single random seed
I'm interested in designing a game with a randomly-generated world. I'd like the world to be generated from a seed value, so that players could share these seeds among each other and play in the same world. What I'm not clear about is how to properly derive multiple independent world variables from the same seed, without players being able to deduce one facet from another. For example:

`Fairy fruit is (n % 3): 0: delicious: 1: disgusting: 2: poisonous`

`The Troll King's heart is in his (n % 6): 0: skull 1: left elbow 2: right knee 3: left ankle 4: chest (cavity) 5: chest (loot)`

The problem is, the player can deduce down to two possibilities where the Troll King's heart is by force-feeding a peasant some fairy fruit and watching the reaction. Likewise, if he's already fought the Troll King, he knows whether fairy fruit is safe to eat.

One workaround I thought of is to have each of those modulo values be a different prime number, which if I understand math would mean that you couldn't guess one value from another. But this would break if I wanted a non-prime number of options. In the Troll King example above, I'd have to remove one of the options, add another option, or make 6 a duplicate of an existing option and accept a non-uniform distribution. Does anyone have a better idea of how to do this?

# Answer
Most games and applications solve this problem by using a pseudorandom number generator (PRNG). With a PRNG, your initial, sharable seed value is used to generate a *sequence* of numbers whose properties approximate the properties of sequences of random numbers which are then used as needed to generate your content and determine the outcomes of random events.

So using your example, one would not be able to deduce where the Troll King's heart is by force-feeding a peasant some fairy fruit and watching the reaction because each fairy fruit, as well as the location of the heart would be determined by a different random number.

It's a little bit more work if you want the outcomes of events to be independent of order. For instance, if you want a system in which fairy fruit has only a single outcome for a seed regardless of when or how often it is consumed, but that probably justifies its own post.
> 0 votes

---
Tags: random
---


title: Object is not moving after collision

text:
# Question
Title: Object is not moving after collision
I have player and walls. When the player hits the wall, its not moving.

This is the code for moving:

```
void MoveTileBased()
{
    transform.position = Vector3.MoveTowards(
       transform.position,
       destination,
       Time.deltaTime * speed);

    if (Input.GetKeyDown(KeyCode.W))
    {
        nextPos = Vector3.forward;
    }

    if (Input.GetKeyDown(KeyCode.S))
    {
        nextPos = Vector3.back;
    }

    if (Input.GetKeyDown(KeyCode.A))
    {
        nextPos = Vector3.left;
    }

    if (Input.GetKeyDown(KeyCode.D))
    {
        nextPos = Vector3.right;
    }

    if(Vector3.Distance(destination, transform.position) < 0.01f)
    {
        destination = transform.position + nextPos;
    }
}

```

This is collision script:

```
private void OnCollisionEnter(Collision collision)
{
    player.speed = 0f;
}

```

Walls collider:

Player rigidbody and collider:

# Answer
When the player hits (enters the collider of) the wall, does the `speed == 0` and does the player stop moving?

If this is the case, then the problem is that you're setting the player `speed` to 0 if they're in the wall, but because their speed is now 0 there's no way for them to escape the wall.

### Solutions

There's many ways you could go about solving this, here are some options.

##### Unity Physics System

The simplest and probably most robust solution, unless you have very specific needs or need a lot of control, is just to use Unity's Physics system. You would add physics colliders to the walls and player (along with corresponding rigidbodies). In your code, you would replace all instances of `transform.position = target` with `myRigidBody.MovePosition(target)`.

```
Vector3 target = Vector3.MoveTowards(transform.position, destination, Time.deltaTime * speed);

//instead of this
//transform.position = target;

//use this
myPlayerRigidBody.MovePosition = target

```

`RigidBody.MovePosition(Vector3 v)` will automatically resolve collisions for you, so rigidbodies will never overlap. You could also just change the rigidbody's velocity, instead of using your own `speed` variable, but then you would have less control over the movement.

#### Custom

The other solution(s), is to perform your own intersection/resolution logic. This can be done in countless ways, with varying levels of robustness and complexity (eventually you could end up creating your own custom Physics system).

The minimum viable behavior I'd start with, would be preemptively check if a destination or target is within a wall (this could be achieved using `Physics.OverlapSphere`): if it is overlapping, don't move that frame and set your speed to 0; if there is **no** overlap, then move to the destination and keep whatever speed you have.

This is a huge topic though, and the complexity will vary with what type of movement (3D/2D) and colliders you want to support.
> 2 votes

# Answer
Here you go my dude.

```
public float speed;
[SerializeField]
private Vector3 nextPos;
[SerializeField]
private Vector3 destination;
[SerializeField]
private KeyCode lastKey;
[SerializeField]
private KeyCode preventKey = KeyCode.None;

private void Update()
{
    MoveTileBased();
}

void MoveTileBased()
{
    KeyCode[] keycodes = new KeyCode[] { KeyCode.W, KeyCode.A, KeyCode.S, KeyCode.D };

    if (Input.GetKeyDown(KeyCode.W))
        nextPos = Vector3.forward;
    if (Input.GetKeyDown(KeyCode.S))
        nextPos = Vector3.back;
    if (Input.GetKeyDown(KeyCode.A))
        nextPos = Vector3.left;
    if (Input.GetKeyDown(KeyCode.D))
        nextPos = Vector3.right;

    for (int i = 0; i < keycodes.Length; i++)
    {
        if (Input.GetKeyDown(keycodes[i]))
        {
            if (keycodes[i] != preventKey)
            {
                preventKey = KeyCode.None;

                Debug.Log("Pressed " + keycodes[i]);
                lastKey = keycodes[i];
                destination = transform.position + nextPos;
                StartCoroutine(MoveFromTo(this.transform, transform.position, destination, speed));
            }
        }
    }
}

IEnumerator MoveFromTo(Transform objectToMove, Vector3 a, Vector3 b, float speed)
{
    float step = (speed / (a - b).magnitude) * Time.fixedDeltaTime;
    float t = 0;
    while (t <= 1.0f)
    {
        t += step; // Goes from 0 to 1, incrementing by step each time
        objectToMove.position = Vector3.Lerp(a, b, t); // Move objectToMove closer to b
        yield return new WaitForFixedUpdate();         // Leave the routine and return here in the next frame
    }
    objectToMove.position = b;
}

private void OnCollisionEnter(Collision collision)
{
    Debug.Log("Collision!");
    preventKey = lastKey;
    StopAllCoroutines();
}

```
> 1 votes

# Answer
I don't really have enough information to help, but here are some tips to try

1. You might try reorganizing this method into a coroutine
2. If it is a collider issue, try replacing the box collider with an edge collider
3. You might try assigning physics materials
4. How are you calling the "MoveTileBased" Method? If it is not being called in the update function, it won't register.
5. Is the missing script on "Left Wall" Important at all?

Last thing... Why not just use rigidbodies and add force instead?
> 0 votes

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


# Question
Title: Editing Pixel Art, Copyright and "The Ship of Theseus" Problem
*(Please read the entire question before you crucify me :p)*

This is a question that has been on my mind for some time.

Basically, How much of a sprite needs to be changed in order for you to claim "ownership" of said sprite. I've made a few examples to illustrate my point.

*(I made these examples specifically to illustrate my point)*

I did not make this. I do not know who made this, I found it on Pinterest.

Focus on Far Left, Second to bottom. The Feather Hat Guy.

Would this be enough to call your own? (I would say probably not.)

...But what if your create unique animations?

What if I make it nearly unrecognizable...

...And give this unique animations.

What if the end product has nothing in common except the skin tone?

What if a design is so simplistic, it would actually be easier to draw it yourself? Would this even be considered editing at this point?

So, my two main questions are...

1. Can you Copyright an pixel art "Style"?
2. How much of a sprite needs to be changed in order for you to claim "ownership" of said sprite.

# Answer
From the memorandum opinion from the US court case of Dave Grossman Designs, Inc. v. Bortin:

> The law of copyright is clear that only specific expressions of an idea may be copyrighted, that other parties may copy that idea, but that other parties may not copy that specific expression of the idea or portions thereof. For example, Picasso may be entitled to a copyright on his portrait of three women painted in his Cubist motif. Any artist, however, may paint a picture of any subject in the Cubist motif, including a portrait of three women, and not violate Picasso's copyright so long as the second artist does not *substantially* copy Picasso's.

Based on that precedent, in the US you cannot copyright style per say and you can assert ownership of a specific expression (for instance a sprite) provided that it doesn't not substantially copy someone else's work. To my knowledge, there's no specific definition of what constitutes "substantially". US copyright caselaw is complex; such is the dominion of legal professionals.
> 2 votes

---
Tags: sprites, copyright, art, pixel-art
---


# Question
Title: How to update vertex buffer in DirectX 12
I would like to create cloth simulation. Which type of buffer should i use for vertices. I will need to update them on every frame. And how updates need to be done. I'm new to graphics programming, but still i'm mostly interesting in high level overview. If there is open-source project implementing it, reference to it would be of help.

For now i have only rigid body geometries. For this i create a resource with

```
    THROW_IF_FAILED(g_device->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize),
        D3D12_RESOURCE_STATE_COPY_DEST,
        nullptr,
        IID_PPV_ARGS(buffer_.GetAddressOf())));

```

Then i update it with initial data using another upload buffer to initialize first buffer. Lastly i transition first buffer into `D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER` state.

---

Well, i got some comments directing me toward DirectX11, but for my purposes i will better use DirectX12, and again, i'm pretty matured programmer and just need a highlevel overview of what need to be done.

For example,

> create default buffer with geometry, then create upload heap, and when needed create placed resource buffer to upload data into your default buffer.

But here a lot of questions arise. For now i use frame resources e.g. for transforms to update them on each frame and do not stall CPU. But if i will copy once a frame to the same default buffer will my it cause stalling? And should i use different queue for copying, and how then do resource state transitioning?

From what i understood for now, i need to implement this, but how to implement `CopyResource` functionality?

# Answer
This is an old question, so I'm not sure how relevant this answer will be now, but...

In DirectX 11 there are "4 kinds" of resources indicated by their `D3D11_USAGE` at creation time.

* `D3D11_USAGE_IMMUTABLE` indicates that the texture/VB/IB was to be immediately filled with data passed as `initData` and then would never change again.

> This was meant as an optimization, but it was often hard to use in practice. Many apps created a set of textures for streaming-style experiences and reused them, so this wasn't an option. Others had to use auto-gen mips which can't use this flag, etc.

* `D3D11_USAGE_DEFAULT` indicates that the resource should reside in Video RAM and was only accessible by the GPU. On many hardware designs, render targets and depth/stencil buffers must be this usage type, and is usually the 'optimal' choice for resources that will be loaded once or occasionally, but used almost every render frame.
* `D3D11_USAGE_STAGING` indicates the resource is in standard system memory. The GPU can not access this memory directly although the driver may use a DMA engine to read or write this data to GPU-accessible memory. This is normally used to create resources that are copied by Direct3D to the "default" video memory or captured from such memory.
* `D3D11_USAGE_DYNAMIC` indicates that the resource should reside somewhere where both the CPU and the GPU can access it. This resource style is designed for updating 'per-frame' VBs/IBs/ or textures generated by the CPU, but is generally not as fast to access as *default* memory by the GPU.

> Of course all this is abstracted from the real hardware and you can have many different kinds of architectures with different trade-offs. For example, the Xbox consoles are 'Unified Memory Architectures' meaning that the GPU and CPU can access all the same memory, so "DEFAULT", "STAGING", and "DYNAMIC" were all the same thing at least from a high-level.

So with *all that* out of the way, DirectX 12 expects you to create resources in the "DEFAULT" pool for the same kinds of cases that you'd use `D3D11_USAGE_DEFAULT`. The DirectX 12 Runtime doesn't do 'magic behind your back', so there's no implicit uploading system. You have to create a resource in a `UPLOAD` heap which is accessible by the CPU and copy data into that resource.

From there you can render directly from the `UPLOAD` heap, which is essentially the same as `D3D11_USAGE_DYNAMIC`. More often, you set up a copy from the "upload" heap copy a "default" pool resource.

In DirectX 12 you have to manage all the resource state and synchronization as well--think "lockfree" programming. This means for correctness, you need to inject resource barriers into the command-list that indicate state transitions.

Putting it all together for a **USAGE\_DEFAULT** style resource:

1. Create a resource in the DEFAULT heap type
2. Create a resource of the same layout in the UPLOAD heap. You assign it a `D3D12_RESOURCE_STATE_COPY_SOURCE` initial resource state.
3. Copy data with the CPU into the UPLOAD resource.
4. Submit a CopyResource to a command-list to move data from the UPLOAD resource to the DEFAULT resource.
5. Then add a resource barrier to the command-list which transitions the resource from "COPY\_SOURCE" to something you can use to render which depends on the resource usage: `D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER`, `D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE`, or `D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE`.
6. At some point you need to inject a fence into the command-list because you the programmer have to keep the UPLOAD resource alive until the fence is crossed or you will crash the app/GPU.
7. Then you can submit work to use that resource. Because of the resource barrier, you know at that point the resource will be completely filled out and in the proper state for the GPU to use.
8. Keep in mind *nothing* has happened yet until you execute the command-list.

For a **USAGE\_DYNAMIC** style resource, you can just stop with the data in the UPLOAD heap and transition it to the right resource state to render.

See Microsoft Docs

> This process is what the `ResourceUploadBatch` class in DirectX Tool Kit for DX12 helps manage. Constant Buffers use a similar model, but are typically fenced 'per-frame' and kept alive for 2 or 3 frames depending on the swapchain. That's what the `GraphicsMemory` class manages.

> The *DirectX Tool Kit* leverages the 'simple' nature of the "upload' heap for `GeometricPrimitive`, `Model`, etc. where you can just create the VB/IB/etc. on the fly and render directly from there. For better performance, you use the `ResourceUploadBatch` with a **LoadStaticBuffers** method which moves the data from "upload" to "default".

> For cases where you just want to get some data from system memory into GPU memory like your situation, the BufferHelpers functions submit the right kind of object using `ResourceUploadBatch` and `GraphicsMemory` in the tool kit.
> 4 votes

---
Tags: vertex-buffer, directx12
---


title: How do ticks work on game servers?

text:
# Question
Title: How do ticks work on game servers?
So I'm currently learning more about game networking and how clients and servers work, and something that I have a hard time wrapping my head around is how game servers works in terms of ticks.

Why do servers use ticks and how do they use them? Does the server start and then accept packets into a queue and then dequeues x amount every tick or how does that work? What if it can't process that x amount within a certain tick, does it go on to the next tick?

# Answer
> 2 votes
First of all, software architecture is no exact science. Different gameservers use different architectures. So this answer represents how *I* implement tick-based gameservers.

---

Yes, message queues are very common in client-server game programming. Usually all the messages from clients get put into a queue which is then read while processing a game tick.

Game ticks are usually processed by some form of timer system. For example, when a server runs at 50 ticks per second, then there is a timer which will process a tick every 20ms.

When a server processes a tick, then it usually empties its message queue completely. Processing it just partially usually makes little sense and might overcomplicate a lot of things. The messages processing is also very rarely the bottleneck. The bottleneck is simulating the game. Update the positions of characters (when there is no message, then player-characters usually keep moving in the same direction they did in the past tick), update the trajectories of projectiles, check for collisions, do path-finding for AI agents and so on. All of that needs to happen regardless of how much the players are doing right now. So it's largely independent of how much messages there were to process this tick.

Yes, when there is a lot going on in the game, then it can occasionally happen that the server takes so long to calculate a tick that it should have already started processing the next one. In that case you process the next tick immediately after completing the current one, hoping it will take less time and let the server catch up. But when the load persists, then the server might start to lag behind more and more. In that case you usually start to skip ticks in order to catch up.

---
Tags: networking, client-server, server
---


title: How to get area of grids?

text:
# Question
Title: How to get area of grids?
Firstly,I don't know if my question title is true but I couldn't find better title, sorry If I titled wrong.

I'm trying to grid base game. The player is moving grid to grid and never stop between grids even if ıt takes command to move another direction between grids.

So, I want to get area of grids where the character walks on the edge of area.

To clarify myself

Player starts to move and tries to reach edge following brown lines. When player reaches any edge, the all tiles should be colored.

# Answer
First let me rephrase your question. You are basically asking "**how to know my current tile?**".

To do that you write Position2Tile function which takes objects position and returns tile coordinates which object is in right now. Then if your object is moving, - in Update() function you just call this function and get tile coordinates from it.

It should look something like this:

```
int[] Position2Tile(Vector3 pos)
{
    int[] tile;

    // write your logic here

    Debug.Log("yeay! current tile is: " + tile[0] + ", " + tile[1]);
    return tile;
}

```

Regarding the logic itself. Let's say grid starts at position 0,0. And let's say that tile size is 1 meter. So if for example players position is (2.73 , 4.86), not too hard to notice that tile coordinates would be \[3 , 5\]. In such case logic would be like this:

```
  int xcord = Mathf.CeilToInt(pos.x);
  int ycord = Mathf.CeilToInt(pos.y);
  tile = new int[] { xcord, ycord };

```

In case tile size is not 1 meter but some other size, (for example 2.58 meters), divide your position by tile size:

```
pos.x/tileSize  // do this before converting to integer

```

Once you know current tile you know where you are all times. For example if tile\[0\] == 1 then you have reached the left edge.

So in your specific case if you know starting tile (and finishing tile) all tiles to the left, and below will need to be colored.
> 1 votes

---
Tags: unity, tilemap
---


# Question
Title: Multiple Precompiled Assemblies of Same Name
I'm getting an error after I imported a package to Unity,

Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included or the current platform. Only one assembly with the same name is allowed per platform. (Assets/Plugins/Newtonsoft Json/Runtime/AOT/Newtonsoft.Json.dll)

I looked around for a solution, and people were saying it had to do with Unity Ads(which I don't have) and another solution I found was to delete one of the Newtonsoft.Json.dll files, which, if I delete either or the app fails to build. I don't even know how to get rid of the package that's caused it, nor do I really want to, the issue started after I imported the package from this website, https://readyplayer.me/

Does anyone know of any way to fix this? I really wish Unity would detect this errors on import, man, especially considering it was a Unity package. Or automatically ignore one of the assemblies lol

For reference, the other error is as follows, Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included or the current platform. Only one assembly with the same name is allowed per platform. (D:/VR-Chat/Library/PackageCache/com.unity.nuget.newtonsoft-json@2.0.0/Runtime/Newtonsoft.Json.dll) I'm not even sure why this is being imported with the package, but this one seems to be referenced in the manifest of the ReadyPlayerMe package.

I tried deleting one or the other, but it just creates issues with the relevant packages. When I deleted one it says my Java NDK is missing?

I thought this would fix the issue:

But it turns out that unticking the box for the NewtonSoft asset just creates more issues: it says it can't find the NewtonSoft, and fails to build seemingly due to some NDK related error with the Webview asset of the package.

Also, I tested this on a completely empty project, the same issue occurs. There are two NewtonSoft Json files included, deleting either one of them does not get rid of the error, and deleting both allows it to successfully build on my empty project, but not on my main project.

# Answer
> 1 votes
I solved this by deleting the two Newtonsoft files(there's one inside the folder as well)

The reason I hadn't tried this before was because I deleted one or the other and it didn't fix any of the errors(there was still 2 errors). I didn't think deleting both of them would fix it, but it did.

---
Tags: unity, dll
---


title: How do I find voxels along a ray?

text:
# Question
Title: How do I find voxels along a ray?
I am making a voxel engine, and I want to make it possible to create and destroy voxels with the mouse. I use C++ and OpenGL, so C++ examples would be best.

So far, I have the camera position and appropriate angle as `Vector3` values. I need to find voxels along a ray extending from the camera position along the angle. I tried to solve it myself, and essentially came up with a slow, 3D version of Bresenham's line. This would be okay, but it skips diagonals, meaning if I point toward the edge of a voxel, it usually misses.

The "bad" line skips over where the line crosses diagonals, while the good line hits them. I currently have the bad, but I want the good:

I have tried reading around this, but most of what I find relates to sparse octree rendering.

# Answer
I actually found anothe stackexchange answer that answers this. Cast ray to select block in voxel game

It turns out I was searching for the wrong stuff, and I was looking for C++ specific code. The link is in JS, but I ported it to C++. Here is my whole voxel function. In the answer, he also has some extra functions (mod, signum, and intbound), but those are easy enough to implement yourself.

```
void World::mouseVoxel(GLFWwindow* window, int button, int action, int mods) {

if (action == GLFW_PRESS && (button == GLFW_MOUSE_BUTTON_1 || button == GLFW_MOUSE_BUTTON_2)) { //make voxel
    //calculate angle vector of the mouse
    double cursorX, cursorY;
    glfwGetCursorPos(window, &cursorX, &cursorY);
    //std::cout << cursorX << ", " << cursorY << std::endl;
    float x = (2.0f * cursorX) / 1280.0f - 1.0f;
    float y = 1.0f - (2.0f * cursorY) / 720.0f;
    vec4 rayClip = vec4(x, y, -1.0, 1.0);
    vec4 rayEye = inverse(projectionMatrix) * rayClip;
    rayEye = vec4 (rayEye.v[0], rayEye.v[1], -1.0f, 0.0f);
    vec3 rayWOR = vec4(inverse(camera->getMatrix()) * rayEye);
    rayWOR = normalise(rayWOR);

    float range = 64.0f; //max range to check (in voxels)
    vec3 camPos = camera->getPosition() * (1 / voxelSize);
    float xPos = floor(camPos.v[0]);
    float yPos = floor(camPos.v[1]);
    float zPos = floor(camPos.v[2]);
    int stepX = signum(rayWOR.v[0]);
    int stepY = signum(rayWOR.v[1]);
    int stepZ = signum(rayWOR.v[2]);
    vec3 tMax(intbound(camPos.v[0], rayWOR.v[0]), intbound(camPos.v[1], rayWOR.v[1]), intbound(camPos.v[2], rayWOR.v[2]));
    vec3 tDelta((float)stepX / rayWOR.v[0], (float)stepY / rayWOR.v[1], (float)stepZ / rayWOR.v[2]);
    float faceX;
    float faceY;
    float faceZ;

    print(camPos);

    do {
        if (isVoxelSolid(xPos,yPos,zPos)) {
            std::cout << "boom";
            if (button == GLFW_MOUSE_BUTTON_2) setVoxelType(xPos,yPos,zPos, 0, true);
            else setVoxelType(xPos + faceX, yPos + faceY, zPos + faceZ, 1, true);
            break;
        }
        if (tMax.v[0] < tMax.v[1]) {
            if (tMax.v[0] < tMax.v[2]) {
                if (tMax.v[0] > range) break;

                xPos += stepX;
                tMax.v[0] += tDelta.v[0];

                faceX = -stepX;
                faceY = 0;
                faceZ = 0;
            } else {
                if (tMax.v[2] > range) break;
                zPos += stepZ;
                tMax.v[2] += tDelta.v[2];
                faceX = 0;
                faceY = 0;
                faceZ = -stepZ;
            }
        } else {
            if (tMax.v[1] < tMax.v[2]) {
                if (tMax.v[1] > range) break;
                yPos += stepY;
                tMax.v[1] += tDelta.v[1];
                faceX = 0;
                faceY = -stepY;
                faceZ = 0;
            } else {
                if (tMax.v[2] > range) break;
                zPos += stepZ;
                tMax.v[2] += tDelta.v[2];
                faceX = 0;
                faceY = 0;
                faceZ = -stepZ;
            }
        }
    } while (true);
}
}

```

I'm not sure how efficient this is. In the future when I run it every frame to show an indicator, I'm not sure how it will hold up.
> 4 votes

# Answer
A good source for voxel based questions is PolyVox. For this particular case, just check out this: link. There is also a lot of documentation included there.
> 1 votes

# Answer
For the sake of simplicity lets stick with two dimensions: `(x,y)`

**The problem:**

We have some start position `xs :: vec2(float)`.

We have a (normalized) direction vector `dv :: vec2(float)`.

Given the above, we want to march in the direction of `dv` from `xs`, iterating through *every* voxel cell we cross.

**The naïve solution**

Advance the position along by some small epsilon:

```
xs += dv * 0.1f

```

At each step, I would `floor` my `xs` vector to get a `vec2(int)` \- which represents the voxel cell I was currently in.

This solution works well but fails when casting near the corners of voxels. If your epsilon is too large, you could end up entirely skipping a voxel that your line *barely* intersects. This can be remedied by decreasing the size of epsilon, but this comes with the cost of requiring us to perform more iterations to march the same distance.

**The efficient solution**

At a high level, this solution is similar to above, but instead of marching a fixed epsilon - its dynamic: we work out the *maximum* distance we can move before we hit the next voxel cell and move that amount.

Define a voxel cursor `cur :: vec2(int)` \- which represents the voxel cell we are currently living in.

Initialize the cursor to the cell we begin in:

```
cur = floor(xs)

```

Now lets enumerate through all faces of a square:

```
TOP,
LEFT,
RIGHT,
BOTTOM

```

For each face, `face`, let us grab the normal:

```
normal = get_normal(face)

```

Now lets grab the component of `dv` that travels according to `normal`:

```
proj_dv = dot(dv, normal)

```

If `proj_dv <=0` then there is no motion in the direction of the normal and we can skip.

Next step is to work out how far we would have to travel in the normal's direction to hit a voxel boundary. This can be accomplished as follows:

```
// Will be 1 if the normal has a positive component and -1 if its negative
normal_sign = get_normal_sign(normal)

// Extract the component of the position that is parallel to the normal.
curr_pos = get_component(xs)

// Travelling in the direction of the normal, this is the next voxel
// cell we would hit (for this component)
next_pos = (normal_sign > 0 ? floor : ceil)(curr_pos + normal_sign)

delta_pos = abs(next_pos - curr_pos)

```

Finally, we must calculate how far along the `dv` vector we would need to travel to affect this change:

```
m = delta_pos / proj_dv

```

We can now loop through each face, returning the minimum `m` (and the face that corresponds to it).

We now have an `m` (`min_m`) such that `xs + dv * min_m` will take us to next nearest voxel boundary. Thus we update:

```
cursor += normal(min_face)
xs += dv * min_m

```

We can emit the cursor and continue...
> 0 votes

---
Tags: c++, voxels, raycasting
---


title: DDS Photo | Gimp Auto remap Mipmaps

text:
# Question
Title: DDS Photo | Gimp Auto remap Mipmaps
I'm trying to edit CoD4 guns to add a diff texture, however... no matter what program I use the DDS auto remaps the MIPS so instead of importing normally as texture should for mapping it actually imports as the gun would look like in the game

This is an example of how one should like as a character mapping but the same concept for a gun that is a template for Dead Pool just only example I could find but you see how it's not altogether, it's split up. I need something similar for the gun to edit it properly - it needs to be split up based on the geometry.

Any help with this would be really great. I've tried Photoshop, Gimp and even online services - all come out the same.

# Answer
> 1 votes
This is not a problem with your image editing software. You cannot change this result by importing this file any differently or using different software.

You've simply opened the wrong texture file.

Games will often contain many different textures relating to a weapon, including a diffuse/albedo texture, a normal map, various combinations of smoothness/metalness/occlusion/etc. maps... and an *icon* used to display the weapon in the HUD or menus.

You have opened the icon texture here, not a texture that is used when rendering the material on the 3D model.

A DDS file is just an image file - it does not contain any of the geometry information that would be needed to "fold up" the texture into the shape of the gun. So the only way to get a 2D side view of the full gun surrounded by transparency when you open a DDS file is if that's all the DDS file contained in the first place.

Search for a different texture file related to this weapon to get the source material texture you're looking for.

---
Tags: dds
---


# Question
Title: How to make different Rule Tiles interact with each other?
I am using Unity's RuleTiles to automatically change sprites of adjacent similar blocks.

For example, when a `Dirt` tile notices there are two `Dirt` tiles to the left and the right of it, it will change texture, like this:

I would also like to do this with walls. However, I plan to have many types of walls (`Wood`, `Stone`, `Metal`). How would I make different types of walls still affect each other?

Imagine that `Dirt` is now a `Wood` wall. If I place a `Stone` wall to the left, and a `Metal` wall to the right, I'd still like for it to apply a texture change.

Is it possible to make different types of rule tiles interact with each other?

# Answer
For my purposes, this example from Unity's Github worked flawlessly (Source):

```
public class ExampleSiblingRuleTile : RuleTile
{

    public enum SiblingGroup
    {
        Poles,
        Terrain,
    }
    public SiblingGroup siblingGroup;

    public override bool RuleMatch(int neighbor, TileBase other)
    {
        if (other is RuleOverrideTile)
            other = (other as RuleOverrideTile).m_InstanceTile;

        switch (neighbor)
        {
            case TilingRule.Neighbor.This:
                {
                    return other is ExampleSiblingRuleTile
                        && (other as ExampleSiblingRuleTile).siblingGroup == this.siblingGroup;
                }
            case TilingRule.Neighbor.NotThis:
                {
                    return !(other is ExampleSiblingRuleTile
                        && (other as ExampleSiblingRuleTile).siblingGroup == this.siblingGroup);
                }
        }

        return base.RuleMatch(neighbor, other);
    }
}

```

In my case, I'd have a single value in the `SiblingGroup` enum, `Wall`. Then I'd create multiple instances of the `ExampleSiblingRuleTile`, and assign the `Wall` value to them. Now they will all react to neighbor tiles and update their textures accordingly.
> 2 votes

---
Tags: unity, c#, tilemap, tiles
---


# Question
Title: Why can't the player walk properly on the moving platform?
I'm making a platformer with Unity. In one of the scenes, I have a moving platform that moves back and forth. The problem is that the player can't walk (or sometimes jump) properly on the platform and it seems like a force or collider makes it cling to the ground. This effect is visible in the gif. I think this is because of the fact that the player becomes a child of the object (otherwise it will fall behind while the platform is moving). Is there a way to fix this?

Moving Platform code:

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

public class MovingPlatform : MonoBehaviour
{
    public GameObject platform;
    public float moveSpeed;
    public Transform currentPoint;
    public Transform[] points;
    public int pointSelection;

    private void Start()
    {
        currentPoint = points[pointSelection];
    }

    private void Update()
    {
        platform.transform.position = Vector3.MoveTowards(platform.transform.position, currentPoint.position, Time.deltaTime * moveSpeed);

        if(platform.transform.position == currentPoint.position)
        {
            pointSelection++;

            if(pointSelection == points.Length)
            {
                pointSelection = 0;
            }

            currentPoint = points[pointSelection];
        }
    }
}

```

The second gif is for after using the new code. Here, the player is moving but even when it is in idle mode, it will fall behind.

***Note:** Moving platform script is on an empty game object (on default layer) and that object has three children: the platform that has sprite renderer and box collider and start point and end point which have only a transform component.*

---

Edit: Code after reading the answer by Philipp:

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

public class MovingPlatform : MonoBehaviour
{
    public GameObject platform;
    public float moveSpeed;
    public Transform currentPoint;
    public Transform[] points;
    public int pointSelection;

    private Vector2 velocity;
    private Rigidbody2D rb2D;

    void Awake()
    {
        rb2D = gameObject.AddComponent<Rigidbody2D>();
    }

    private void Start()
    {
        currentPoint = points[pointSelection];
        velocity = new Vector2(1.75f, 1.1f); // This
    }

    private void Update()
    {
        //platform.transform.position = Vector3.MoveTowards(platform.transform.position, currentPoint.position, Time.deltaTime * moveSpeed);

        if(platform.transform.position == currentPoint.position)
        {
            pointSelection++;

            if(pointSelection == points.Length)
            {
                pointSelection = 0;
            }

            currentPoint = points[pointSelection];
        }
    }

    void FixedUpdate()
    {
        rb2D.MovePosition(rb2D.position + velocity * Time.fixedDeltaTime);
    }
}

```

# Answer
One way to handle this is to parent your player to the moving platform while he is on it and remove the parent when he is off of it. This is a script I use on my moving platforms to prevent the weird behavior you are seeing.

```
private void OnTriggerEnter(Collider other)
{
    if (!other.CompareTag("Player")) return;

    other.transform.parent = transform;
}

private void OnTriggerExit(Collider other)
{
    if (!other.CompareTag("Player")) return;

    other.transform.parent = null;
}

```

This small script along with the code for the movement of the platform is included on the MovingPlatform's script.
> 1 votes

# Answer
When you want to have a moving collider in your game which interacts with rigidbodies in the way you would expect it to, then that collider needs a Rigidbody too. When you want to take complete control of its movement, like you would do with a platform moving along a fixed path, then mark that rigidbody as "Kinematic". That way its movement is unaffected by gravity or collisions.

When you control an object with a rigidbody using a script, then you should avoid moving it through the transform. Move it through the Rigidbody/Rigidbody2D component, for example with MovePosition or velocity.
> 1 votes

---
Tags: unity, c#, collision-detection, moving-platforms
---


# Question
Title: Elegantly transition from 4-grid to 6-grid and back
I find in general map creation that I prefer hex grids for natural environments, but square grids for interior and urban/constructed environments.

Is there a smooth or elegant way to transition between these that doesn't require a scene break? Most importantly, is there an *intuitive* way?

As long as they don't differ too vastly, the ratio of sizes between the two cell types is largely irrelevant to me. I'd also happily use several rows of transitional tiles if their borders can be procedurally determined. I also have no inherent preference for up-point or side-point hexes...

I'd show some things I've already tried, but they are genuinely all varieties of the same eldritch mess...

# Answer
> 2 votes
> As long as they don't differ too vastly, the ratio of sizes between the two cell types is largely irrelevant to me. I'd also happily use several rows of transitional tiles if their borders can be procedurally determined. I also have no inherent preference for up-point or side-point hexes...

This paragraph made me think of another, more *universal* solution: **Voronoi diagram**. It could adapt to and transition between any kind of grids.

Here's example that joins together hexagonal grid with square grid and uneven terrain:

Please don't mind the terrain cells being too big, contrary to what's proposed in the answer. The tool to make the diagram wasn't very convenient.

The obvious downside is that Voronoi diagram would probably require (more of) manual setup. But most of it can be automated with proper tooling (and to stitch the grids, you'll need the tooling anyways, I presume):

* constraints may be set to keep cells' sizes reasonable
    + perhaps even automatically splitting cells that are too big
* mark "open-ended" (touching the level's bounds) cells impassable by default
* designate areas where the diagram should self-stabilize to particular type of grid with given orientation
    + pentagonal grid, anyone?
* a tool to flood-fill transition terrain
* custom shapes to define walls and other kinds of obstacles
* etc

# Answer
> 7 votes
This is most intuitive way that I can think of.

# Answer
> 1 votes
You can create a hexagonal pattern with square tiles by creating each logical tile from 2x2 technical tiles and then arranging them in a staggered pattern like this:

This might, however, require quite a lot of transition tiles. But if your engine allows tiles which are larger than the technical grid size, then you can design tiles like this:

The overlapping parts of each tile fit into the transparent part of the tiles below/above.

---
Tags: maps, grid, hexagonal-grid
---


title: How to clear Resources.Load cache?

text:
# Question
Title: How to clear Resources.Load cache?
I am loading my assets and tile information through YAML files.

While working on the game, I needed to quickly change some values and test them in-game, and I realized I could just re-load the YAML information without having to restart.

However, before my files are processed by my YAML parser, they are loaded by using `Resources.LoadAll`, like this:

```
    foreach (var buildingTileType in Resources.LoadAll(Settings.BUILDING_TILES_PATH, typeof(TextAsset)))
    {
        var buildingTile = Deserializer.Deserialize<BuildingTile.Initializer>(((TextAsset) buildingTileType).text);
        BuildingTileInstances.Add(buildingTile.Name, buildingTile.CreateInstance());
    }

```

When I want to reload my defs, I clear the `BuildingTileInstances` dictionary and call the def-loading method again. However, I noticed the values were remaining the same until I restarted the game.

I've read that Resources.Load actually caches your files for optimization, and in this case, I'd like to somehow clear that cache to allow for live reloading.

I've tried using `Resources.UnloadUnusedAssets()` and `Caching.ClearCache()`, but none of them worked. Is there any way to achieve this?

# Answer
Calling `AssetDatabase.Refresh()` before using `Resources.LoadAll` seems to have cleared the cache and everything works as intended.
> 1 votes

---
Tags: unity, c#, assets, loading, asset-management
---


# Question
Title: How can I avoid alienating players when switching genres mid-game?
So I recently saw an idea on r/gameideas. It was for a game which starts off as a horror game, with monsters hunting you with no way to defend yourself, while in the climax, you get an insanely strong weapon to hunt them.

It seemed like a neat idea at first, but now I think that there are major problems with it. Since it switches from Outlast to DOOM so unexpectedly, I think it may lead to alienating a large group of players as those who want to play a horror game, as well as those who want to play an action game, would both avoid playing it.

What are the possible solutions to this issue?

# Answer
> 4 votes
I disagree with the general sentiment in the comments that the only solution is to stick to one genre - you just have to know what you're doing.

The biggest problems with an abrupt, late-game genre switch are with execution and expectations. In terms of execution, making a good game is hard, and making two good games stitched back-to-back is harder. That's where games like Spore fall apart. And in terms of expectations, entirely changing the rules of the game can break the "contract" between the player and the designer that the player agrees on when starting the game. If you can confidently execute on both a horror game and a DOOM-like shooter, and make it clear to the player that the rules of the game are subject to change, you can absolutely get away with making a game like this.

"How to make a good horror game" and "how to make a good shooter game" are both massive questions, too big to address here. But we can look to other games that switch genres (for certain definitions of genre) for clues on how to manage the "expectations" half of the issue:

* The entire contracts of minigame-based games like Mario Party are built around genre switches - you know from the beginning that that's what you're getting into. Those games solve the execution problem by breaking each style of gameplay into manageable 1-3 minute chunks.
* In the horror space, the Dread X collections do something similar, but with larger and more linear sub-games. Like Mario Party, the different genres are unified by a grander logic - if you can couple the horror and shooter portions of your game using some deeper intricacies of your game design, the switch will feel much more natural.
* Undertale is a great example of a game that doesn't advertise its genre switches - instead, it's able to get away with them by constantly poking at and playing with the tropes of (J)RPGs. Like its spiritual predecessors, it makes that kind of postmodern rule-breaking part of the player contract.

Something that all three examples do well is maintain a sort of emotional logic through their genre switches - chaotic fun in Mario Party, mysterious horror in Dread X, subversive sentimentality in Undertale. In your case, that might be the (a)symmetry between the powerlessness of the horror segment and the power fantasy of the DOOM-shooter segment. That has to be handled with care to avoid tonal whiplash, but I'd argue it's the most interesting part of the game idea.

So, say you make a terrifying and tense horror game and end it with the euphoria of absolutely sticking it to the monster in a storm of guts and glory, and telegraph it well-enough that it feels earned. You still won't get people to play both parts of your game if they only enjoy shooting and hate horror, or vice versa. That's ok - not every game can be or should be for everyone. You're better off making a game that's a smash hit with your core audience than a game that everyone thinks is just OK at best, especially at indie scale where word of mouth can make or break you. (But you might be able to get away with *meh* if you have the marketing budget of a triple-A company.)

That said, the intersection of players in the genres you're working with may or may not be big enough for you to be able to hit your financial goals with the game. That's a calculation you'll have to make.

---
Tags: game-design
---


# Question
Title: Is it a good idea to give NPCs unnatural hair colors while keeping that of the PC a natural color?
I don't know if it's the right place to ask or not but:

I would like to color most NPCs’ hair colors orange, green, etc. Do you think this will damage the main characters and secondary characters? (I mean does it show them less important?) should I use colors like black and brown (usual colors)?

# Answer
The player-character is the most important character in the game, so it is a good idea to spend some effort into making them look unique. Every creative choice about the look of the PC should be deliberate and well-justified.

However, hair color is not the only way to do that. There are lots and lots of details you can add to a character to give them some unique touch.

I would argue that giving the player-character a realistic hair color while giving some NPCs fantastic hair colors might in fact not be the worst decision, because it will make it easier for the player to identify with the player-character. For example, did you notice that anime and manga, the art style which basically invented the idea that every color of the visible spectrum is a natural hair color, more often than not use natural haircolors for the protagonist and unnatural colors for supporting characters? This serves two effects:

1. It is easier for the audience to identify with the protagonist, because they are the most "normal-looking" person on the screen.
2. Ironically, it *helps* the protagonist stand out, because they are the only character who does *not* have an unnatural hair color.
> 2 votes

---
Tags: color, art, npc
---


# Question
Title: Pygame some methods aren't working properly (collidepoint and get_rect)
I'm making a game menu in Pygame, consider the following block of code:

```
pygame.init()
...
exit_button = pygame.image.load(r'/home/salem/Documents/MyGame/exit_b.png').convert_alpha()
cursor = pygame.image.load(r'/home/salem/Documents/MyGame/clicker.png').convert_alpha()
mouse = pygame.mouse.get_pos()
x, y = mouse
cursor_x = x + cursor.get_width() / 2
cursor_y = y + cursor.get_height() / 2

while 1:
...
menu.blit(exit_button, (10, 555))
menu.blit(cursor, (cursor_x, cursor_y))
if exit_button.get_rect(x=10, y=555).collidepoint(mouse):
    exit()
pygame.display.update()
...

```

I'm experiencing some problems with the `pygame.mouse` module and `get_rect` method. They're not working correctly.

If I get the mouse position on the exit\_button image while the script is running, nothing happens and it doesn't exit!

Furthermore, for some reason, the cursor's image is not being displayed, I can only see the system's cursor while moving the mouse though it's remarkably different from the cursor's image. (the system's cursor is black while the other one is white) At first, I thought they could be merged together, so to check that, I changed the cursor's coordinates but still the same result!

# Answer
> 1 votes
You are not ever updating the cursor position so the code will only check collisions at whatever the cursor position happens to be immediately after initialization.

If you want to check against the real position of the cursor, you need to call `pygame.mouse.get_pos()` again each iteration of the game loop, and of course then recalculate `cursor_x` and `cursor_y` using the new updated mouse position to make sure your cursor image is rendererd in the correct position.

---
Tags: collision-detection, pygame, mouse
---


# Question
Title: Sonic 3 Bonus Stage - Technique Discussion
This will be my first discussion on the gamedev stack exchange, so thanks for reading. My question pertains specifically to the special/bonus stages in Sonic 3 where the game gives you a convincing effect of running around a checkerboard sphere, collecting orbs as you go, jumping to try and avoid obstacles. Have you played it? Probably not the most enjoyable of the Sonic bonus stages, but fun nonetheless.

https://www.youtube.com/watch?v=\_QCmIbYm5Rg

So I was wondering how to go about reproducing this in a modern 3D environment like Unity. I came up with this (very high level):

1. Produce a tilemap (however one likes) to store the data about what is on the map
2. On init, layout this tilemap in the world along the x-z plane
3. Player moves through the world on this x-z plane. This simplifies movement a bit as opposed to having to plot the spherically around a sphere
4. UVs could be animated to give the impression of moving along the board
5. Curvature of the world could be simulated using a curved shader or the like.

Alternatively, the tilemap could be mapped to a sphere of R radius and then simply animated the UVs on the sphere. Though, this has its own problems such as the poles of the sphere. In this approach you could move the player or the world around the player.

Maybe I am overcomplicating this entire thing? ;)

Thoughts?

# Answer
> 0 votes
i think a simple handle on the matter would be to have the player(sonic) not moving on the space and create a big sphere that you can control the rotation. So think of it as an endless runner, where the environment is moving, not the player.

# Answer
> 0 votes
A couple of years late, but I was looking for the answer to this myself, so will share my progress.

Sonic is actually running along the lines of a 32x32 grid in which opposite edges are identified, i.e. a toroidal grid. The camera angle only ever shows a section of this grid, so you can render this section as if it is flat in the plane.

Task 1) Code the game with Sonic running on a flat grid, rather than drawing the squares using polygons I would recommend using a custom shader and drawing objects as sprites or meshes on top.

Once you have that you can change the rendering, there are two remaining tasks:

Task 2) Calculate the position of each object so they now lie on the sphere. You could probably just cast a ray in a fixed direction from each and take the intersection with a sphere, if there is no intersection then discard it.

Task 3) Fix the rendering of the sphere itself, with a custom shader this involves taking a point on the sphere and then casting in back to a fixed plane.

I would really like to know how they did this on the original Megadrive/Genesis!

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


# Question
Title: What's the difference between a "Gameplay Programmer" and a "Gameplay Engineer?"
I was reading some job descriptions from some AAA developers in the gaming industry, and I noticed there were jobs for "Gameplay Programmers" as well as "Gameplay Engineers."

Are those the same thing? Do they do the same thing?

# Answer
> 14 votes
Generally, the title "engineer" and "programmer" are interchangeable in the game development industry. If the titles have a distinction, it will usually be specific to the company in question.

Similarly, the actual day-to-day tasks performed by employees with one particular title (such as "gameplay programmer") will often vary significantly between studios.

# Answer
> 12 votes
Most job titles are arbitrary. This applies for all industries.

The meanings of those titles are probably different for each company, so your best bet is to read the *description* of each one of those jobs, instead of just the *title*.

# Answer
> 2 votes
My interpretation would be that a *gameplay programmer* is someone who works with code most of the day while an *engineer* **could** do that, but s/he could also work with gameplay mechanics, user experience and other things that are not as code oriented.

# Answer
> 1 votes
Engineers, from my understanding, work on the functionality of the engine itself. For example, if you are using the unreal engine and are an engineer, you can extend the functionality of the engine for use by other programmers.

**Relationship:**

**Galaga engineer** \- *creates ship class, including movement, laser, collision. Gets specs from designers on what functions are necessary*

**Galaga programmer** \- *programs controllers for which buttons move, shoot lasers, and what happens upon collision. Gets specs from designers on how to implement functions via parameters.*

But as others have rightly pointed out, duties of game programmers often include both types of coding.

# Answer
> -1 votes
A Software Engineer uses science, engineering principles and programming languages to create, design, maintain, develop and test software products and networks. Furthermore, the role of a Software Engineer and Software Developer can be differentiated further, more detail check link enter link description here

---
Tags: software-engineering, jobs
---


# Question
Title: If an AI is sure it is going to lose, what can it do to make the game fun for the player?
Context: I am contributing to a sequential turn based strategy game. I have an idea of how to improve it, but I need some input to help me do so. We currently have a really dumb AI that just follows a rough set of rules each turn. I'm considering upgrading it to a basic search based AI that is not guaranteed to win every time I play against it.

There are many reasons why an AI could be behind the curve. These include:

* wasn't able to grow its economy well due to bad luck with map generation, * its economy was disrupted early by an enemy raid while the defending army was out of reach
* the starter army was defeated early and resources had to be invested to replace it instead of economic upgrades or more importantly there being a big awesome deciding battle with all units involved and it lost.

A search-based AI will be able to know when it is obvious that it is growing slower than it should, can't recover and now cannot win due to runaway success. Such a runaway success is often boring to play, especially if it happens three times in a row.

Assume there is no meta game where multiple players can gang up on the strongest one. I am open to nudging the game rules in the AI's favor if this happens. However, rubber banding can give the player the impression that they are punished for playing well, as the AI drags out a game into an almost stalemate or even wins unfairly.

### The problem I'm trying to solve is not that the AI is losing but that the AI rolling over and dying is not fun or interesting.

It is even worse if the player is sufficiently good that he experiences this on every play.

In some theories of literature, after the conclusion seems forgone and the tension is falling a new small conflict that is relevant enough or something else that justifies further elaboration and excitement.

My idea is to have a library of endgame scenarios, a handful of which end up with player losing unless he plays really well; most of these would pose a small challenge that the player is entirely able to deal with and some are "I roll over, just kill me already, please".

**Are you aware of anyone trying something like this before?** If someone tried this in a strategy game or even outside of strategy games before, then I would like to learn from them.

**Can you spot some obvious problems with this idea?** I already considered the AI misjudging the impossibility of winning. However, I might be too enamored with my idea to spot different problems.

**How can I make sure that this still feels fair?** It is easy for the AI to get some extra resources, however if a player is losing, I am afraid that he would feel cheapened if he got some extra money and units.

**How do I help the player having fun or at-least variety when they are losing?** I really have no ideas for this.

# Answer
> 9 votes
One thing you could do is give the AI an "all or nothing" response to losing. If he thinks he's going to lose, he could do something crazy like, spend all his money on the lottery. Gather all his forces and attack your fortress. Invest all his money into research for a new weapon. Hire barbarians to attack you at the risk of getting attacked himself. The options are limitless. Basically these events would keep his defeat from being boring, while also offering a chance for him to win, be strengthened, or another enemy to rise in his place. The player experience would have several options. The player would think, "He is definitely going to lose." Then he would think, "Is he seriously attacking my fortress with everything he has? Well, he's stupid". Or, "What!? He hired Barbarians! I didn't even know that was possible! I better work on a defense strategy." Whether it causes the AI to lose, or helps him, I think it would add flavor and keep it from being boring, especially if you add cool dialogue for the AI when he takes these approaches. Anyway, I hope this helps. =)

# Answer
> 5 votes
Use random events which are not actually that random.

When the player is losing the game, throw them a bone by giving them a "random" event which lets them catch up.

When there is nothing left which can stop the player from winning and the game becomes just a matter of playing down the clock, then give them a "random" event which creates a new challenge for them to solve. Not one which prevents them from winning, but one which prevents the road to victory from becoming a cakewalk from here on.

# Answer
> 4 votes
A potential problem with the endgame scenarios is that you change the already established win conditions in a way that could feel unfair to the player if they have a "certain" victory snatched away from them.

You could instead introduce extra endgame objectives. You still win regardless but completing them for "bonus points" gives you something to (optionally) focus on instead of running down the clock.

The war is practically won but the enemies has not yet given up:

* We want to capture Berlin before the Soviets
* Minimize civilian losses by not destroying city terrain tiles/not use bombing
* Also capture their rocket scientists

In a similar way you could add new objectives when losing. Trying for them could become a different experience to playing the normal game and leave the player with some sense of achievement even from a lost game.

* Don't go down without a fight, kill X amount of enemy units before you lose
* The final charge, capture an enemy city even if you can only hold it for a turn
* Escape in a starship to another system for a chance to rebuild and return another time (the next game)

If you can fit them within existing game mechanics (like unit movement to certain map coordinates or whatever you have) you could probably add enough of them that you can randomize which ones appear each game to add further variation. Having the same one always would be predictable and therefore less of a challenge.

# Answer
> 2 votes
One option is to implement a scorched earth policy. Burn towns, farmlands, manufacturing facilities, resource fields and so forth. Prevent the player from receiving even the smallest gains wherever the enemy has already retreated, thereby stretching their supply lines and making them more susceptible to guerilla warfare and ambushes.

The principle: It is easier to destroy than it is to create. A small, well-armed group can do a lot of damage, quickly, when the time is right.

# Answer
> 1 votes
You could make the AI simply decide to resign when it knows it's going to lose. That way the human player gets to skip the dull endgame and move on to the next challenge.

That's something a human player might well do in the same situation, and is common in games like Chess.

---
Tags: game-design, ai, balance, strategy, dynamic-difficulty
---


title: Top-Down Tank Physics with Pygame

text:
# Question
Title: Top-Down Tank Physics with Pygame
I am trying to make a top-down tank shooter game in Python and pygame, but I can't get the tank movement right. My objective is to make it move forward in the direction it is pointing in which would be the `angle` variable. I am expecting the answer to change the up and down code and that is fine, it was temporary anyway. Here is the code:

```
import pygame
from pygame.locals import QUIT
import math

# Initalizing everything
pygame.init()
pygame.display.set_caption('Top Down Tank Wars || Cloud Multiplayer')
screen = pygame.display.set_mode((600, 600))

# Loading, converting and coloring the space around the tank_body and
# tank_turret images white.
tank_body = pygame.image.load(
    '../Python Projects/Tank Game/blue tank body.png'
).convert()
tank_body.set_colorkey((0, 0, 0))

tank_turret = pygame.image.load(
    '../Python Projects/Tank Game/blue tank turret.png'
).convert()
tank_turret.set_colorkey((0, 0, 0))

class Tank(pygame.sprite.Sprite):
    def __init__(self, startingX, startingY, starting_angle, speed):
        super(Tank, self).__init__()
        self.x = startingX
        self.y = startingX
        self.angle = starting_angle
        self.speed = speed

    def up(self):
        self.y = self.y - self.speed
        return self.y

    def down(self):
        self.y = self.y + self.speed
        return self.y

    def left(self):
        self.angle = self.angle + self.speed
        return self.angle

    def right(self):
        self.angle = self.angle - self.speed
        return self.angle

running = True
x = 300
y = 300
angle = 0
speed = 0.05
tank = Tank(x, y, angle, speed)

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    # Set 'key_pressed' to the key that is being currently pressed
    keys_pressed = pygame.key.get_pressed()

    # Forward and backward manuevers
    if (keys_pressed[pygame.K_UP] or keys_pressed[pygame.K_w]):
        y = tank.up()

    if (keys_pressed[pygame.K_DOWN] or keys_pressed[pygame.K_s]):
        y = tank.down()

    # Turning tank body
    if (keys_pressed[pygame.K_LEFT] or keys_pressed[pygame.K_a]):
        angle = tank.left()

    if (keys_pressed[pygame.K_RIGHT] or keys_pressed[pygame.K_d]):
        angle = tank.right()

    angle = round(angle)
    screen.fill((255, 255, 255))

    # Rotating tank and rendering it
    tank_body_copy = pygame.transform.rotate(tank_body, angle)
    screen.blit(
        tank_body_copy,
        (300 - int(tank_body_copy.get_width() / 2),
         y - int(tank_body_copy.get_height() / 2))
    )

    # Rotating turret and rendering it
    tank_turret_copy = pygame.transform.rotate(tank_turret, angle)
    screen.blit(
        tank_turret_copy,
        (300 - int(tank_turret_copy.get_width() / 2),
         y - int(tank_turret_copy.get_height() / 2))
    )

    pygame.display.flip()

# Quit pygame when main loop has finished
pygame.quit()

```

Thanks in advance!!

# Answer
> 0 votes
change `pygame.display.flip()` to `pygame.display.update()` that should solve the problem I think cause I heard flip function is not working well

---
Tags: physics, python, pygame
---


# Question
Title: Having issues with 3rd-person Camera Raycasting / Local<->World Space / Clipping
I would like my camera to inherit the player in the hierarchy, and get closer when there is a wall or floor between the player and the camera.

Right now I am trying to raycast from the player to the desired position, and set the camera as close as possible to that desired position. But my camera is flicking all over the place.

Both of these scripts are attached to the player's camera, which inherits from the player.

.. RotateCamera adjusts x rotation of the camera with mouse movement, and sends the desired y-position to the FollowCamera script (y-position should shift to keep player in view). The way this is working is a little hacky, but I'd really like to first focus on the raycast situation before improving this code.

```
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    [SerializeField] private float rotSpeed, downAngleLimit;
    [Header("Up angle limit should be negative number")]
    [SerializeField] private float upAngleLimit;
    [SerializeField] private FollowCamera followCamera;

    private Vector3 oglocpos;
    private Transform tx;

    void Start()
    {
        tx = transform;
        oglocpos = tx.localPosition;
        upAngleLimit += 360;
    }

    void Update()
    {
        GetInput();
    }

    private void LateUpdate()
    {
        ClampAngle();
    }

    void GetInput()
    {
        float mouseY = Input.GetAxis("Mouse Y");
        Rotate(mouseY);
    }

    void Rotate(float degrees)
    {
        // Just takes care of up/down rotation
        tx.Rotate(Vector3.left * (degrees * rotSpeed * Time.deltaTime));
        ShiftCamera(tx.localEulerAngles.x);
    }

    void ShiftCamera(float degrees)
    {
        // Determines desired y-position by linear equation with current x-angle as variable
        var pos = oglocpos;

        if (degrees < upAngleLimit)
        {
            pos.y = .05f * degrees; // f(x) = .05x
        }
        else if (degrees > upAngleLimit)
        {
            pos.y = (.05f * degrees - 18); // f(x) = .05x - 18
        }

        // send this desired position (in local coordinates) to the raycasting script
        followCamera.desiredPosition = pos;

    }

    void ClampAngle()
    {
        Vector3 eul = Vector3.zero;

        var loceul = tx.localEulerAngles;
        eul.x = loceul.x;
        if (eul.x > upAngleLimit)
        {
            eul.x = Mathf.Clamp(eul.x, upAngleLimit, 360);
        }
        else if (eul.x < downAngleLimit)
        {
            eul.x = Mathf.Clamp(eul.x, 0, downAngleLimit);
        }

        tx.localEulerAngles = eul;
    }
}

```

.. FollowCamera does the raycasting and actual camera adjustment. I'm sure the issue is in this second script, but I don't know how else to approach it.

```
using UnityEngine;

public class FollowCamera : MonoBehaviour
{
    public Vector3 desiredPosition;
    [SerializeField] private Transform ptx; // player transform
    [SerializeField] private LayerMask layerMask;

    void Update()
    {
        // Send raycast from player to camera's desired position (in world space)
        if (Physics.Raycast(ptx.position, transform.TransformPoint(desiredPosition), out var hit, 6f, layerMask))
        {
            // turn that into a local coordinate and send the camera there
            var lochitpos = transform.InverseTransformPoint(hit.point);
            transform.localPosition = lochitpos;
        }
        else
        {
            transform.localPosition = desiredPosition;
        }
    }
}

```

# Answer
If you're reading this and need help, I've decided to just use Cinemachine.. the effort for a manual camera wasn't worth it.

I recommend you take this angular logic from Brackeys, but use a Rigidbody and set its velocity manually based on that given direction. That gives you non-jittery movement and less hassle.

This is also a good video for Cinemachine that helped me

My code looks like:

```
void MoveAndRotate()
{

    // Change target angle if moving
    if (moveState != MoveState.Still)
    {
        // Translate the input to an angle in degrees
        // Add camera rotation for camera based movement
        targetAngle = Mathf.Atan2(inpDir.x, inpDir.z)
            * Mathf.Rad2Deg + ctx.eulerAngles.y;
        movDir = (Quaternion.Euler(0, targetAngle, 0) * Vector3.forward);
    }
    else
    {
        movDir = Vector3.zero;
    }

    // Smooth out the angle for transform rotation
    realAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y,
        targetAngle, ref turnVelocity, turnSmoothTime);
    // Set the transforms Y-Rotation to the smooth angle
    transform.rotation = Quaternion.Euler(0, realAngle, 0);

    // Set Rigidbody velocity by camera direction
    movDir = (movDir.normalized * realSpeed);
    movDir.y = rb.velocity.y;
    rb.velocity = movDir;
}

```
> 0 votes

---
Tags: unity, c#, camera, raycasting
---


# Question
Title: How can I provide access to a Python command-line from in-game?
Is there a way to interact with the command line from in-game? I would like to have the user be able to jump on a console or even just interact with a button and have the game run a Python script in the background, ideally passing the output back to the user in-game.

# Answer
You can run your Python script using a spawn or fork-exec command and have the two programs running simultaneously, it will be invisible to the user. Or you can use a simpler exec command which will pause your main program while running the Python script. The exact name, implementation and functionality of both these options depend on the programming language and operating system.

But in general, if you need scripts in a game it is probably a better option to use an embedded script engine. Lua is a very popular option. Alternately both Unreal Engine and Unity come with a scripting engine, if they are already embedded in your application anyway you could probably use one of those.
> 1 votes

# Answer
You can have the game generate a text file with instructions from an in-game command line for the external python script to run.
> 0 votes

---
Tags: python, scripting
---


# Question
Title: How do I make 2D Camera Matrix with zoom?
I trying to understand how to make a 2D Camera Matrix. The problem now is when I zoom the world shifts horizontally. The Camera need to zoom on the current Position.

```
public class MyCamera
{
    public Vector2 Position;
    public float Zoom;
    public Matrix2D Transform = Matrix2D.identity;

    public void Update()
    {
        Vector2 screen = new Vector2(Screen.width, Screen.height);

        Transform = Matrix2D.Translate(-Position) *
            Matrix2D.Scale(new Vector2(Zoom, Zoom)) *
            Matrix2D.Translate(screen / 2);
    }
}

public class MyGame
{
    MyCamera Camera = new MyCamera();

    Sprite TestImage;
    float Zoom;
    float ScrollSpeed = 0.2f;

    public void Update()
    {
        Vector2 size = new Vector2(Screen.width, Screen.height);
        Zoom += Input.mouseScrollDelta.y * ScrollSpeed;

         Camera.Zoom = Zoom;
         Camera.Position = Input.mousePosition;
         Camera.Update();

     //Update my sprite
        TestImage.Position = Camera.Transform.MultiplyPoint(Vector2.zero);
        TestImage.Size = Camera.Transform.MultiplyVector(new Vector2(512, 512));
    }
}

```

# Answer
> 1 votes
**Unity**

In Unity, there is no such as 2D rendering. Transforms will always have three component Vectors, and Quaternions which support representations of three-dimensional rotations. If your camera is set to perspective, then you can simply move the camera along the z-axis to zoom in/out. If your camera is orthographic, then you can just change the `orthographicSize` of you your camera.

**In General**

The reality that 2D doesn't really exist in Unity from a rendering POV, is the same case for most low-level 2D APIs that I know of. If you're converting your code to JS and using webGL 3D, then you'll still be passing 4x4 matrices through the rendering pipeline (last column and row are for translations) even if your game logic is all in 2D. Then the same strategies that I outlined above, which depend on whether your camera is perspectived' or orthographic, will work. If you're using webGL 2D, then just use a normal scale matrix, and multiply it with your perspective, rotation and translation matrices to get your final camera matrix.

$$ \begin{pmatrix} scale & 0 \\ 0 & scale \end{pmatrix} $$

**Order of matrix multiplications**

I realize that one of the things you might be struggling with, is the order of matrix multiplications. It seems you understand that a scale-matrix is needed, but in order for a scale to have the visual effect of zooming the scaling has to be done from the camera view's **center**. This means that before you apply the scale-matrix/zoom, you have to first get all the sprites into camera-space (with the camera at (0,0), pointing directly forward).

Otherwise a scale matrix will have the visual effect of making sprites look like they're getting bigger/smaller from some arbitrary anchor point. Or it'll look like you're zooming **and** panning the camera in an unpredictable and uncontrollable manner.

These are fundamental graphics programming topics though, so you'll be able to find really great tutorials out there online.

---
Tags: camera, matrix
---


# Question
Title: an almost failed space invaders project in godot
thats the line Im getting the error on and those line mainly just go away. this is gdscript in godot

# Answer
GDscript uses a syntax similar to Python, where *indention* is important. You can learn more about the basics of GDScript here.

In your code, the parser expects that `func` be stuck completely on the left, with no whitespace before the keyword.

That would probably fix an issue; your still stuck with having 3 times the same function with the same signature, and I don't think the parser will like that (especially if one of them has no body). Looking at your code, you should probably keep only the first one and delete the other two.
> 2 votes

---
Tags: gdscript
---