# Question
Title: Hard edges with non power of 2 images in OpenGL
When down scaling 2D images in Java2D, it does a great job at preserving hard edges while downscaling to non power of 2s. However, in OpenGL, I have been unable to find a solution to this. I have tried using `GL_NEAREST` to get hard edges, but it also creates the wonky edges aswell. I cannot use `GL_LINEAR` in this case either, but still, the linear interpolation still looks wonky.

Example (Both rendering 30x30 hard image, rendering at 30x30 pixels).

**Please note** : I am aware that this occurs with images that aren't power of twos, like 30, but the main problem is, if I try to upscale or downscale an image that is power of two (say 16x16) to something that isn't a power of two (say 20x20), I still get this effect. This issue with scaling this occurs in Java2D, but it is by far less noticable.

My question is: What parameters will I need to use when rendering a non power of two image? So I can get a similar effect that I get in Java 2D.

I can post source code if needed.

**EDIT**

Original Image (30 x 30 png)

Turns out I wasn't scaling them at all! Both were being rendered at the original 30 x 30 pixels on both OpenGL and Java2D.

Sample Code: Java2D:

```
 g.drawImage(heart, 0, 0, 30, 30, null);

```

No rendering hints are being applied, just the bare minimum.

In OpenGL

Vertex Shader:

```
#version 400

in vec2 position;

out vec2 textureCoords;

uniform float width;
uniform float height;
uniform float xOffset;
uniform float yOffset;
uniform mat4 transformationMatrix;

void main(void)
{

    gl_Position = transformationMatrix * vec4(position.x, position.y, 0.0, 1.0);
    gl_Position.x += (xOffset) / (width / 2);
    gl_Position.y += (yOffset) / (height / 2);
    gl_Position.y = gl_Position.y;

    textureCoords = vec2(position.x / 1, position.y / 1);
}

```

Fragment Shader:

```
#version 400

in vec2 textureCoords;

out vec4 out_Color;

uniform sampler2D texture2d;
uniform float transparency;

void main()
{
    out_Color = texture2D(texture2d, vec2(textureCoords.x, textureCoords.y));
    if(textureCoords.y > 1 || textureCoords.y < 0)
    {
        discard;
    }
}

```

Rendering methods:

```
public void makeWonkyImage()
{
    render(0, 0, 30, 30, heart);
}
public void render(float x, float y, float width, float height, int textureID)
{
    PostProcess.imageRenderer.render(x, Gfx.HEIGHT - y, width / 1000, -height / 1000, textureID);
}
public void render(float x, float y, float width, float height, int textureID)
{
        shader.start();

        prepare(textureID);
        Vector2f position = new Vector2f((-Display.WIDTH / (width * 1000f))
                , (-Display.HEIGHT / (height * 1000f)));
        Matrix4f matrix = Maths.createTransformationMatrix(position,
                new Vector2f(width / Gfx.WIDTH * 1000f, height / Gfx.HEIGHT * 1000f));
        shader.loadTransformation(matrix);
        shader.loadScreenDimensions((float) Display.getWidth(), (float) Display.getHeight());
        shader.loadOffsets(x, y);
        GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, quad.getVertexCount());
        end();
        shader.stop();
}

public void prepare(int texture)
{
        GL30.glBindVertexArray(quad.getVaoID());
        GL20.glEnableVertexAttribArray(0);
        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

        GL11.glDisable(GL11.GL_DEPTH_TEST);
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
        GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
}

```

# Answer
TL;DR: There is no guarantee of pixel-perfectness in OpenGL, but try adding (0.375f, 0.375f) of a pixel to your render coordinates. This magic offset is "expected" by many drivers to render pixel-perfect.

---

There are multiple gotchas when rendering pixel-perfect images in OpenGL (and DirectX, and almost any other GPU APIs in general).

* Coordinates are given to the GPU in normalized device space (NDS) (-1 to 1) then converted to pixels before drawing. To render in pixel coordinates we use a model-view-projection matrix which cancels out the normalized device space. This process (pixels-\>NDS-\>pixels) can create rounding errors.
* Not all GPUs can render non-power-of-two (NPOT) textures the same way. Some can't at all in hardware and the texture will be scaled to a power-of-two by the driver. Even if the GPU can, rounding errors may occur. It is best to expand your texture to the next power of two and crop it using the texture coordinates.
* Screen rotation in some drivers can add a 1 pixel offset causing the geometry to not line up with the edge(s) of the screen.
* Anti-aliasing, multi-sampling, super-sampling, etc, may ruin your pixel-perfect texture sampling and rendering.
* Drivers sometimes add a magic fraction-of-a-pixel offset to the screen-space coordinates and/or a magic fraction-of-a-texel offset to the texture coordinates.

Regarding that last point, try adding (0.375f, 0.375f) of a pixel to all your drawing coordinates. It may be all that's needed on "most common" OpenGL implementations to get pixel-perfect rendering. Note that screen rotation may require negating the X,Y or both values of this offset.

If you search the web for "opengl" and "0.375" you will find many different explanations and opinions as to why this magic offset exists.
> 2 votes

---
Tags: opengl, 2d, textures, scale
---


title: .obj file reader for DirectX 11

text:
# Question
Title: .obj file reader for DirectX 11
It's been something like a week and i still can't sort this out. I need something that converts a .obj file into data readable and drawable by my framework. I have 1 main issues: indices. I think i'm getting the vertices right (i checked in the debugger and everything was fine) but when i draw my model something always goes wrong. I see the shape of the model but some triangles are not seen. I think this is a problem of clockwise/counterclockwise drawing. I exported a cube from blender to see how is done and i took pen and paper and draw it by hand following the indices the program created for me and i saw it uses a different indexing order that doesn't work in my program. For i cube i create 36 vertices using the indices described by the "f" word. Every vertex has texture coordinates and normal vectors. Than from the indices i take the vertices indices and i use those to draw the cube, but it doesn't work. I followed this tutorial to get into how i should script the converter ( http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading/ ) and i modified the code to make it work for DirectX drawing (which is similar to OpenGL i think) but it doesn't work at all.

```
void OBJLoader::loadOBJFromFile(char * fileName, std::vector<Vertex::Basic32> &output, std::vector<UINT> &vertexIndicesFinal)
{
    UINT numberOfVertices = 0, numberOfNormals = 0, numberOfUVs = 0, numberOfFaces=0;
    std::vector<Vertex::Basic32> outputDaMettere;
    std::vector< UINT> vertexIndices, uvIndices, normalIndices;
    std::vector< XMFLOAT3 > temp_vertices;
    std::vector< XMFLOAT2 > temp_uvs;
    std::vector< XMFLOAT3 > temp_normals;

    std::vector<XMFLOAT3> outVertices;
    std::vector<XMFLOAT3> outNormals;
    std::vector<XMFLOAT2> outUvs;

    FILE * file = fopen(fileName, "r");
    if (file == NULL) {
        MessageBox(0, L"NULL FILE", 0, 0);
    }
    while (1) {
        char lineHeader[128];
        int res = fscanf(file, "%s \n", lineHeader);
        if (res == EOF)
            break;

        if (strcmp(lineHeader, "v") == 0) {
            XMFLOAT3 vertex;
            int a = fscanf(file, "%f %f %f \n", &vertex.x, &vertex.y, &vertex.z);
            temp_vertices.push_back(vertex);
            numberOfVertices++;
        }
        else if (strcmp(lineHeader, "vt") == 0) {
            XMFLOAT2 uv;
            fscanf(file, "%f %f\n", &uv.x, &uv.y);
            temp_uvs.push_back(uv);
            numberOfUVs++;
        }
        else if (strcmp(lineHeader, "vn") == 0) {
            XMFLOAT3 normals;
            fscanf(file, "%f %f %f \n", &normals.x, &normals.y, &normals.z);
            temp_normals.push_back(normals);
            numberOfNormals++;
        }
        else if (strcmp(lineHeader, "f") == 0) {
            std::string vertex1, vertex2, vertex3;
            UINT vertexIndex[3], uvIndex[3], normalIndex[3];
            int matches = fscanf(file, "%i %i %i %i %i %i %i %i %i \n", &vertexIndex[0], &uvIndex[0], &normalIndex[0],
                &vertexIndex[1], &uvIndex[1], &normalIndex[1],
                &vertexIndex[2], &uvIndex[2], &normalIndex[2] );

            if (matches != 9) {
                MessageBox(0, L"File cant be read", 0, 0);
                break;
            }
                vertexIndices.push_back(vertexIndex[0]);
                vertexIndices.push_back(vertexIndex[1]);
                vertexIndices.push_back(vertexIndex[2]);
                uvIndices.push_back(uvIndex[0]);
                uvIndices.push_back(uvIndex[1]);
                uvIndices.push_back(uvIndex[2]);
                normalIndices.push_back(normalIndex[0]);
                normalIndices.push_back(normalIndex[1]);
                normalIndices.push_back(normalIndex[2]);
                numberOfFaces++;
        }
    }
    numberOfFaces *= 3;
    int cont = 0;
    for (int i = 0; i < numberOfFaces; i++) {

        UINT vertexIndex = vertexIndices[i];
        UINT normalIndex = normalIndices[i];
        UINT uvIndex = uvIndices[i];
        Vertex::Basic32 temp;
        temp.Pos = temp_vertices[vertexIndex - 1];
        temp.Normal = temp_normals[normalIndex - 1];
        temp.Tex = temp_uvs[uvIndex - 1];

        output.push_back(temp);

        cont++;
    }
for (int i = 0; i < numberOfFaces; i++) {
            vertexIndices[i]--;  //Starts from 1, i need it to start from 0
        }
    int toAdd = 0;
    for (int i = 0; i < numberOfFaces; i += 3) { //Needed to get the indices working for my draw function
        vertexIndices[i] += toAdd;
        vertexIndices[i + 1] += toAdd;
        vertexIndices[i + 2] += toAdd;
        toAdd += 2;
    }
    vertexIndicesFinal = vertexIndices;

}

```

I really need this to work, or some other code that does work and that is not impossible to understand. Thanks.

# Answer
You are indeed correct to use Draw. The reason is that the .obj file format is a little bit deceiving (and im going off my own recollection since I tried to erase the trauma).

You basically get a list of vertex points, normals and texture coords referenced by an index. Those indexes are based upon the list of vt, vn, v's you loaded in.

The indexes for a face you see are in a format such as f 1/4/6 which is a reference to vertex location/normal/texture. This ends up making your actual complete vertex point. Yes, they are indexes, but they aren't indicies for use in drawing, just in composing the complete vertex point.

So, when you compose your face, you can add an index for each point but it doesn't really do much, in fact as you probably have worked out its slower.

By rights, you could have an index buffer of 36 indices, and only 24 vertex points (each face has 4 points with texture uvs and normals). But at the moment, upon loading you are creating 36 individual vertex points.

If you wanted to use indicies, you would need to scan the complete 36 vertices and eliminate the 12 duplicates and create an indice list.

Yes, I know your pain on this one...
> 1 votes

# Answer
Solved by using

```
deviceContext -> Draw ()

```

Instead of

```
deviceContext -> DrawIndexed()

```

