# Question
Title: Saving/Loading PlayerPrefs only works in the editor
I'm creating a game which stores a few variables using PlayerPrefs. It saves and loads the PlayerPrefs perfectly fine while testing in the editor, however when I build it to WebGL or Unity Web Player, both of them fail to save or load (I don't know which fails) and WebGL throws an exception on loading. Heres the c# script. Loading and saving are in their own procedures: loadData() and saveData()

```
public decimal money = 0;
public Text moneyTxt;

public Modal modal;

public AudioSource clickSFX;

private bool hasLoaded = false;

public Prog lemonadeStand;
public Prog newspaperDelivery;
public GameObject newspaperDeliveryBuy;
public Prog carWash;
public GameObject carWashBuy;

void Start () {
    askToLoad ();
}

// Update is called once per frame
void Update () {
    moneyTxt.text = "$" + money.ToString ("F2");

    if (Input.GetButtonDown ("Fire1")) {
        clickSFX.Play();
    }
}

void OnApplicationQuit() {
    if (hasLoaded) {
        saveData ();
    }
}

void saveData () {
    PlayerPrefs.SetString ("SaveMoney", money.ToString ());

    PlayerPrefs.SetFloat ("LemonadeStandMultiplier", lemonadeStand.multiplier);
    PlayerPrefs.SetFloat ("LemonadeStandUpgradeCost", lemonadeStand.upgradeCost);
    PlayerPrefs.SetInt ("LemonadeStandHired", lemonadeStand.hired ? 1 : 0);
    PlayerPrefs.SetFloat ("LemonadeStandPercentage", lemonadeStand.percentage);
    PlayerPrefs.SetFloat ("LemonadeStandTimeMultiplier", lemonadeStand.timeMultiplier);

    if (newspaperDelivery.transform.parent.gameObject.activeSelf) {
        PlayerPrefs.SetFloat ("NewspaperDeliveryMultiplier", newspaperDelivery.multiplier);
        PlayerPrefs.SetFloat ("NewspaperDeliveryUpgradeCost", newspaperDelivery.upgradeCost);
        PlayerPrefs.SetInt ("NewspaperDeliveryHired", newspaperDelivery.hired ? 1 : 0);
        PlayerPrefs.SetFloat ("NewspaperDeliveryPercentage", newspaperDelivery.percentage);
        PlayerPrefs.SetInt ("NewspaperDeliveryBought", newspaperDelivery.bought ? 1 : 0);
        PlayerPrefs.SetFloat ("NewspaperDeliveryTimeMultiplier", newspaperDelivery.timeMultiplier);
    } else {
        PlayerPrefs.SetInt ("NewspaperDeliveryBought", newspaperDelivery.bought ? 1 : 0);
    }

    if (carWash.transform.parent.gameObject.activeSelf) {
        PlayerPrefs.SetFloat ("CarWashMultiplier", carWash.multiplier);
        PlayerPrefs.SetFloat ("CarWashUpgradeCost", carWash.upgradeCost);
        PlayerPrefs.SetInt ("CarWashHired", carWash.hired ? 1 : 0);
        PlayerPrefs.SetFloat ("CarWashPercentage", carWash.percentage);
        PlayerPrefs.SetInt ("CarWashBought", carWash.bought ? 1 : 0);
        PlayerPrefs.SetFloat ("CarWashTimeMultiplier", carWash.timeMultiplier);
    } else {
        PlayerPrefs.SetInt ("CarWashBought", carWash.bought ? 1 : 0);
    }

    PlayerPrefs.Save ();
}

void loadData () {
    money = decimal.Parse(PlayerPrefs.GetString("SaveMoney"));

    lemonadeStand.multiplier = PlayerPrefs.GetFloat ("LemonadeStandMultiplier");
    lemonadeStand.upgradeCost = PlayerPrefs.GetFloat ("LemonadeStandUpgradeCost");
    lemonadeStand.hired = PlayerPrefs.GetInt ("LemonadeStandHired") == 1 ? true : false;
    if (lemonadeStand.hired) { lemonadeStand.enable(); lemonadeStand.percentage = PlayerPrefs.GetFloat ("LemonadeStandPercentage");}
    lemonadeStand.timeMultiplier = PlayerPrefs.GetFloat ("LemonadeStandTimeMultiplier");

    if (PlayerPrefs.GetInt ("NewspaperDeliveryBought") == 1) {
        newspaperDelivery.multiplier = PlayerPrefs.GetFloat ("NewspaperDeliveryMultiplier");
        newspaperDelivery.upgradeCost = PlayerPrefs.GetFloat ("NewspaperDeliveryUpgradeCost");
        newspaperDelivery.hired = PlayerPrefs.GetInt ("NewspaperDeliveryHired") == 1 ? true : false;
        if (newspaperDelivery.hired) {
            newspaperDelivery.enable ();
            newspaperDelivery.percentage = PlayerPrefs.GetFloat ("NewspaperDeliveryPercentage");
        }
        newspaperDelivery.transform.parent.gameObject.SetActive (true);
        newspaperDeliveryBuy.SetActive (false);
        newspaperDelivery.timeMultiplier = PlayerPrefs.GetFloat ("NewspaperDeliveryTimeMultiplier");
    }

    if (PlayerPrefs.GetInt ("CarWashBought") == 1) {
        carWash.multiplier = PlayerPrefs.GetFloat ("CarWashMultiplier");
        carWash.upgradeCost = PlayerPrefs.GetFloat ("CarWashUpgradeCost");
        carWash.hired = PlayerPrefs.GetInt ("CarWashHired") == 1 ? true : false;
        if (carWash.hired) {
            carWash.enable ();
            carWash.percentage = PlayerPrefs.GetFloat ("CarWashPercentage");
        }
        carWash.transform.parent.gameObject.SetActive (true);
        carWashBuy.SetActive (false);
        carWash.timeMultiplier = PlayerPrefs.GetFloat ("CarWashTimeMultiplier");
    }

    hasLoaded = true;
}

void askToLoad () {
    modal.choice ("Load previous save?", loadData, dontLoad, null, "Yes", "No", null);
}

void dontLoad () {
    modal.choice ("Not loading will reset your progress, this cannot be undone!", loadData, reset, null, "Load the save", "Reset everything, I'm sure!", null);
}

void reset() {
    PlayerPrefs.DeleteAll ();
    hasLoaded = true;
}

```

# Answer
> 0 votes
Updating Unity to 5.1.2f1 seemed to fix the issue.

# Answer
> 1 votes
Playerprefs are stored in different places depending on if you're in the editor or web player. So information saved in the editor will not be accessible from the web player and vice versa.

# Answer
> 0 votes
Forget about PlayerPrefs. Serializing your game data will be more secure and more inline with OOP practices. For WebGL builds you'll need to interact with the browser by calling the JavaScript method SyncFiles(), but that can be done completely within your project. I detail the process HERE, including source code and error handling.

---
Tags: loading, data, savegame, unity
---


# Question
Title: Casting a directional line of which an object is coming from
I want to create a directional line ( curve / linear ) depending where the direction is coming from.

In some games, similar to Angry Birds, a dotted guideline is shown to provide where the gameObject is going.

I want to create something like that. But not from the starting point. When i mean starting point, it simply means a dotted guideline from where the gameObject is released.

What i want is a dotted guideline from the end point. However, this end point is fixed. How i imagine this is, i have a gameObject. When this gameObject is near to land around this end point, it will show the dotted guideline.

Am i asking too much ? Sorry if i am, a structural guideline of how to write this code would be great.

Thanks.

**Edit**

So this how i want it visual. In Diagram ( A ) it shows a dotted line through the whole course of the path.

However what i want is shown in Diagram ( B ). It is split into two parts, a orange and red path. I only want the red path. But for a clear understand i included the red path. I only want the object to land or around that spot of Diagram ( B ).

What i dont want is from Diagram ( C ). Because it is not landing in the spot of Diagram ( B ). I dont want it to show anything. I only want the red dotted line from Diagram to appear when it is near or going to land in that spot of Diagram ( B ).

Thanks

# Answer
Suppose if you have a curve starting from (0,0) and lands at (100,0). If you only want to draw say 30% of the curve at end, then only draw the segment of curve between x=70 and x=100.
> 0 votes

# Answer
I happened to be writing a script that draws this kind of preview arc for a workshop I'm putting together:

(Public domain art assets courtesy of Kenney)

Here's the script:

```
[RequireComponent(typeof(LineRenderer))]
public class PreviewArc : MonoBehaviour {

    public float predictionSeconds = 4f;
    public int subdivisionCount = 20;

    LineRenderer _line;
    Vector3[] _points;

    void Awake ()
    {
        _line = GetComponent<LineRenderer>();
        _line.SetVertexCount(subdivisionCount);
        _points = new Vector3[subdivisionCount];
    }

    public void Preview(Vector3 startPosition, Vector3 initialVelocity)
    {
        float timeStep = predictionSeconds / _points.Length;
        for(int i = 0; i < _points.Length; i++)
        {
            float t = i * timeStep;

            // Standard ballistic motion:
            Vector3 point = startPosition
                          + t * initialVelocity
                          + 0.5f * t * t * (Vector3)(Physics2D.gravity);

            _points[i] = point;
        }

        _line.SetPositions(_points);
    }
}

```

(You can convert this from 3D to 2D by replacing `Physics2D` with `Physics`)

To draw only the tail end of the arc, you can do one of two things:

1. When calling `Preview()`, pass a `startPosition` and `initialVelocity` that match the state of the object at the moment of descent that you want to illustrate
2. Advance the time window covered by the loop that fills in the `_points` array so it includes just the segment you want.

eg. `float t = i * timeStep + startTime;`
> 0 votes

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


# Question
Title: How do i make floors of varying height in OpenGL?
So I am currently working on a small Game(/engine) in OpenGL and I want to build a little world editor. Nothing too fancy: Just some functions to add objects to a scene and manipulate them (rotation, translation etc). Up to now I have everything set up for loading models into the scene and setting up simple directional- and pointlights.

But one thing has been bugging me since the start: What is an average floor / ground made out of? I would guess that, for exmaple, a grass floor is just a lot of vertices / faces with a grass texture wrapped on them. But **how are those textures connected** and **how can you change the elevation for certain vertices** to create **hills**?

I am essentially asking how the recommended implementation of floors is in 3D environments (preferrably OpenGL 3.3) since I can't find anything on that topic on Gergl.

