# Question
Title: Libgdx Animation class? not iterating through frames?
I am making a 'simple' top-down space shooter in 2d using Libgdx. I have loaded the texture regions into arrays and created Animations inside my sprite, but when I call the getKeyFrame it seems to jump straight to the last frame in the spritesheet.

The spritesheet is 9 frames in total of a spaceship banking to the left (hence I have enabled FlipX for when turning the other way. But all works as I expected apart from that it just jumps to the last frame in the sequence rather than the gradual banking animation.

The class in question is below, please do let me know if you need to view the rest of the code:

```
package com.moneylife.spaceattackers.Sprites;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;
import com.moneylife.spaceattackers.Screens.PlayScreen;

public class Player extends Sprite {
private PlayScreen playScreen;
private Animation bankRight, bankLeft;
private int totalFrames = 9;
private int frameWidth = 100, frameHeight = 100;
private float frameDuration = 0.3f;
private TextureRegion straightFlyingTextureRegion;

enum flyState { STRAIGHT, LEFT, RIGHT }
private flyState currentFlyState;

public Player(PlayScreen playScreen){
    super(new Texture("ship.png"));
    currentFlyState = flyState.STRAIGHT;
    this.playScreen = playScreen;
    Array<TextureRegion> frames = new Array<TextureRegion>();
    for (int i = 0; i < totalFrames; i++){
        frames.add(new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight));
        bankLeft = new Animation(frameDuration, frames);
        frames.clear();
    }
    for (int i = 0; i < totalFrames; i++){
        TextureRegion region = new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight);
        region.flip(true, false);
        frames.add(region);
        bankRight = new Animation(frameDuration, frames);
        frames.clear();
    }
    straightFlyingTextureRegion =  new TextureRegion(getTexture(),0,0,frameWidth, frameHeight);
    setPosition(playScreen.viewport.getWorldWidth() / 2 - frameWidth / 2,0);
    setRegion(straightFlyingTextureRegion);

    bankLeft.setPlayMode(Animation.PlayMode.NORMAL);
    bankRight.setPlayMode(Animation.PlayMode.NORMAL);
}

public void update(float dt){
    switch (currentFlyState){
        case STRAIGHT: {
            setRegion(straightFlyingTextureRegion);
            setSize(frameWidth, frameHeight);
            break;
        }
        case LEFT: {
            setRegion(bankLeft.getKeyFrame(frameDuration, false));
            break;
        }
        case RIGHT: {
            setRegion(bankRight.getKeyFrame(frameDuration, false));
            break;
        }
    }
    if (Gdx.input.isKeyPressed(Input.Keys.A)){
        currentFlyState = flyState.LEFT;
    }
    else if (Gdx.input.isKeyPressed(Input.Keys.D)){
        currentFlyState = flyState.RIGHT;
    }
    else
        currentFlyState = flyState.STRAIGHT;
    }
}

```

I beleive that the issue must be in the frames.add part (is it perhaps overwriting each frame with the other until the end??) but I cant figure out how to fix this. Can somebody please see what I am missing here?

EDIT: I have also tried moving " bankLeft = new Animation(frameDuration, frames); frames.clear();" moving that from the For loops to just below the for loop. But that meant I only got the 2nd frame in the animation only for some reason :S So my constructor now looks like this, but neither work as needed :(

```
    public Player(PlayScreen playScreen){
        super(new Texture("ship.png"));
    currentFlyState = flyState.STRAIGHT;
    this.playScreen = playScreen;
    Array<TextureRegion> frames = new Array<TextureRegion>();
    for (int i = 0; i < totalFrames; i++){
        frames.add(new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight));
    }
    bankLeft = new Animation(frameDuration, frames);
    frames.clear();
    for (int i = 0; i < totalFrames; i++){
        TextureRegion region = new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight);
        region.flip(true, false);
        frames.add(region);
    }
    bankRight = new Animation(frameDuration, frames);
    frames.clear();

    straightFlyingTextureRegion =  new TextureRegion(getTexture(),0,0,frameWidth, frameHeight);
    setPosition(playScreen.viewport.getWorldWidth() / 2 - frameWidth / 2,0);
    setRegion(straightFlyingTextureRegion);

    bankLeft.setPlayMode(Animation.PlayMode.NORMAL);
    bankRight.setPlayMode(Animation.PlayMode.NORMAL);
    setSize(frameWidth, frameHeight);
}

```

# Answer
```
public TextureRegion getKeyFrame (float stateTime, boolean looping)

```

It doesn't take a 'frame time' - it takes the time now (and you should add delta time to it every frame).

Instead of calliing

```
setRegion(bankLeft.getKeyFrame(frameDuration, false));

```

change the `frameDuration` name for `stateTime` and make it `0f` in constructor:

```
float stateTime = 0f;

```

in update call:

```
stateTime += dt;
setRegion(bankLeft.getKeyFrame(stateTime, false)); // for both cases

```

And you're ready to go! Also, move your `new Animation`, `frames.add()` and `frames.clear()` outside of loops.

**Edit**

Now I read it all. You can keep your frameDuration (make it final) - and pass it to the `Animation`'s constructors, but make another variable like `stateTime` as I said. Here's your rewritten code: (I wrote //fix where I did a fix!)

```
public class Player extends Sprite {
private PlayScreen playScreen;
private Animation bankRight, bankLeft;
private int totalFrames = 9;
private int frameWidth = 100, frameHeight = 100;
private final float FRAME_DURATION = 0.3f; // each frame will last 0.3f
private final float stateTime = 0f; // fix
private TextureRegion straightFlyingTextureRegion;

enum flyState { STRAIGHT, LEFT, RIGHT }
private flyState currentFlyState;

public Player(PlayScreen playScreen){
    super(new Texture("ship.png"));
    currentFlyState = flyState.STRAIGHT;
    this.playScreen = playScreen;
    Array<TextureRegion> frames = new Array<TextureRegion>();
    for (int i = 0; i < totalFrames; i++){
        frames.add(new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight));
    }
    bankLeft = new Animation(FRAME_DURATION, frames); // fix
    frames.clear();

    for (int i = 0; i < totalFrames; i++){
        TextureRegion region = new TextureRegion(getTexture(), i * frameWidth, 0, frameWidth, frameHeight);
        region.flip(true, false);
        frames.add(region);
    }
     bankRight = new Animation(FRAME_DURATION, frames); // fix
    frames.clear();

    straightFlyingTextureRegion =  new     TextureRegion(getTexture(),0,0,frameWidth, frameHeight);
    setPosition(playScreen.viewport.getWorldWidth() / 2 - frameWidth / 2,0);
    setRegion(straightFlyingTextureRegion);

    bankLeft.setPlayMode(Animation.PlayMode.NORMAL);
    bankRight.setPlayMode(Animation.PlayMode.NORMAL);
}

public void update(float dt){

    stateTime += dt; // fix
    switch (currentFlyState){
    case STRAIGHT: {
        setRegion(straightFlyingTextureRegion);
        setSize(frameWidth, frameHeight);
        break;
    }
    case LEFT: {
        setRegion(bankLeft.getKeyFrame(stateTime, false)); // fix
        break;
    }
    case RIGHT: {
        setRegion(bankRight.getKeyFrame(stateTime, false)); // fix
        break;
    }
}
if (Gdx.input.isKeyPressed(Input.Keys.A)){
    currentFlyState = flyState.LEFT;

```
> 0 votes

---
Tags: 2d, libgdx, game-design, animation
---


# Question
Title: I am Trying to build a survival game using procedural Generation, successful in generating a Mesh, need help in Spawn and texture
I have create a Terrain using perlin-noise map, I am successful so far. But, now when i am trying to add texture, I can't figure out how. I am using using a colorMap to test, I want grass to have grass like texture instead of green color. Also, I want to spawn GameObject in certain area depending on heightMap (like Minecraft spawn bear in snow mountain). can someone help

**HeightMap Generation Script**

```
using UnityEngine;  using System.Collections;

public static class Noise {

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) {
        float[,] noiseMap = new float[mapWidth,mapHeight];

        System.Random prng = new System.Random (seed);
        Vector2[] octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++) {
            float offsetX = prng.Next (-100000, 100000) + offset.x;
            float offsetY = prng.Next (-100000, 100000) + offset.y;
            octaveOffsets [i] = new Vector2 (offsetX, offsetY);
        }

        if (scale <= 0) {
            scale = 0.0001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {

                float amplitude = 1;
                float frequency = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++) {
                    float sampleX = (x-halfWidth) / scale * frequency + octaveOffsets[i].x;
                    float sampleY = (y-halfHeight) / scale * frequency + octaveOffsets[i].y;

                    float perlinValue = Mathf.PerlinNoise (sampleX, sampleY) * 2 - 1;
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxNoiseHeight) {
                    maxNoiseHeight = noiseHeight;
                } else if (noiseHeight < minNoiseHeight) {
                    minNoiseHeight = noiseHeight;
                }
                noiseMap [x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {
                noiseMap [x, y] = Mathf.InverseLerp (minNoiseHeight, maxNoiseHeight, noiseMap [x, y]);
            }
        }

        return noiseMap;
    }

}

```

**MapGenerator Script**

```
using UnityEngine;
using System.Collections;

public class TerrainGenerator : MonoBehaviour {

    public enum DrawMode    {
        NoiseMap,
        ColorMap,
        Mesh
    };

    public DrawMode drawMode;
    public int mapWidth;
    public int mapHeight;
    public float noiseScale;

    public int octaves;
    [Range(0,1)]
    public float persistance;
    public float lacunarity;

    public int seed;
    public int meshHeightMultiplyer;
    public AnimationCurve meshHeightCurve;

    public Vector2 offset;

    public bool autoUpdate;

    public TerrainType[] regions;   float[,] noiseMap;

    public void GenerateMap() {
        noiseMap = Noise.GenerateNoiseMap (mapWidth, mapHeight, seed, noiseScale, octaves, persistance, lacunarity, offset);

        Color[] colourMap = new Color[mapWidth * mapHeight];
        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {
                float currentHeight = noiseMap [x, y];
                for (int i = 0; i < regions.Length; i++) {
                    if (currentHeight <= regions [i].height) {
                        colourMap [y * mapWidth + x] = regions[i].colour;
                        break;
                    }
                }
            }
        }

        MapDisplay display = FindObjectOfType<MapDisplay> ();
        if (drawMode == DrawMode.NoiseMap) {
            display.DrawTexture(TextureGenerator.TextureFromHeightMap (noiseMap));
        } else if (drawMode == DrawMode.ColorMap) {
            display.DrawTexture (TextureGenerator.TextureFromColourMap (colourMap, mapWidth, mapHeight));
        } else if (drawMode == DrawMode.Mesh) {
            display.DrawMesh (MeshGenerator.GenerateMesh (noiseMap, meshHeightMultiplyer, meshHeightCurve), TextureGenerator.TextureFromColourMap (colourMap, mapWidth, mapHeight));
        }
    }

    public void CreateMob()
    {
      MobSpawner ms = new MobSpawner (noiseMap);
      ms.GenerateMod ();
    }

    void OnValidate() {
        if (mapWidth < 1) {
            mapWidth = 1;
        }
        if (mapHeight < 1) {
            mapHeight = 1;
        }
        if (lacunarity < 1) {
            lacunarity = 1;
        }
        if (octaves < 0) {
            octaves = 0;
        }
        if (meshHeightMultiplyer < 1) {
            meshHeightMultiplyer = 1;
        }
    }

    [System.Serializable]
    public struct TerrainType {
        public string name;
        public float height;
        public Color colour;
    }
 }

```

# Answer
> 0 votes
You could Use a shader that takes multiple textures and then depending on a weightmap, or the height of some vertices interpolate between those textures.

I did that once and it works pretty well, only issue is that you cannot use an array of textures (yet).

Internally Unity seems to be using something at the renderer level, that is blind to the material/shader and to the number of textures used.

At some point they were using Vertex mapping, but it seems it's not the case anymore.

All those are valid ways to deal with this issue.

---
Tags: unity, c#, textures, procedural-generation, scripting
---


# Question
Title: Simultaneous line of sight for hundreds of individual agents on a grid?
I have a large grid with hundreds of individual agents, each of which is moving around based on its own visual inputs and a fast control algorithm.

My question is: How can I efficiently provide each agent with a set of other agents (or walls) that they can see?

Ray casting from each individual works, but is slow. It seems like I should be able to preprocess the world at each step to speed up this process since I'll be doing it MANY times, but I haven't been able to come up with an appropriate algorithm. Is there some known trick that I've missed?

# Answer
If you haven't already, look into using optimisation algorithms and data structures such as quadtrees, spatial hashing, binary space partitioning, and so on.

A quadtree in particular would do just fine in this case, and is fairly simple to implement. It subdivides a rectangular area of the game world into four equally sized rectangles, and continues to do so for each of the resulting rectangles for a specified number of levels. If an object overlaps one of these rectangles, its reference is stored in that rectangle's 'bucket' (array of object references).

When you look for a particular object inside the quadtree, you check each rectangle's bucket for the object, and continue down to the last rectangle (the leaf of the quadtree) that contains the object in its bucket. Then you just perform a check on each of the object in that bucket to find the one you're looking for.

In your case, you would look for the rectangles the ray intersects, and then sort through the objects to see which is the closest one. That part could be a little tricky, but it shouldn't be impossible to do.

If you have rooms or walls / barriers, you could look into partitioning the map according to how the walls intersect when extended infinitely. Objects in the same room or region would be visible to each other, which limits the pool of objects you have to check the ray against.
> 1 votes

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


title: Legality of using names in a game?

text:
# Question
Title: Legality of using names in a game?
If I am creating a board-game type game, does anyone know if it is legal to use others' names in the game?

ie. A playing card with "George Bush" or "Michael Jackson" on it.

Also, is it the same for brand names?

# Answer
I would say no, unless you have been given permission. For example, think of sports games that do not own the rights to the league they are covering. They end up resorting to using similar, but different names to their real life counterparts.

---

I found this discussion about using sports peoples names in websites: It is a copyright violation to use cricket or football players' name in a website?.

It seems a name itself can not be copyright (so you can use their name in a news article for instance), however if you are benefiting from using their name/image then it is a violation of publicity rights.

See also:
> 6 votes

# Answer
I think with celebrities you would be fine(as long as its not slander). It would be safer to use names that are close, if you are using them as a character in a game. But for board games you should be alright.
> 2 votes

# Answer
I am not a lawyer, I only have a working knowledge from releasing software and reading a lot about how copyright works and TV is made, but if you want a safe, short answer, then I'd say don't do it unless the person has been dead for 100 years or so, and make sure you portray them according to official sources and don't add anything negative that isn't backed by several other, reputable sources (like official biographies from themselves or their peers).

The long answer is that there are many factors that play into it:

# Libel Laws

If you are painting a person in a negative light, or people understand you as alluding to negative occurrences in their career that haven't been proven in court, you could be sued for badmouthing them. (See the Lindsay Lohan vs. Rockstar Games lawsuit over GTA V for one way how this can end)

# Personality Rights

Are you violating anyone's personality rights? In some countries, there is an expectation of privacy, so using someone else's name might draw them into the public, or parts of their life that are considered private (especially their young children fall into this category).

# Public Interest

There is also the mitigating factor of "public interest" in many jurisdictions, where, if you are using someone's name in the news and disclosing new private facts, you may do so if the public's need to know these facts (e.g. because a crime has occurred) is bigger than the personality's right to privacy. (This is unlikely to be the case for a game usually, though)

# Public Personalities' Rights

If a person is already in the public, things they have already publicly disclosed are usually fair game. E.g. Michael Jackson grew up giving interviews and talking about private things, so he was pretty much fair game for anything (though his image is still protected, see the story of PopCap and their "Thriller" zombies in Plants vs. Zombies for details), but since he put a blanket over the head of his kid whenever he showed him in public, he grew up mostly protected from press. OTOH had he not done that and other protective measures, it would have been easier for the press to follow the kid's life and report on it.

# Time

Is the personality still alive? Usually, if a person has been deceased long enough, their name and countenance are fair game. So it's fine to have George Washington or Jesus in your game.

However, since there are still organizations that identify with these people, you might want to be careful not to draw their ire (e.g. Monty Python's Life of Brian was famously advertised as "being so funny it was forbidden in Norway" because they considered it putting down Jesus and Christian religions).

There are also countries where certain institutions (like prime ministers, regents etc.) may not be portrayed disrespectfully because they represent the state (e.g. if you make fun of the queen of Great Britain, you might get in trouble there)

# Parody

Parody exemptions. Many countries have them, none agree on what constitutes a parody. But if you're obviously using an exaggerated version of a personality to humorous effect, there are special protections. However, given how subjective humor is, again, if it's not backed by someone else's existing (and accepted as true) description of a personality, you can get in trouble easily.

# Other Miscellaneous Laws

After WWII, for example, Germany enacted laws intended to make it harder to bring back a Nazi movement, which included bans on certain symbols used to represent political groups (mostly runes and the Swastika). I'd expect that if you made a game that painted Hitler in a positive light, you might run afoul of some of those laws and be classified like Nazi propaganda. So even painting someone solely in a positive light might be an issue when it implicitly paints someone else in a negative light (e.g denying the holocaust).

# Money

Even if you know you are legally right, can you afford to fight whoever would sue you over it in court? Depending on your country of jurisdiction, fighting a court battle is expensive. If you're a small indie games developer, even if you get awarded lawyer fees, you still spend every hour in court away from growing your business, processing support and sales, adding new features ... can you afford that? And do you have enough savings to live until the case is decided in a year or so and you actually get paid the awarded fees?

# In Summary

I say "play into it" because, depending on where you are making this game (which can be legally complex if e.g. your graphic designer is in a different country) and where you are selling it (in case of online stores, that can be "everywhere that store can be called up and the payment form works", and also depends on where the company doing the selling resides, e.g. for Apple's store that would be California in the US), some of these laws may apply, and others may not.

But as always, when in doubt, get a lawyer and ask them.

**Fun fact:** TV shows and movies have a dedicated process for clearing character names. They actually make sure a name is very common or does not exist yet so that nobody who has the same name can come to them and and feel libeled.
> 1 votes

---
Tags: legal
---


title: How to remove fragment from VAO?

text:
# Question
Title: How to remove fragment from VAO?
I have the OpenGL VAO object (~40K) to draw the 3D scene

```
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 4, GL_UNSIGNED_BYTE, nullptr);
glBindVertexArray(0);

```

To add some data I can use glMapBuffer:

```
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, (2 * steps) * sizeof(float),
     NULL, GL_STATIC_DRAW);
float *data = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
myFuncAddingData(data,{2.4f, 40.0f, 19.0f});
glUnmapBuffer(GL_ARRAY_BUFFER);

```

Can I to remove (hide/mask) some verteces (3 from 40K) directly from the located in the grafical memory VAO without full complete replacement all of the 40K?

# Answer
> 0 votes
If you would use vertex indices, you could just skip those indices, but you would have to almost completely replace the indices list, which I guess would defeat the purpose of this question.

If you only want to have the visual effect of removing a polygon you can flip the order of vertices and use face culling. Or change the color of the polygon to clear(few ways to do this, but generally hard to do with UV mapping).

Because the data is linearly mapped to memory you can't really just remove data without rewriting your code in a more complicated manner. If you really desire to do this you can.

What I suggest you do is to use GLMultiDrawArrays or GLMultiDrawElements which would allow you to have all the objects in your scene in a single VAO, but you get to specify which you want to draw. The downside is that they all have to use the same state for drawing (rarely an actual problem). The upside is that you use code with minimal driver overhead. Now if you want to add and remove data from this VAO you have to apply your own memory management code so you wouldn't override data that is still in use. I wouldn't worry about deleting the data because your VAO is still linearly mapped and the memory is inaccessible for the GPU anyways and vertex data is rarely a significant part of used memory.

Now if you want to go hardcore on the optimizations you can use GLMultiDrawArraysIndirect or GLMultidrawElementsIndirect, but this requires OpenGL 4.3 or greater. The added benefit would be even less communication with the GPU, but you have to store some data in GPU memory and also manage that.

---
Tags: opengl, 3d, vao
---


title: Random Abstract Art Assignment

text:
# Question
Title: Random Abstract Art Assignment
So I have a school assignment where we have to make a little program that makes random abstract art out of drawn rectangles.

This is what is should look like:

It's the top right element of the canvas.

Now the function has to consist of this: When you press 'backspace' the program should generate a new abstract 'painting' within the boarders and it should consist of 15 new random sized and random colored rectangles.

We work in a custom game engine that our teacher made for us. It uses C# as base.

I basically got everything to work. When I press backspace 15 random rectangles are being drawn on the canvas with random colors. The only problem is that when I press backspace again, only the colors change but not the rectangles.

Here is a pastebin link to the code I made so far: http://pastebin.com/YCrjb2T1

So basically for the colors I made a list (CreateRandomColorList) of int arrays. The int arrays are being filled with 3 random numbers between 0 and 255 (RGB colors). These 3 numbers can be given as parameters to set the color. So everytime you press backspace the rectangles are given new random colors.

I wanted to do exactly the same for the rectangles themselves but that did not seem to work.

There are 3 parameters you can give to a rectangle: The x position on the canvas, the y position on the canvas, the width and the height.

Any insights/tips on what could be wrong would be welcome, I hope my explanation is good enough.

# Answer
> 1 votes
All of the code you need seems to be there. You call `CreateRandomColorList()` when backspace is pressed, but you don't modify the rectangles at all.

So you want to add some code inside the backspace if-statement that also regenerates the rectangles in `Rectangle_Array` which seems to be the array you use to render the rectangles.

```
if (GAME_ENGINE.GetKeyUp(Key.Back))
{
    CreateRandomColorList();
    Rectangle = true;

    for (int i = 0; i < Rectangle_Array.Length; i++)
    {
        Rectangle_array[i] = CreateRandomRectangle();
    }
}

```

Here `CreateRandomRectangle()` is defined as

```
private Rectanglef CreateRandomRectangle()
{
    return new Rectanglef(Kunst.Next(310, 410), Kunst.Next(60, 300), Kunst.Next(0, 100), Kunst.Next(0, 100))
}

```

My C# is a little rusty so there might be a few issues but the basic principles should be there.

In any case, your code that happens inside the backspace checkup should be quite similar to what you do on initialization (assuming that a set of rectangles is displayed on init, otherwise you don't need to do a whole lot other than initialize `Rectangle_Array` to some placeholder values).

---
Tags: c#
---


title: How to use texelFetch

text:
# Question
Title: How to use texelFetch
I'm trying to switch from using the GLSL `texture()` function in my shader to using `texelFetch()` because I want very little processing of the texture pixels (no smoothing), and I want to use pixel coordinates instead of normalized coordinates. I am quite new to GLSL, so I walked through a tutorial that helped me arrive at the following code, which I got working in an OpenTK-based application in C# in Visual Studio 2015 (the form has an `OpenTK.GLControl` control on it called `display`, which is not shown in this code). I wanted to get all the code in one place so I put it all in one file where I could get my head around everything that was involved.

```
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private const TextureTarget texTarget = TextureTarget.Texture2D;

    private void display_Click(object sender, EventArgs e)
    {
        VertexBuffer<ColoredVertex> vb = new VertexBuffer<ColoredVertex>(ColoredVertex.Size);
        vb.AddVertex(new ColoredVertex(new Vector2() { X = 0, Y = 0 }, new Vector2() { X = 1f/4f, Y = 1f/4f }));
        vb.AddVertex(new ColoredVertex(new Vector2() { X = 32, Y = 0 }, new Vector2() { X = 2f/4f, Y = 1f/4f }));
        vb.AddVertex(new ColoredVertex(new Vector2() { X = 32, Y = 32 }, new Vector2() { X = 2f/4f, Y = 2f/4f }));
        vb.AddVertex(new ColoredVertex(new Vector2() { X = 0, Y = 32 }, new Vector2() { X = 1f/4f, Y = 2f/4f }));

        VertexBuffer<ColoredVertex> vb2 = new VertexBuffer<ColoredVertex>(ColoredVertex.Size);
        vb2.AddVertex(new ColoredVertex(new Vector2() { X = 16, Y = 16 }, new Vector2() { X = 2f/4f, Y = 2f/4f }));
        vb2.AddVertex(new ColoredVertex(new Vector2() { X = 48, Y = 16 }, new Vector2() { X = 3f/4f, Y = 2f/4f }));
        vb2.AddVertex(new ColoredVertex(new Vector2() { X = 48, Y = 48 }, new Vector2() { X = 3f/4f, Y = 3f/4f }));
        vb2.AddVertex(new ColoredVertex(new Vector2() { X = 16, Y = 48 }, new Vector2() { X = 2f/4f, Y = 3f/4f }));

        int texture;
        GL.GenTextures(1, out texture);
        GL.BindTexture(texTarget, texture);
        GL.TexParameter(texTarget, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
        GL.TexParameter(texTarget, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
        GL.TexParameter(texTarget, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
        GL.TexParameter(texTarget, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);

        Bitmap bmpTexture = (Bitmap)Image.FromFile(@"C:\Users\Benjamin Marty\Desktop\Test.png");
        System.Drawing.Imaging.BitmapData bmpData = bmpTexture.LockBits(new Rectangle(Point.Empty, bmpTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        GL.TexImage2D(texTarget, 0, PixelInternalFormat.Rgba8, bmpTexture.Width, bmpTexture.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
        bmpTexture.UnlockBits(bmpData);
        bmpTexture.Dispose();

        Shader vshader = new Shader(ShaderType.VertexShader,
            @"#version 130

            // a projection transformation to apply to the vertex' position
            uniform mat4 projectionMatrix;

            // attributes of our vertex
            in vec2 vPosition;
            in vec2 vTexCoord;

            out vec2 vTex; // must match name in fragment shader

            void main()
            {
                // gl_Position is a special variable of OpenGL that must be set
                gl_Position = projectionMatrix * vec4(vPosition, -2.0, 1.0);
                vTex = vTexCoord;
            }");

        Shader fshader = new Shader(ShaderType.FragmentShader,
            @"#version 130

            in vec2 vTex; // must match name in vertex shader

            out vec4 fragColor; // first out variable is automatically written to the screen

            uniform sampler2D tex;

            void main()
            {
                fragColor = texture(tex, vTex);
            }");
        ShaderProgram sp = new ShaderProgram(vshader, fshader);
        VertexAttribute vap = new VertexAttribute("vPosition", 2, VertexAttribPointerType.Float, ColoredVertex.Size, 0);
        VertexAttribute vac = new VertexAttribute("vTexCoord", 2, VertexAttribPointerType.Float, ColoredVertex.Size, 2 * 4);
        VertexArray<ColoredVertex> av = new VertexArray<ColoredVertex>(vb, sp, vap, vac);

        GL.ClearColor(Color.Purple);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        sp.Use();

        Matrix4 projectionMatrix = Matrix4.CreateOrthographicOffCenter(
            ClientRectangle.Left, ClientRectangle.Right, ClientRectangle.Bottom, ClientRectangle.Top, 1.0f, 10f);
        GL.UniformMatrix4(sp.GetUniformLocation("projectionMatrix"), false, ref projectionMatrix);

        vb.Bind();
        av.Bind();
        vb.BufferData();
        vb.Draw();

        vb2.BufferData();
        vb2.Draw();

        GL.BindVertexArray(0);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        GL.UseProgram(0);

        display.SwapBuffers();
    }

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        if (display.Handle != IntPtr.Zero)
            GL.Viewport(ClientRectangle);
    }
}

struct ColoredVertex
{
    public const int Size = (2 + 2) * 4; // size of struct in bytes

    private readonly Vector2 position;
    private readonly Vector2 texCoord;

    public ColoredVertex(Vector2 position, Vector2 texCoord)
    {
        this.position = position;
        this.texCoord = texCoord;
    }
}

sealed class VertexBuffer<TVertex>
where TVertex : struct // vertices must be structs so we can copy them to GPU memory easily
{
    private readonly int vertexSize;
    private TVertex[] vertices = new TVertex[4];

    private int count;

    private readonly int handle;

    public VertexBuffer(int vertexSize)
    {
        this.vertexSize = vertexSize;

        // generate the actual Vertex Buffer Object
        this.handle = GL.GenBuffer();
    }

    public void AddVertex(TVertex v)
    {
        // resize array if too small
        if (this.count == this.vertices.Length)
            Array.Resize(ref this.vertices, this.count * 2);
        // add vertex
        this.vertices[count] = v;
        this.count++;
    }

    public void Bind()
    {
        // make this the active array buffer
        GL.BindBuffer(BufferTarget.ArrayBuffer, this.handle);
    }

    public void BufferData()
    {
        // copy contained vertices to GPU memory
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(this.vertexSize * this.count),
            this.vertices, BufferUsageHint.StreamDraw);
    }

    public void Draw()
    {
        // draw buffered vertices as triangles
        GL.DrawArrays(PrimitiveType.Quads, 0, this.count);
    }
}

public class ShaderException : Exception
{
    public ShaderException(string message) : base(message) { }
}

sealed class Shader
{
    private readonly int handle;

    public int Handle { get { return this.handle; } }

    public Shader(ShaderType type, string code)
    {
        // create shader object
        this.handle = GL.CreateShader(type);

        // set source and compile shader
        GL.ShaderSource(this.handle, code);
        GL.CompileShader(this.handle);
        string info;
        GL.GetShaderInfoLog(this.handle, out info);
        if (!string.IsNullOrEmpty(info))
            throw new ShaderException(info);
    }
}

sealed class ShaderProgram
{
    private readonly int handle;

    public ShaderProgram(params Shader[] shaders)
    {
        // create program object
        this.handle = GL.CreateProgram();

        // assign all shaders
        foreach (var shader in shaders)
            GL.AttachShader(this.handle, shader.Handle);

        // link program (effectively compiles it)
        GL.LinkProgram(this.handle);
        string info;
        GL.GetProgramInfoLog(handle, out info);
        if (!string.IsNullOrEmpty(info))
            throw new ShaderException(info);

        // detach shaders
        foreach (var shader in shaders)
        {
            GL.DetachShader(this.handle, shader.Handle);
        }
    }

    public void Use()
    {
        // activate this program to be used
        GL.UseProgram(this.handle);
    }

    public int GetAttributeLocation(string name)
    {
        // get the location of a vertex attribute
        return GL.GetAttribLocation(this.handle, name);
    }

    public int GetUniformLocation(string name)
    {
        // get the location of a uniform variable
        return GL.GetUniformLocation(this.handle, name);
    }
}

sealed class VertexArray<TVertex>
    where TVertex : struct
{
    private readonly int handle;

    public VertexArray(VertexBuffer<TVertex> vertexBuffer, ShaderProgram program,
        params VertexAttribute[] attributes)
    {
        // create new vertex array object
        GL.GenVertexArrays(1, out this.handle);

        // bind the object so we can modify it
        this.Bind();

        // bind the vertex buffer object
        vertexBuffer.Bind();

        // set all attributes
        foreach (var attribute in attributes)
            attribute.Set(program);

        // unbind objects to reset state
        GL.BindVertexArray(0);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
    }

    public void Bind()
    {
        // bind for usage (modification or rendering)
        GL.BindVertexArray(this.handle);
    }
}

sealed class VertexAttribute
{
    private readonly string name;
    private readonly int size;
    private readonly VertexAttribPointerType type;
    private readonly bool normalize;
    private readonly int stride;
    private readonly int offset;

    public VertexAttribute(string name, int size, VertexAttribPointerType type,
        int stride, int offset, bool normalize = false)
    {
        this.name = name;
        this.size = size;
        this.type = type;
        this.stride = stride;
        this.offset = offset;
        this.normalize = normalize;
    }

    public void Set(ShaderProgram program)
    {
        // get location of attribute from shader program
        int index = program.GetAttributeLocation(this.name);

        // enable and set attribute
        GL.EnableVertexAttribArray(index);
        GL.VertexAttribPointer(index, this.size, this.type,
            this.normalize, this.stride, this.offset);
    }
}

```

The PNG file (texture) I'm using for testing looks like this:

*C:\Users\Benjamin Marty\Desktop\Test.png*

When I run this program and click on the form, I get what I expect:

Now, I change the program to use `ivec2` texture coordinates whose components are of type `Int` instead of `Float`. First I update my vertex buffer code to use pixel coordinates in `Point` structures instead of using `float`-based `Vector2` structures:

```
VertexBuffer<ColoredVertex> vb = new VertexBuffer<ColoredVertex>(ColoredVertex.Size);
vb.AddVertex(new ColoredVertex(new Vector2() { X = 0, Y = 0 }, new Point() { X = 32, Y = 32 }));
vb.AddVertex(new ColoredVertex(new Vector2() { X = 32, Y = 0 }, new Point() { X = 64, Y = 32 }));
vb.AddVertex(new ColoredVertex(new Vector2() { X = 32, Y = 32 }, new Point() { X = 64, Y = 64 }));
vb.AddVertex(new ColoredVertex(new Vector2() { X = 0, Y = 32 }, new Point() { X = 32, Y = 64 }));

VertexBuffer<ColoredVertex> vb2 = new VertexBuffer<ColoredVertex>(ColoredVertex.Size);
vb2.AddVertex(new ColoredVertex(new Vector2() { X = 16, Y = 16 }, new Point() { X = 64, Y = 64 }));
vb2.AddVertex(new ColoredVertex(new Vector2() { X = 48, Y = 16 }, new Point() { X = 96, Y = 64 }));
vb2.AddVertex(new ColoredVertex(new Vector2() { X = 48, Y = 48 }, new Point() { X = 96, Y = 96 }));
vb2.AddVertex(new ColoredVertex(new Vector2() { X = 16, Y = 48 }, new Point() { X = 64, Y = 96 }));

```

Then I update the `ColoredVertex` structure to accept `Point`s instead of `Vector2`s for texture coordinates:

```
struct ColoredVertex
{
    public const int Size = (2 + 2) * 4; // size of struct in bytes

    private readonly Vector2 position;
    private readonly Point texCoord;

    public ColoredVertex(Vector2 position, Point texCoord)
    {
        this.position = position;
        this.texCoord = texCoord;
    }
}

```

I change the `vTexCoord` vertex attribute information to transfer `Int`s instead of `Float`s:

```
VertexAttribute vac = new VertexAttribute("vTexCoord", 2, VertexAttribPointerType.Int, ColoredVertex.Size, 2 * 4);

```

And finally I change my shaders to use `ivec2`, and `flat ivec2` texture coordinate variables instead of `vec2`. I also change my `texture` call to `texelFetch` and add the appropriate `0` parameter to reference LOD 0.

```
Shader vshader = new Shader(ShaderType.VertexShader,
    @"#version 130

    // a projection transformation to apply to the vertex' position
    uniform mat4 projectionMatrix;

    // attributes of our vertex
    in vec2 vPosition;
    in ivec2 vTexCoord;

    flat out ivec2 vTex; // must match name in fragment shader

    void main()
    {
        // gl_Position is a special variable of OpenGL that must be set
        gl_Position = projectionMatrix * vec4(vPosition, -2.0, 1.0);
        vTex = vTexCoord;
    }");

Shader fshader = new Shader(ShaderType.FragmentShader,
    @"#version 130

    flat in ivec2 vTex; // must match name in vertex shader

    out vec4 fragColor; // first out variable is automatically written to the screen

    uniform sampler2D tex;

    void main()
    {
        fragColor = texelFetch(tex, vTex, 0);
    }");

```

After all this, the result I get has something wrong because the texture is all black:

What am I missing?

## Edit

I tried changing the `Set` method of the `VertexAttribute` class to the following code in an attempt to use `VertexAttribIPointer` instead of `VertexAttribPointer` when appropriate in this test cast:

```
public void Set(ShaderProgram program)
{
    // get location of attribute from shader program
    int index = program.GetAttributeLocation(this.name);

    // enable and set attribute
    GL.EnableVertexAttribArray(index);
    if (type == VertexAttribPointerType.Int)
        GL.VertexAttribIPointer(index, size, VertexAttribIntegerType.Int, stride, IntPtr.Add(IntPtr.Zero, offset));
    else
        GL.VertexAttribPointer(index, this.size, this.type,
            this.normalize, this.stride, this.offset);
}

```

The result had an effect, but not the desired effect:

# Answer
To allow the fragment shader to interpolate texture coordinates between the vertices, it was necessary to figure out how to remove the flatness of the vectors being communicated between the vector shader and the fragment shader. One way to do this is to make `vec2` copies of the `ivec2` structures to allow interpolation between the shaders, then type-cast back to `ivec2` in the fragment shader. But why bother casting to float and then back to int when all I'm really trying to accomplish is to use non-normalized coordinates. I can eliminate the need to use `VertexAttribIPointer` altogether and just postpone the casting to ivec2 until the fragment shader. I end up with the original vertex shader that was dealing only with `vec2` structures, and the following fragment shader:

```
Shader fshader = new Shader(ShaderType.FragmentShader,
    @"#version 130

    in vec2 vTex; // must match name in vertex shader

    out vec4 fragColor; // first out variable is automatically written to the screen

    uniform sampler2D tex;

    void main()
    {
        fragColor = texelFetch(tex, ivec2(vTex), 0);
    }");

```
> 0 votes

# Answer
I'm not sure about C#/OpenTK, but in OpenGL when specifying an integer vertex attribute you must use glVertexAttribIPointer, not glVertexAttribPointer; see https://www.opengl.org/sdk/docs/man4/html/glVertexAttribPointer.xhtml

> For **glVertexAttribPointer** ... values will be converted to floats directly without normalization.
>
> For **glVertexAttribIPointer** ... Values are always left as integer values.

I expect that OpenTK has an equivalent.
> 1 votes

---
Tags: c#, opengl, glsl, opentk
---


# Question
Title: How do I get the 3d coordinates of my model Instance? [LibGDX]
I want to get the 3d coordinates (as a Vector3) from my model Instances. with the following code I can only get the original coordinates, but in the render method, my model is rotating around the Y-axis (and moving at the same time) and I want to get its coordinates each frame. I'm using a little class created by @Xoppa :

```
public static class GameObject extends ModelInstance {
    public Vector3 center = new Vector3();
    public Vector3 dimensions = new Vector3();
    public float radius;

    public BoundingBox bounds = new BoundingBox();

    public GameObject (Model model, String rootNode, boolean mergeTransform) {
        super(model, rootNode, mergeTransform);
        calculateBoundingBox(bounds);
        bounds.getCenter(center);
        bounds.getDimensions(dimensions);
        radius = dimensions.len() / 2f;
    }
}

```

and here's my code:

```
public void render(float delta) {
    super.render(delta);
    if (loading && manager.update()) {
        doneLoading();
    }

    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    batch.begin();
    backgroundSprite.draw(batch);
    batch.end();

    for(GameObject instance : instances){
        instance.transform.rotate(new Vector3(0, 1, 0), 0.5f);
        float x = instance.bounds.getCenterX();
        float y = instance.bounds.getCenterY();
        float z = instance.bounds.getCenterZ();
        System.out.println(x+" "+y+" "+z);
        if(isVisible(cam, instance)){
            modelBatch.begin(cam);
            modelBatch.render(instance, environment);
            modelBatch.end();
        }
    }
}

```

Please help, there's no function "getPosition" or sth like that, it's all about Matrix4 and I have never had a math course about it. I'm stuck.

# Answer
> 3 votes
Try something like:

```
Vector3 position;
position = modelInstance.transform.getTranslation(new Vector3());

```

This gets the position and stores it in the `position` vector.

---

Sometimes you might have to transform the transform with the view and projection matrix to get the correct result.

```
/* Make sure that you use a new Matrix4, otherwise you will
   change the models transform, which we don't want to do. */
Matrix4 modelTransform = new Matrix4();
modelTransform.set(modelInstance.transform);
/* Multiply the transform with the combined matrix of the camera. */
modelTransform.mul(camera.combined);
/* Extract the position as usual. */
Vector3 position;
position = modelTransform.getTranslation(new Vector3());

```

This gets the position and stores it in the `position` vector and the transform and stores it in the `modelTransform` matrix. You should probably re-use this vector and matrix every time you get the position instead of creating new ones.

---
Tags: java, libgdx, 3d, coordinates
---


# Question
Title: How to spin Imported FBX model 360* in unity3d
I have been trying to spin my imported wheel from blender 360\* but when I do it, it doesn't rotate on the center (on one spot). I'm using C#.

I have tried this:

```
transform.Rotate(Vector3.forward, 5f - 90);

```

But this doesn't spin on one spot.

# Answer
That is probably because your model's origin isn't in its center. You need to either

1. position your model in Blender so that its center is in the global origin

or

2. change the call to `RotateAround` which you can then for an example pass in `collider.bounds.center` to rotate around your collider's center position.
> 1 votes

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


# Question
Title: How to get surface position from 3D objects in 2D space
I am working on simple drag and drop game with JavaScript and PixiJS. The game itself is 2D, but I have some pseudo-3D objects (I guess isometric) and I am trying to get the position of those objects.

My question is if there is any mathematical equation or algorithm to solve my problem:

I have some fruit objects, and the user should put those objects in the basket I have below, but only in the yellow surface like below in the picture. Currently, I am using the code below to check if the object is inside the basket or not, but this checks the entire texture and not the yellow surface!

```
isInside()
{
    if (this.object.x > basket.x1 && this.object.x <= basket.x2 &&
        this.object.y > basket.y1 && this.object.y <= basket.y2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

```

Which algorithm can I use to check only the yellow surface?

# Answer
Usually, you would specify a shape or mask that would serve as that object's "physical area", so to speak, with which the other objects in the world can interact.

I haven't used Pixi.js, but it seems to me like that concept is realised by the `hitArea` property of an `InteractiveTarget` (see sources). It should be enough to set a polygon of the proper shape as the `hitArea` for the fruit basket object.
> 2 votes

---
Tags: 2d, 3d, javascript, isometric, 2.5d
---


# Question
Title: Why does my capsule collider fall without my object (Unity)?
I've got a player with a rigidbody/capsule collier (gravity enabled) and a plane with a box collider. When the player is on the plane, everything works as expected, the player can walk across the plane with no issue. However, when the player walks off the plane, I want the player to fall. However, what happens instead is that the capsule collider falls but the player just keeps walking in thin air. Why is this happening?

**Problem:**

**Colliders setup:**

**Code:**

```
void Update () {
    i = 0.1f;
    transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + i);
}

```

Sorry if I'm doing something stupid, I'm new to game development/Unity, I usually program other things, not 3D games. Just expiermenting a bit to learn.

# Answer
> 5 votes
In your code you are moving the transform forward and keeping the y value the same at each call to Update(). By doing this your transform cannot drop because the y value is being reset at each call to Update(). A better way to move your character forward would be like this:

```
transform.position += transform.forward * Time.deltaTime * movementSpeed;

```

# Answer
> 4 votes
Welcome to game development world. First of all I suggest to you not to move the player changing the transform values by code. Because, as you can see that can produce weird behaviours. So you have to use the Translate function. I will give you a really good resource, where you can read how to program a really cool control system and learn a bit of the "modus operandi" in Unity.

http://www.habrador.com/tutorials/programming-patterns/1-command-pattern/

Cheers!

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


title: Saving game timer?

text:
# Question
Title: Saving game timer?
When I load my script, `time` starts from zero. How do I save my game timer?

Here is my script:

```
public float seconds, minutes, hours;
public Text levelTimer;
public float GameTime;

// Update is called once per frame
void Update ()
{
    hours = (int)(GameTime / 3600.0f);
    minutes = (int)(GameTime / 60f);
    seconds = (int)(GameTime % 60f);

    levelTimer.text = hours.ToString("00") + ":" +
            minutes.ToString("00") + ":" + seconds.ToString("00");
    GameTime += Time.deltaTime;
}

public void save()
{
    PlayerPrefs.SetFloat("second1",seconds);
    PlayerPrefs.SetFloat("mins1",minutes);
    PlayerPrefs.SetFloat("hour1",hours);
}

public void load()
{
    seconds = PlayerPrefs.GetFloat("second1");
    minutes = PlayerPrefs.GetFloat("mins1");
    hours = PlayerPrefs.GetFloat("hour1");
}

```

# Answer
> 1 votes
In the `Update` method, `hours` `minutes` and `seconds` are always getting updated with `GameTime`, so it won't get the saved preferences. On `load`, you should set your `GameTime` to `seconds + minutes + hours` or just save `GameTime` and use that.

Maybe it's worth that you check TimeSpan. It may help you with this timer and the way of represent it in a string.

---
Tags: unity, savegame
---


# Question
Title: Strategies for using Dijkstra's Algorithm on "larger" (4096+ node) graphs (tower defense)
I am using Dijkstra's for pathfinding in my 2d game, my game is similiar in style to a tower defense game which has waves of monsters trying to reach a goal. I am currently building the paths while loading the level, saving the results, so that I do not need to perform the search during gameplay.

There is only 1 goal node in each level, so for each tile I perform the search to discover the optimal path and then store the next location to move to.

Sample of my search times for building 1 set of paths for a level:

```
4096 Tiles

Total time taken (Milliseconds): 157789
avg time taken to find each path (Milliseconds): 38.000000

1024 Tiles

Total time taken (Milliseconds): 13499
avg time taken to find each path  (Milliseconds): 13.000000

256 Tiles

Total time taken (Milliseconds): 425
avg time taken to find each path  (Milliseconds): 1.000000

```

For added context, here is my search algorithm:

```
struct MatrixPosition
{
    int y;
    int x;
};

struct WeightedNode
{
    int nodeId;
    int weightValue;
};

struct orderLeastWeight
{
    inline bool operator()(const WeightedNode& weightedNode1, const WeightedNode& weightedNode2)
    {
        return (weightedNode1.weightValue < weightedNode2.weightValue);
    }
};

// The Weighted queue always returns the lowest weight value node from get()
class WeightedQueue {
public:
WeightedQueue();
int get();                           // return the item with the lowest weight value and remove it from the map
void push(int weight, int NodeId);   // add item
bool empty();                        // is it empty
private:
std::vector <WeightedNode> mNodeVec; //  nodeId
};

WeightedQueue::WeightedQueue()
{

}

void WeightedQueue::push(int weightValue, int nodeId)
{
    WeightedNode weightedNode;

    weightedNode.weightValue = weightValue;
    weightedNode.nodeId = nodeId;

    mNodeVec.push_back(weightedNode);
    std::sort(mNodeVec.begin(), mNodeVec.end(), orderLeastWeight());
}

bool WeightedQueue::empty()
{
    return mNodeVec.empty();
}

int WeightedQueue::get()
{
    int nodeId = mNodeVec.begin()->nodeId;

    mNodeVec.erase(mNodeVec.begin());
    return nodeId;
}

void Board::setMatrixPositions()
{
    for (int i = 0; i < mTileCount; i++)
    {
        MatrixPosition matrixPosition = { i / mTileRows, i % mTileRows  };
        mMatrixPosition[i] = matrixPosition;
    }
}

int Board::getTileId(MatrixPosition matrixPosition)
{
    int tileId = mTileRows * matrixPosition.y + matrixPosition.x; // left to right

    return tileId;
}

int Board::getTileId(int tileIdX, int tileIdY)
{
    int tileId = mTileRows * tileIdY + tileIdX; // left to right

    return tileId;
}

MatrixPosition Board::getMatrixPosition(int tileId)
{
    return mMatrixPosition[tileId];
}

// reconstruct the path taken
void Board::setPath(int startTileId, int endTileId, AIStrategy aiStrategy, std::map<int, int> & cameFrom)
{
    std::vector<int> path;
    int currentTileId = endTileId;
    path.push_back(currentTileId);
    while (currentTileId != startTileId)
    {
        currentTileId = cameFrom[currentTileId];
        path.push_back(currentTileId);
    }
    std::reverse(path.begin(), path.end()); // invert order to be start->end

    if (path.size() >= 2)
    {
        mTileMap[startTileId]->setPath(aiStrategy, path[1]); // set path to the first move
        // printf("setPath -- %d -> %d \n", startTileId, path[1]);
    }
}

// search the board for the optimal path
void Board::findPath(int startTileId, int endTileId, AIStrategy aiStrategy)
{
    std::map<int, int> cameFrom; // neighborTileId, current tileId
    std::map<int, int> costSoFar;    // total cost so far for the path from startTileId
    std::vector<int> neighbors; // vec of the neighboring tileIds

    WeightedQueue weightedQueue;
    weightedQueue.push(0, startTileId); // Lowest weight item moves to the front of the queue
    costSoFar[startTileId] = 0;
    cameFrom[startTileId] = startTileId;

    while (!weightedQueue.empty())
    {
        // current tile we are working with
        int currentTileId = weightedQueue.get();

        // exit if we've reached the goal tile
        if (currentTileId == endTileId)
        {
            break;
        }

        // get all the neighbors for this position
        neighbors.clear();
        collectNeighbors(currentTileId, neighbors);
        for (size_t i = 0; i < neighbors.size(); i++)
        {
            int neighborTileId = neighbors[i];
            Tile *neighborTile = mTileMap[neighborTileId];

            int totalCost = costSoFar[currentTileId] + neighborTile->getWeight(aiStrategy);
            if (!costSoFar.count(neighborTileId) || totalCost < costSoFar[neighborTileId])
            {
                // if we haven't been here yet, add it to the weightedQueue
                weightedQueue.push(neighborTile->getWeight(aiStrategy), neighborTileId);
                cameFrom[neighborTileId] = currentTileId;
                costSoFar[neighborTileId] = totalCost;
            }
        }
    }
    setPath(startTileId, endTileId, aiStrategy, cameFrom);
}

// [ 0][ 1][ 2][ 3][ 4]
// [ 5][ 6][ 7][ 8][ 9]
// [10][11][12][13][14]
// [15][16][17][18][19]
// [20][21][22][23][24]
void Board::collectNeighbors(int tileId, std::vector<int> & neighbors)
{
    MatrixPosition tile = getMatrixPosition(tileId);
    const int x = tile.x;
    const int y = tile.y;

    if (y > 0) // otherwise an underflow occurred, so not a neighbour
    {
        int up = y - 1;
        int neighborTileId = getTileId(x, up);
        neighbors.push_back(neighborTileId);
        // printf("up -- neighborTileId: %d y: %d x: %d\n", neighborTileId, up, x);
    }
    // down
    if (y < mTileRows - 1)
    {
        int down = y + 1;
        int neighborTileId = getTileId(x, down);
        neighbors.push_back(neighborTileId);
        // printf("down -- neighborTileId: %d y: %d x: %d\n", neighborTileId, down, x);
    }
    // left
    if (x > 0)
    {
        int left = x - 1;
        int neighborTileId = getTileId(left, y);
        neighbors.push_back(neighborTileId);
        // printf("left -- neighborTileId: %d y: %d x : %d\n", neighborTileId, y, left);
    }
    // right
    if (x < mTileColumns - 1)
    {
        int right = x + 1;
        int neighborTileId = getTileId(right, y);
        neighbors.push_back(neighborTileId);
        // printf("right -- neighborTileId: %d y: %d x: %d\n", neighborTileId, y, right);
    }
}

```

Here is my question:

What I'm currently doing works fine if I wanted to keep my level sizes small (256) or pre-generate larger levels. However the problem is that I would really like to support large maps (4096+ tile) and I want to allow the player to change the level. However with the search taking 2-3 Minutes on a 4096 node graph that's not an option even if I did it between "waves" of monsters.

Looking for other ideas to this problem, one thing I thought of was that I could pre-generate the initial level save the complete path to the goal on every tile along with their total costs. Then, between waves of monsters I would only need to update the weight values of those tiles which changed, re-sum the weight totals for the changed paths, and re-order the paths.

Appreciate any thoughts on that, or any other suggestions.

# Answer
> 3 votes
Don't search every tile-path. Most of your data is going to be redundant. If there is a solution for tile a, going through tiles b,c,d,e,f - goal then the solution for tile b is by definition c,d,e,f - goal. Your goal shouldn't be solving for which path from tile X is the best. But rather, assigning directional vectors to all tiles and the direction each of them should go for the optimal path. If I am on tile X, which direction do I go. The answer to that is *always* the same, regardless where you came from.

So you want to actually solve from the goal, outward painting every spot with an optimal direction vector. Basically you can do this by what amounts to Dijkstra's, giving each node you see traveling backwards from the goal with an optimum amount you can offer with that direction, and if it currently has a better option, pass, else give that tile that direction. Until all tiles have been visited and have the optimal path. It should take a few milliseconds to complete.

# Answer
> 3 votes
Dijkstra's Algorithm uses a *priority queue* as its main data structure. In your code it's `WeightedQueue`.

A priority queue can be implemented with O(log N) insert and O(log N) remove. Your queue has O(N log N) insert and O(N) remove. This doesn't matter for small N but as you've found, as N increases, it's too slow.

I suggest using `std::priority_queue<WeightedNode>` instead of `std::vector<WeightedNode>`; I have some code here you can look at.

---
Tags: algorithm, ai, path-finding, dijkstra
---


# Question
Title: Timebased transition from start to end value
I'm trying to implement time line objects, the purpose of those would be to issue events at specific times. When and what is specified through objects called units, which is what you attach in the time line.

Got two types of time units, Action and Transit. Action counts to the end of the time unit, then issue whatever event with provided values intact.

My problem is Transit, which, frame by frame, modifies provided value(s) by multiplying time ratio before issuing the event.

I calculate ratio as: (in pseudo code)

```
ratio = (counter += delta time) / unit end time

```

My issue is that I keep getting either different results, or unbalanced progress, like adding 90% of the value quick then the last 10% of value at a much slower phase.

I've tried something like (in pseudo code) so far:

```
delta value = (end value - earlier delta values) * ratio

```

for each new frame.

Not sure how to put this together, so could really use a few pointers on this. Hope I made myself clear.

PS. I'm doing this in JavaScript, I know JS isn't the most accurate language when it comes to precision numbers, but it should be able to handle something like this.

Thank you in advance.

# Answer
I managed to figure it out. I wasn't supposed to keep track of already applied delta times, but applied ratios.

Pseudo code.

```
ratio = (counter += delta time) / transition end time

if(ratio > 1)
    ratio = 1

ratio -= ratios
ratios += ratio

result = value * ratio

```

Even after 20+ subsequent 1000ms transitions which increase the same value, the result values offset was less than .0001 against expected, so I'm satisfied with this.
> 0 votes

# Answer
Considering how the ratio is calculated, the culprit seems to be the delta time (time step). It is the only variable that depends on unknown factors in the context of the calculation.

The issue described is likely caused by a variable time step. In that case, the counter would not increment uniformly, but faster or slower depending on arbitrary conditions.

A fixed time step should provide you with the behaviour you're looking for. Then the counter increments would always occur at the same rate.
> 2 votes

---
Tags: mathematics, javascript, timestep
---


title: VB.NET game engine drawing sprites

text:
# Question
Title: VB.NET game engine drawing sprites
I have been looking into making a game engine using VB.NET but I'm having some trouble finding how I would draw stuff to the screen. In some places, people draw to the screen using the picture box control but I have read else where that it is not recommended to do this as I will run into problems in the future if I draw to a picture box

So I would like to know what would be the best way to draw sprites etc. to the screen. Is it OK to use picture boxes or is there another way?

# Answer
I once started with VB.NET and the Picture Box control to create a Bejeweld like game. This worked out fine, but the game had no effects and was very static. People are right by stating that you'll run into trouble as soon as you want anything more dynamic.

Therefore, I'd recommend using some .NET framework such as XNA, which allows you to draw sprites easier and far more efficiently. Visual Basic XNA Example on MSDN explains how to do exactly this.
> 2 votes

# Answer
XNA\MonoGame will get you up and running almost over night but I would not get to deep into XNA because while I loved it and it was awesome to get me started by the time you are good with the API you will be wanting to move over to sharpDX, then have to unlearn heaps of stuff that XNA lets you do and get used to the power DX11 brings.

I came in to XNA just before they dropped support and I wish I had moved to sharpDX sooner because its a bit harder but I found that having to write all my own tools and framework to be very rewarding.

I use the sharpDX toolkit for all my 2d stuff and raw sharpDX for the rest, the toolkit also looks just like XNA so moving to the sharpDX toolkit is easy once you get your head around XNA.

SharpDX.Toolkit

My point is, use XNA to get your feet wet but don't get to locked in and move over to sharpDX as soon as you can.

Because not many ppl seem to do fun stuff with VB.net you will have to convert the XNA samples from C# to VB.net and there are some parts of sharpDX that need to be changed in order to work with VB.net.

I know sharpDX seems like a lot of work, it is but its worth it in the end.

GitHub is your friend and the sharpDX dev is a beast and knows his shit, I'm also proly going to add a VB.net repo for sharpDX to my GitHub(at some point).
> 0 votes

---
Tags: sprites
---


# Question
Title: How to start simple game development with Unity 5
I want to start developing games with Unity because it's easy to learn, but I don't know where to start.

My questions are: \- Which preparations should I make for a game? \- Are there any tips and tricks for efficient work? \- Do I need special equipment?

Thank you for your response!

# Answer
> 1 votes
That's a big question. I'll give you a general set of ideas of what to pick up, but do note that the most important thing is to **always be eager to learn new things**. Game development is so big that you will need that to enjoy it.

Here are the main components you'll need to make any sort of a game ( you don't need any special equipment whatsoever ):

**Programming**

You do not need to be an expert programmer for game development. Some roles do not **need** programming skills. I do, however, highly recommend for everyone involved to be capable of scripting.

For being successful as a game developer ( as in writing the code ) - you will obviously need to be an expert in programming. You can start learning at Code Academy, Khan Academy, Coursera, and EdX to name a few.

Even if you're striving to design games - you'll better get good coding skills. You will be the best person to create the initial versions of your designs to show them off to the public or to give your friends/coworkers/testers to play around with ( to gather testing data ).

Nowadays even artists could use some basic scripting to make their life easier - Photoshop scripts, shaders and even some logic can help them achieve the perfect look that only textures might not be able to do alone.

**Game Design**

Play a lot of games. But don't just absorb the story - focus on how the game works and why it works. Build up systems and form ideas for games that already exist.

Prototype a lot - create a lot of mini projects to test different concepts and designs. Gather data and use it to improve them. AB testing and stats are your best friends.

For something more academic check:

**Unity3d**

Unity3d is huge. You should start with the official resources:

There is a lot of places to learn unity from, but those should give you a good start. If you get frustrated with anything - the forums are filled with discussions and people who might prove helpful and YouTube is filled with great examples you can follow along.

**Fin**

If you've never done any of that before - take it slowly. Start simple and gradually build better games. Find mentors and other people that can help you grow. Ask a lot of questions and make great games!

---
Tags: unity, game-design, game-mechanics, unityscript
---


# Question
Title: Developing interesting game mechanics when not an avid gamer
I've realized that though I like playing videogames, I find it much more entertaining to actually *make* them. This makes me wonder, if I'm planning to develop an \[X\]\* game, do I need to be an avid \[X\] gamer? How can I develop interesting mechanics if I play that genre sparingly?

In order to get empirical answers, I'm more interested in listening to the opinion of those who have worked/are working in the game industry. Are you and your co-workers avid gameplayers or "casual" gamers? What about the Schafers, Carmacks, McGees and Gilberts of the industry (should anyone know any of them :) )?

\*being \[X\] any game genre: Platformer, RPG, RTS, FPS, etc.

PS: I'm trying to make this question as subjective-less as possible, so feel free to point any improvements.

# Answer
**Why playing is important...** If you were designing the interior seating and controls of a car would you start by never sitting in one or driving? You might be able to eventually design that interior, but you would been reinventing wheels all over the place and you would likely build an interface that would alienate users who were used to the steering wheel + 2 or 3 pedal conventions.

**Understanding genre conventions**: You should always take a look at the top games in whatever genre you plan on making. Your players are going to attempt to interact with your game based on expectations of having played those other titles. That doesn't mean that you can't deviate from the established conventions of a genre, but when you do deviate it should only be for something your title is focusing on.

**See how things go wrong:** I would also suggest playing a few of the lowest rated games in your target genre. Learning from good games is often hard as it can be difficult to nail down precisely what makes a system work since it can be effected by multiple elements. On the other hand with bad games, it is often incredibly easy to get a feel for what doesn't work. This lets you avoid making those same mistakes in your game.

**Do designers play?** Yes, all the time, and not just video games. Boardgames, card games, miniature games, physical sports. Playing a wider variety of titles is a great way to pick up on little mechanics or rule combinations that you can add to your toolbox for future titles. However, there is a big difference between playing a massive number of games, and playing a massive amount of one game. Spending massive numbers of hours in WoW or Call of Duty or whatever your interest might be is fun, but not directly helpful to designing. You only need to spend enough time with a game to see it's range of content and then move on. By all means keep playing for enjoyment, but at that point it's no longer research.
> 11 votes

# Answer
You ought to play the type of game you are developing at least some so that you understand how the game type works.

One advantage of not playing too much is that your mind doesn't get filled with the ideas of other people. Give yourself a chance to think of things that are new and different.

One great way to at least get an introduction to new games is to play free demos. A few years back I went on a kick of playing all the 10 day free trials of MMOs I could find.
> 8 votes

# Answer
It's important to do your research.

Playing other peoples' games is a great way to get some case studies. See how their controls compare to yours. See what features you have that they don't, and vice versa. You can also pull from these games to see what gamers *expect* who play that genre of games. This is particularly important to controls.

That being said once you get the core feeling down, the rest of it is usually just details that can be skipped over. You don't need to know the storyline, settings, or particular puzzles that other games in the same genre employ to make your own game. But if you're making a platformer, you'd better know that your movement and jumping is as good as the other games. If you're making a console FPS you should play games that get aiming down properly. Modern RTS games all have a "select idle resource gatherers" key binding, which unless you're making a game without resource gathering you should also include because the players expect it.

So no, you don't have to play games religiously in order to make good games. You do have to have an analytical, player-focused mindset, and most players do play other games and have certain expectations. Not fulfilling those expectations can lead to disappointments.
> 4 votes

# Answer
In some games, there´s an special "behind the scenes" documentary where the interviewees talk about their gaming habits.

Lately, I´ve watched those from God of War, Heavy Rain and Uncharted 2.

Personal opinion: You don´t have to be a hardcore gamer but at least try to play those games similar to the one you want to make.
> 3 votes

# Answer
Gaming can quickly teach you the standard way of doing things in genres. This is **awesome** because you get to know a lot of great practices very quickly. On the other hand this could be **harmful** because you get used to seeing things in a very conventional way.

The best way to learn to make games is to actually **make games**. The question is how to make games quickly and efficiently so you can learn from thousands of projects, instead of just a few.

The answer is **rapid prototypes**. You quickly mock-up a partial game ( might be a few mechanics or even a whole level ) and get feedback on it. Then iterate again and get more feedback.

Getting feedback on a game is another beast on its' own, but for some general advice:

* AB test a lot of ideas
* Get relevant metrics ( how many plays, how long, what meaningful actions did the player take, what did they miss )

Overall, I'd suggest in being educated on new games and how they work because it can potentially save you tons of time solving a problem that someone already solved. But don't play too much because you'll lose precious time that you might've put into making games.
> 1 votes

---
Tags: game-design, game-mechanics
---


title: HLSL mipmapping not working

text:
# Question
Title: HLSL mipmapping not working
I want to implement a mipmap filter in my 3D game, so that textures which are located far away are using a lower resolution than the original. For the shader I'm using hlsl version 4\_0\_level\_9\_1 or 4\_0 depends on which one I will get this running. I have tried this:

```
texture Texture;
sampler diffuseSampler = sampler_state
{
    Texture = (Texture);
    MAGFILTER = ANISOTROPIC;
    MINFILTER = ANISOTROPIC;
    MIPFILTER = ANISOTROPIC;
    AddressU = Wrap;
    AddressV = Wrap;
};
[...]
Color PixelShaderFunctionTex(VertexShaderOutputTex input)
{
    return tex2Dlod(diffuseSampler, float4(input.TexCoord, 0.0, 0.0));
}

```

in vs\_4\_0 it still uses the full-res texture. And in vs\_4\_0\_level\_9\_1 it won't even compile: "texlod not supported on this target"

I could manually generate the downscaled textures, but there must be a way to only input one texture and let hlsl do the rest.

In short: How to apply the mipmap filter in hlsl?

# Answer
You don't.

Unfortunately some online resources don't make this explicit, but the code you've given is actually not HLSL; instead it's part of the old (and deprecated) effects framework. What actually happens if you use the effects framework (which is nothing more than a wrapper around the D3D API) is that a shader object and a state object will be created and set for the current draw call.

In the absence of the effects framework (which I assume because you actually have to intentionally set out to use it these days) you need to create your own sampler state object and set it.
> 2 votes

# Answer
That there is DX9 HLSL

You want something like this:

```
Texture2D Texture : register(t0);;
sampler diffuseSampler : register(s0);

struct VertexShaderOutput
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;

};
// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VertexShaderOutput VSQuad( uint vertexID : SV_VertexID )
{
VertexShaderOutput result;
result.TexCoord = float2((vertexID << 1) & 2, vertexID & 2);
result.Position  = float4(result.TexCoord  * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
return result;
}

float4 PixelShaderFunctionTex(VertexShaderOutput input) :SV_Target0
{
// float3(UV,Mip)
float4 color = Texture.SampleLevel(diffuseSampler, float3(input.TexCoord, 0.0f));

return color;
}

```

then like Le Comte du Merde-fou said, set all state by hand.

like this:

```
  _Context.XXXXShader.SetSampler(0, yourSampler)
  _Context.XXXXShader.SetShaderResource(0, yourSRV)

```

ps. that's sm 5.0 but I think sm 4.0- m 5.0 is close if not the same and you wont need the vertex shader, that's just a bonus incase u want a cool way of doing full screen quads too.
> 1 votes

---
Tags: 3d, hlsl, level-of-detail
---


title: Backing up non-text based assets

text:
# Question
Title: Backing up non-text based assets
I'm using a Source Control Management tool (*git*) for backing up configurations, code etc. But how do I manage art assets and other game assets that are in binary formats, and tend to be big (animators, audio sources etc)?

The working theory is to backup all assets using cloud storage services like *Google Drive* or similar. But how do you effectively manage your projects? That would work for me being solo, but if I added another team member, how would I effectively manage projects while multiple developers/artists are contributing?

I'm working with Unity, if it's relevant.

# Answer
> 2 votes
If you specifically mean revisioning large assets, GitHub has recently come to your rescue: Git Large File Storage :)

Git LFS is supported by GitHub, BitBucker Server, Visual Studio Online, and GitLab. I'm sure some of the more boutique Git services have it as well, and you can install git-lfs on any servers you've manually configured.

There's also source revision systems designed with game-like development in mind. For instance, Plastic SCM has a kinda-sorta git-like model, support for large binary assets, various GUI tools optimized around 3D assets, and they even have a Unity plugin ready to go.

Alternatively, you could use a non-distributed revision system. Many developers in our industry really have no use for the "distributed" model of git or Mercurial and mostly just want the cheap branching and merges. Perforce and the like are slowly getting less terrible in this regard.

# Answer
> 0 votes
For game development, Perforce is an excellent version control system. The reasoning is, aside from being able to handle anything you throw at it, it works well for the developer who only works from the command line, to the artist who prefers having an application to manage their assets.

The Perforce server has a free model that you can use, either for open-source projects or for yourself at home.

If you need to work in a disconnected fashion, Perforce supports it's own native DVCS in addition to already having support for Git.

I am currently using the DVCS feature in Perforce for a small iOS game I'm been doing on the side: I prefer the p4 command line apps over the git ones as it is something I worked longer with and is easier to grasp over git.

---
Tags: unity, asset-management, version-control, asset-workflow, workflow
---


# Question
Title: Texture color change not working on custom effect
I'm new to custom effects (ex. pixel shaders) in monogame, but I've researched a bit and made some test effects.

I've noticed that the color variable **"Color.\[color\]"** doesn't change the color of the texture when an effect is active.

**example:**

I can't draw text that uses the effect, because the text doesn't turn black, it stays white.

This is my custom shader file:

```
sampler2D TextureSampler = sampler_state
{
    Texture = <Texture>;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float4 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = tex2D(TextureSampler, texCoord);

    float high = .6;
    float low = .4;

    if (color.r > high) color.r = 1;
    else if (color.r < low) color.r = 0;

    if (color.g > high) color.g = 1;
    else if (color.g < low) color.g = 0;

    if (color.b > high) color.b = 1;
    else if (color.b < low) color.b = 0;

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

And this is an example of the color change that doesn't happen:

```
spriteBatch.DrawString(font, [text], [position], Color.Black);

```

When the program starts (with the effect on), the text stays white and doesn't turn black. The effect works on all the other textures, when they don't need a color change.

Is this because of the sampler in the effect file?

**EDIT**

My question is actually if I can use the "Color.\[color\]" variable with a custom effect, or do I need to add a color parameter to the effect?

I ask this because I also have a button class that draws buttons with text on it. The draw function for the button draws the text and the button at almost the same time. color change for the text is written in that button class (ex. Color.Black). But when I use the custom shader, it doesn't work.

I'm also not sure if this will work with hlsl parameters for the colors, because I don't know how to seperate the button and the text with a hlsl shader, and only change the color of the text.

# Answer
Something like this should work, I use it for drawing my sprites with sharpDX toolkit.spritebatch so I'm hoping with some changes it may work for you.

HLSL:

```
Texture2D<float4> Texture : register(t0);

// SpriteBatch expects that default texture sampler parameter will have   name 'TextureSampler'
sampler TextureSampler : register(s0);

// SpriteBatch expects that default vertex transform parameter will have name 'MatrixTransform'
row_major float4x4 MatrixTransform;

void VSMain(
inout float4 color : COLOR0,
inout float2 texCoord : TEXCOORD0,
inout float4 position : SV_Position)
{
position = mul(position, MatrixTransform);
}

struct PixelShaderOutput
{

float4 Color : SV_Target0;

};

// Blurs the input image horizontally
PixelShaderOutput PS(float4 color : COLOR, float2 UV : TEXCOORD0) : SV_Target0
{

PixelShaderOutput output = (PixelShaderOutput) 0;
float4 c = Texture.Sample(TextureSampler, UV);

output.Color.rgb = color.rgb * c.rgb;
output.Color.a = c.a;

return output ;
}

technique Tech
{
pass P0
{

    SetVertexShader(CompileShader(vs_5_0, VSMain()));
    SetPixelShader(CompileShader(ps_5_0, PS()));
}
}

```

Or something like this could work(made a change to your code)

```
sampler2D TextureSampler = sampler_state
{
Texture = <Texture>;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0,    float4 texCoord : TEXCOORD0) : SV_TARGET0
{
float4 color = tex2D(TextureSampler, texCoord);

float high = .6;
float low = .4;

if (color.r > high) color.r = 1;
else if (color.r < low) color.r = 0;

if (color.g > high) color.g = 1;
else if (color.g < low) color.g = 0;

if (color.b > high) color.b = 1;
else if (color.b < low) color.b = 0;

return color1 * color;
}

technique Technique1
{
pass Pass1
{
    PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
}
}

```
> 1 votes

---
Tags: c#, monogame, hlsl
---


title: Align spawned particle system

text:
# Question
Title: Align spawned particle system
I am working on a game in which tanks can shoot at each other. I intend to spawn a spark particle system (particles emit to Z) when a bullet hits a surface. I want to align the Z axis of the newly spawned particle system to be

a) in a 90 degree angle to surface that has been hit b) in a reflective angle from the original trajectory

I know that I can "fake it" by setting particle Z to World 90 degrees, however then it will do so on any angled surface, while I would like to have the particle system dynamically orient itself in a 90 degree angle away from the surface that has been hit/ or reflect into the direction away from the incoming bullet.

hope you can help me, getting quite frustrated.

# Answer
Usually what I do in that case after the instanciation of the transform is that :

```
sparksTransform.forward = hitPoint.normal;

```

And normally that's all there is.
> 1 votes

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


# Question
Title: Implementing Skyrim's save system in Unity
Unity has it's own way of saving in which you can add values and any type of information to the registry and it will be saved for future use. However what happens when you try to create a more complex save system such as the one featured in Skyrim. In this case it even get's a screenshot of the moment you pause the game to save and uses it to identify the save file. Also all the current actions the user and the npcs where doing at the moment gets save. How can I implement this complex save system into unity using it's current way of handling save data?

# Answer
> 4 votes
Skyrim actually does not look like it uses an individual record for every enetity on the screen. It actually seems like it does something a little less creative and more robust.

If you take a look at the source code for OpenMorrowind, they did quite a large amount of reverse engineering, and a good look at some of it's entity and script code showed me that Skyrim and Oblivion actually uses a very massive Database.

So instead of iterating over everything at once, assuming you can keep some amount of locality, Or be able to quickly blast through several lists, you can just write your data to a file and patch the pointers later.

The trickier part is recording the data in the scripts. But interestingly enough, Skyrim actually stores all variable data and animation data in the database as well. So you can load back into a game in the middle of a fight, or with a lot of actors near you animating instead of starting off in a standing pose.

In my current game engine, I'm actually heavily basing it's data system off of this fact, but using Lua. The benefit is that I can actually easily implement mods now and not worry about data conflicts.

# Answer
> 1 votes
Well what I would do is have each actor have a SaveMe method. On Save all the active actors (ie. The ones in the vincinity) will call that method.

That pre supposes that you have a manager that tracks either all objects or all relevant objects.

Also that SaveMe method should take a ref of the save file (xml is great) and append it's own relevant info in it. (maybe you could also do that with a binary of the game objects that you store to bytes instead)

And finally your save manager should store another file, that keeps track of all the existing save files, their path, and takes care of taking and storing the screenshots. (with a binary save file you could store the screenshots inside the save file)

---
Tags: unity, savegame
---


title: Is it ok to mix shader types?

text:
# Question
Title: Is it ok to mix shader types?
The title might not be precise. Let's say I have one material consisting of vertex and pixel shader, another one consisting of vertex, geometry and pixel shader, and yet another one consisting of vertex, hull, domain and pixel shader. I use these 3 materials (shaders) for 3 different objects. If I want to render all 3 objects in one frame can I just apply the first material, render the first object, apply the second one, render the second object and the same with the third one? Is there any restriction to "mixing" shader types this way?

I think there isn't but I'm asking because I'm getting a strange bug in my application. I have 1 material using only vertex and pixel shader and another one using tessellation (vertex, hull, domain and pixel). When I render only 1st object everythings works fine. If I render only 2nd object everythings works fine, as well. But when I try to render both in one frame my application seems to freeze/crash and I get system notification that my graphics card driver crashed. Am I using shaders incorrectly or should I just look for some bug in my code?

**Update:**

When I assigned a tessellation shader to my first object as well and tried to render both objects... it worked. Or at least it didn't crash like before. And it's a different shader (material) but with the same stages (vertex, hull, domain, pixel) as the other object's material.

Again - is there any restriction to mixing tessellation shader with non-tessellation one?

**Update:**

Found the culprit - my tessellation shader (vertex, hull, domain and pixel) set 4 stages as active and my other shader (vertex and pixel) used only 2. But I never disabled the unused shader stages (hull and domain) which caused the crash. Still, the main question was "Is it ok to mix shader stages?" which Sean's just answered.

# Answer
> 3 votes
**Yes it is ok to mix shader types.**

There is no restriction to mixing up use shader stages.

The crash is being caused either by something specific you're doing incorrectly or a driver bug. Turn on the debug layer or trying using the WARP driver when setting up your D3D context. You can also try running under a graphics debugger; NVIDIA, AMD, and Intel have hardware-specific tools and Microsoft supplies hardware-independent tools.

And of course, make sure your driver is up to date, all Windows patches are applied, etc.

# Answer
> 3 votes
Yes you can mix shaders, I have around 25 shaders that run per frame from terrain shaders using the full pipeline to post processing.

You are getting the crash because after you bind shaders to hull, domain or geometry stages you need to unbind them before you draw with a shader that doesn't use that stage.

My terrain shader uses everything but the geometry shader so before I switch back to none terrain rendering I unbind the hull and domain shaders and reset the primitive type or I get a driver lock up.

---
Tags: shaders, directx11
---


# Question
Title: I can't set the Source image for a UI image; how to fix it?
I am new to Unity. As a learning project, I started to make a very basic car racing game. In order to add an on-screen speedometer for my car, I imported an image UI.

The problem is that I can't set a source image for my speedometer UI. I tried using .jpg .png or .psd image files as well. In any case, I'm not able to drag and drop the image.

Under the list *Source Image*, I already have selected *UISprite* from the drop-down list, but still, I'm not able to set source image.

Can anyone provide me any solution? I also have attached a screenshot of what I have.

# Answer
> 3 votes
Click on the imported image. You should see a dropdown in the inspector that says "texture". Change it to "sprite and UI" if not already. Now you should be able to change the source image of the blank image to your desired image.

---
Tags: unity, gui
---


title: How to clear the scores?

text:
# Question
Title: How to clear the scores?
My issue is when I exit the game the lives and scores still appears in my game menu so how do I clear them after I quit the game and get back to the menu?

# Answer
> 3 votes
Just set an event which triggers the following GML code:

```
// Clears current lives and score
lives = 0;
score = 0;

```

That's it.

# Answer
> 1 votes
You can use the "Enter Room" event and then set the lives and score to an arbitrary value of your choice. You can also set so it doesn't draw with the built in function.

---
Tags: game-maker
---


title: Gamemaker display orientation detection

text:
# Question
Title: Gamemaker display orientation detection
I am making a game that needs to detect when the device gets turned over in landscape mode to landscape-flipped to change some game mechanics when the player does so. The project is already set to work only in those two orientations.

I am using an object instantiated in the room with the following code in Step :

```
show_debug_message("Orientation : " + string(display_get_orientation()));

```

But I always get the same input - either "landscape" or "landscape-flipped" and it doesn't seems to change the output in runtime, although if I press the power button on the phone and the game goes in pause, if I flip the phone and I return to the game I get the opposite status, but it keeps repeating itself, as it could not read the real orientation of the phone.

Anyone has faced this problem before?

Cheers!

# Answer
After trying different options I finally achieved the result I wanted using the get\_tilt\_x() function, so:

```
if ((os_type == os_android) || (os_type == os_ios) || (os_type == os_tizen))
{
    show_debug_message("Mobile device detected" + string(orientation));

    //this always prints the same orientation:
    show_debug_message("Orientation : " + string(display_get_orientation()));

    //this is how I solved it:
    if (device_get_tilt_x()<0)
    {
        //flipped state
        show_debug_message("X: " + string(device_get_tilt_x()));
        show_debug_message("ORIENTATION FLIPPED");
        //do something in flipped state
    }
    else if (device_get_tilt_x()>=0)
    {
        //normal state
        show_debug_message("X: " + string(device_get_tilt_x()));
        show_debug_message("ORIENTATION NORMAL");
        //do something in normal state
    }

}

```

Special thanks to Dmi7ry for his advice!

Cheers!
> 0 votes

---
Tags: game-maker, screen, orientation
---


# Question
Title: Create a seemless grid-based polygonal tileset
The aesthetics I am going for is demonstrated by many simulation games such as *Simcity*. But I am looking at this particular example: *Polygonal Planet Project* by *Oskar Stålberg*.

I understand the concept: when the player places or upgrades a tile, the game looks at adjacent tiles to figure out which tile should be used. And in most cases, a tile would be self-contained, so I just need to design all possible variant of such tile.

And I have some experience on procedural generation in 3D, so coding isn't the main problem for me.

What I am wondering, are:

* **Does this type of continuous 3D tilesets have a name**? I tried to google some examples/tutorials but failed to find the appropriate keyword.
* **Are there tools to make the process of creating tile variants easier**?
* **Is there a preferable process to create such tileset?** Do I start by creating structures then divide them into repeatable patterns, or should I start with basic tiles and find way to create smooth transition between them?

That's probably too much to answer in detail, but I would like some pointers on this topic (more about asset design than programming I suppose). Thx!

# Answer
This can be done with a generalization of Wang Tiles or Corner Tiles. These associate labels with the boundaries of a tile, and enforce the constraint that two tiles that meet along a particular boundary must have matching labels. This lets us create tiles tagged with these labels and ensure that there will be no visible seams, because the label constraint controls which tiles can abut one another.

* Wang Tiles associate a label with each (oriented) edge in the grid.

(If your data is stored at the vertices, you can create an edge label from an ordered pair of vertex labels - eg. "this vertical edge goes from \[water\] at the bottom to \[mountain\] at the top, so it's a water-mountain edge")
* Corner Tiles associate a label with each vertex in the grid. This is sometimes more natural for tile-based level authoring, and can result in smaller tilesets or more pleasing tiling properties, as described in the linked paper.

When deciding what tile to draw at each location, you form a tile ID from the labels of its bounding vertices/edges (eg. water, mountain, forest, town...), and use that information to look up or generate an appropriate tile to fill the space inside.

For example, here's the complete set of square corner tiles needed to handle all possible combinations of three corner types:

The ID in the center of each tile is formed this way:

```
ID = 0
For each cornerIndex, from 0 (top-left) clockwise to 3 (bottom-left)
    cornerLabel = GetCornerLabel(cornerIndex); //red: 0, yellow: 1, green: 2
    ID += cornerLabel * pow(3, cornerIndex)

```

To generate such a tileset directly, you'd enumerate each feature label you need (eg. water, sand, grass, forest, mountain, town) then build a tile for each possible permutation of these features around the border of your tile shape.

Note that the complete set of tiles needed grows very quickly as we increase complexity. Specifically:

```
SizeOfCOmpleteTileset(numLabels, numFeaturesPerTile) = pow(numLabels, numFeaturesPerTile)

```

Things you can do to address this:

* Break your tiles into smaller pieces. A square tile depends on four edge/corner labels, but a triangular tile depends on only three, reducing the complexity by an order of magnitude.

I'd be willing to bet that Oskar Stålberg's planetary example above models its border/tile transition logic on triangles, breaking each hexagon/pentagon of the Goldberg polyhedron into a fan of 6/5 triangles. This both reduces the number of distinct tile types and allows handling the 5- and 6-sided tiles more uniformly, rather than creating a unique tileset for each tile shape.
* Forbid certain permutations of features from meeting at a single tile.

Eg. maybe "jungle" never appears adjacent to "desert" - there must be a patch of another terrain like "grassland" or "mountain" separating them. This reduces the number of combinations you need to support, but restricts your level creation flexibility (and slightly complicates your tile indexing, since a naive index will contain gaps representing forbidden tiles that are never used).
* Automatically flip/rotate tiles to handle duplicate tiles that differ only by orientation. This means you can't have oriented features in your tiles, or rely on identical orientation along edges.
* Generate tiles on demand, by layering or parametrizing features, rather than storing every combination explicitly.

It looks like the planetary example in the question may use this strategy, having rules to build things like "junction between town wall and higher town wall" so it can generate needed permutations of this pattern on the fly. There also seems to be some procedural logic in the placement of buildings to fill the towns - the cluster of buildings in the center of each hex/penta fan stays the same, but the buildings along the edges change as their surroundings are modified.

There are tools to help generate these types of tiles from 2D textures (though usually for texture synthesis and not directly suitable to typical tile-based game uses where we want more structure) - see the references in the Corner Tile paper linked above - but I'm not aware of any for working in 3D.
> 4 votes

---
Tags: unity, tiles, tilemap
---