Indices were totally wrong, but by drawing triangle by triangle with that method i solved. I think is heavier than the other one but it works
> 0 votes

---
Tags: 3d, directx, directx11, c++
---


title: Should I talk about my game concept?

text:
# Question
Title: Should I talk about my game concept?
I have what I think is a great idea for a small android game. It might be crap, but for the sake of the discussion, let's assume it is potentially good. I'm currently learning game development as a self-taught. So if I succeed in creating that game, it won't be before a few years, until I get the technical knowledge to fully build it.

In the mean time, should I talk about that idea (in order to get help, advices, feedbacks) to confirmed developpers I might encounter? My game is not incredibly complex, so it could probably be developped by an experienced programmer in a few months. So if it's actually any good, talking about it means taking the risk of having my idea stolen and developped by someone else.

Is this risk real, or am I completely foolish?

More generally, are there some caveats that a newbie developper should be aware of when sharing ideas and concepts with other people?

# Answer
> 4 votes
There are two possibilities:

1. Your idea is not actually very innovative
2. Your idea is truly revolutionary

In addition, two main groups may or may not take it:

1. Big companies
2. Indie developers

Let us see how this play out:

1-1. A big company has nothing to take from your idea, they already have a backlog of ideas to do in the near future (or sequels to do, *har har*), and there is people pitching ideas to them regularly. For a big company, ideas are cheap. They do not need to go out taking ideas from individuals, much less, if they are not far from what is already in the industry.

1-2. Chances are the other developers have their own pet projects for which they have passion. Without a wow concept, the only indie developers that may take yours are those who lack ideas of their own... more on this later.

2-1. You have a crazy new concept. It is too much of a risk for a big company to try to copy it before knowing it will work. On the other hand, if you can make a proof of concept and get some publicity, you try to get people or companies to invest in you. Therefore, in this case you should not fear big companies. Just make sure any attention the game gets is associated with you.

2-2. If you got a great concept, in theory somebody may try to rush you to the market. In this case, you may want to be vague until you can say you are actually working on it.

---

On the work ethics of indie developers, indie developers are people. There have to be a few with little regard for others as in any group.

In general the risk only exist if they perceive your idea as better as theirs and their own talent as better than yours, because that's the situation in which they may win at rushing to the market.

You are going to mitigate this in two ways:

1. Once you start getting help on your game, pay attention on your language, you aren't a guy with a concept and no idea how to make it... you are working on your idea and you are looking for help.
2. Everything you do about the game must have your name. Set up a blog; make presence in social media, etc. If somebody else comes up with the same thing, we will all know who is stealing from who, and you will have evidence that you were working on this beforehand.

This will convince others that you are taking this project seriously, which will suggest that it will be harder to rush you to market. In addition, if they do, you have how hold your ground (on one hand because you reached people first, and on the other because they have any legal battle lost♪).

♪: They will not risk a legal battle; they have not reached success yet. Remember that those that may even consider this are not big, and have poor ideas. These are generalizations, of course.

I do not know the future, so I cannot really tell if people will try to steal your idea. In general, other indie developers will more likely want to work with you if they want to work on your concept than try to steal it. Besides, most ideas gets replicated once the pioneer showed that it was a good idea not before.

---

For abstract: own your game idea. As in, make it clear it is yours.

Are you wondering what would happen, if it fails? Pff, who cares, people will forget about it soon enough. It the game is bad, you would have reached only a small fraction of the people you will reach when eventually you make a good game (so most of those will not know your prior failure).

*You are still learning, c'mon! Who can blame you‽ -- me*

On that note, every indie developer that has reached fame (that I know of), did not get it on his or her first project.

*Release early. Release often. And listen to your customers. -- Eric S. Raymond*

*It takes twenty years to make an overnight success. -- Eddie Cantor*

# Answer
> 5 votes
Talk about your idea as often and with as many people as you can. The more feedback you can get, the better.

Ideas are far less valuable than you think. Everyone has great game ideas (at least they sound good in their heads...). And just like you, they would rather prefer to work on their own ideas, and not those of someone else. The only ideas people rip off are those which are *proven* to be commercially successful. Even the most experienced developers can't tell if an idea works just by listening to the concept. You have to actually play it to know if it's fun. That means they won't steal your ideas until they have seen your finished game and verified that your idea works. And even if they steal it before: So what? Similar games come to market all the time. That doesn't make them any worse.

In fact, **when someone beats you to market, that's good for you!** It gives you the opportunity to look at your game idea in reality and read what players and reviewers have to say about it. That will allow you to find out what works, what doesn't work and how to tweak it to perfection. When you release your game, it will do the idea even better.

# Answer
> 0 votes
It's best to talk to as many people as you can about the game you are developing, or planning on developing because there may be someone out there with a very similar idea, or someone with a fully-fledged game similar to yours. If someone owns a game very similar to yours you would want to know about it since, (I assume), you don't want to have a lawsuit on your hands.

---
Tags: legal, marketing
---


# Question
Title: Gamepad R2 button number for input manager
This should hopefully be an easy one but i'm stuck on this. I need to stop character movement and camera look if the R2 button on a gamepad is held down.

The gamepad i'm using is a third-party generic usb gamepad and can't find out anywhere which joystick button R2 (right shoulder button) is to enter in the input manager.

Below is the code i'm using for the character move which looks like it should work, its just getting the right button in the input manager - i've tried 0-15 but nothing.

Is there a way to find out the button number or is there a better method for doing what i need?

Thanks,

Paul..

The input was set up by duplicating a Fire button input and changing it's name to DoorTrigger (gravity, deadzone and sensitivity are as they were for the fire button, so 1000, 0.0001 and 1000 respectively) and have been testing the positive button with different button numbers.

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

public class CharacterController : MonoBehaviour {

    public float speed = 10.0f;
    public Read_move ReadMove;
    bool TriggerBt = Input.GetButtonDown ("DoorTrigger");

    // Use this for initialization
    void Start () {
        Cursor.lockState = CursorLockMode.Locked;
        GameObject Mover = GameObject.Find ("PlayerA");
        ReadMove = Mover.GetComponent<Read_move> ();
    }

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

        if (!TriggerBt) {
            ReadMove.mUP = Input.GetAxis ("Vertical");// * speed;
            ReadMove.mLEFT = Input.GetAxis ("Horizontal");// * speed;
            float translation = ReadMove.mUP * speed;
            float straffe = ReadMove.mLEFT * speed;

            translation *= Time.deltaTime;
            straffe *= Time.deltaTime;

            transform.Translate (straffe, 0, translation);
        }

        if (Input.GetKeyDown ("escape"))
            Cursor.lockState = CursorLockMode.None;
    }
}

```

# Answer
Unity treats the L2 and R2 buttons as an *axis* rather than a button.

From the answer on this post:

Create an input named "R2" set the gravity to 1.5, dead zone to 0.3, and the sensivity to 1.1, then use "Joystick Axis" for the type and have it use "10th Axis (Joystick)" for the Axis.

And that should work using `Input.GetButton("R2")`

Or you can set up the existing button you have to use those values.
> 1 votes

# Answer
thanks for the replies. Well, I sussed it. It was Joystick Button 7 and i simply used this if statement and the input manager set up as below:

```
if (!Input.GetButton ("DoorTrigger")) {

}