# Answer
They're usually just big planes cknsisting of smaller planes, and each vertex has a separate heoght attached to them.

For heights, people usually use heighmaps or pseudo random noise generation using Perlin or Simplex noise.

Some other games only use a small amount of pre-generated terrain, then scale it up to the size of the whole terrain, and lastly put the information on it again, but repeated multipke times with smaller sizes. This creates a fractal look and is able to generate huhe terrains with only a fraction of the information it would need.

Objects, such as grass, flowers, trees etc get generated procedurally too.

If you use OpenGL 3.2 and above, there's a chance ypu can use geometry shaders to create vertex information on the fly. This is not recommended though, as of 2016 it's still missing from many GPUs.
> 0 votes

---
Tags: opengl, terrain-rendering
---


# Question
Title: Rotating a Sprite and Moving It along That Angle in Unity
first time posting here. What I want to do seems extremely simple, but I'm not familiar enough with Unity to be able to implement it. Also, I wasn't able to find an answer that exactly solved my problem, but I'm sure it's simple enough.

I'm trying to rotate a sprite based on left arrow down and right arrow down:

```
    if (Input.GetKey (KeyCode.RightArrow)) {
        this.transform.Rotate (new Vector3(0, 0, -2));
    }

    if (Input.GetKey (KeyCode.LeftArrow)) {
        this.transform.Rotate (new Vector3(0, 0, 2));
    }

```

Once the sprite has been rotated, I would like to be able to apply a force in the direction it's facing by holding down the up arrow. And when the down arrow is held down, apply a negative force (or the same force in the opposite direction).

Here's what I have thus far:

```
    if (Input.GetKeyDown (KeyCode.UpArrow)) {
        Vector2 direction = new Vector2 (Mathf.Cos(body.rotation), Mathf.Sin(body.rotation));
        body.AddForce (direction * 10);
    }

```

This code just moves it along some unchanging angle that body (Ridigbody2D) has. Again, this is probably an extremely simple issue, but I can't seem to find anything that helps. I know I'll probably feel like an idiot when I see the solution!

# Answer
> 1 votes
Here are two extension methods that will help you:

```
/// <summary>
/// Returns the positive angle in degrees of given Vector2. This method assumes +X axis is 0 degrees.
/// </summary>
public static float Rotation(this Vector2 vector2)
{
    return Mathf.Atan2(vector2.y, vector2.x) * Mathf.Rad2Deg;
}

/// <summary>
/// Rotates the Vector2 by given angle.
/// </summary>
public static Vector2 Rotate(this Vector2 v, float degrees)
{
    float sin = Mathf.Sin(degrees * Mathf.Deg2Rad);
    float cos = Mathf.Cos(degrees * Mathf.Deg2Rad);

    float tx = v.x;
    float ty = v.y;
    v.x = (cos * tx) - (sin * ty);
    v.y = (sin * tx) + (cos * ty);
    return v;
}

```

What you need to take care of is, `Rigidbody2D` assumes +Y axis is 0 degrees, but our method assumes +X axis is 0 degrees; so you have to extract 90 degrees from the result of `Rotation()` method before applying it to `Rigidbody2D`'s rotation.

This is not a case for `Rotate()` method, you can use it directly since it is rotating relative to the vector itself.

# Answer
> 0 votes
Firstly, if you want the player to hold the up arrow you should use `Input.GetKey()` instead of `Input.GetKeyDown()`. Then you can create an empty object and then make the sprite it's child and rotate it so that when ever this empty object is facing forward the sprite is visible. Then you just move the empty object forward by simply applying the force forward like this: `GetComponent<Rigidbody2D>().AddForce(transform.forward);`. I hope this helps, sorry i couldn't test it yet, but I'm quite sure it will work.

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


# Question
Title: Why does iPhone games include a sound option?
Why does iPhone games include a sound option? It seems very unnecessary because the sound options (on/off, volume) are already on the hardware itself. Unless the player wants to shut out music, or specific effects it seems like a useless setting. But still there are tons of games that only have on/off and volume setting, is there a particular reason for that?

# Answer
> 0 votes
One reason to support a software version of some option (such as volume control) when a hardware option exists is simply to provide users the choice: they can disable sound, or adjust the volume of sounds, for just the game while leaving other more important device sounds unaffected.

It's also possible that a game can just expose a software control to the same system volume that is controlled by hardware buttons.

Often such features are not difficult to implement, especially if they already needed to be implemented on another platform with fewer hardware controls, or if they were provided by the game engine being used. The cost to provide the feature is thus relatively small compared to the "quality of life" improvement seen by some subset of the player base.

---
Tags: iphone, sound
---


title: Static variable not holding its value

text:
# Question
Title: Static variable not holding its value
I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this:

```
if (waitingToEndGame)
{
    waitTime += Time.deltaTime;
    if (waitTime >= 5f)
    {
        showGameScores = false;
        waitingToEndGame = false;
        if (type == "Multiplayer") MultiplayerController.Instance.LeaveGame();
        GameObject levelManager = GameObject.Find("Level Manager");
        levelManager.GetComponent<LevelManager>().LoadLevel("MainMenu");
    }
    DisableAllMovingObjects();
}

```

My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop.

# Answer
My issue ended up being that multiplayer was hitting some extra code that I was not seeing when tracing through and I could not debug this as it had to be on a device. I found a solution to logging while using a device here:http://answers.unity3d.com/questions/175161/debugging-android.html

This allowed me to find where I was getting a NullReferenceException so I could easily fix my code.
> 0 votes

# Answer
Well the sample you posted looks fine. For sure there is something else going bad. Check if there is any runtime error or any null reference exception. I prefer using coroutines when dealing with time to wait and looks a bit cleaner.
> 1 votes

# Answer
You should move the line, that changes the boolean to false, to the bottom of your if statement. Because the rest will not run after you change the boolean to false, so it has to be moved to the bottom of the if statement. To be executed last.
> -1 votes

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


title: How to get the GameObject's LayerMask?

text:
# Question
Title: How to get the GameObject's LayerMask?
I am currently following Unity's 2D Roguelike tutorial.

In that tutorial, I have `Player`, `Enemy`, and `Wall` Prefabs, which all belong to a `Layer` called `BlockingLayer`.

The `Player` and `Enemy` Prefabs both have a script inheriting from a script called `MovingObject`.

While writing the `MovingObject` class, I was meant to write the following line of code:

```
public LayerMask blockingLayer;

```

Later on, after creating the `Player` and `Enemy` scripts and attaching them to their respective Prefabs, I was supposed to set the `blockingLayer` to `BlockingLayer` from within the editor.

I thought this was stupid, because the Prefabs already belonged to the correct `Layer`, otherwise they couldn't interact with one another, so I changed the variable to `private` and instead added the following line to the `Start()` method:

```
blockingLayer = gameObject.layer;

```

However, suddenly collisions no longer worked. The `Player` and `Enemy` could now walk through each other as well as through `Wall`s. Using the Visual Studio debugger, I noticed the following:

* Setting the `blockingLayer` via the editor yielded following value: 256.
* `gameObject.layer` has a value of 8.

Obviously, the two layers are completely different, which explains why my modification didn't work. Still, I believe that setting the `Layer` twice — once on the GameObject, and once on the script — is dumb.

How do I get the correct Layer programmatically?

# Answer
You'll notice something about the numbers you're seeing, 8 and 256. If we look at **256** in binary, it looks like: `100000000`. That's a one, with **8** zeros! The layer is just the index in a binary integer. So, to get the mask for a specific layer, you need to left shift a 1 by that number of spaces.

```
int layerMask = 1 << layerValue;

```

If you want to combine multiple layers together, you'd OR them together.

```
int layerMask1 = 1 << layerValue1;
int layerMask2 = 1 << layerValue2;

int combinedLayerMask = layerMask1 | layerMask2;

```
> 2 votes

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


# Question
Title: Rendering three-dimentional array of tiles (as a tilemap)
I'm trying to create 2d game engine in C++ using SDL2 (actually some code was migrated from SFML). **I want to have a flexible multilayer tilemap that can store different types of tiles**. My current version of this kind of map uses three-dimensional array of pointers to base class of tiles (*"tilemap"*).

**First of all - is it even a good approach?**

I'm using pointers to make tiles polymorphic (eg. ground tile (tile\_basic) has it's act number and texture id, but chest tile (tile\_chest) has also a list of items in it). However scanning trough this array every time when I'm rendering my map would take a lot of time. So I'm scanning trough three-dimensional array of sprites (drawable objects) which is generated from the *tilemap* every time when new sprites are meant to be shown on the screen.

```
std::vector<std::vector<std::vector<mg::CompactSprite> > > sprites;

```

The first two dimensions are quite constant, they depend on the size of the application window. When moving the camera sprites move up to their size (width, heght) and when they are about to exceed this limit, their coordinates reset (x, or y, depending on which direction the camera is moving), getting it into simple words - I'm using modulo.

**The problem is that this is terribly slow** (~43ms with 23x18 map with only few layered tiles; using SDL2, similar results with SFML). I know I could render the whole visible area to the one image and just move that image and then render only new areas, but then I won't be able to make animated tiles without listing their coordinates, checking if they are in the visible area and then rerendering them which sounds bit overcomplicated, and I'm not quite sure if it'll really boost the rendering process.

---

So is there any better way to do this? Or I should change my approach?

# Answer
What you have here is not a multidimensional array. What you have is a vector which references a bunch of vectors which reference a bunch of vectors which reference a bunch of objects.

The problem with these many layers of indirection is 1. that your CPU needs to jump through all these memory references each time it looks for a tile and 2. that these memory structures likely end up all over the place in RAM instead of in one block of memory. Why is that a problem? Memory locality!

But you can avoid this by using an actual multidimensional array `mg::CompactSprite tiles[width][height][depth]`. Arrays are always a contiguous block in memory. If you insist on using an `std::vector` instead of an array, create a single vector with a size of `width * height * depth`. You can then access individual tiles with `tiles[tiles.x + y * width + z * width * height]` (when this is too unreadable, you can easily build your own 3dArray-class around it which abstracts this away)

Another way to improve memory locality is to make your tile-class as small and simple as possible. Polymorphism is something I would avoid here. Anything not related to their appearance (like the content of a treasure chests) should be stored somewhere else.

> When moving the camera sprites move up to their size (width, heght) and when they are about to exceed this limit, their coordinates reset

I am not sure if I understand this correctly, but it sounds to me like when you move the camera, you aren't moving the camera but instead move all the tiles, which implies that you iterate the complete array and overwrite the coordinates of every single tile. This is a bad idea, because it likely takes quite a lot of time to do that. A tile doesn't even need coordinates, because these are implied by its position in the array. What you should be doing is:

* calculate which tile index ranges are inside the viewport
* do a loop over the tiles which are inside these index ranges
* draw each tile with the position calculated from the camera position and the indexes of the tile
> 0 votes

---
Tags: c++, performance, tilemap
---


title: Constructing a Planetoid Cube World?

text:
# Question
Title: Constructing a Planetoid Cube World?
This is sort of a multidisciplinary question, so I'm asking it here rather than on one of the other Stack Exchange sites.

I've been toying with the idea of making a game that's a mix between Minecraft and Kerbal Space Program, where the world is actually a planet and can be traveled around (either on the ground or in orbit) seamlessly, yet still consisting entirely or mostly of cubes à la Minecraft. It turns out this is actually incredibly difficult to wrap my head around!

There are a few requirements and concessions.

# Requirements

1. Must be able to travel and build on all parts of the planet seamlessly (poles included)
2. Every tile must be able to be mapped exactly or roughly to a spherical coordinate.

# Concessions

1. Planet's perceived 'radius' at varying depths can be uniform.
2. Depth of buildable area can (and should) be limited, meaning you don't need to be able to tunnel into the center of the planet and you don't need to be able to make an absurdly large tower.

Those are the main points, and the problem is open to interpretation and more concessions are able to be made so long as the illusion of being on a planet is maintained.

# Initial Idea

Here is an I've had that may have some merit but I'm not sure if it'd actually work.

## Tesselated Platonic Solid

The idea here is to create a 'virtual' sphere made of a patchwork of faces of a platonic solid (e.g. cube, icosahedron, octahedron). The faces represent a plot of flat land, with each edge being the 'portal' to another faces and so on. In this way the world is always 'flat' and you are basically traveling over a 2D unwrap of the original shape.

One of the problems with this method is that with some tesselated platonic solids (such as the cube above), the tesselated faces are warped and the surface area of each face is not uniform. A little bit of this is acceptable, but not too much.

## The Question

The real question here is ultimately "is this possible?" and if so, what would be the best method to achieve all of the requirements. If not, what kind of concessions would I need to make to make a believable world?

# Answer
> 5 votes
I would cheat, and represent each planet as a flat plane in terms of "cubelets" and graphically wrap the plane around the sphere for distance POV. This will work as long as you don't have tiny planets (IE: from the surface, the planet is big enough to appear flat).

The other option is to simply construct the entire planet out of cubes, including the interior. Which would use an extraordinary amount of memory/disk/etc.

When in doubt, cheat :)

# Answer
> 2 votes
Would you be amenable to using a triangular grid as opposed to a square one? If so, I think the worst-case distortion can be reduced, relative to using a square grid.

If your planet is "really" an icosahedron before your rounding effect is applied, then each face can be covered with a grid of equilateral triangles, as densely as you like. The icosahedron approximates a sphere more closely than any other platonic solid. The only distortion occurs at the 12 vertices of the icosahedron, where you'd have 5 triangles joining instead of 6. (A shortfall of 60 degrees, a third less than you'd get with squares).

If you can control where the continents end up, you can ensure these 12 problem points are located in the middle of oceans, so they don't impact typical gameplay. (See, for instance, the points of the Dymaxion projection)

Your unit of construction would then be a triangular prism, rather than a cube. These are a bit trickier to work with, but you may be able to make that a natural part of your game's aesthetic.

# Answer
> 0 votes
Make a variable Scale of the Planet,and a variable Distance and Position,distance receives a relativity of Position(x,y,z) of block and the Center of Mesh. And make a if(Distance \<= Scale) { MakeVoxel(x,y,z,Material); } Ok.

---
Tags: voxels, planet, sphere
---


# Question
Title: Unity 2D Following player on the x-axis only, at a constant speed
This following code does work, but I have one issue with it. Once the gameobject starts getting close to the player that it is chasing it slows down and does not continue going at a constant speed to the target. Is there another way I can code this to keep the speed constant even if the gameobject is close to the target?

```
Vector3 followXonly = new Vector3(target_position.x, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, followXonly, speed * Time.deltaTime);

```

# Answer
Unity provides a helper method to deal with exactly this kind of situation:

```
Vector3 followXonly = new Vector3(
                            target_position.x,
                            transform.position.y,
                            transform.position.z);

transform.position = Vector3.MoveTowards(
                            transform.position,
                            followXonly,
                            speed * Time.deltaTime);

```

Vector3.MoveTowards handles advancing the position in the direction of the target at a constant speed regardless of distance, and also guards against overshooting when your object is less than one full frame duration away from its destination.
> 1 votes

# Answer
It slows down because your transformation is a *linear* interpolation of a *non-normalized* vector. That is: as the distance between where the object is now and its target gets *shorter*, the speed will slow down because you're only moving (say) 5% of that distance every frame.

You get this:

It's like taking 1 and multiplying by 0.95 20 times and expecting to get 0 (it's actually 0.35848 and a bit).

You need to replace the `speed * Time.deltaTime` portion with a counter that you increment by deltaTime every frame and the `transform.position` with its starting location. That way the Lerp is actually Linear (because you're supplying it with a linearly increasing value, rather than a constant).

Or refactor the code to be something more like:

```
Vector3 followXonly = new Vector3(target_position.x - transform.position.x, transform.position.y, transform.position.z);
followXonly = followXonly.normalized * speed;
transform.position = transform.position + followXonly;

```
> 0 votes

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


# Question
Title: Movement looks funny If player takes up multiple tiles in tile-based game
So here is my problem:

```
Start = +++
        +++
        +++
End = ---
      ---
      ---

Player = ***
         ***
         ***

+++000000000000
+++000000000000
+++000000000000
000000000000000
000000000000000
000000000000000
000000000000---
000000000000---
000000000000---

```

I've made an A\* path finding algorithm to tell it where to go, and it works!

```
+***00000000000
+***00000000000
+***00000000000
000000000000000
000000000000000
000000000000000
000000000000---
000000000000---

+++000000000000
+***00000000000
+***00000000000
0***00000000000
000000000000000
000000000000000
000000000000---
000000000000---
000000000000---
000000000000---

+++000000000000
++***0000000000
++***0000000000
00***0000000000
000000000000000
000000000000000
000000000000---
000000000000---
000000000000---

+++000000000000
+++000000000000
++***0000000000
00***0000000000
00***0000000000
000000000000000
000000000000---
000000000000---
000000000000---

+++000000000000
+++000000000000
+++***000000000
000***000000000
000***000000000
000000000000000
000000000000---
000000000000---
000000000000---

+++000000000000
+++000000000000
+++000000000000
000***000000000
000***000000000
000***000000000
000000000000---
000000000000---
000000000000---
etc...

```

The player also has 4 sprite sheet animations: looking up, looking left, looking right, and looking down. My problem is that, moving this way, the player jitters from looking right to down really quickly, making it look like it is spazzing, and ultimately it is aesthetically unappealing. In a game where the player takes up one tile, it looks OK, but if it takes up, say 3X3 or 4X4, it does not. I want to make it have a move diagonal animation as a last resort, so any tips are appreciated. Thank You!

# Answer
> 2 votes
One possible solution, without modifying the computation or directness of the path itself (which might have unwanted effects on your gameplay), is to just tweak your logic for selecting which animation or frame to display.

When the animation controller asks the movement logic which way it's moving, the movement logic can tell it a little white lie:

* If my current movement direction is different from the last one I reported, and my path takes me only one tile before I change direction again, then report back the last direction instead.
* Otherwise, report back the actual direction of movement

That should help smooth-out the small steps you'll have when walking along arbitrary diagonals - the avatar will just keep facing the dominant direction (for 45-degree angles, picking one arbitrarily based on the way it was facing at the start of the path)

If you find the zigzag step of the movement itself is also distracting, you can tell a similar lie about the display position of your character - interpolating over multiple moves - again without impacting the underlying tile-based movement logic.

# Answer
> 0 votes
The A\* algorithm contains a heuristic, meaning you can modify it to get a path that may not be optimal, but better suits your requirements (i.e. prefer orthogonal movement over diagonal movement). You'd modify your A\* algorithm to make quick direction changes more costly. For example, if you've just changed from going down to going right, the cost of going down again would be much higher than the cost of continuing to go right (if such option exists). This additional cost would reduce over longer stretches of straight moves.

Alternatively, since you don't appear to be allowing diagonal movement, you get this jitter back and forth between orthogonal movements. One solution is to allow diagonal movements and simply choose the most appropriate orthogonal animation.

---
Tags: path-finding
---


# Question
Title: How do I get A.I. that follows a list of movement commands to move smoothly in a tilemap based game?
This is for a school project so it's not intended to be sold/fun/or a complete game, rather just a demonstration of stuff we've learned without resorting to frameworks and stuff.

My ai agents choose a random point in the grid and generate a sequence of actions to take to get there using breadth first search. They do this indefinitely until they're killed (something I haven't gotten to yet). Each action corresponds to one tile movement so I'm having trouble translating that into smooth movement transitioning from one tile to the next rather than just stuttering to it. What I have at the moment is limiting how many actions can be taken per second so the agent doesn't just teleport around the game because it's moving so fast. Can I modify what I have here to achieve smooth movement, or do I need to take a different approach in how to generate my action sequence?

I had smoothish movement when my MAX\_VELOCITY = 1 by just rounding down if the time step made the agent move past more than one tile, but it didn't work for higher numbers, like MAX\_VELOCITY = 10. The player character moves at MAX\_VELOCITY = 10 which I think is perfect.

Edit: I'm thinking of something now though I don't know if it'll work or if it's the right way to do it. If I only use enough of the time step to advance to the next square, then I could use the rest of the timestep on the next action, or something like that until I'm out of time.

Edit2: It seems to work properly. There's some collision detection issues coming up, but it looks pretty much as smooth as the player character movement. I'll leave the answer unchosen for now since my solution isn't very good but I'll post what I have here once I figure out the collision detection issues.