```

**Input Manager:** Name: DoorTrigger. Positive: joystick button 7. Gravity: 1.5 DeadZone: 0.3 Sensitivity: 1.1 Type: Key or Mouse Button.

Thanks,

Paul..
> 0 votes

---
Tags: unity, input, joystick, gamepad
---


# Question
Title: Diamond-Square algorithm output is random and noisy
I have implemented a rough interpretation of the Diamond-Square algorithm in C++ to create some semi-realistic fractal terrain, but the output just seems like a random y value at each point rather than smooth rocky shapes. I have altered parameters but feel like an outside look at the code might help me understand the issue. Here are examples of the output:

As a bitmap (top-down) with height variation lowered:

What it *should* look like (this is loaded from a file):

The code:

```
//Diamond-square algorithm
HeightMap::HeightMap(float maxY) {
//type = GL_POINTS;
//type = GL_LINES;
numVertices = RAW_WIDTH*RAW_HEIGHT; //256^2 squares => 257^2 vertices
numIndices = (RAW_WIDTH - 1)*(RAW_HEIGHT - 1) * 6; //each square is 2 triangles (6 indices)
vertices = new Vector3[numVertices];
textureCoords = new Vector2[numVertices];
indices = new GLuint[numIndices];
colours = new Vector4[numVertices];

int cornerA, cornerB, cornerC, cornerD; //Identify corners
cornerA = 0;
cornerB = RAW_WIDTH - 1;
cornerC = RAW_WIDTH*RAW_HEIGHT - RAW_WIDTH;
cornerD = RAW_WIDTH*RAW_HEIGHT - 1;

//Create vertices
for (int x = 0; x < RAW_WIDTH; ++x) {
    for (int z = 0; z < RAW_HEIGHT; ++z) {
        int offset = (x * RAW_WIDTH) + z;
        float y = 0; //Start with vertices set flat
        if (offset == cornerA ||
            offset == cornerB ||
            offset == cornerC ||
            offset == cornerD) {
            vertices[offset] = Vector3(x * HEIGHTMAP_X, maxY/2, z * HEIGHTMAP_Z); //Initialise corners to mid height
            std::cout << "Corners: " << offset << std::endl;
        }

        if (vertices[offset] == Vector3(0, 0, 0)) {
            vertices[offset] = Vector3(x * HEIGHTMAP_X, y * HEIGHTMAP_Y, z * HEIGHTMAP_Z);
        }
        //  textureCoords[offset] = Vector2(x * HEIGHTMAP_TEX_X, z * HEIGHTMAP_TEX_Z);
    }
}

Vector3 tl, tr, bl, br;
tl = vertices[cornerA];
tr = vertices[cornerB];
bl = vertices[cornerC];
br = vertices[cornerD];

float roughness = 1.0f;

Square square = Square(tl, tr, bl, br);
diamondSquare(vertices, numVertices, square, roughness);

//Colour
for (int x = 0; x < RAW_WIDTH; ++x) {
    for (int z = 0; z < RAW_HEIGHT; ++z) {
        int offset = (x*RAW_WIDTH) + z;
        float shade;
        if (vertices[offset].y > 0) {
            shade = 1 - 1.0f / (vertices[offset].y / maxY * 2);
        }
        else {
            shade = 0.1f;
        }
        colours[offset] = Vector4(shade, shade, shade, 1.0f);
        //Colour any vertex that hasn't been passed over red
        if (vertices[offset].y == maxY / 2 + 100) {
            colours[offset] = Vector4(1, 0, 0, 1);
        }
    }
}

//Create indices
numIndices = 0;
for (int x = 0; x < RAW_WIDTH - 1; ++x) {
    for (int z = 0; z < RAW_HEIGHT - 1; ++z) {
        int a = (x*(RAW_WIDTH)) + z;
        int b = ((x + 1)*(RAW_WIDTH)) + z;
        int c = ((x + 1)*(RAW_WIDTH)) + (z + 1);
        int d = (x*(RAW_WIDTH)) + (z + 1);

        indices[numIndices++] = c;
        indices[numIndices++] = b;
        indices[numIndices++] = a;
        indices[numIndices++] = a;
        indices[numIndices++] = d;
        indices[numIndices++] = c;

    }
}
BufferData();

```

}

```
void HeightMap::squareStep(Vector3 vertices[], int len, Vector3 tl, Vector3 tr, Vector3 bl, Vector3 br, float mid, float roughness) {
for (int i = 0; i < len; i++) {
    Vector3 top = (tl + tr) / 2;
    Vector3 bot = (bl + br) / 2;
    Vector3 left = (tl + bl) / 2;
    Vector3 right = (tr + br) / 2;
    top.y = 0;
    bot.y = 0;
    left.y = 0;
    right.y = 0;
    if (vertices[i] == top ||
        vertices[i] == bot ||
        vertices[i] == left ||
        vertices[i] == right) {
        float y = rand() % (int)(mid/5);
        y *= roughness;
        vertices[i] = Vector3(vertices[i].x, mid + y, vertices[i].z); //Set Diamond centre points to mid height + rand
        std::cout << "Square: " << vertices[i];
    }
}

```

}

```
float HeightMap::diamondStep(Vector3 vertices[], int len, Vector3 tl, Vector3 tr, Vector3 bl, Vector3 br, float roughness) {
float avg;
float y;
    for (int i = 0; i < len; i++) {
        Vector3 corners = (tl + tr + bl + br) / 4;
        avg = corners.y;
        y = rand() % (int)(avg/5);
        y *= roughness;
        corners.y = 0;
        if (vertices[i] == corners) {
            vertices[i] = Vector3(vertices[i].x, avg + y, vertices[i].z);         //Set Square centre point to avg height of corners + rand
            std::cout << "Diamond: " << vertices[i];
        }
    }
return avg + y;

```

}

```
void HeightMap::diamondSquare(Vector3 vertices[], int numVertices, Square s, float roughness) {
Vector3 tl = s.tl;
Vector3 tr = s.tr;
Vector3 bl = s.bl;
Vector3 br = s.br;
float mid = diamondStep(vertices, numVertices, tl, tr, bl, br, roughness);
squareStep(vertices, numVertices, tl, tr, bl, br, mid, roughness);
roughness *= 0.75f;
if (s.width > 2 * HEIGHTMAP_X) {
    std::vector<Square> squares = s.split();
    for (int i = 0; i < 4; i++) {
        diamondSquare(vertices, numVertices, squares[i], roughness);
    }
}

```

}

# Answer
I think usually you would include the height of the middle point in the square step (and do the diamond step first. which) would slightly affect how spiky it looks making it a more gradual slope. Did you try it with the random offset decreased?

It also seems that as long as the heights are positive there is no chance for the height offset to be negative so the higher the points, the higher the offset making it more spiky.

I made a fairly simple program with this algoritihm giving okay results and instead of basing the random offset off the average of the heights, I made it affected by the current gridwidth.
> 1 votes

# Answer
To Fix height randomness you can implement Perlin Noise.

Which generating height based on the adjecent heights and thus you got very smooth results.

Here is some Implementation on C++
> -3 votes

---
Tags: c++, procedural-generation, terrain, heightmap
---


# Question
Title: What is the most efficient way to render a textbox in C++ SDL2?
I'm a beginner in and I'm trying to make a window, with a (where you can move a sprite around) and a CLI (a textbox where the game can return some text and the user can insert commands).

Let's say the entire output textbox is 800x280 pixels and below is the input textbox which is 800x20 pixels. This means, each line of text should be 800x20 pixels, we can divide the entire output by 14 parts, or 14 textures. Maybe I can use a class\` but I'm still looking for more efficient ways.

I don't plan to make the textbox scrolling but when there is an input, all the boxes get incremented down (where the lowest box get moved up to the top).

---

This is my unfinished attempt (excuse my horrible code structure):

```
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>
#include <string>

// Screen dimensions, constants
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 900; // 600 for ground, 280 for output, 20 for input

SDL_Window* gWindow = NULL; // The window we'll be rendering to
SDL_Surface* gScreenSurface = NULL; // The surface contained by the window
SDL_Surface* gCurrentSurface = NULL; // Current displayed image
SDL_Surface* gTextSurface = NULL;

SDL_Renderer* gRenderer = NULL; // The renderer we'll be using
SDL_Texture* gTextOutput = NULL;
TTF_Font* gFont = NULL;
SDL_Color gTextColor = { 0, 0, 0, 0xFF };
SDL_Rect rcSprite, rcGround, rcTextInput;

SDL_Rect rcTOB0, rcTOB1, rcTOB2, rcTOB3, rcTOB4, rcTOB5, rcTOB6, rcTOB7,
         rcTOB8, rcTOB9, rcTOB10, rcTOB11, rcTOB12, rcTOB13;
SDL_Rect rcTextOutputBox[14] = { rcTOB0, rcTOB1, rcTOB2, rcTOB3, rcTOB4, rcTOB5,
                               rcTOB6, rcTOB7, rcTOB8, rcTOB9, rcTOB10,
                               rcTOB11, rcTOB12, rcTOB13 };
int iTOBInc = 0;

void init();
void loadMedia();
void quit();
void output(std::string text);

void output(std::string text)
{
  SDL_Surface* gTextSurface = TTF_RenderText_Solid(gFont, text.c_str(), gTextColor);
    if (gTextSurface != NULL)
    {
        gTextOutput = SDL_CreateTextureFromSurface(gRenderer, gTextSurface);
    if (gTextOutput == NULL)
    {
      throw "Unable to render texture! SDL ERROR: ";
    }
    SDL_RenderCopy(gRenderer, gTextOutput, NULL, &rcTextOutputBox[iTOBInc]);
    SDL_RenderCopyEx(gRenderer, gTextOutput, &rcTextOutputBox[iTOBInc], NULL, 0.0, NULL, SDL_FLIP_NONE);
    }
    else
    {
        throw "Unable to render text surface! SDL_ttf Error: ";
    }
}

void init()
{
  if(SDL_Init(SDL_INIT_VIDEO) > 0)
  {
    throw "SDL failed to initialise! ERROR: ";
  }
  else
  {
    gWindow = SDL_CreateWindow("Caventure",
                                SDL_WINDOWPOS_UNDEFINED,
                                SDL_WINDOWPOS_UNDEFINED,
                                SCREEN_WIDTH,
                                SCREEN_HEIGHT,
                                SDL_WINDOW_SHOWN);
    if(gWindow == NULL)
    {
      throw "Window failed to initialise! ERROR: ";
    }
    else
    {
      gScreenSurface = SDL_GetWindowSurface(gWindow);
    }

    gRenderer = SDL_CreateRenderer(gWindow,
                                    -1,
                                    SDL_RENDERER_ACCELERATED);
    if (gRenderer == NULL)
    {
      throw "Renderer could not be initialised! ERROR: ";
    }
    else
    {
      SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0x00);
      if (TTF_Init() == -1)
      {
        throw "TTF could not be initialised! ERROR: ";
      }
    }
  }
}

void loadMedia()
{
  // Ground rendering
  rcGround.x = 0;
  rcGround.y = 0;
  rcGround.w = 800;
  rcGround.h = 600;

  // Sprite rendering
  rcSprite.x = 400;
  rcSprite.y = 300;
  rcSprite.w = 4;
  rcSprite.h = 4;

  // TextOutput box rendering
  for (int i = 0; i < 14; i++)
  {
    rcTextOutputBox[i].x = 0;
    rcTextOutputBox[i].y = 20 * i + 600;
    rcTextOutputBox[i].w = 800;
    rcTextOutputBox[i].h = 20;
  }

  // TextInput box rendering
  rcTextInput.x = 0;
  rcTextInput.y = 880;
  rcTextInput.w = 800;
  rcTextInput.h = 20;

  gFont = TTF_OpenFont("resources/consolas.ttf", 14);
  if (gFont == NULL)
  {
    throw "Failed to load font! ERROR: ";
  }

  SDL_SetTextInputRect(&rcTextInput);
}

void quit()
{
  // Destroy window
    SDL_DestroyWindow(gWindow);
    SDL_DestroyRenderer(gRenderer);
  TTF_CloseFont(gFont);
    gWindow = NULL;
  gRenderer = NULL;
  gFont = NULL;

    // Quit SDL subsystems
  TTF_Quit();
    SDL_Quit();
}

int main()
{
  try
  {
    init();
    loadMedia();

    bool quit = false;
    bool renderText = false;
    SDL_Event event;
    std::string inputText = "";
    std::string inputCmd = "";
    SDL_StartTextInput();

    while(!quit)
    {
      while(SDL_PollEvent(&event) != 0)
      {
        if(event.type == SDL_QUIT)
        {
          quit = true;
        }
        else if(event.type == SDL_KEYDOWN)
        {
          switch(event.key.keysym.sym)
          {
            case SDLK_UP:
            rcSprite.y -= 5;
            break;

            case SDLK_DOWN:
            rcSprite.y += 5;
            break;

            case SDLK_LEFT:
            rcSprite.x -= 5;
            break;

            case SDLK_RIGHT:
            rcSprite.x += 5;
            break;
          }
        }
        else if (event.type == SDL_TEXTINPUT)
        {
          inputText += event.text.text;
        }
        else if (event.key.keysym.sym == SDLK_BACKSPACE && inputText.length() > 0)
        {
          inputText.pop_back();
        }
        else if (event.key.keysym.sym == SDLK_RETURN && inputText.size() != 0)
        {
          inputCmd = inputText.c_str();
          renderText = true;
          inputText = "";
        }
      }
      if (rcSprite.x < 0 ||
          rcSprite.y < 0 ||
          rcSprite.y > rcGround.h ||
          rcSprite.x > rcGround.w)
      {
        rcSprite.x = 400;
        rcSprite.y = 300;
      }

      SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0x00);
      SDL_RenderClear(gRenderer);

      SDL_RenderFillRect(gRenderer, &rcGround);
      SDL_BlitSurface(gCurrentSurface, NULL, gScreenSurface, &rcGround);

      SDL_RenderFillRect(gRenderer, &rcTextInput);
      SDL_BlitSurface(gCurrentSurface, NULL, gScreenSurface, &rcTextInput);

      SDL_SetRenderDrawColor(gRenderer, 0x40, 0x40, 0x40, 0x40);

      for (int i = 0; i < 14; i++)
      {
        SDL_RenderFillRect(gRenderer, &rcTextOutputBox[i]);
        SDL_BlitSurface(gCurrentSurface, NULL, gScreenSurface, &rcTextOutputBox[i]);
        if (i == iTOBInc &&
            renderText &&
            inputCmd != "")
        {
          output(inputCmd);
          iTOBInc++;
          renderText = false;
        }
        if (SDL_GetError() != NULL || TTF_GetError() != NULL)
        {
          throw "ERROR: ";
        }
      }

      SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

      SDL_RenderDrawLine(gRenderer, 0, 600, 800, 600);
      SDL_RenderDrawLine(gRenderer, 0, 880, 800, 880);

      SDL_RenderFillRect(gRenderer, &rcSprite);
      SDL_BlitSurface(gCurrentSurface, NULL, gScreenSurface, &rcSprite);

      SDL_RenderPresent(gRenderer);
    }
    SDL_StopTextInput();
  }
  catch (const std::string& msg)
    {
        printf("%s", msg.c_str());
        if (SDL_GetError() != NULL)
        {
            printf("%s", SDL_GetError());
        }
    else if (TTF_GetError() != NULL)
    {
      printf("%s", TTF_GetError());
    }
    else
    {
      printf("%s", "NULL");
    }
    quit();
        exit(EXIT_FAILURE);
    }
  quit();
  return 0;
}

```

Right now, this code doesn't work, it just returns a `SIGABRT` regarding a `const char*`.

# Answer
> 3 votes
So what you're looking for is `SDL_RenderSetClipRect`. This allows you to specificy where you want the text to be visible. The following example makes some assumptions but I'm sure you can figure out how to make it more generic.

So, let's say that you have your textbox at `X`, `Y` and it's `W` wide and `H` tall. You have rendered text into `TextTexture`, and `TextTexture` is `TextWidth` pixels wide and `TextHeight` tall.

So, start by figuring out where you want the text to render. The logic of this can be a little tricky and depends on how you want it to behave, but for this example, I'm just going to right-align the text as that's easiest.

```
SDL_Rect destination;
destination.x = X + W - TextWidth;
destination.y = Y;
destination.W = TextWidth;
destination.H = TextHeight;

```

So, the important thing here is the `x` coordinate. We calculate where the textbox ends, and then decrease that position with the text width, making it so that the last character of the text always ends at the edge of the text box. You can tweak this to behave how you want (like using the textbox' X-coordinate when the text is shorter than the textbox).

Now, all you have to do is to set the clip rect:

```
SDL_Rect clip;
clip.x = X;
clip.y = Y;
clip.w = W;
clip.h = H;
SDL_RenderSetClipRect(renderer, &clip);

```

This prevents the text from drawing outside of the text box.

Then you can just render the whole string of text, and then clear the cliprect.

```
SDL_RenderCopy(renderer, TextTexture, NULL, &destination);
SDL_RenderSetClipRect(renderer, NULL);

```

This way you don't have to worry about splitting the textbox into smaller rects or whatever.

Abstracting this all into a nice reusable class can surely help but is not required, and is left for the asker to do.

# Answer
> 0 votes
I think what you're referring to is line wrapping i.e. when a line of text gets too wide for the current display, it is automatically distributed across a number of lines (much like this text depending on the device you're reading this on).

You can use the `SDL_TTF` function `TTF_RenderText_Blended_Wrapped` to do this, passing your desired width at which the line will wrap (e.g. 800 pixels).

Also one thing that might make your coding easier, you can declare an `SDL_Rect` like this (note the curly braces):

```
SDL_Rect RectToDeclare = {int x, int y, int w, int h};

```

so

```
SDL_Rect rcGround = {0, 0, 800, 600};

```

---
Tags: c++, sdl2, text, text-based
---


title: Unity Physics - Attract(Rigidbody body)

text:
# Question
Title: Unity Physics - Attract(Rigidbody body)
I have this script `Gravity.cs`

```
public class Gravity : MonoBehaviour
    {

        public float planetGravity = -10f;

        public void Attract(Rigidbody body)
        {
            Vector2 normalForce = (body.position - transform.position).normalized;
            Vector2 localUp = body.transform.up;

            body.AddForce(normalForce * planetGravity);

            body.rotation = Quaternion.FromToRotation(localUp, normalForce) * body.rotation;
        }
    }

```

In this script I make a "gravity field", for a 2D sprite of a planet, I then have my player walk around it.
My problem, I want multiple of these planets, all with different gravity fields, When the player is out of the sphere of influence (a trigger sphere collider in unity) the player should be attracted to the closest planet with the highest gravity eg. if the player is exactly between two planets the player should fall to the planet with the highest gravity(or mass idk), how can I do this?

# Answer
instead of your current method you could use a gravity formula.

F=a\*m/d

a is a constant to control the gravity.
m is the mass/size of the planet.
d is the distance from player to planet.

if you apply this for every planet then it should be pretty realistic. maybe you can ignore a planet when the distance is greater than b\*m where b is some other constant to control the size
> 1 votes

# Answer
I have recently written about this issue. I will say it here again so that it may be of use:

Use the existing Physics2D. Don't reinvent the wheel. There's a component called PointEffector2D, you're trying to achieve its effects manually, which will end badly if it's not implemented correctly.

Here's the manual for effectors. What you want, is to have inverse squared force mode with a negative number as the force. You don't need a rigidbody on the planet but you do need a Collider2D that will be used by effector.
> 1 votes

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


# Question
Title: rotating a sprite around a non-fixed center
I'm trying to get this character to spin in a circle to aim at the cursor. It all works pretty well, but I can't get the image to rotate around its center. Only around its corner. I've been trying to find a solution be using some crazy trig stuff, but I'm not getting anywhere.

```
public void draw(Graphics g, double inter)
{
BufferedImage im;
Graphics2D g2d = (Graphics2D)g;
GImage gImage;

gImage = GImages.getImage(p.sprite);
im = gImage.imageFile;
AffineTransform at = new AffineTransform();
at.translate((p.xcord+((float)p.width/2))+(p.xspd*inter), (p.ycord+((float)p.height/2))+(p.yspd*inter));
at.rotate(p.angle+(Math.PI/2));
at.scale((double)gImage.xsize/im.getWidth(), (double)gImage.ysize/im.getHeight());
//at.translate(-(float)p.width/2, -(float)p.height/2);
g2d.drawImage(im, at, null);
g2d.setColor(Color.BLUE);
g2d.drawRect((int)p.xcord,(int)p.ycord,1,1);
//g.setColor(Color.BLACK);
//g.drawString(p.suh, (int)(p.xcord+(p.xspd*inter)), (int)(p.ycord+(p.yspd*inter)));
}

```

p is my sprite object, the cords make up the point of the corner of the image. The sprite moves around the screen, so I can't use a fixed point method as far as I know. If anyone has any suggestions to make this work.

# Answer
> 0 votes
The `rotate` method has an overload which takes in an anchor point which will be used as the origin of the rotation. I'm not 100% sure how you calculate the center of your sprite in the framework you are using, but the cal should look something like the following:

`at.rotate(your_angle, pos.x + image.width / 2.0f, pos.y + image.height / 2.0f);`

---
Tags: java, 2d
---


title: Pick Up Object disapppears

text:
# Question
Title: Pick Up Object disapppears
I'm trying to work with picking up and throwing objects. So far I've come up with a solution which does pick up the object but the same time disappears the object also. Please check to the functionality I've used.

```
public class pickupobject : MonoBehaviour {
     //GameObject mainCamera;
     bool carrying;
     GameObject carriedObject;
     Camera cam;
     public float distances;
     public float smooth;

     // Use this for initialization
     void Start()
     {
         cam = GameObject.Find("MainCamera").GetComponent<Camera>();
     }

     // Update is called once per frame
     void Update () {
         if(carrying)
         {
             carry(carriedObject);
         }
         else
         {
             pickup();
         }

     }

     private void pickup()
     {
         if(Input.GetKeyDown(KeyCode.E))
         {
             int x = Screen.width / 2;
             int y = Screen.height / 2;
             Ray ray = cam.ScreenPointToRay(new Vector3(x, y));
             RaycastHit hit;
             if(Physics.Raycast(ray, out hit))
             {
                 pickupable p = hit.collider.GetComponent<pickupable>();
                 if(p!=null)
                 {
                     carrying = true;
                     carriedObject = p.gameObject;
                 }
             }
         }
     }

     void carry(GameObject o)
     {
         o.GetComponent<Rigidbody>().isKinematic = true;
         o.transform.position = o.transform.position + cam.transform.position + cam.transform.forward * distances;
     }
 }

```

# Answer
The problem here is, you're calling the function **Carry** in Update method, which means the position of your pickup object will keep increasing per frame by a factor of *cam.transform.position + cam.transform.forward * distances* , which will instantaneously shoot it off-screen.

If you just want to hold it, use the **Carry** function like this :

```
void carry(GameObject o)
     {
         o.GetComponent<Rigidbody>().isKinematic = true;
         o.transform.position = cam.transform.position + offset;
     }

```
> 1 votes

---
Tags: unity
---


# Question
Title: How do I get an attribute of a function?
```
function randArray(arrayName) {
    arln = arrayName.length;
    arst = arrayName[Math.floor(Math.random() * arln)];
    return arst;

}

    create: function(){
        //starts physics engine
        game.physics.startSystem(Phaser.Physics.ARCADE);
        player = game.add.sprite(width/2, height/2, 'player');
        randSpawnItem = game.add.sprite(10, 10, randArray(randItem));
        randSpawnItem2 = game.add.sprite(50, 50, randArray(randItem));

```

So the randArray function works, and there is nothing wrong with the create. I'm using Phaser, and I'm trying to spawn items randomly (kind of like in Binding of Issac.) I forsee a problem in the future, when I'm detecting for collison, I need to know what item spawned to give the right kind of item to the player. How would I get that third attribute of `randSpawnItem` or `randSpawnItem2`, or is there another way to go at this completely? Sorry if that's a noobie question! Didn't know how to word it and didn't find it anywhere else. Thanks in advance for your time.

# Answer
You absolutely can. Just change what's returned and how you interact with it.

```
function randArray(arrayName) {
    arln = arrayName.length;
    arst = arrayName[Math.floor(Math.random() * arln)];
    return this;
}

var someArray = [1, 2, 3, 4, 5];

var random = randArray(someArray);
document.getElementById('placeholder').textContent = 'Length: ' + random.arln + ' Random item: ' + random.arst;
```

```
<div id="placeholder">
</div>
```

However, if you're going to continue using Phaser you might want to look at how to extend sprites in Phaser. Creating custom objects will allow you to do most of the plumbing in a single location, and help with maintainability.
> 1 votes

---
Tags: javascript, phaser
---


# Question
Title: Unity2D 100x100 tile map, best practice?
I'm trying to create a top-down map in Unity2D, this map will act as an ocean that a 1 tile sized boat will drive across. I want to be able to generate this map programmatically by going through the grid to create shallow areas, spawn things, etc.

I've been reading it's not good practice to create game objects for each tile as there's so many. You can use object pooling but that sounds harder to manage. I've read that using a mesh map is the best way but no one follows up with the best way to implement it. Any clues to push me in the right direction?

# Answer
UPDATE: As of Unity 2017.2, Unity now comes with an implementation of the mesh-grid-textured-quad approach. See the Unity documentation on Tilemap, and refer to the techdemo repository here for some examples of custom tiles.

Old Post------ There's a number of ways to do this sort of thing.

One is with Object Pooling. It's useful if you know you'll only show a small number of tiles to the player, but with a potentially huge map. A tutorial by the Unity team on how object poolers work can be found here.

The second way, if you plan to show potentially all of your tiles at a time, is to render them as individual quads on a single mesh. Basically you just swap out the texture mapped to the specific quad in the mesh. This can be more difficult to get started, but is very efficient for large maps that you always want visible (think civilization style). A tutorial on 2d maps built in this manner can be found here.
> 1 votes

---
Tags: unity, 2d, tilemap
---


# Question
Title: Changing the current state of an entity in the middle of an update step or wait for the end?
Let's say that I use a behaviour component that holds a function call to be called every update step assigned to an entity. Inside that function call I'm changing the active state for the entity to activated or deactivated, something like this:

```
void fun_update() {
 this_entity->set_active(true);
 if (this_entity->is_active()) { // This should return true or false?
  ....
 }
}

```

What would be more correct? To change the state for the current update iteration or wait for the end of the current update step to update the state of the entities?

I know that, unity3d for example, changes the current state, but when coding my own engine I find easier to update it at the end.

# Answer
> 1 votes
For me, `set_active()` having an immediate effect seems more usable because it does exactly what it says - the entity is active, and the next line of code can assume that.

I'm a little bit afraid of the word 'correct' up there, though, because it suggests that there is one "best way" to do things. If you aren't sure which is best for your code, then perhaps you can choose the one that seems most useful for right now. If that isn't clear, then try to write your entity and component code so both options are reasonable to implement. You can start to write some code that uses the system and see what feels best.

If you're very concerned about making the wrong choice and getting locked into an inconvenient structure, you could add both options - maybe `set_active()` and `set_active_delayed()` \- and use the one that best fits each case.

---
Tags: architecture, game-loop, component-based, entity-component
---


# Question
Title: Best way to get the maximum moveable Area
I was thinking about creating a polygonal area, for a given unit, in which it can move with a given range (radius) but with care for obstacles.

Here is a picture to visualize my idea:

My Ideas so far...

# The Pathfinding Way

* Create a Circle around 'unit' with given 'radius'
* Check for intersections with obstacles
* If an intersection is found, create a Path from 'unit' to intersectionPoint, but with pathLength == 'radius'
* connect all endPoints to get the maximum moveable area
* **But what if no intersection is found because the obstacle is fully into the circle?**

# The Ray Way

* Cast #Rays into all directions (e.g. 8 Rays for N, NE, E, SE, S, SW, W, NW) from 'unit'
* Check for intersections between each Ray and the obstacles
* If an intersectionPoint is found, create a Path from 'unit' to rayEndPoint with pathLength == 'radius'
* connect all endPoints to get the maximum moveable area
* **But this needs more than 8 rays to be accurate enough and this will take calculation time**

Have you got an idea on how to do this the best way? Thanks in advance - LuaNoob

*Edit #1:*

# The Flood Fill Way

Read something about flood filling algorithm. I guess this will be the best thing to try.

Example for maximum moveable range = 4

* 'X' = unit
* '#' = wall

# \# # # # #

# 3 3 3 3 # 4

# 2 2 2 # 3 4

# 1 1 1 2 3 4

# 1 X 1 # # 4

# 1 1 1 #

# \# # #

*Edit #2:*

# Current attempt: Custom Visibility Graph (not tried yet)

I now got i to work to create fast and accurate visible Areas. What im gonna to do next is:

* try to find the first point on the obstacle, that is in a line of sight by 'unit' and the not reachable endPoint of the Visibility-Ray-Cast
* create a new Visibility Graph from there but with 'newRadius' = 'radius' - distance(unit, firstPointOnObstacle)
* connect the Points
* repeat it for every not reachable Point with custom 'newradius'
* **One Problem left: Holes cant be created, but these are the rarest occuring situations, where i can fit with**

# Answer
Place the origin *z* at what you call the "unit." In that coordinate system, list all the vertices of your objects. Sort them angularly about *z*. Walk through the sorted list, and determine whether you are (a) just now entering an obstacle, (b) already inside an obstacle, or (b) just now leaving an obstacle. You can intersect a ray with the relevant object to decide. Then you have determined a star-shaped polygon centered on *z* representing the visible region.

---

Wikipedia image.

---
> 1 votes

---
Tags: path-finding, geometry, raycasting, line-of-sight
---


title: What is adaptive super-sampling?

text:
# Question
Title: What is adaptive super-sampling?
I'm trying to implement anti-aliasing into a raytracer with super-sampling.

**What exactly is adaptive super sampling?** I'm picturing it as just sampling all of the pixels which are on the edge of each object. Is that a correct explanation?

Also, **is adaptive super sampling a type of MSAA?** To my understanding, MSAA is essentially an anti-alising process that does not sample every pixel more than needed/is adaptive.

# Answer
It's a special form of anti-aliasing, where the level of AA is floating. So if you have a very complex scene, the program raises the factor of AA and if it's a flat scene without any spectacular things in it, it lowers it. The problem with all other forms of AA is, AA is always on. And that costs GPU time.
> 1 votes

# Answer
"Adaptive Supersampling" may refer to a lot of different techniques but generally it means a form of Anti-Aliasing where pixels are shaded1 a variable amount. It detects pixels that contain triangle edges and shades these pixels at a higher rate than not-edge pixels.

It is generally faster than pure Supersampling, as it avoids having to shade "nomal" non-edge pixels multiple times. For scenes with frequent depth discontinuities (thin bars, cables, antennas, grass) large parts of the image may get Supersampled which hurts performance.

Although Adaptive Supersampling is slower than Multisampling, it may provide better quality as it can mitigate specular edge artifacts2 to some degree.

Adaptive Supersampling is not generally implemented in major games because it requires rasterizing the scene with a multisampled rendertarget. Such rendertargets may become a substantial graphics memory bandwidth bottleneck as most major game engines use deferred shading3.

---

1 "Shading" refers to the process (implemented in a shader) of calculating the color of a pixel, how much light it "reflects" into the camera, taking lights, shadows, complex materials, etc into account and is therefore quite expensive and should be done as few times as possible per frame.
2 Specular Edge Artifacts: https://www.youtube.com/watch?v=VWRfLhOY2AA
3 Deferred Shading: https://learnopengl.com/#!Advanced-Lighting/Deferred-Shading
> 0 votes

---
Tags: antialiasing
---


# Question
Title: How to create an OpenGL texture using primitives?
I'm currently rendering a large proportion of the graphics of my game using custom OpenGL primitive functions (e.g. `DrawCircleFilled()`, `DrawPolygonFilled()`, etc) drawing procedurally generated objects (e.g. trees). Typically the core of these functions is a `glBegin` and `glEnd` loop, and use `GL_TRIANGLE_FAN`, `GL_LINE_LOOP`, `GL_LINES`, or `GL_POLYGON`. While this generally works, I'm seeing some performance issues if I have too many objects using these functions on screen at once.

For instance, I could render a brick wall by drawing 128 small brick-coloured rectangles with an outline. Alternatively I could render a single OpenGL texture with these bricks pre-drawn, which takes up more video memory but seems to be less processor intensive.

With this in mind, my question is: how do I take the output of the primitive functions and store them in an OpenGL texture at runtime? I'm aware of how to do with with an `SDL_Surface`, but I don't have access to the primitive drawing functions in SDL and SDL primitive drawing is very slow (one of the reasons why I switched to raw OpenGL in the first place).

Advice appreciated.

Thanks, Nathan

# Answer
> 2 votes
@Pikalek's suggestion in the comments is spot-on. You can render to a texture using a texture-backed FBO. Using retained mode will allow you to keep some of your geometry on the video card and not upload it on every frame (which is what happens when you call `glBegin()`/`glEnd()`).

There's another way that may also be useful. You can render some of your shapes using a shader. For example, a brick wall can be rendered as a single quad with an appropriate shader that divides it up into smaller rectangles that you shade as desired. It's too much to describe the process in a single answer here, but if you look up some introductions to glsl, that should get you going.

---
Tags: opengl, c++, textures, procedural-generation
---


# Question
Title: Moving ship towards mouse click not working well in the "boundary deadzone"?
```
#pragma once
#include "SFML\Graphics.hpp"
#include "ResourceIdentifier.h"
#include "ResourceManager.h"

class Entity {

public:

    Entity() : m_angle(0) {
    }

    float getX() const noexcept { return m_sprite.getPosition().x; }

    float getY() const noexcept { return m_sprite.getPosition().y; }

    float left() const noexcept { return getX() - m_sprite.getGlobalBounds().width / 2.0f; }

    float right() const noexcept { return getX() + m_sprite.getGlobalBounds().width / 2.0f; }

    float top() const noexcept { return getY() - m_sprite.getGlobalBounds().height / 2.0f; }

    float bottom() const noexcept { return getY() + m_sprite.getGlobalBounds().height / 2.0f; }

    float spriteWidth() const noexcept { return m_sprite.getGlobalBounds().width; }

    float spriteHeight() const noexcept { return m_sprite.getGlobalBounds().height; }

    void draw(sf::RenderWindow& window) {
        window.draw(m_sprite);
    }

    bool checkCollision(const Entity& entity) const {
        return (m_sprite.getGlobalBounds().intersects(entity.m_sprite.getGlobalBounds()));
    }

    const sf::Sprite& getSprite() const {
        return m_sprite;
    }

    virtual ~Entity() {
    }

protected:

    double m_angle;
    sf::Sprite m_sprite;
    int m_speed;//speed that you travel every second

};

#pragma once
#include "Globals.h"
#include "ResourceManager.h"
#include "ResourceIdentifier.h"
#include "Entity.h"
#include <iostream>
#include <cmath>

class Shooter : public Entity{

private:
    bool m_moving;
    bool m_targetInDeadzone;
    sf::Vector2f m_targetPos;
    const int m_deadzoneRadius = 5;
public:
    Shooter();
    void initialize(const TextureManager&);
    void moveShip(float dt);
    void angleShipToMouse(const sf::Vector2i&);
    void handleInput(const sf::Event&, const sf::Vector2i&);
    void update(const sf::Vector2i&, float);
    void adjustingTargetPosition();
    bool inDeadzone();
};

#include "SpaceShooter.h"

Shooter::Shooter() : m_moving(false)
{
}

void Shooter::initialize(const TextureManager& text)
{
    m_speed = 700;
    this->m_sprite.setTexture(text.get(TextureID::Shooter));
    this->m_sprite.setOrigin(m_sprite.getGlobalBounds().width / 2.0f, m_sprite.getGlobalBounds().height / 2.0f);
    this->m_sprite.setPosition(Globals::m_windowWidth / 2.0f, Globals::m_windowHeight / 2.0f);
}

void Shooter
::moveShip(float dt)
{
    if (m_moving) {

        if (m_targetInDeadzone) {
            adjustingTargetPosition(); //angle can change the width and height of sprite and this changes the size of the deadzone
        }

        sf::Vector2f shipVelocity(cos(m_angle * Globals::deg2rad) * m_speed * dt, sin(m_angle * Globals::deg2rad) *  m_speed * dt);

        float targetDistance = sqrt(pow(m_targetPos.x - getX(), 2) + pow(m_targetPos.y - getY(), 2));
        float distanceToTravel = sqrt(pow(shipVelocity.x, 2) + pow(shipVelocity.y, 2));

        if (targetDistance > distanceToTravel) {
            this->m_sprite.move(shipVelocity.x, shipVelocity.y);
            std::cout << m_targetPos.y << std::endl;
        //  std::cout << targetDistance << " > " << distanceToTravel << std::endl;
        }
        else {
            this->m_sprite.setPosition(m_targetPos.x, m_targetPos.y);
            m_moving = false;
        }
    }
}

void Shooter::angleShipToMouse(const sf::Vector2i& mousePosition) {

    sf::Vector2f mouseRelativeShip(mousePosition.x - getX(), mousePosition.y - getY());

//5 pixel circular deadzone where mouse position cant change ship angle
    if (sqrt(pow(mouseRelativeShip.x, 2) + pow(mouseRelativeShip.y, 2)) <= m_deadzoneRadius) {
        return;
    }

    float rotation = atan2(mouseRelativeShip.y, mouseRelativeShip.x)*Globals::rad2deg; //atan2 produces negative angles if vector is in QUADS 1&2, positive in QUADS 3&4

    this->m_sprite.setRotation(rotation);

    m_angle = this->m_sprite.getRotation();
}

void Shooter::handleInput(const sf::Event& event, const sf::Vector2i& mousePos) {
    if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) {
        if (!m_moving) {
            m_moving = true;
            m_targetPos = static_cast<sf::Vector2f>(mousePos);
            m_targetInDeadzone = inDeadzone();
        }
    }
}

void Shooter::update(const sf::Vector2i& mousePosition, float dt) {
    angleShipToMouse(mousePosition);
    moveShip(dt);
}

void Shooter::adjustingTargetPosition()
{
    if (m_targetPos.x < spriteWidth() / 2.0f) {
        m_targetPos.x = spriteWidth() / 2.0f;
    }
    else if (m_targetPos.x > Globals::m_windowWidth - spriteWidth() / 2.0f) {
        m_targetPos.x = Globals::m_windowWidth - spriteWidth() / 2.0f;
    }
    else if(m_targetPos.y < spriteHeight() / 2.0f){
        m_targetPos.y = spriteHeight() / 2.0f;
    }
    else if (m_targetPos.y > Globals::m_windowHeight - spriteHeight() / 2.0f) {
        m_targetPos.y = Globals::m_windowHeight - spriteHeight() / 2.0f;
    }
}

bool Shooter::inDeadzone()
{
    if (m_targetPos.x < spriteWidth() / 2.0f || m_targetPos.x > Globals::m_windowWidth - spriteWidth() / 2.0f ||
        m_targetPos.y < spriteHeight() / 2.0f || m_targetPos.y > Globals::m_windowHeight - spriteHeight() / 2.0f) {
        return true;
    } return false;
}

```

The problem is that clicking on a new target position or dragging the mouse while the spaceship is in motion will cause the ship to follow the cursor, but I am trying to do 1 click, spaceship flies there and cannot redirect before it reaches the target. I tried to achieve this by not letting it change the target position with the flag (!m\_moving) while flying and I tested this by debugging it and it seems the target is not changing which is great which is why im confused as to why it lets me do this. I've disabled repeated key presses for the windows.

The second problem is the boundaries, sometimes it works correctly but often it won't, the spaceship will fly through at times. I've printed out targetposition vs the distancetotravel, and it showed it working for a while and then eventually (the targetposition starts increasing when it should be gradually decreasing before it satisfies the condition that targetposition

This shows the targetdistance \> distancetotravel when it goes towards the boundary, as you can see it bugs out at one point, and I can't think why because it works fine if its not against the boundary.

# Answer
I think your problem lies here:

```
void Shooter::adjustingTargetPosition()
{
    if (m_targetPos.x < spriteWidth() / 2.0f) {
        m_targetPos.x = spriteWidth() / 2.0f;
    }
    else if (m_targetPos.x > Globals::m_windowWidth - spriteWidth() / 2.0f) {
        m_targetPos.x = Globals::m_windowWidth - spriteWidth() / 2.0f;
    }
    else if(m_targetPos.y < spriteHeight() / 2.0f){
        m_targetPos.y = spriteHeight() / 2.0f;
    }
    else if (m_targetPos.y > Globals::m_windowHeight - spriteHeight() / 2.0f) {
        m_targetPos.y = Globals::m_windowHeight - spriteHeight() / 2.0f;
    }
}

```

See that this is all one else-if chain, but you are attempting to clamp both `x` and `y`, thus `y` is never clamped if `x` is clamped beforehand.

Try the following:

```
void Shooter::adjustingTargetPosition()
{
    const float xMin = spriteWidth() / 2.0f;
    const float xMax = Globals::m_windowWidth - spriteWidth() / 2.0f
    const float yMin = spriteHeight() / 2.0f;
    const float yMax = Globals::m_windowHeight - spriteHeight() / 2.0f

    m_targetPos.x = (m_targetPos.x < xMin) ? xMin : (m_targetPos.x > xMax) ? xMax : m_targetPos.x;
    m_targetPos.y = (m_targetPos.y < yMin) ? yMin : (m_targetPos.y > yMay) ? yMay : m_targetPos.y;
}

```
> 1 votes

# Answer
*I am not a pro in C++ so I might be totally wrong:*

First problem: your vector `m_target` get the adress of your `mousePointer`. If you click elsewhere, even if the condition are not met to update the value of the target, your the value of your `mousePointer` is changing so does your `m_target`, am i wrong?

Second problem: Do you update your `m_angle` when you are near the deadzone?
> 0 votes

---
Tags: c++, sfml
---


title: In iOS, where/how to do a back button?

text:
# Question
Title: In iOS, where/how to do a back button?
Edit: To sum up my question, **what is the established back gesture for iOS games (when no pause button exists)?**

I have a **block puzzle game**, square grid, and some levels fill up the whole screen with them. In Android this is no problem because there's a hardware back button. iOS devices, however, have **no such thing.**

I need some kind of back button to get to the menu, where you can restart, undo, select other levels, go to options page, etc.

I looked at iOS game demos on youtube. All I found was many of them have a pause button in some corner, but this is **not** a great solution in my case. I could not find a demo illustrating some kind of back gesture, like **swiping from the left edge towards the right?** Most demos are direct screen captures instead of showing a user and their hands, so I could not confirm this.

I figure most iOS games have adopted some kind of standard practice for this. What is it?

**EDIT:** I found this article about iOS 7 doing a left-right swipe to go back one page, apparently for safari. This was kinda my first though, because surely there is a back gesture for the back button of web pages? I don't know if this same gesture is standard practice in iOS games, but I put it here because it's my first guess.

# Answer
> 3 votes
The standard practice *is* to have a button somewhere onscreen to do this. That's because it is obvious, clear and present whenever the user decides they need to pause.

While the swipe / gesture is a nice idea, users will have trouble actually remembering *how* to pause, when the time comes - remember that they're not going to read the help each time before they play, instead they'll maybe read it just *once* \- when they first play your game. It could be a few sessions before they ever decide they need to pause; by then they've forgotten *how*. **Then again, you could have a loading screen before each level, with a tip showing user how to pause.**

In case they have forgotten how to pause using a swipe, they will probably hit the Home button that goes back into iOS, and when they find the game icon and come back in, gamestate should be paused (you'd need to code this explicitly if you haven't already). **This is unorthodox as the primary means of pausing, but it may work if you absolutely cannot tolerate a button,** since it is in any case standard behaviour for mobile games.

**Auto-pause** once a certain amount of time has gone by without user input. Whether or not this can be made to work with your game, is down to you.

Have a **pause block, or pause tile** revealed beneath a vanished block. These can be scattered randomly around. Of course this may trigger unwanted pausing during actual play. You could also have these trigger some sort of an "upgrade / level up screen" that implicitly pauses the game.

Allow some kind of **multi-tap** (say tap three times in quick succession) rather than a swipe. Again you will have the difficulty of ensuring the user knows how to do this, but you'll be less likely to have the input confusion that a swipe may cause. Maybe something like holding your thumbs on left and right edge of the screen for a second could work well.

---
Tags: ios, user-experience, gestures
---


# Question
Title: Ensuring linear velocity remains constant even when turning
I am using Ackermann steering to rotate a vehicle. The code is as follows:

```
    if (turningLeft || turningRight) {
        // Rotate around a dummy pivot point
        float turnDir = turningLeft ? -1 : 1;
        Vector3 turningPivotPoint =
            dummyPivot.transform.TransformPoint(
                new Vector3(turningCenterDistance * turnDir, 0, 0));
        dummyPivot.transform.RotateAround(
                    turningPivotPoint,
                    Vector3.up * gasDir * turnDir,
                    angleVel * Time.deltaTime);
    }

    // The player is pressing the gas
    if (isGas) {
        angleVel = Mathf.Lerp (angleVel, maxAngleVel,Time.deltaTime);
    }

    if (angleVel == 0) {
        turningLeft = turningRight = false;
    }

    gasVel = Mathf.Lerp(gasVel, angleVel * Mathf.Deg2Rad * turningCenterDistance, Time.deltaTime);

    dummyPivot.transform.position =
        dummyPivot.transform.position + dummyPivot.transform.forward * Time.deltaTime * gasVel * gasDir;

```

The issue is that the speed of the vehicle when it is turning does not match its speed when driving straight. Driving the vehicle in circles will be slower than driving the vehicle forward.

How do I fix this?

# Answer
```
using UnityEngine;
using System.Collections;

public class CarController : MonoBehaviour
{
    int turn = 0;
    float acceleration = 0;
    float speed = 0;
    public float friction = 0.98f; //feel free to fiddle with this

    void Update ()
    {
        turn = 0;
        acceleration = 0;
        speed *= friction; //dampen

        turn += Input.GetKey("a") ? -1 : 0;
        turn += Input.GetKey("d") ? +1 : 0;

        acceleration += Input.GetKey("w") ? 0.2f * Time.deltaTime : 0;
        speed += acceleration;

        transform.Rotate(0, turn, 0);
        transform.Translate(Vector3.forward * speed , Space.Self); //look up what Space.Self does!
    }
}

```

You can see that our position is always updated by adding `Vector3.forward * speed`. This means we will always have the same linear velocity regardless of whether or not we are turning, provided the speed, which is a function of the gas pedal, is the same.

P.S. You can also supply `turnAcceleration` to smooth turning. This is just a simple example.
> 1 votes

---
Tags: unity, physics, geometry
---


title: Throwing a grabbed object

text:
# Question
Title: Throwing a grabbed object
I'm trying to throw the carried object in the direction of the first person controller, but unable to make it. I could make the carried object drop, but the same time i need to instantiate velocity to the carried object, so that i could forward. I'm building up a bowling game and trying to make the ball behave like the same when the player throws the ball. It should hit the alley and move forward to hit the pins. Below is what so far I've tried.

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

public class pickupobject : MonoBehaviour {
    GameObject mainCamera;
    //public GameObject empty;
    bool carrying;
   public GameObject carriedObject;
   // Camera cam;
    public float distances;
    public float smooth;
    float speed = 1000f;

    // Use this for initialization
    void Start()
    {
        //cam = GameObject.Find("MainCamera").GetComponent<Camera>();
        mainCamera = GameObject.FindWithTag("MainCamera");
    }

    // Update is called once per frame
    void Update () {
        if (carrying)
        {
            carry(carriedObject);
            CheckDrop();
        }
        else
        {
            pickup();
        }

    }

    private void pickup()
    {
        if(Input.GetKeyDown(KeyCode.E))
        {
            int x = Screen.width / 2;
            int y = Screen.height / 2;
            Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
            RaycastHit hit;
            if(Physics.Raycast(ray, out hit))
            {
                pickupable p = hit.collider.GetComponent<pickupable>();
                if(p!=null)
                {
                    carrying = true;
                    carriedObject = p.gameObject;
                }
            }
        }
    }

    void carry(GameObject o)
    {
        o.GetComponent<Rigidbody>().isKinematic = true;
        o.transform.position =  mainCamera.transform.position + mainCamera.transform.forward * distances;

    }

    //void ThrowBall()
    //{
    //    GameObject go = (GameObject)Instantiate(carriedObject,transform.forward, Quaternion.identity);
    //    pickupable to = go.GetComponent<pickupable>();
    //    to.Throw(carriedObject.transform.forward * speed);
    //}

    void CheckDrop()
    {
        if(Input.GetKeyDown(KeyCode.U))
        {
            Drop();
        }
    }

    void Drop()
    {
        carrying = false;
        // carriedObject = Instantiate(carriedObject, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
        carriedObject.GetComponent<Rigidbody>().isKinematic = false;
        gameObject.GetComponent<Rigidbody>().AddForce(carriedObject.transform.forward * 100);
       // carriedObject.GetComponent<Rigidbody>().AddForce(0,0,1f);
        //carriedObject.gameObject.GetComponent<Rigidbody>().isKinematic = false;
        carriedObject = null;

    }
}

```

Thanks in advance!

# Answer
Continuing my comment: you need some changes in your code to check when to throw the object.

I've updated the code to account for those changes, it should work as expected now.

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

public class Pickupable : MonoBehaviour
{
    //GameObject mainCamera;
    bool carrying;
    GameObject carriedObject;
    Camera cam;
    public float distances;
    public float smooth;

    // Use this for initialization
    void Start()
    {
        cam = GameObject.Find("MainCamera").GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        //Check for user input ('T' key here) and make sure the object is being carried
        if(Input.GetKeyDown(KeyCode.T) && carrying)
        {
            carrying = !carrying;
            ThrowBall();
        }
        if (carrying)
        {
            carry(carriedObject);
        }
        else
        {
            pickup();
        }

    }

    private void pickup()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            int x = Screen.width / 2;
            int y = Screen.height / 2;
            Ray ray = cam.ScreenPointToRay(new Vector3(x, y));
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                Pickupable p = hit.collider.GetComponent<Pickupable>();
                if (p != null)
                {
                    carrying = true;
                    carriedObject = p.gameObject;
                }
            }
        }
    }

    void carry(GameObject o)
    {
        o.GetComponent<Rigidbody>().isKinematic = true;
        o.transform.position = cam.transform.position + new Vector3(0f,0f, 10f);
    }

    void ThrowBall()
    {
        carriedObject.GetComponent<Rigidbody>().isKinematic = false;
        carriedObject.GetComponent<Rigidbody>().AddForce(0f, 0f, 100f);
    }
}