```
@Override
public void move(double dt) {
    this.elapsedTime += dt;
    if (this.actionsIndex == this.actionsToGoal.length() || this.actionsIndex == -1) {
        long startTime = System.nanoTime();
        if (this.goal != null) { //Debugging stuff
            startingPosition = new Point((int) this.posX, (int) this.posY);
            System.out.println("Arrived at goal");
            System.out.println(startingPosition.toString());
            System.out.println(goal.toString());
        }
        chooseGoal();
        this.frontier.clear();
        generateActionSequence();
        double timeTaken = (System.nanoTime() - startTime) / 1000000000.0;
        this.elapsedTime += timeTaken;
    }

    if (this.actionsIndex != -1) {
        while (elapsedTime >= 1.0 / this.actionsPerSecond && this.actionsIndex != this.actionsToGoal.length()) {
            char action = actionsToGoal.charAt(this.actionsIndex++);
            switch (action) {
                case State.LEFT:
                    this.posX -= MAX_VELOCITY;
                    break;
                case State.RIGHT:
                    this.posX += MAX_VELOCITY;
                    break;
                case State.UP:
                    this.posY += MAX_VELOCITY;
                    break;
                case State.DOWN:
                    this.posY -= MAX_VELOCITY;
                    break;
            }
            elapsedTime -= 1.0 / this.actionsPerSecond;
        }
    }

}

```

# Answer
> 1 votes
This is the while loop above redone. Kind of ugly and repetitive but it works. I had to use Math.floor and Math.ceil to solve the collision issues which is due to precision I guess. Any spare dt left over if the action sequence is finished is discarded so that might be something to save for accuracy but the timesteps are really small so it may not be significant.

Edit: This one is better than the one I posted first. Since the precision might cause it to either under or overshoot the +1 tile movement, it's difficult to know when to floor or ceil to get the whole number. So when there is less dt needed than what's available, just floor or ceil the current double position according to which way you're moving to get to the starting tile position and add or subtract one from that to get the proper tile position after moving. With the original my agents would move outside the walls when they shouldn't but with the second they stay inside.

```
while (dt > 0 && actionsIndex != actionsToGoal.length()) {
            char action = actionsToGoal.charAt(actionsIndex);
            double dtNeeded;
            switch (action) {
                case State.LEFT:
                    dtNeeded = (this.posX - Math.ceil(this.posX-1))/MAX_VELOCITY;
                    if(dtNeeded > dt) { //There's not enough time needed to fully move to the next tile, use all of what's left.
                        this.posX -= MAX_VELOCITY * dt;
                        return;
                    }
                    else{ //Less than total timestep needed to advance to next tile.
                        this.posX = Math.ceil(this.posX) - 1;
                        dt -= dtNeeded;
                        actionsIndex++;
                    }
                    break;
                case State.RIGHT:
                    dtNeeded = (Math.floor(this.posX+1) - this.posX)/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posX += MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posX = Math.floor(this.posX) + 1;
                        dt -= dtNeeded;
                        actionsIndex++;
                    }
                    break;
                case State.UP:
                    dtNeeded = (Math.floor(this.posY+1) - this.posY)/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posY += MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posY = Math.floor(this.posY) + 1;
                        dt -= dtNeeded;
                        this.posY = Math.ceil(this.posY);
                        actionsIndex++;
                    }
                    break;
                case State.DOWN:
                    dtNeeded = (this.posY - Math.ceil(this.posY-1))/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posY -= MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posY = Math.ceil(this.posY) - 1;
                        dt -= dtNeeded;
                        actionsIndex++;
                    }
                    break;
            }

```

---

```
while (dt > 0 && actionsIndex != actionsToGoal.length()) {
            char action = actionsToGoal.charAt(actionsIndex);
            double dtNeeded;
            switch (action) {
                case State.LEFT:
                    dtNeeded = (this.posX - Math.ceil(this.posX-1))/MAX_VELOCITY;
                    System.out.println(dtNeeded);
                    if(dtNeeded > dt) { //There's not enough time needed to fully move to the next tile, use all of what's left.
                        this.posX -= MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posX -= MAX_VELOCITY * dtNeeded;
                        dt -= dtNeeded;
                        this.posX = Math.floor(this.posX); //Ensuring no precision error. One action = 1 tile movement
                        actionsIndex++;
                    }
                    break;
                case State.RIGHT:
                    dtNeeded = (Math.floor(this.posX+1) - this.posX)/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posX += MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posX += MAX_VELOCITY * dtNeeded;
                        dt -= dtNeeded;
                        this.posX = Math.ceil(this.posX);
                        actionsIndex++;
                    }
                    break;
                case State.UP:
                    dtNeeded = (Math.floor(this.posY+1) - this.posY)/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posY += MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posY -= MAX_VELOCITY * dtNeeded;
                        dt -= dtNeeded;
                        this.posY = Math.ceil(this.posY);
                        actionsIndex++;
                    }
                    break;
                case State.DOWN:
                    dtNeeded = (this.posY - Math.ceil(this.posY-1))/MAX_VELOCITY;
                    if(dtNeeded > dt) {
                        this.posY -= MAX_VELOCITY * dt;
                        return;
                    }
                    else{
                        this.posY -= MAX_VELOCITY * dtNeeded;
                        dt -= dtNeeded;
                        this.posY = Math.floor(this.posY);
                        actionsIndex++;
                    }
                    break;
            }
        }

```

---
Tags: java, movement, ai
---


title: Pixel Animation is tearing in Unity

text:
# Question
Title: Pixel Animation is tearing in Unity
I am working on a 2D game and I have created a simple sprite sheet. The sprite sheet represents a medkit. The size of the sprite sheet is 128x16 pixels with 8 different frames that animate the medkit bobbing up and down.

I have imported the sprite sheet into Unity as a Sprite with Sprite Mode set to multiple, Generate Mip Maps unchecked, Filter Mode set to Point, and Format set to Truecolor. I have sliced the sprite sheet using the Unity Sprite Editor and added the animation to my scene.

After doing so, I am able to see my sprite in my game. However I noticed that the animation of the sprite did not correspond to the sprite sheet. Some pixels seem to be distorted and tearing. I have searched online and couldn't find anyone with the issue I had. As you can see from the gif below, the top of the sprite is tearing.

Does anyone know what is causing this issue?

Gif of the issue:here

Sprite sheet used:

# Answer
> 0 votes
Well, I don't know why you get this tearing. Perhaps the spritesheet itself is too small and unity is messing up. I suggest you try two things to solve your problem. 1. Up the resolution of the sprite and see if that solves the problem 2. If the animation is bobbing up and down you dont need a frame by frame animation. Just animate the transform component of the gameObject and you will get the same effect.

---
Tags: unity, animation, spritesheet
---


# Question
Title: How do I access variables using namespaces?
I've got a whole lot of scripts, none of them so far use namespaces. But as I get more and more scripts to deal with I thought it would be a wise idea to start using namespaces. I've never used them before so I'm having a little bit of difficulty. I've declared the namespace in one of my scripts:

```
using UnityEngine;
using System.Collections;

namespace Train.OnBoardChecker {
    public class OnBoardChecker : MonoBehaviour {
        [SerializeField]private bool isOnBoard;

        public void OnTriggerEnter (Collider col) {
            if(col.gameObject.tag == "Character"){
                isOnBoard = true;
            }
        }

        public void OnTriggerExit (Collider col) {
            if(col.gameObject.tag == "Character"){
                isOnBoard = false;
            }
        }
    }
}

```

And in my main train script, I've tried to access the 'isOnBoard' bool from the OnBoardChecker script. I was told there were a few ways of doing this, this is what I did:

```
using UnityEngine;
using System.Collections;
using Train.OnBoardChecker;

namespace Train {
    public class TrainSystems : MonoBehaviour {

        void Start () {

        }

        void Update () {

        }
    }
}

```

I'm not sure if I'm misunderstanding the whole namespace thing, but I can't access my variables from that script. I've making the variable public, and private (with serialzefield). I've tried these, with the public and private variables, and I even tried making the voids public and not public:

```
(namespace onboard checker) > OnBoardChecker.OnBoardChecker.insertvariablenamehere
OnBoardChecker.varname

```

What am I doing wrong, how do I access my variables from the OnBoardChecker script in the TrainSystems script with the namespaces without having to make it public, kind of like the standard assets does.

# Answer
> 1 votes
You can't access that variable without an actual object of type `OnBoardChecker`

So you will do something like:

```
OnBoardChecker myChecker = get some reference to the object/create a new() one

myChecker.isOnBoard; // or if it is private use a get method for it.

```

What you are trying to do is get a static member of the class. A static member does need a instance of the class to exist.

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


# Question
Title: How do I efficiently choose the terrain chunks to render based on the player position?
Well, I have an array with all the terrains. How do I render them? I just add them to a List of terrains that are sent to the Renderer. There, every terrain of the list is rendered.