```
> 1 votes

---
Tags: unity
---


title: Is this a good Java gameloop?

text:
# Question
Title: Is this a good Java gameloop?
I wonder if this gameloop in Java is accurate to give around 60 frames a second, is it?

```
public void run() {
    long then = System.nanoTime();
    long targetFPS = 60;
    Timer timer = new Timer();

    while(running){
        long now = System.nanoTime();
        long updateLength = now - then;
        long update = updateLength / targetFPS;
        then = now;
        System.out.println(update);
        if(update >= 16){
            render();
            tick();
            System.out.println(updateLength);
        }
    }
}

```

# Answer
> 2 votes
It isn't.

This keeps the CPU running constantly, which uses a lot of power. Also, system.nanotime can be really slow on certain PCs. Instead try something like:

```
long time = System.currentTimeMillis();
// Do your stuff
Thread.sleep(Math.max(0, time - 16));
run();

```

This doesn't exactly produce 60 fps, because that requires 16,66 milliseconds between frames, but it's really close.

---
Tags: java, game-loop
---


# Question
Title: How to use a DualShock 4 controller in Java?
I want to use a DualShock 4 controller in a computer program I'm developing.

Do I only need to use a library? Or do I need some other things too?

I don't have any code yet, I'm just starting to look at it. I'll be using Eclipse if it has any relevance.

# Answer
> 2 votes
LibGDX is a Java-based engine that has support for Controllers. However, you would have to do some research on what Input ID is used for the DualShock 4.

---
Tags: java
---


# Question
Title: Change Time.timeScale during an animation event - Unity
I have an animation. A few seconds after this animation starts I set an animation event that is correctly being triggered. This animation event calls a method where I am trying to modify `Time.timeScaleand` set it to 0.05f.

This event is calling the following method:

```
public void Slowmotion()
{
    Time.timeScale = 0.05f;
    //Time.fixedDeltaTime = Time.timeScale * 0.02f;
}