The problem is that if I add all the terrains of the array to the list (let's call it *toRenderList*), my computer explodes because of the number of terrains.

What I've tried to achieve it's to add to the list ONLY the terrains that are into a certain range. This is what I've done:

```
private static Terrain[][] terrains;
private List<Terrain> toRenderList;
private static final int NUMBER_CHUNKS = 3; //Number of terrains that are added to the list.

public void update(Player player){
    if(player.hasChangedTerrainPosition()){
        toRenderList.clear();
        for(int x = player.getTerrainPosition()[0]-NUMBER_CHUNKS;
            x == player.getTerrainPosition()[0]+NUMBER_CHUNKS; x++){
            for(int y = player.getTerrainPosition()[1]-NUMBER_CHUNKS;
                y == player.getTerrainPosition()[1]+NUMBER_CHUNKS; y++){
                terrainList.add(terrains[x][y]);
                System.out.println("Terrain "+x+","+y+" added!");
            }
        }
    }
}

```

Just to clarify, the method player.*getTerrainPosition* returns a int\[\] with the current terrain coords in where the player is standing. The method player.*hasChangedTerrainPosition* returns **true** if the player has changed of terrain.

The problem of this method is that for example if the player is in the position \[0,0\] it pops an error of ArrayIndexOutOfBounds because of a negative number.

I don't know if I've been specific. This is more basic Java than GamePrograming, but any help will be appreciated. Thanks!

# Answer
Treat all the chunks around player, as offsets (shown in one axis but applies for both):

`-3 -2 -1 0 +1 +2 +3` \<- 7 offsets for 1 axis; for `x` * `y` that would be 49 offsets.

`0, 0` is the offset where the player is - the origin of "player space". `3, -2` might be roughly to the northeast or whatever, depending on your coordinate system setup, and so forth.

Now we add each of these coordinates to the player's actual position

`coords = player.getTerrainPosition() + offset`

Lastly, we need to ensure `coords` are in terrain array range(s). So for example if I was standing at `x=1` and was adding an offset of `-3` then `coords == (-2, y)`. We can't have any negative values like this, because then you get array indexing errors.

**To not show outside world bounds**, simply check for any negative coordinates and then do not use them to add a new terrain chunk! In this case any negative value, either `x` or `y`, is invalid.

**To wrap around on world bounds** for each axis `x` and `y`, modify `coords` one more time:

```
if (offset.x < 0)
    offset.x += terrainArrayWidth;
else
{
    if (offset.x >= terrainArrayWidth)
    {
        offset.x -= terrainArrayWidth;
    }
}

```
> 1 votes

# Answer
You are not clearing the list before you add new chunks. Tyy adding `terrainList.clear()` at the start of the update method.
> 0 votes

---
Tags: java, terrain-rendering, spatial-partitioning
---


# Question
Title: LibGdx TextField - How to hide Keyboard when not focused?
I'm creating a registration screen for my game. I implemented textfields and input is getting correctly. But when I click elsewhere after text is entered, the keyboard stays visible and does not hide automatically, even when a new screen is loaded. Is there any listener methods for hiding the keyboard?

Right now I did a workaround by calling the `setOnscreenKeyboardVisible(false)` in the sign up and sign in buttons. But I want the keyboard to hide right when it is unfocussed. Is it possible?

**UPDATE:**

Actually I thought when I click elsewhere the textfield focus changed automatically but that's not the case. The cursor keeps blinking even after the keyboard is hidden explicitly. I edited the correct answer to include this.

# Answer
> 5 votes
Try this:

```
@Override
public void keyboardFocusChanged(FocusEvent event, Actor actor, boolean focused) {
    super.keyboardFocusChanged(event, actor, focused);
    if (!focused)
        setOnscreenKeyboardVisible(false);
}

```

Otherwise you could go for a better work around. You place a big clickable transparent actor behind everything. When you click anywhere next to your buttons, textfields, etc this field will be triggered and you can get rid of your keyboard ;).

**EDIT:**

The textfield will remain focused even after this, so the cursor will keep blinking and we don't want that. As mentioned here:

http://www.java2s.com/Code/Flash-Flex-ActionScript/TextField/ToremovefocusfromatextfieldyoushouldassignStagefocusthenullvalue.htm

you should also unfocus the stage along with hiding the keyboard.

```
stage.unfocusAll()

```

# Answer
> 3 votes
Menno Gouw's answer is correct and is probably the way to go in most cases, but just in case someone runs into my problem where that solution might distort the positioning of other actors I thought I'd post how I solved it.

First Create an "invisible" button:

```
ImageButtonStyle style = new ImageButtonStyle();
style.up = null;
style.down = null;
cancelFocusButton = new ImageButton(style);

```

Second, add your listener to the invisible button:

```
cancelFocusButton.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        Gdx.input.setOnscreenKeyboardVisible(false);
        stage.unfocusAll();
    }
});

```

Third, add this button to a stack together with the table that holds all your other actors (Textfields, labels, button etc):

```
Stack stack = new Stack();
stack.addActor(cancelFocusButton);
stack.addActor(tempTable);

```

Lastly add your stack to your "main table" (in my case the ContentTable inside the dialog):

```
getContentTable().add(stack).expand().fill();

```

# Answer
> 1 votes
I needed to do the same thing and went for an extremely simple solution in the end and it seems to work well.

I created my own StageExtension class that extends Stage (for other reasons), but within this I simply override the touchDown method adding 2 lines;

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    super.unfocusAll();
    Gdx.input.setOnscreenKeyboardVisible(false);
    return super.touchDown(screenX, screenY, pointer, button);
}

```

You can of course add some simple checks in there to match your needs, but this works perfectly for me.

---
Tags: libgdx, keyboard
---


# Question
Title: HTML5 point and click adventure game code structure with CreateJS
I'm a programming beginner.

I made a tiny one scene point and click adventure game to try to understand simple game logic and came up with this: CreateJS features prototypes for creating bitmap images, sprites and sounds objects. I create them and define their properties in a corresponding function (for example images(); spritesheets(), sounds()...). I then create functions for each animation sequence and "game level" functions, which handle user interactions and play the according animations and sounds for a certain event (when the level is complete, the current level function calls the next level function). And I end up with quite the mess.

What would be the "standard (if something like that exists)" OOP approach to structure simple game data and interactions like that?

I thought about making game.images, game.sprites, game.sounds objects, which contain all the game data with its properties using CreateJS constructors. game.spriteAnimations and game.tweenAnimations objects for sprite animations and tweens and a game.levelN object, which communicates with a game.interaction object, processing user interaction. Does this make any sense?

How do you structure your simple game code? Thanks in advance!

# Answer
Well maybe all what you're saying leads to one conclusion you need to get a higher level game framework that will handle more of the not-so-easy low level stuff for you.

I know of Ganvas (free), ImpactJS (paid), Construct 2 (free/paid for more features), Unity(paid). Other gamedev folks might have other framework ideas.

But if you feel CreateJS is a too tiny framework for you, go search for a more developped framework first. Developing a framework by yourself or even extending an existing one is a huge task (especially if you target both desktop browsers and smartphones) that no one should under-estimate.
> 2 votes

# Answer
I am creating a Point and Click game right now, using the Phaser engine. Structuring is quite easy and obvious with that engine, especially if you are using JavaScript ES6 classes. Each room in the game is a "Room State" that extendes a "Base State" - which extends the basic Phaser Game State class. There is one Class for the Player, one for NPCs, one for Items, one for the Controls or the inventory...all those classes just extend the "Phaser Sprite class". Phaser already comes with a lot of other things too (audio, resize functions, animations, spritesheets, ...).

Here´s the link to the engine: http://phaser.io/

Take a look at the examples too: http://phaser.io/examples
> 0 votes

---
Tags: javascript, software-engineering, architecture, oop
---


# Question
Title: Handle shared vertices in mesh deformation
I have a cube-sphere made from 6 planes. I am deforming each of the plane vertices using this code (C#):

```
aPlane.transform.aPoint(vertices[i]).normalized * this.radius + (randomFloat));

```

This gives me large gaps where my planes join. How can I separate between shared and non-shared vertices, adding the `randomfloat` to shared/non-edge vertices only.

Pseudo code could be (C#):

```
Vector3[] vertices = mesh.vertices;
//maybe add int[] tris = mesh.triangles?
if (vertice is shared)
add randomfloat;
else deform without randomfloat;

```

I'm quite certain I need to create an array and add triangle vertices and check if the vertices belong to one triangle or two/more triangles.

Everything is generated from code and this is for a hobby project. I already have planet generators from the Asset store but if I use those I might as well just slap together Asset store content and put my name on it.

# Answer
I've solved this in a couple of different ways in the past:

1. Use a 3-dimensional noise function, like Perlin noise or a noisy volume texture, instead of a pure random value. Seed the noise lookup with the original position of your vertex. Since shared vertices have the same position, they'll get the same displacement, keeping them tightly joined.
2. Use vertex colours to associate a mask with each of your vertices. eg. Make the blue channel of each edge vertex 0, fading to 1 away from the edge. Multiply your random offset by this value so it falls off to zero at the shared vertices. Or, use it as a lerp weight between your pure random method and a more coherent method like 1.

As for your comment about the Asset Store, remember, that's what it's there for — other creators uploaded content there specifically so that fellow developers can use it in their games. Software development, and game development in particular, has a bit of a macho culture where we feel like doing everything ourselves from scratch is the only way to be a "real" developer — but it leads to a lot of reinventing the wheel, and stumbling into mistakes that have been solved by others long ago. If there's already a high-quality solution to your problem out there, I say just use it, and use the time you save to make your core gameplay even better. :)
> 0 votes

---
Tags: unity
---


title: Terrain making in unity

text:
# Question
Title: Terrain making in unity
I'm making a minecraft-like game, I'm trying to make a terrain made of cubes, but copying and pasting the same cube takes too much time and uses too much of my pc's RAM. So, any suggestions?

# Answer
Don't copy and paste the cubes by hand. Create one cube for each block-type you have, make them into prefabs, and then write a script which `Instantiate`s your cube prefabs over and over again when the game starts.

Here is a small example script to get you going. It will spawn a 10x10x10 block of the prefab you assign to it.

```
using UnityEngine;

public class MapLayoutNew : MonoBehaviour
{
    public GameObject cubePrefab;

    void Start () {
        for (var x = 0; x < 10; x++) {
            for (var y = 0; y < 10; y++) {
                for (var z = 0; z < 10; z++) {
                     Instantiate(cubePrefab, new Vector3(x, y, z), this.transform.rotation);
                }
            }
         }
     }
 }

```

This method will only work on a small scale. If you are trying to build something with as many cubes in the scene as Minecraft has, the performance will suffer because you will have way too many game objects in your scene. Remember that Minecraft is not built with a stock game-engine like Unity. The graphic engine was tailor-made to allow for a 100% procedural and changeable environment.

When you want to do something similar in Unity, you will have to apply some performance enhancement tricks to keep the framerate bearable. One is to turn multiple adjacent cubes into one game-object with a procedurally-generated mesh. Another is to disable any cubes the player can't see and enable them when they become visible.
> 0 votes

---
Tags: unity, terrain, minecraft-modding
---


# Question
Title: What is the difference between getting a reference and creating a new instance of an object?
I asked a question a while ago and got an answer that I can either get a reference to the object or create a new one, like the below example:

```
Example myExample = get some reference to the object/create a new() one

myExample.testing; // or if it is private use a get method for it.

```

Whats the difference between the two examples above (get a reference and create a new one)?

# Answer
> 1 votes
**Quick Answer:**

The main difference between getting a reference to an object and creating a new object is how many objects you end up with and how they behave when you manipulate them. When creating a new object you end up with one more object than you had before.

**Expanded Answer:**

There are some behaviors in code that you need to be aware of to know when you need multiple objects vs multiple references to an object.

First, if you have multiple objects you will use up more memory. This usually isn't a big deal if you're just creating one object, but if you're creating a new instance of an object each time you iterate though a loop that executes thousands of times... It may or may not be a problem depending on what is all happening. It also may or may not be required.

Second there is some behavioral differences you need to be aware of. Consider the below example.

```
Person p1 = new Person("John");// original person
Person p2 = new Person("Jill");// another instance of a person
// change the age on each person
p1.SetAge(23);
p2.SetAge(45);
// print each person's age
Console.WriteLine("p1 age: " + p1.GetAge());
Console.WriteLine("p2 age: " + p2.GetAge());

```

This will have the below output:

```
p1 age: 23
p2 age: 45

```

Now we'll do the same thing except `p2` will be a reference the the instance `p1`.

```
Person p1 = new Person("John");// original person
Person p2 = p1;// a reference to an existing person
// change the age on each person
p1.SetAge(23);
p2.SetAge(45);
// print each person's age
Console.WriteLine("p1 age: " + p1.GetAge());
Console.WriteLine("p2 age: " + p2.GetAge());

```

Here's where you might get tripped up. The output is below.

```
p1 age: 45
p2 age: 45

```

Wait a minute. That can't be right... or can it? Let's look at what happened. We said `p1` is a person named "John." Then we said `p2 = p1`. This is saying that `p2` is also "John." Think of it as an alias (because that's exactly what it is). If you were to pause a debugger at any point after setting both variables, you could see that in the second example both `p1` and `p2` point to the same location in memory. Therefore changing one of them changes both of them.

**Which is better**

This really depends on your needs. Look at how you want the object to behave in your program and make a decision. If you find out you made the wrong one, just switch.

# Answer
> 1 votes
If you declare a variable

```
Gameobject reference = existing_gameobject

```

then operations that you'll do on `reference` will apply to `existing_gameobject`.

If you create a new `GameObject` you will interact to a brand new one instead.

Coming back to the previous example, if you do

```
reference.transform.position += Vector3.Right

```

the position of the `existing_gameobject` will be modified. If you create a new one

```
GameObject newGO = new GameObject();

```

and then

```
newGO.transform.position += Vector3.Right

```

you will modify just the `newGO` position.

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


# Question
Title: Pathfinding to unknown destination point
Usually you need path finding algorithms to find one or the best path between two points. Do you know if path finding algorithm where you don't know the destination point exists?

I have a graph made of thousands of nodes, I'd like to pick one, and tell my path finding algorithm "find a destination node that is at least at N units of distance of my origin point".

Is it a common problem? How would you solve it?

Thanks.

# Answer
Create an isochrone map (https://en.wikipedia.org/wiki/Isochrone\_map), get a polygon of all the points accessible within N units of time.

An isochrone map basically looks like this (3 isochrones are represented in this example):

Let's just focus on the red one, which takes a center point and a time (or a distance). Based on this time/distance limit, the road network is tested to find all destinations within this limit. This kind of map is often used in marketing/logistics as you can determine which of your customers/warehouse/whatever is accessible within X minutes, so that you can target a specific audience.

The result of the calculation is a polygon (the red polygon for instance, or red+yellow+green). Then by definition, every node which does not intersect this polygon will be at least N units of time away

There are multiple ways to calculate isochrones (or "isodistance" if you are working with distance limits), but this is a broader question. Also if you don't own the data, some web services will allow you to calculate isochrones worldwide.

The OP seem to have its own road network to work with, so an algorithm will need to be implemented to calculate the isochrone in the first place. The OSM wiki has some interesting links: OSM Isochrone
> 2 votes

---
Tags: algorithm, path-finding, path
---


# Question
Title: Doing legacy DirectX Coding on Windows 10
I decided to study couple of old computer graphics books like Andre LaMothe's Tricks of 3D Game Programming Gurus. I feel like this book is full of great general computer graphics knowledge and I want this to be an exploration.

The problem is, since the book is old, it uses a very old DirectX API. It is DirectX 7 I guess. I want to be able to code the presented ideas myself and I have a Windows 10 machine. And I have couple of more old books which uses old APIs like DirectX 7 and 8. The question is;

What are my options if I want to code the examples in these books? Is there a way to write DirectX 7,8 and 9 code in Windows 10? I checked the articles "Where is the DirectX SDK?" from MSDN but they are mainly about how to move from D3D9 to new APIs. I want to code in those APIs for the sake of doing the exercises in the book, not move from those APIs. I think this should be possible because I am playing games from these eras in my computer today. If my computer is able to run them, there should be a way for me to write them as well.

If this is not possible or is very hard, how hard it would be for me to convert and try these ideas on modern OpenGL while I read the books?

In the case that I am completely lost, do you think I can still learn the computer graphics ideas presented in the books by reading the code and making sense of it, even if I don't code them myself?

NOTE: I have fundamental knowledge of computer graphics and modern OpenGL. It is not like I am choosing these books to begin my CG exploration. There are probably better, modern books for those and I read couple of them. The reason I want to read these books is because I like old books :) and I want to explore old wisdom lay in these.

# Answer
> 5 votes
You can continue to use the legacy DirectX SDK for Direct3D 9 on Windows 10, but there are a number of caveats:

First, there is no Direct3D 9 Debug support on Windows 8.0, Windows 8.1, or Windows 10. That means no helpful diagnostic information in the debug window. The last OS to support Direct3D 9 debugging was Windows 7.

Second, if you are using VS 2012, VS 2013, or VS 2015 then you have to 'mix' the old legacy DirectX SDK with the newer Windows 8.x SDK carefully. The basic instructions for doing this are on Microsoft Docs and essentially involve swapping the include order for headers and libs: the Windows 8.1 SDK headers first, then the legacy DirectX SDK headers.

> The old `DXERR.LIB` is simply not compatible with VS 2015 at all. You can use this replacement instead.

> **UPDATE**: You can also use the Windows 8.x SDK or Windows 10 SDK for the Direct3D 9 headers, and then use the Microsoft.DXSDK.D3DX NuGet package to get D3DX9 without needing the legacy DirectX SDK or DirectSetup.

It's also useful to read The Zombie DirectX SDK. This is a more nuanced exploration of which parts of the legacy DirectX SDK still have legitimate uses and which should not be used.

> Actually installing the legacy DirectX SDK is also a challenge as it has some known issues.

This gets you 80% there and works for Direct3D 9. It's a bit more complicated if you want to use XAudio 1.3 or XAudio 2.7, but If you have Windows 10 you can just use the built-in XAudio 1.4 and XAudio 2.8 anyhow. See XINPUT and Windows 8 and XAudio2 and Windows 8 for more information.

There's really no good way to get an old enough DirectX SDK to contain D3DX8 to work with modern compilers, so Direct3D 9 is already pushing it. The DirectDraw7, Direct3D 7, Direct3D 8.x, and DirectSound APIs are supported for appcompat purposes by the OS, but YMMV. For more on which APIs are available where, see DirectX SDKs of a certain age.

**This is a whole lot of pain to sign up for just to use outdated books and legacy APIs that have much better modern replacements.** You should probably instead focus on DirectX 11, take a look at DirectX Tool Kit, and look for newer books. Once you actually understand how to code against DirectX 11, then you should have little problem in adapting the older books where the content is still applicable.

---
Tags: directx
---


# Question
Title: Authoritative Server Movement and Collision
I am attempting to write a proof of concept in preparation to do my first networked game. I have decided to do an authoritative server with client side prediction.

I am trying to implement my architecture like this diagram from an excellent article on the subject

In the article, the data that is synchronized is the player's position. This works great for turn based games, but what about real time games?

In my game, each entity has a position and a velocity vector. It is the server's job to detect collisions. I have attempted to send the server velocity changes, but I am having an issue where the server's position and the client's position begins to diverge because their clocks are not perfectly synchronized.

So my question is, is it standard practice to send positions as the synchronized state between a client and server instead of a velocity vector? Will changing to synchronizing positions instead of velocities open my game up to cheating? Is there a better way to synchronize the players' states with the server?

Also, if I use positions, doesn't that mean that the other players are going to be seen in a past state? Will that mean that the server might send a player killed message before the collision is visible to the player in the present?

# Answer
Making good multiplayer games isn't a trivial thing, we know. There are many aspects to care about: network architecture, machines synchronization, network delays, cheating... But, let's start one step per time.

In turn-based games, as you said, you are limited to send objects positions, because that is the only important information you'll need. In real-time, fast-paced video games (such as FPS, racing games...), good timing is the key to make the game enjoyable, and mostly *playable*.

When playing an FPS there are many objects to sync: players, bullets, weapons, vehicles, and then scores, chat messages... The more the objects, the more the packets to send over the network, and with few to no delays independently of your connection. That means you need a proper network protocol to connect different players to play together. That means you can't rely on TCP, because you are focusing on real-time simulation and fast updates, not packets integrity and reliability. UDP is better for this task. Well, not UDP as is, but a custom net protocol built on top of it.

The image you posted shows a basic client-server interaction, where the server is authoritative over the client. That means the client always applies the information received from the server, whatever it is, because it *is* the server and it is always right. And it is right because it is the only one running the game logic, whilst clients are only replicating it on different machines. Also, clients should replicate *exactly* the server simulation: this is called deterministic lockstep. A system is said deterministic if we can know every single action to perform to get to a state *B* from a given starting state *A*.
A video game *is* a deterministic system: if I hold the 'move forward' key for a certain amount of time, I can foresee the position I'm going to be at (thanks, high school physics).
Deterministic lockstep - together with floating point determinism, the property of several machines to compute same results if given the same starting numbers and operations to perform - is the reason a client can simulate for a small amount of time what is happening on the server when some packets are suddendly lost, if given the right state information such as position and velocity instead of one only of them.
On the other hand, deterministic lockstep and client-server synchronization is only possible if both the client and server are running the same code, and assuming that there are no game logic delays because of internal application integrating/rendering time.

In the FPS scenario, a server must send clients many updates per second, so that they are always running the most recent simulation possible (for example 20 updates per seconds). This rate should be nor low enough to cause lag because of many server-side corrections, neither too high for the client machine to handle (we don't want to congestionate one's connection).

Syncing your game isn't just telling clients objects coordinates and velocities vectors, and updating; you *must* make sure clients are able to sync single entities as well as whole game session (e.g. when a player wants to join a game in progress). Or, your game should be able to compensate network latency so that shooting to a player is actually shooting to a player on the server: clients are running a simulation *in the past* because of networking, and there are efficient ways to prevent players from feeling frustrated for playing a "bad" game.

Now, answering your question: what info does one need to send to sync clients? The Quake source code shows how they dealt with client synchronization: the server receives from clients every players' input, and then sends every player avatar's position, speed and direction, this way - using the same physics code - both clients and server will compute the same frames after small amounts of time. Eventually the server will perform corrections over the clients, and there is some data to update instantly and other one should interpolate smoothly, but the game will maintain its logical integrity most of the time. And let's not forget client-side prediction!

You can read more about networked physics, server authority, client-side prediction and server-side compensation here. Also, the Valve Developer Community is a place full of interesting guides to understand better how their engine (and, generally speaking, any possible engine) works.
> 7 votes

# Answer
In addition to the excellent and compact answer by Giorgio Liggio:

> is it standard practice to send positions as the synchronized state between a client and server instead of a velocity vector?

You send both and use both, they complete each other in a fault-tolerant and stretchful way. In addition, you would send events, like "client just turned his steering wheel right 20 degrees", etc.

> Will changing to synchronizing positions instead of velocities open my game up to cheating?

No. You use other protection mechanisms against cheating, like encryption, packet checksums, signature checking, secret numeric questions and answers, IP and MAC address housekeeping. You are free to code your own mambo jambo :-).

> Is there a better way to synchronize the players' states with the server?

See Giorgios answer and links. In addition, one way is to synchronise all invloved computers against a time server (you get a few ms of accuracy) and include a timestamp with each physics packet. Then receiving end then gets an accurate "snapshot" of the situation at a give timestamp, regardless of how fast or slow the packet was transmitted. From that on, you can correct and predict.

> Also, if I use positions, doesn't that mean that the other players are going to be seen in a past state?

No matter how you do it, the other end of the wire will be in past state. Hence the correction and prediction. In addition, ... well there is a nice saying for game developers: Add fog. If you have something that maybe doesn't look so good, then hide it, that's the easiest way. If you need time to think, then distract the user. For example, hide the opponent with a huge explosion and a ka-boom that last for 1 second. Then you get 1 second time to negotiate with server and other clients whether he died or not, before you must show the result.

> Will that mean that the server might send a player killed message before the collision is visible to the player in the present?

Not at all impossible, but this is more a question of your code design and logic. You have probably heard players accusing others for being cheaters, when they suddenly die without obvious reason. If it doesn't happen too often, players stay happy and want to continue using the product. A matter of gaming experience.
> 4 votes

---
Tags: game-design, client-server
---


# Question
Title: Visual cues in a full 3D game to help the player to identify the location of each object
I am working on adding some visual cues to the player to help identify where each objects are in 3D. In many space games, there is usually an indicate on the edge of screen that reflects the direction towards that particular object. For example, an indicator in the upper middle edge of screen may indicate that particular object is straight ahead and an indicator in the lower middle of edge screen may indicate that object is directly behind.

If the game is mostly 2D, such as most FPS shooters, this would not be a difficult problem. Then the indicator is basically a top down radar. But with full 3D, Im unsure how to translate this inherently 3D information to 2D in a intuitive, yet meaningful way. If just using the 2D radar method, then I cant convey pitch/elevation information. For example, an indicator in the upper middle edge of screen can not differentiate between an object that is straight head in the same plane as the player versus something that the player needs to tilt 45 degrees upwards to see.

Is there something better than the top down radar method?

# Answer
If we consider a 'classic' top-down view minimap, we can consider that the minimap is at the plane of z = 0.

To help show the 3d dimension, you could add an additional plane at x = 0 and another at y = 0, and project a line between the object and the 3 planes.

Of course, you'll have to modify the angle of view of the 3d map with regard to the current view of the

Another thing you could try is have the map around the 'ship' in the environment and have have the objects in space project a line down (or up) on that map: this gives an idea where the other objects are relatively to the 'ship'.

Eve Online does this and it gives a nice feeling. In the following screenshot, we can see that the space station is at a bit more than 10 km, with the player's ship is in the centre of the concentric circles.
> 0 votes

---
Tags: 3d, game-design, user-experience
---


# Question
Title: How to tell OpenGL to use normals for lighting?
Let's say I have

```
    glGenBuffers(1, &vertexbuffer);
    glGenBuffers(1, &indexbuffer);
    glGenBuffers(1, &normalbuffer);

    glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(float)*numVertices*3,verticesArr,GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,numIndices*sizeof(GLuint)*3,indicesArr,GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER,normalbuffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(float)*numVertices*3, normalsArr, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
    glVertexAttribPointer( 0, 3GL_FLOAT,GL_FALSE,24, (void*)(0));

    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER,normalbuffer);
    glVertexAttribPointer( 1, 3GL_FLOAT,GL_FALSE,24, (void*)(12));

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexbuffer);