```

But this `Slowmotion` method is not working.

Any ideas on what may be happening?

# Answer
I made a scene based on your question and the "Slowmotion" method worked just fine, the steps I followed were:

1. Create a new scene in a project
2. Add a cube to the scene
3. Create a new **Animator Controller** asset
4. Add the **Animator** component to the cube and link the **Animator Controller** asset to it
5. Select the cube and open the **Animation** window
6. Create a new **Animation Clip** from the **Animation** window with a duration of 3 seconds and a simple movement curve
7. Create a new C# Script called *ChangeScale* with the following code:

```
using UnityEngine;
public class ChangeScale : MonoBehaviour {

    public void Slowmotion() {
        Time.timeScale = 0.05f;
    }
}

```
8. Add the new script to the cube
9. Add an **Animation Event** calling the "Slowmotion" method:
10. Press Play (In the main editor window, not the **Animation** window)

Hope this helps you find the issue in your setup
> 0 votes

---
Tags: unity, animation, timer
---


title: Direct3D11 Depth buffer problem

text:
# Question
Title: Direct3D11 Depth buffer problem
Encountered a strange error when using Direct3D11, feature level 10.0.

If the depth buffer texture is created with the format DXGI\_FORMAT\_R24G8\_TYPELESS, bind flag D3D11\_BIND\_DEPTH\_STENCIL | D3D11\_BIND\_SHADER\_RESOURCE and the depth stencil view format DXGI\_FORMAT\_D24\_UNORM\_S8\_UINT, everything is correct. Also, there are no problems when the depth buffer texture format is DXGI\_FORMAT\_R32G8X24\_TYPELESS and the depth stencil view format is DXGI\_FORMAT\_D32\_FLOAT\_S8X24\_UINT.

However, when the depth buffer format is DXGI\_FORMAT\_R32\_TYPELESS, and the depth stencil view format is DXGI\_FORMAT\_D32\_FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation/destruction of resources). I do not use the stencil functionality at all, and it is disabled.

I use a Windows 7 virtual machine as a developer machine and using DXGI\_FORMAT\_R32\_TYPELESS and DXGI\_FORMAT\_D32\_FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard-drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine.

Is it possible to have a bug somewhere else in my code?

Is there a limitation when using DXGI\_FORMAT\_D32\_FLOAT and sometimes it may not be possible to use DXGI\_FORMAT\_D32\_FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)?

Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus - Intel HD 4000 + GeForce GTX 650M)?

# Answer
> 0 votes
If you are getting a rejection of all the geometry, just check what you are clearing your depth buffer to initially. Also, are you still binding depth stencil to your buffer when using d32? If so, remove that binding and recheck (I cant remember but there might be an issue there).

I use the same D32/R32 typeless currently in my project for shadow buffers. I will double check if there is anything special.

---
Tags: directx11, windows, depth-buffer, linux
---


title: Math to set tangential force?

text:
# Question
Title: Math to set tangential force?
I have an 2-dimensional planet at coordinate (pX, pY) and an object at the surface of the planet at some coordinates (oX, oY). I want to have the object go left or right when the user press the keys, which I'd like to simulate by applying a force. I have a homemade physics engine built and all I'm missing is the x/y amounts to use to apply the force in a tangential direction.

What calculation is needed to apply a tangential force clockwise/counterclockwise on an object at (oX, oY) around a center of (pX, pY)?

# Answer
You need a unit vector tangent to the planet surface:

```
v = normalize((pY - oY, oX - pX))