```

is it possible to tell OpenGl to use the normals in buffer for light "calculation"?

Basically I want to know how to say to OpenGl: "Here are my normals take them and make me nice lighting". Since I didn't find answer in google I posted my question here. Thank you for attention.

# Answer
I found solution:

```
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, 0, normalsArr);

```

above code tells OpenGL to consider normals
> 1 votes

---
Tags: opengl
---


title: Unity - Order in Z layer for objects

text:
# Question
Title: Unity - Order in Z layer for objects
Sorry if the title isn't exactly what my question is, I don't really know how to describe it.

I have an image for my city floor and an image (same size) for all the walls or trees that the player is supposed to be hidden behind, if he walks past behind it. My result doesn't even look so bad:

The problem is that if the player walks infront of the wall, he vanishes, because the layerorder of the wall is above the order of the player:

**Is there a rather simple way to fix this, or do I have to add all those objects manually and connect them to some scripts?**

# Answer
> 17 votes
To achieve this effect:

Create two sorting layers: **Ground** and **Objects**.

Have your road, grass, and path sprites use the Ground layer.

Have your character, walls, and house sprites use the Objects layer.

Sprites on your Objects layer will want to have their Sprite Mode Pivot Point be either Bottom Left, Bottom, or Bottom Right. You can choose this by selecting a Sprite within your Project tab, and choose the pivot point in the Inspector tab to adjust the sprite's import settings.

For ground sprites, you won't have to worry about changing their order.

For objects, however, you can either change their Sprite Renderer's sorting order, or change their `transform.position.z` value. I'd recommend changing the transform, as the floats will probably be easier to look at and adjust as you move your character around, whereas changing the sorting order might not look as precise in certain situations, depending on the measurements and sizes of your objects in the scene.

In either case, some code will be needed.

```
public class SpritePositionSetter : MonoBehaviour {

    void Awake () {
        SetPosition();
    }

    void Update () {
        SetPosition();
    }

    void SetPosition () {
        // If you want to change the transform, use this
        Vector3 newPosition = transform.position;
        newPosition.z = transform.position.y;
        transform.position = newPosition;

        // Or if you want to change the SpriteRenderer's sorting order, use this
        GetComponent<SpriteRenderer>().sortingOrder = (int)transform.position.y;
    }

}

```

For either way of doing this, you're basically telling the sprite to have its Z index match its Y position.

If you attach this script to a static object (like a wall), you'll want to untick the component in the Inspector so that its `Update` method isn't called every frame; its `Awake` method will call `SetPosition` once and that's all you need.

But for your character, leave the component ticked so that `Update` will call `SetPosition` every frame, which will change the character's Z order as you move around. And as you move, as long as every sprite on the Objects layer is using a Bottom pivot point, changing the Z index as you move will ensure your character appears in front of or behind other objects appropriately.

Depending on your camera setup, you may need to multiply the new Z position by `-1` if things seem backwards.

If you want to adjust the Z index while editing your Scene, check out ExecuteInEditMode.

---
Tags: unity, pixel-art
---


# Question
Title: Unity - Hide GameObject that is behind UI
I have the following example:

How can I prevent the part of the sprite that is highlighted in red and is behind the UI from being displayed on the camera, but having the background image still showing?

# Answer
Your Question is NOT clear ..but We can do following ways to hide the GAMEOBJECT..

1.If you use the gameobject -\> sprite renderer -\> order in layer (set order in layer into **0 or -1**)

2.If you use the Canvas Concept Change the gameobject Z position or do game object like,

```
 public gameobject hideobj;
  hideobj.setActive(false);

```

whenever you want that game object again you can true the gameobject `hideobj.setActive(true);`

3.Disable the Gameobject component

```
 Gameobject("hideobj").getComponent<Image>.enabled=false;

```
> 1 votes

---
Tags: unity, gui, gameobject
---


title: Rendering 2d sprites into a 3d world?

text:
# Question
Title: Rendering 2d sprites into a 3d world?
In opengl how do I render 2d sprites in opengl given that I have a png of the sprite? See images as an example of the effect I'd like to achieve. Also I would like to overlay weapons on the screen like the rifle in the bottom image. Does anyone know how I would achieve the two effects? Any help is greatly achieved.

# Answer
What you are looking for is called a billboard or projective sprite. A billboard is basically a quad that always faces the camera. If you don't need it to always face the camera then the code/math will be much simpler.

You can read more about how to implement them here:

http://www.lighthouse3d.com/opengl/billboarding/index.php3?billCyl

http://nehe.gamedev.net/data/articles/article.asp?article=19

http://www.flipcode.com/archives/Billboarding-Excerpt\_From\_iReal-Time\_Renderingi\_2E.shtml
> 13 votes

# Answer
**opengl-tutorial** has:

Screenshot:

Code:

```
#include <stdio.h>
#include <stdlib.h>

#include <vector>
#include <algorithm>

#include <GL/glew.h>

#include <glfw3.h>
GLFWwindow* window;

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/norm.hpp>
using namespace glm;

#include <common/shader.hpp>
#include <common/texture.hpp>
#include <common/controls.hpp>

#define DRAW_CUBE // Comment or uncomment this to simplify the code