```

Then just multiply `v` by your force amount.
> 2 votes

# Answer
First, calculate the relative coordinates using `rX = oX - pX` and `rY = oY - pY`

Next, we'll find the angle. Use the Atan2 method: `angle = atan2(rY, rX)`

Next, more trigonometry! We should be able to do `totalforce * sin(angle)` to find the amount of force to be applied on the X-axis and `totalforce * -cos(angle)` to find the amount of force to be applied on the Y-axis. Change totalforce to be positive or negative based on the direction desired.
> 0 votes

---
Tags: physics, mathematics, javascript
---


# Question
Title: Managing Unity Scenes during refactoring?
Most of my Unity project code is in a visual studio project, and I use Unity for UI/Rendering/wiring things together.

I renamed some fields in an object and suddenly the game, when run in unity, became unrunnably buggy. It turned out that a field I had set in the unity frontend had been unset when I renamed it.

What's a good way to avoid these sorts of problems when working with unity? I was using version control and could have reverted to an old build in the worst case, but I couldn't find any human-readable Unity Scene files that could have just shown me what I changed.

# Answer
> 9 votes
For refactoring fields check out the `FormerlySerializedAs` attribute. See: https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html

When changing class names make sure that the file and the respective meta file is also renamed accordingly.

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


# Question
Title: Unable to Merge Android manifest error is showing up
I used Google Admob to put ads in my game but as soon as I hit build and run this error showed up I used a Github file and imported into my unity project, I will link it right here

https://github.com/unity-plugins/Unity-Admob.

**CommandInvokationFailure: Unable to merge android manifests. See the Console for more details. C:\Program Files (x86)\Java\jdk1.8.0\_101\bin\java.exe -Xmx1024M -Dcom.android.sdkmanager.toolsdir="C:/Users/jayso/AppData/Local/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" - stderr\[ Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-ads-10.2.0\AndroidManifest.xml:2\] Main manifest has but library uses minSdkVersion='14' Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-ads-lite-10.2.0\AndroidManifest.xml:7\] Main manifest has but library uses minSdkVersion='14' Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-base-10.2.0\AndroidManifest.xml:2\] Main manifest has but library uses minSdkVersion='14' Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-basement-10.2.0\AndroidManifest.xml:2\] Main manifest has but library uses minSdkVersion='14' Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-gass-10.2.0\AndroidManifest.xml:2\] Main manifest has but library uses minSdkVersion='14' Error: \[Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-tasks-10.2.0\AndroidManifest.xml:2\] Main manifest has but library uses minSdkVersion='14' \] stdout\[ \] exit code: 1 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String\[\] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String\[\] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()**

# Answer
Your project is set to link with android version 14 (your main manifest oder in build settings), but the admob library uses another version. Try aligning those up
> -1 votes

---
Tags: unity, c#, android, admob
---


# Question
Title: .png file to Sprite(2D and UI) - still not visible under source image
I am trying to use an image as a UI Image but even after changing its texture type to Sprite(2D and UI), it isn't visible in the source image menu. The file was created in MS Paint and I'm accessing the source image menu via the "circle selector" next to Source Image in the Inspector. I'm pretty sure I've never had this issue before. I wish I could share more details but there's nothing much to say. What could be causing this issue?

# Answer
> -1 votes
I figured it out, I had to select a sprite mode as well. By default, the field was blank.

---
Tags: unity
---


title: Setting Texture to material slowly

text:
# Question
Title: Setting Texture to material slowly
Have an idea to set the *texture* to *3D material* **slowly**. It would be like some animation, that change previous texture to new sloowly from bottom to top.
I need it to my game... Can't find the solution...
Can you help me with this problem?

# Answer
> 1 votes
Create a new transition material that would use 2 textures and some 'transition amount' float in a \[0-1\] range. Use your custom shader to do the transition in a way you want.

Then, when you want to start animation replace initial material with your new one and start animating your 'amount' parameter. When you end the animation then set the basic material back, but with 2nd texture.

This way you'll avoid costly modifications of texture pixels and move all the work to GPU shaders.

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


# Question
Title: How do I add freeglut to a Visual Studio project?
I am working on making a game for Windows in c++. I have previously made games for Ubuntu using freeglut, and I found freeglut for windows, but when I added it to the `Configuration Properties\VC++ Directories\Library Directories` tab in visual studio, visual studio complains about 'undefined reference' whenever I use a freeglut method. Does anyone have a solution?

# Answer
When you right click on the project you have to also add the filename of the library under "Linker-\>Input-\>Additional Dependencies".

Just in case: You also have to tell Visual Studio where to find the header files in case you haven't yet. This can be done under "VC++ Directories-\>Include Directories"

Make sure you define the right libraries for Debug and Release builds. Most libraries have libraries/dlls with d added to the name that can be used for debugging. Switch the Configuration between Debug and Release in oder to set input files. Of course you can use the release libraries for Debug too.
> 2 votes

---
Tags: c++, graphics, visual-studio, glut
---


title: Different Sprite sizes for animation

text:
# Question
Title: Different Sprite sizes for animation
I have a character which has a size of 32x64 when walking or standing. Using the libgdx animation class I can easily animate him with a texture atlas. When I want to make him attack however, the Sprite appears squished because the frames for the attack animation are 64x64 to accommodate the sword. My question is as the artist and programmer, would it make more sense to have each Sprite frame for every animation be 64x64? Or in code, resize the Sprite origin and bounds before the attack animation and set them back to 32x64 when the attack is done?

# Answer
> 0 votes
It's not wise to increase the size of the smaller sprites, so they fit your needs. If you have a choice, to write more code and gain efficiency - do so.

It's good that these sprites are POT because it saves you alot of memory - keep it that way.

The thing you need to do is to translate your player (and possibly other entities) positions to their center.

For now, if you draw a texture on `(0,0)`, you'd have it fully visible, in the left corner of the screen.

What you need to do is to translate it, so if the `width` of the `player` is `64`, you draw him at `(-32,0)`. You'd need to adjust some algorithms for it, but it's not complicated. In `GDX`, you should probably override the `draw()` method.

If you always draw your entities relative to their width-center, you can use as many animations as you want.

If you have the player's `width` and `height`, in your `draw()` method you can do

```
batch.draw(currentTexture,
     center.x - (currentTexture.width / 2f),
     center.y - (currentTexture.height / 2f),
     currentTexture.width,
     currentTexture.height);