int main( void )
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow( 1024, 768, "Tutorial 18 - Billboards", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    // Hide the mouse and enable unlimited mouvement
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Set the mouse at the center of the screen
    glfwPollEvents();
    glfwSetCursorPos(window, 1024/2, 768/2);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS);

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // Create and compile our GLSL program from the shaders
    GLuint programID = LoadShaders( "Billboard.vertexshader", "Billboard.fragmentshader" );

    // Vertex shader
    GLuint CameraRight_worldspace_ID  = glGetUniformLocation(programID, "CameraRight_worldspace");
    GLuint CameraUp_worldspace_ID  = glGetUniformLocation(programID, "CameraUp_worldspace");
    GLuint ViewProjMatrixID = glGetUniformLocation(programID, "VP");
    GLuint BillboardPosID = glGetUniformLocation(programID, "BillboardPos");
    GLuint BillboardSizeID = glGetUniformLocation(programID, "BillboardSize");
    GLuint LifeLevelID = glGetUniformLocation(programID, "LifeLevel");

    GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");

    GLuint Texture = loadDDS("ExampleBillboard.DDS");

    // The VBO containing the 4 vertices of the particles.
    static const GLfloat g_vertex_buffer_data[] = {
         -0.5f, -0.5f, 0.0f,
          0.5f, -0.5f, 0.0f,
         -0.5f,  0.5f, 0.0f,
          0.5f,  0.5f, 0.0f,
    };
    GLuint billboard_vertex_buffer;
    glGenBuffers(1, &billboard_vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_DYNAMIC_DRAW);

#ifdef DRAW_CUBE
    // Everything here comes from Tutorial 4
    GLuint cubeProgramID = LoadShaders( "../tutorial04_colored_cube/TransformVertexShader.vertexshader", "../tutorial04_colored_cube/ColorFragmentShader.fragmentshader" );
    GLuint cubeMatrixID = glGetUniformLocation(cubeProgramID, "MVP");
    static const GLfloat g_cube_vertex_buffer_data[] = { -1.0f,-1.0f,-1.0f,-1.0f,-1.0f, 1.0f,-1.0f, 1.0f, 1.0f,1.0f, 1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f, 1.0f,-1.0f,1.0f,-1.0f, 1.0f,-1.0f,-1.0f,-1.0f,1.0f,-1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f,1.0f,-1.0f, 1.0f,1.0f, 1.0f, 1.0f,1.0f,-1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f,-1.0f,-1.0f,1.0f, 1.0f, 1.0f,1.0f,-1.0f, 1.0f,1.0f, 1.0f, 1.0f,1.0f, 1.0f,-1.0f,-1.0f, 1.0f,-1.0f,1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f,1.0f,-1.0f, 1.0f};
    static const GLfloat g_cube_color_buffer_data[] = { 0.583f,  0.771f,  0.014f,0.609f,  0.115f,  0.436f,0.327f,  0.483f,  0.844f,0.822f,  0.569f,  0.201f,0.435f,  0.602f,  0.223f,0.310f,  0.747f,  0.185f,0.597f,  0.770f,  0.761f,0.559f,  0.436f,  0.730f,0.359f,  0.583f,  0.152f,0.483f,  0.596f,  0.789f,0.559f,  0.861f,  0.639f,0.195f,  0.548f,  0.859f,0.014f,  0.184f,  0.576f,0.771f,  0.328f,  0.970f,0.406f,  0.615f,  0.116f,0.676f,  0.977f,  0.133f,0.971f,  0.572f,  0.833f,0.140f,  0.616f,  0.489f,0.997f,  0.513f,  0.064f,0.945f,  0.719f,  0.592f,0.543f,  0.021f,  0.978f,0.279f,  0.317f,  0.505f,0.167f,  0.620f,  0.077f,0.347f,  0.857f,  0.137f,0.055f,  0.953f,  0.042f,0.714f,  0.505f,  0.345f,0.783f,  0.290f,  0.734f,0.722f,  0.645f,  0.174f,0.302f,  0.455f,  0.848f,0.225f,  0.587f,  0.040f,0.517f,  0.713f,  0.338f,0.053f,  0.959f,  0.120f,0.393f,  0.621f,  0.362f,0.673f,  0.211f,  0.457f,0.820f,  0.883f,  0.371f,0.982f,  0.099f,  0.879f};
    GLuint cubevertexbuffer;
    glGenBuffers(1, &cubevertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, cubevertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_cube_vertex_buffer_data), g_cube_vertex_buffer_data, GL_DYNAMIC_DRAW);
    GLuint cubecolorbuffer;
    glGenBuffers(1, &cubecolorbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, cubecolorbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_cube_color_buffer_data), g_cube_color_buffer_data, GL_DYNAMIC_DRAW);
#endif

    double lastTime = glfwGetTime();
    do
    {
        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        double currentTime = glfwGetTime();
        double delta = currentTime - lastTime;
        lastTime = currentTime;

        computeMatricesFromInputs();
        glm::mat4 ProjectionMatrix = getProjectionMatrix();
        glm::mat4 ViewMatrix = getViewMatrix();

#ifdef DRAW_CUBE
        // Again : this is just Tutorial 4 !
        glDisable(GL_BLEND);
        glUseProgram(cubeProgramID);
        glm::mat4 cubeModelMatrix(1.0f);
        cubeModelMatrix = glm::scale(cubeModelMatrix, glm::vec3(0.2f, 0.2f, 0.2f));
        glm::mat4 cubeMVP = ProjectionMatrix * ViewMatrix * cubeModelMatrix;
        glUniformMatrix4fv(cubeMatrixID, 1, GL_FALSE, &cubeMVP[0][0]);
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, cubevertexbuffer);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0  );
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, cubecolorbuffer);
        glVertexAttribPointer(1, 3, GL_FLOAT,  GL_FALSE, 0, (void*)0   );
        glDrawArrays(GL_TRIANGLES, 0, 12*3);
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
#endif

        // We will need the camera's position in order to sort the particles
        // w.r.t the camera's distance.
        // There should be a getCameraPosition() function in common/controls.cpp,
        // but this works too.
        glm::vec3 CameraPosition(glm::inverse(ViewMatrix)[3]);

        glm::mat4 ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;

        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        // Use our shader
        glUseProgram(programID);

        // Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Texture);
        // Set our "myTextureSampler" sampler to user Texture Unit 0
        glUniform1i(TextureID, 0);

        // This is the only interesting part of the tutorial.
        // This is equivalent to mlutiplying (1,0,0) and (0,1,0) by inverse(ViewMatrix).
        // ViewMatrix is orthogonal (it was made this way),
        // so its inverse is also its transpose,
        // and transposing a matrix is "free" (inversing is slooow)
        glUniform3f(CameraRight_worldspace_ID, ViewMatrix[0][0], ViewMatrix[1][0], ViewMatrix[2][0]);
        glUniform3f(CameraUp_worldspace_ID   , ViewMatrix[0][1], ViewMatrix[1][1], ViewMatrix[2][1]);

        glUniform3f(BillboardPosID, 0.0f, 0.5f, 0.0f); // The billboard will be just above the cube
        glUniform2f(BillboardSizeID, 1.0f, 0.125f);     // and 1m*12cm, because it matches its 256*32 resolution =)

        // Generate some fake life level and send it to glsl
        float LifeLevel = sin(currentTime)*0.1f + 0.7f;
        glUniform1f(LifeLevelID, LifeLevel);

        glUniformMatrix4fv(ViewProjMatrixID, 1, GL_FALSE, &ViewProjectionMatrix[0][0]);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer);
        glVertexAttribPointer(
            0,                  // attribute. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );

        // Draw the billboard !
        // This draws a triangle_strip which looks like a quad.
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glDisableVertexAttribArray(0);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0 );

    // Cleanup VBO and shader
    glDeleteBuffers(1, &billboard_vertex_buffer);
    glDeleteProgram(programID);
    glDeleteTextures(1, &TextureID);
    glDeleteVertexArrays(1, &VertexArrayID);
#ifdef DRAW_CUBE
    glDeleteProgram(cubeProgramID);
    glDeleteVertexArrays(1, &cubevertexbuffer);
    glDeleteVertexArrays(1, &cubecolorbuffer);
#endif
    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}

```

Tested on Ubuntu 15.10.

Axis oriented version of this question: How do I implement camera axis aligned billboards? Here we have done a viewpoint oriented billboard.
> 0 votes

---
Tags: graphics, opengl, iphone, opengl-es, webgl
---


# Question
Title: SDL Key Input previous and current key states not working as expected, how to fix?
Here is my code that's part of the main game loop:

```
  // ResetKeyState stores currentKeyState in previousKeyState
  // and then clears currentKeyState
  engine.ResetKeyState();

  // Fill currentKeyState
  while (SDL_PollEvent(&e) != 0)
  {
     // Call input to notify
     engine.Input(e);
     if (e.type == SDL_QUIT)
        engine.Quit();
  }

  // Return control to programmer for implementation
 engine.EngineUpdate();

  // Draw a pretty picture
  engine.EngineDraw();

```

and then to handle the input I have Input(e)

```
void Engine::Input(SDL_Event e)
{
   switch (e.type)
   {
   case SDL_KEYDOWN:
      KeyIsDown(e.key.keysym.sym);
      break;

   case SDL_KEYUP:
      KeyIsUp(e.key.keysym.sym);
      break;

   default:
      break;
   }
}

```

`KeyIsDown` stores the boolean state in an array as a true value.

`KeyIsUp` stores a false value.

Then later, I thought I would be able to do this to get a single input.

```
if (IsCurrentKeyDown('a') && !IsPreviousKeyDown('a'))

```

`IsCurrentKeyDown` and `IsPreviousKeyDown` just get data from their arrays

```
bool currentKeyState[INPUT_SIZE];
bool previousKeyState[INPUT_SIZE];

```

This way if you've are currently pressing the key but the value hasn't yet been stored it takes input once.

IE: You press the key so `currentKeyDown` is true and `previousKeyDown` is `false` until next update where `currentKey` gets passed to `previousKey` and the statement is then `false`. It's how Monogame and XNA do it so I figured I'd implement it here.

But it didn't work. I put a break point with a hit counter on it and it would hit it more than once per press. What am I doing wrong?

# Answer
Your issue is that SDL sends keyboard events only when the state changes. So, if you move your current buffer to the previous buffer and then clear the current buffer, your keystate won't be correct on any of the frames after a key press. On the frame when the key was pressed, the current buffer should hold the value, but on frames after, there won't be a mark in the current buffer. Even the prevous buffer will lose it's value after a couple of frames.
> 1 votes

---
Tags: c++, input, sdl2
---