```

Each texture will be rendered in the center of the player. You just have to adjust these two variables some reasonable values.

You can switch textures depending on the current state (jump, fight, whatever) - it will always work and you don't have to change the origins (you shouldn't).

---
Tags: libgdx
---


# Question
Title: Find which collider is causing collision (implementing danger zone)
I have multiple `SphereColliders` attached to `GameObject`, one bigger to detect collision danger zone and the other, smaller, for actual collision (both triggers!). When the `OnTriggerEnter()` how do I find which one of those two caused trigger enter event?

```
private void OnTriggerEnter(Collider other)
{
    foreach (var collider in GetComponents<SphereCollider>())
    {
        if(isColliding(collider)) //how to find if this particular trigger isColliding ?
        {
            if(collider.radius > 0.5)//smaller or bigger one
               GetComponent<MeshRenderer>().material.color = _dangerColor;
            else handleCollision();
        }
    }

}

```

---

Because the accepted answer provides two solutions, it would be in order to specify how I solved the problem. In the end I went for keeping outter collider and doing "manual" overlap test for inner one (since I did not need physics response, it was the lesser evil). It also turned into new feature, it allows me to lerp danger color.

# Answer
As far as I know, there is no good way to accomplish this when having two triggers on the same GameObject. You could do sphere overlap tests, but then you would just be duplicating what the physics engine has already done!

What I normally do is put each trigger on a separate GameObject (perhaps one parent, one child) each with a script with its own `OnTriggerEnter`. Using that, one script could handle your danger zone, and the other could handle your collision event.
> 1 votes

# Answer
As detecting the danger zone and handling the actual collisions is something different, I think you should have two gameobjects, one with the big collider and a DetectDangerZone script, another gameobject with the smaller collider which handles your collision.
> 1 votes

# Answer
You could check the distance between the object and the object colliding with it, in this way you could have multiple checks to see if the object has passed certain distances.

```
//Distances are equal to the radii of the colliders they replace
float hitZone = 1f;
float closeZone = 2f;
float dangerZone = 3f;

private void OnTriggerEnter(Collider other)
{
    float distance = Vector3.Distance(transform.position,other.position);
    if(distance < dangerZone){
        //Object is in the danger zone
    }
    else if (distance < closeZone){
        //Object is in the close zone
    }
    else if (distance < hitZone){
        //Object is in the hit zone
    }
}

```
> 0 votes

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


# Question
Title: Unity, how to detect landing after jump?
How do I detect the landing of the player without getting interrupt by the onGround check ?

I got 2 scripts, one is the normal player script and the other is what I was trying. in the onGround Script it activates the collider when I jump which is positioned under the player and when I dont press the jump button anymore it will disable the Collider again which checks if I am landed or not. It is working but when im jumping and press quick S and you will hear the landing sound more then just once, but when I jump high and hold S for 2 seconds and then Pushdown to the ground the sound appears once. So my Idea is how it checks the landing correctly without the problem in the last sentence. And the Pushdown() Code is when I jump and press S while in the air it smashes down to the ground. To sum up I want to check the landing correctly.

Player Code:

---

```
public class PlayerScript : MonoBehaviour {

    //MOVEMENT
    public float moveSpeed;
    public float pushDownForce;
    //PUSHDOWN
    public GameObject pushDownParticle;
    bool pushdown;
    private Vector3 offset;
    public GameObject lander;
    private AudioSource audo;
    public AudioClip audoClip;
    public Transform checkGround;
    //JUMP
    public bool onGround;
    bool onLand;
    public float jumpPressure;
    private float minJump;
    private float maxJumpPressure;
    private Rigidbody rb;
    //ANIMATION
    private Animator anim;
    //PHYSICS
    public PhysicMaterial pm;

    void Start ()
    {
        //JUMP
        onGround = true;
        onLand = false;
        jumpPressure = 0f;
        minJump = 2f;
        maxJumpPressure = 10f;
        rb = GetComponent<Rigidbody>();
        //ANIMATION
        anim = GetComponent<Animator>();
        //PUSHDOWN
        audo = GetComponent<AudioSource>();
        //checkGround.gameObject.SetActive(false);
        checkGround.GetComponent<Collider>().enabled = false;
    }

    void FixedUpdate ()
    {
        //ANIMATION

        transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed, 0f, 0f);

        //PushDownPhysics
        if(Input.GetKey(KeyCode.S))
        {
            if(!onGround)
            {
                //checkGround.gameObject.SetActive(true);
                checkGround.GetComponent<Collider>().enabled = true;
                pm.bounciness = 0.25f;
                PushDown();

                /*if(onGround)
                {
                    audo.pitch = (Random.Range(0.95f, 1f));
                    audo.PlayOneShot(audoClip, 0.7F);
                }
                */
            }
            else
            {
                pm.bounciness = 0.5f;;
                //checkGround.gameObject.SetActive(false);
                checkGround.GetComponent<Collider>().enabled = false;
            }

            if(Input.GetKeyUp(KeyCode.S))
                //checkGround.gameObject.SetActive(false);
                checkGround.GetComponent<Collider>().enabled = false;
        }

        //JUMP
        if(onGround)
        {
            //holding JumpButton
            if(Input.GetButton("Jump"))
            {
                if(jumpPressure < maxJumpPressure)
                {
                    jumpPressure += Time.deltaTime * 8f;
                }
                else
                {
                    jumpPressure = maxJumpPressure;
                }
                //ANIMATION
                anim.SetFloat("jumpPressure", jumpPressure + minJump);
            }
            //not holding JumpButton
            else
            {
                //Jump
                if(jumpPressure > 0f)
                {
                    jumpPressure = jumpPressure + minJump;
                    rb.velocity = new Vector3 (0f, jumpPressure, 0f);
                    jumpPressure = 0f;
                    onGround = false;
                    anim.SetFloat("jumpPressure", 0f);
                    anim.SetBool("onGround", onGround);
                }
            }
        }
    }
    //JUMP
    void OnCollisionEnter( Collision other)
    {
        if(other.gameObject.CompareTag("ground"))
        {
            onGround = true;
            //ANIMATION
            anim.SetBool("onGround", onGround);
        }
    }

    void PushDown()
    {
        //PUSHES DOWN THE BODY
        rb.AddForce(-transform.up * pushDownForce);
    }

}

```

---

onGround script:

---

```
public class onGroundScript : MonoBehaviour {

    private AudioSource audo;
    public AudioClip audoClip;

    void Start ()
    {
        audo = GetComponent<AudioSource>();
    }

    void Update()
    {
        if(Input.GetButton("Jump"))
        {
            gameObject.GetComponent<Collider>().enabled = false;
        }
    }

    void OnTriggerEnter (Collider other)
    {
        if(other.gameObject.tag == "ground")
        {
            audo.PlayOneShot(audoClip, 1.0F);
            Debug.Log ("Sound played");
            gameObject.GetComponent<Collider>().enabled = true;
        }
        else
        {
            gameObject.GetComponent<Collider>().enabled = false;
        }
    }
}

```

# Answer
You can use a layer Mask and check against it.

`[SerializeField]
 private LayerMask groundLayer;
 bool onground = false;`

Set the ground you use to a ground layer and in fixed Update call the

```
void FixedUpdate()
{
    GroundCheck();
}

```

You can then auto set grounded bool with GroundCheck();

```
void GroundCheck()
{
   onground = Physics.CheckSphere(FeetCheckPosition,ACollisionRadius,groundLayer)
}

```
> 1 votes

---
Tags: unity, c#, collision-detection, raycasting, jumping
---