# Question
Title: Make a cell's content 'listens' to another cell (the closest cells)
I'm a newbie in programming and in java and I need some lights and help.I'm developing a game in which two players have to play with tokens (say red and blue) by placing them in cells (75x75 grid). The goal is to "capture" opponent's tokens by surrounding them. (See the image, which is the actual game output, the surrounding is drawn by hand)

To do so, I need to make the tokens "listen" to neighborhood, meaning other cells in the grid. A token has to check for itself in the grid(what is its position in the grid) and check of there is another token close to it, checks it color (blue or red) then, in certain conditions, trigger the capturing mechanism (draw line segments from the last token to the first).

What I have done, technically:

1. Created the grid ( Grid/board is a 2 dimensional array of Token objects.)
2. The token (which is an enumeration:

public enum Jeton{ VIDE, CERCLE\_ROUGE, CERCLE\_BLEU }).
3. A current player is also a Token `private Token joueurActuel;` When it's a player's turn, they select an empty cell at which they click this place the *joueurActuel* into the grid/board at cell *ligneSelectionnee*, *colonneSelectionnee* then repaint the canvas with the newly added cell in the grid/board.

Everything works: every token is printed and switch as players click. Now i'm stuck on how to make the tokens listen the next cell surrounding them in order to see if there is an opponent or an ally so that

Someone suggested me the *A* algorithm\* and the only documentations i found are in english - imagine the effort i have to do to understand properly. The one i found in french is about c++ implementation, I've no idea how to to it in java: keywords are different, etc.

PS: ***I posted this question on stack overflow first, but I guess no one is very interested in video games there and got downgraded (-3). I'm just 15, so please be more tolerent. Please apologise for my english, i learn it from school and my mother language is french (I live in Congo).***

I'm unable to post image because of my reputation :'(

Here is my code (took me several months and thousands attemps to make it work though): variables names are in french, I can provide translation if needed.

```
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;

    public final class Phagocyte extends JFrame {

        public  static final int LIGNES = 75; //Cellules = lignes x colonnes
        public static final int COLONNES = 75;//Cellules = lignes x colonnes

        //Noms des constants des dimensions variées utilisées pour le dessins graphiques
        public static final float TAILLE_CELLULE = (float) 20.0; //Largeur et hauteur des cellules (de forme carée)
        public static final int LARGEUR_DE_LA_TOILE = (int) (TAILLE_CELLULE * COLONNES); // Dessine la toille (tableau)
        public static final int HAUTEUR_DE_LA_TOILE = (int) (TAILLE_CELLULE * LIGNES);
        public static final int LARGEUR_DE_LA_GRILLE = 2; // La largeur des lignes de la grille
        public static final int DEMI_LARGEUR_GRILLE = LARGEUR_DE_LA_GRILLE / 2;

        //Les symboles (rouge et bleu) sont affichés à l'intérieur des cercles avec rembourage des bordures
        public static final int REMBOURAGE_CELLULE = (int) (TAILLE_CELLULE / 5);
        public static final int TAILLE_SYMBOLE = (int) (TAILLE_CELLULE - REMBOURAGE_CELLULE *2 ); //Largeur / Hauteur
        public static final int LARGEUR_TRAIT_SYMBOLE = 3; //Largeur des traits

        //Utiliser une table d'ennumération (class interne) pour représenter les états variés du jeu
        public enum EtatJeu{
            JOUE, NUL, CERCLE_ROUGE_GAGNE, CERCLE_BLEU_GAGNE
        }

        private EtatJeu etatActuel; //Etat actuel du jeu

        //Utiliser une table d'enumération (classe interne) pour représenter les contenu des cellules et seed
        public enum Jeton{
            VIDE, CERCLE_ROUGE, CERCLE_BLEU
        }

        private Jeton joueurActuel; //Le joueur qui a la main

        private Jeton[][] planche; //l'aire de jeu avec cellules composées des lignes et colonnes
        private DessineToile toile; //Dessine la toile (avec JPanel) pour l'air de jeu
        private JLabel barreDetat; // La barre d'état

        /*Constructeurs pour definir les composants du jeu et de l'interface utilisateur (IU)*/
        public Phagocyte(){

            toile = new DessineToile(); //Construit une toile (JPanel)
            toile.setPreferredSize(new Dimension(LARGEUR_DE_LA_TOILE, HAUTEUR_DE_LA_TOILE));

        //Comportement de la toile (JPanel) en rapport avec un clic de la souris
            toile.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) { //Gestion des clics de souris
            int sourisX = e.getX();
            int  sourisY = e.getY();

            //Verifier le clic sur les lignes et colonnes
            int ligneSelectionnee = (int) (sourisY / TAILLE_CELLULE);
            int colonneSelectionnee;
                colonneSelectionnee = (int) (sourisX / TAILLE_CELLULE);

            if(etatActuel == EtatJeu.JOUE){
                if(ligneSelectionnee >= 0 && ligneSelectionnee < LIGNES && colonneSelectionnee >= 0
                        && colonneSelectionnee < COLONNES &&
                        planche[ligneSelectionnee][colonneSelectionnee] == Jeton.VIDE){
                    planche[ligneSelectionnee][colonneSelectionnee] = joueurActuel; //Joue un tour
                    actualiseJeu(joueurActuel, ligneSelectionnee, colonneSelectionnee); //Met a jour l'etat de jeu
                    joueurActuel = (joueurActuel == Jeton.CERCLE_ROUGE)? Jeton.CERCLE_BLEU : Jeton.CERCLE_ROUGE;
                }
            } else { //Fin de la partie
                initJeu(); //Rejouer le jeu
            }
            //Actueliser le dessin de la toile
            repaint(); //Rappeler la fonction dessinner
        }

      });

        //Barre d'état (JPanel) pour afficher les messages
        barreDetat = new JLabel("  ");
        barreDetat.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 15));
        barreDetat.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));

        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());
        cp.add(toile, BorderLayout.CENTER);
        cp.add(barreDetat, BorderLayout.NORTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack(); //Emballer tous les composants dans cette JFrame
        setTitle("Phagocyte par esQmo");
        setVisible(true); //Afficher cette fenetre

        planche = new Jeton[LIGNES][COLONNES]; //Allouer le tableau
        initJeu(); //Initialise les contenus de l'aire de jeu et ses variables
    }
        /*initialisation  des contenus l'aire de jeu et les differenrs status*/
        public void initJeu(){
            for(int ligne = 0; ligne < LIGNES; ++ligne){
                for(int colonne = 0; colonne < COLONNES; ++colonne){
                    planche[ligne][colonne] = Jeton.VIDE; //Toutes les cellules sont vides
                }
            }
            etatActuel = EtatJeu.JOUE; //Pret a jouer
            joueurActuel = Jeton.CERCLE_ROUGE; //Le rouge ouvre la partie
        }

        public void actualiseJeu(Jeton leJeton, int ligneSelectionnee, int colonneSelectionnee) {
          if (aGagne(leJeton, ligneSelectionnee, colonneSelectionnee)) {  // check for win
             etatActuel= (leJeton == Jeton.CERCLE_ROUGE) ? EtatJeu.CERCLE_ROUGE_GAGNE : EtatJeu.CERCLE_BLEU_GAGNE;
          } else if (estNul()) {  // check for draw
             etatActuel = EtatJeu.CERCLE_BLEU_GAGNE;
          }
          // Otherwise, no change to current state (still GameState.PLAYING).
       }
     public boolean estNul() {
          for (int row = 0; row < LIGNES; ++row) {
             for (int col = 0; col < COLONNES; ++col) {
                if (planche[row][col] == Jeton.VIDE) {
                   return false; // an empty cell found, not draw, exit
                }
             }
          }
          return true;  // no more empty cell, it's a draw
       }

       public boolean aGagne(Jeton leJeton, int ligneSelectionnee, int colonneSelectionnee) {
return
    }

    class DessineToile extends JPanel{

            @Override
            public void paintComponent(Graphics g){ //Invoqué via repaint()
                super.paintComponent(g); //Pour remplir l'arriere plan
                setBackground(Color.WHITE); //Defini la couleur de l'arriere plan

                //Dessine les lignes de la toile
                g.setColor(Color.BLACK);
                for(int ligne = 1; ligne < LIGNES; ++ligne){
                    g.fillRoundRect(0, (int) (TAILLE_CELLULE * ligne - DEMI_LARGEUR_GRILLE), LARGEUR_DE_LA_TOILE - 1,
                            LARGEUR_DE_LA_GRILLE, LARGEUR_DE_LA_GRILLE, LARGEUR_DE_LA_GRILLE);
                }
                for(int colonne = 1; colonne < COLONNES; ++colonne){
                    g.fillRoundRect((int) (TAILLE_CELLULE * colonne - DEMI_LARGEUR_GRILLE), 0
                            , LARGEUR_DE_LA_GRILLE, HAUTEUR_DE_LA_TOILE - 1,
                            LARGEUR_DE_LA_GRILLE, LARGEUR_DE_LA_GRILLE);
                }

                //Dessine le jeton (seed) pour toutes les cellules si elles ne sont pas vides
                //Utilise la Graphic2D pour le trait
                Graphics2D g2d = (Graphics2D)g;
                g2d.setStroke(new BasicStroke(LARGEUR_TRAIT_SYMBOLE,
                        BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); //Dessin en 2D uniquement
                for(int ligne = 0; ligne < LIGNES; ++ligne){
                    for(int colonne = 0; colonne < COLONNES; ++colonne){
                        int x1 = (int) (colonne * TAILLE_CELLULE + REMBOURAGE_CELLULE);
                        int y1 = (int) (ligne * TAILLE_CELLULE + REMBOURAGE_CELLULE);

                        if(planche[ligne][colonne] == Jeton.CERCLE_ROUGE){
                            g2d.setColor(Color.RED);
                            g2d.drawOval(x1, y1, TAILLE_SYMBOLE, TAILLE_SYMBOLE);
                            g2d.fillOval(x1, y1, TAILLE_SYMBOLE, TAILLE_SYMBOLE);
                        } else
                            if(planche[ligne][colonne] == Jeton.CERCLE_BLEU){
                                int x2 = (int) (colonne * TAILLE_CELLULE + REMBOURAGE_CELLULE);
                                g2d.setColor(Color.BLUE);
                                g2d.drawOval(x1, y1, TAILLE_SYMBOLE, TAILLE_SYMBOLE);
                                g2d.fillOval(x2, y1, TAILLE_SYMBOLE, TAILLE_SYMBOLE);
                            }
                    }

                }

                //Imprime les messages sur la barre d'etat
                if(etatActuel == EtatJeu.JOUE){
                    if(joueurActuel == Jeton.CERCLE_ROUGE){
                        barreDetat.setText("ROUGE, c'est votre tour");
                        barreDetat.setForeground(Color.RED);
                    } else {
                        barreDetat.setText("BLEU, c'est votre tour");
                        barreDetat.setForeground(Color.BLUE);
                        barreDetat.addMouseMotionListener(null);
                    }
                } else
                    if(etatActuel == EtatJeu.NUL){
                        barreDetat.setForeground(Color.yellow);
                        barreDetat.setText("Match nul! Cliquez pour rejouer");
                    } else
                        if(etatActuel == EtatJeu.CERCLE_ROUGE_GAGNE){
                            barreDetat.setText("Le jouer X a remporté la partie, cliquez pour rejouer");
                            barreDetat.setForeground(Color.RED);
                        } else
                            if(etatActuel == EtatJeu.CERCLE_BLEU_GAGNE){
                                barreDetat.setForeground(Color.BLUE);
                                barreDetat.setText("Le joueur O a remporté la partie, cliquez pour rejouer");
                            }
            }
        }

        /*La méthode principale*/
        public static void main(String[] args){
            SwingUtilities.invokeLater(() -> {
                Phagocyte phagocyte = new Phagocyte();
            });
        }
    }

```

# Answer
> 2 votes
The best would be to create an independent class `Jeton`, which would contain an enumeration (as you currently do), but also the X and Y position in the grid (in which column and which line). To check if the token next to yours is ally or not, you could keep the table with all your `Jeton`s, and iterate over it like this :

```
for (Jeton token : planche) {
    if(token != Jeton.VIDE) {
        //We check if there is a token in the same line and next to the one we want to place
        if(token.x == colonneSelectionnee - 1 || token.x == colonneSelectionnee + 1) {
            //We check if there is a token in the same column and next to the one we want to place
            if(token.y == ligneSelectionnee - 1 || token.y == ligneSelectionnee + 1) {
                if(token != joueurActuel) { //We check if the token is ally or not
                     doSomething(); //Like attack
                } else {
                     doSomethingElse();
                }
            }
        }
    }
}

```

I don't know if this code is the best way to implement this, but it is a way to do it. I hope it helped you :)

# Answer
> 1 votes
If I understand your question correctly, the problem you're trying to solve is to find out whether a newly placed token closes some area, therefore capturing other tokens.

The first solution that comes to my mind is to run a breadth-first search (explained on Wikipedia). Treat your own tokens as graph nodes, while edges exist whenever two tokens are neighbours. Placing a token captures an area if while running the search algorithm you encounter the starting token again. I can write some pseudocode for you if you need.

---
Tags: java, algorithm, path-finding, swing
---


# Question
Title: How to export Visual Studio game for mass distribution
I've coded a Visual Studio 2015 game in SDL2 and ran some distribution tests, I gave a user the game's .exe (the raw game with no files) and they got the error **SDL2.dll is missing**. How would I export the game so it includes the least amount of rubbish (visual studio) files and doesn't produce these sdl errors.

# Answer
> 1 votes
By testing.

To test your installer - which you build with any of the many installer tools your favorite search engine suggests - you should use a clean virtual machine. Anytime you test the installer, you first reset the machine to it's initial state. Such a reset removes any changes made by a previous run of the installer, including things that are easy to forget about, like registry settings or the visual studio redistributable package.

# Answer
> 0 votes
You could use the costura.fody nuget package. This will take your referenced dll's and embed them into one exe file.

# Answer
> 0 votes
So what you are looking for is some type of an installer-builder. You need something that takes the DLLs your game relies on, the game executable and all the resource files that your game loads in, and packages those into a single installer file, which will then extract all those files to the directory specified by the user. There are multiple systems that allow you to do this, I personally only have experience with WiX Toolset. An installer also allows you to reference VS Redistrubutables, which will be installed on the user's machine if they are not found.

An alternative to this would be to use a zip-file, where you manually copy the DLLs, resource files and the game executable. This way the user can just extract the package to a directory, and run the game. This however doesn't guarantee that any redistributables would be installed on the user's machine.

---
Tags: sdl2, visual-studio, export
---


# Question
Title: Any idea to be able to make the character still continue the game until no heart left
I am newbie I am making a 2d game in unity 3d my code for the character game over is this.. I can get the heart less one heart if game over but turn back to five again I just want to decrease heart whenever character die until it loss all the five heart

and my code for the heart is this...

```
function Start () {
    coins = PlayerPrefs.GetInt("Coin");
    moveSpeed=10;
    anim=GetComponent(Animator);
    MainCode.Hearts = 5;
}

function Update () {

    transform.rotation.z=0;
    if(Input.GetKey(KeyCode.UpArrow)){
         transform.position.y+=moveSpeed*Time.deltaTime;
    }

    if(transform.position.y<-5) {
         Application.LoadLevel(Application.loadedLevel);
         MainCode.Hearts -=1;
    }
    if (MainCode.Hearts <= 0){
         GameOver();
    }

}

var image : GUITexture;
var Image_01 : Texture2D;
var Image_02 : Texture2D;
var Image_03 : Texture2D;
var Image_04 : Texture2D;
var Image_05 : Texture2D;
var Image_06 : Texture2D;

function Update {
    if(MainCode.Hearts == 5){
         image.texture= Image_01;
    }
    if(MainCode.Hearts == 4){
        image.texture= Image_02;
    }
    if(MainCode.Hearts == 3){
        image.texture= Image_03;
    }
    if(MainCode.Hearts == 2){
         image.texture= Image_04;
    }
    if(MainCode.Hearts == 1){
        image.texture= Image_05;
    }
}

```

however its not working properly any help would be really much appreciated thank you in advance

# Answer
> 1 votes
The `Update()` method is executed multiple times per second while your game is running. In the beginning of your update function you set `MainCode.Hearts = 5;`. That means whenever that variable is set to a different value it will be reset back to 5 shortly after.

You likely want to create a `Start()` method and move that line there. The Start-method is called once when the game object it is attached to is created.

Note that reloading the scene with `Application.LoadLevel` also re-creates all objects which re-executes all their `Start`-methods. As a workaround you can either use a start-method on a game-object which is not affected by LoadLevel (`DontDestroyOnLoad`) or reset the level by resetting all objects manually.

# Answer
> 0 votes
Here is how your game logic should be

```
Init function
    Hearts count = 5;

Game loop
    For each frame
        update()
        draw()

update function
    if died
         Hearts count --;
    if Hearts count == 0
         GameOver();

draw function
    your drawing stuff

```

Then all you need to do is call the Init function at the beginning, then lauch the loop.

Beware that I just wrote peudo-code, don't try to copy-paste, try to undestand the underlying logic :)

---
Tags: javascript, unityscript
---


# Question
Title: Why doesn't SDL_Mixer play my audio file?
I'm coding a game in SDL2 and I'm implementing the audio system using SDL\_Mixer. However, my music file won't play during the program and I don't know why. How do I get the music to play?

Audio initialization:

```
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);

```

Opening the audio device:

```
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
    std::cout << "Error:" << Mix_GetError() << std::endl;

```

Loading the sound file:

```
Mix_Chunk *soundEffect = Mix_LoadWAV("Sound\BetaMusic.wav");

```

Playing the sound file:

```
Mix_PlayChannel(-1, soundEffect, -1);

```

# Answer
> 1 votes
You need to change the backslash into a forward slash while loading the audio chunk. `Mix_Chunk *soundEffect = Mix_LoadWAV("Sound/BetaMusic.wav");` should do the trick.

---
Tags: c++, sdl2, visual-studio
---


# Question
Title: Unet, client is unable to control spawned units
I am trying to create a simple table top game with Unet. Right now I am just trying to get simple spawn mechanics working. The issue I am having is that the host computer can spawn and control objects correctly. The object gets instantiated, it gets added as a child to the armylist gameObject correctly. The client is able to see the object move around. Etc. Everything is working correctly it appears from the host side.

The client however, can only instantiate a game object then they lose all reference to it. Also when it gets instantiated it does not become a child of the correct object, it is just its own object in the scene without a parent. The host computer can see the object be spawned.

I am not sure what I am doing wrong, I have tried reading the documentation but to no avail. Any help would be greatly appreciated.

```
public class PlayerManager : NetworkBehaviour {

[SerializeField]
GameObject tank;
[SerializeField]
Camera PlayerCamera;

[SerializeField]
GameObject[] ArmyList = new GameObject[50];

private Vector3 placePos;
GameObject currentUnit;

void Start () {

}

void Update () {
    if (Input.GetKeyDown (KeyCode.A)) {
        Cmd_place_initial_units ();
    }
    Rpc_PlaceUnit ();
}

[Command]
void Cmd_place_initial_units(){
    currentUnit = Instantiate(tank, placePos, Quaternion.identity) as GameObject;
    currentUnit.transform.parent = transform.GetChild(0);
    ArmyList [0] = transform.GetChild (0).GetChild (0).gameObject;
    NetworkServer.SpawnWithClientAuthority (currentUnit, connectionToClient);
}

void Rpc_PlaceUnit(){
    if (ArmyList[0] != null) {
        RaycastHit hit;
        if (Physics.Raycast (PlayerCamera.ScreenPointToRay (Input.mousePosition), out hit)) {
            if (ArmyList[0].tag == "ground") {
                placePos = new Vector3 (hit.point.x, 1f, hit.point.z);
            } else {
                placePos = new Vector3 (hit.point.x, 1.2f, hit.point.z);
            }
            ArmyList[0] .transform.position = placePos;
        }
    }
}
}

```

# Answer
Fixed it on my own. Sometimes walking away from the computer for a minute can really help. Here is what I was doing wrong in case anyone is interested for future reference.

The server was spawning the object correctly, but I was never sending a reference of the object back to the client. I did so by changing my function slightly and adding a new Rpc.

```
[Command]
void Cmd_place_initial_units(){
    currentUnit = Instantiate(tank, placePos, Quaternion.identity) as GameObject;
    NetworkServer.SpawnWithClientAuthority (currentUnit, connectionToClient);
    RpcSyncUnits (currentUnit);
}

[ClientRpc]
void RpcSyncUnits(GameObject x){
    currentUnit = x;
    currentUnit.transform.parent = transform.GetChild(0);
    ArmyList [0] = transform.GetChild (0).GetChild (0).gameObject;
}

```
> 1 votes

---
Tags: unity, unity-networking, unet
---


# Question
Title: Assigning function to button in foreach loop causes all buttons to have the same argument value
I have a script that generates buttons based on a list of assets. Each button is intended to to add the asset's resource path to a variable called `SpawnGlobals.CurrentSelection`. When printing the asset resource name of all button within the loop, the different resoruce paths are shown. When printing the value in the select function, the value is always the last item in the `asset_register` list.

I do not understand why this is happening. Am I using the foreach loop or lambda incorrectly?

```
void Start () {

    //Add Foundry Assets Here:
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Test Sphere", "sphere_obj"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 01", "BuildingBlock10x10x10_01"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 02", "BuildingBlock10x10x10_02"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 03", "BuildingBlock10x10x10_03"));
    foreach (FoundryAsset asset in SpawnGlobals.asset_register) {
        SpawnGlobals.buttons.Add(Instantiate(button_prefab));
        GameObject current_button = SpawnGlobals.buttons.Last ();
        current_button.transform.SetParent(master.transform, false);

        current_button.GetComponentInChildren<Text>().text = asset.AssetName;

        print (asset.AssetName);
        current_button.GetComponentInChildren<Button>().onClick.AddListener (delegate {
            select(asset.ResourcePath);
        });

    }

}
public void select(string selected)
{
    print (selected);
    SpawnGlobals.CurrentSelection = selected;
}

```

# Answer
> 0 votes
The problem does lie in your use of the lambda. Specifically, you're capturing the foreach iteration variable, which is of a reference type. The value pointed to by that reference changes as the loop iterates, but the capture is still of that variable, which means when the lambdas are eventually invoked they are all referring to the same asset (the one that happened to be last in the iteration).

In other words it's the variable that is captured, not the value.

You can fix this simply by capturing a local variable in the loop instead:

```
foreach (FoundryAsset asset in SpawnGlobals.asset_register) {
   FoundryAsset captured = asset;
   ...
   current_button.GetComponentInChildren<Button>().onClick.AddListener (delegate {
        select(captured .ResourcePath);
    });
}

```

(Note that this behavior changes in a later version of C#, but that Unity does not support that version.)

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


# Question
Title: How do I let players control which key does what?
New to coding so this is probably super simple, but I can't find the answer. I'm using Unity 5.4.0 and coding in C#.

Is there a variable for input keys?

I have a game I'm making and it is working good, but I want the players to be able to choose which key does what, but I don't know how to make the key presses changeable. I am using both `Input.GetKeyDown(Keycode."KEY")` and `Input.GetKey(Keycode."KEY")`.

My question is: is there a variable I can use in place of the keys that I can make changeable by the players? Like a float, but instead of numbers, it uses key codes.

# Answer
> 2 votes
I'm still astonished Unity doesn't have editable key mapping built-in, other than their built-in launch screen which most games don't use. But anyway that's for the abstract directional input like "Horizontal"; for specific keys like you are asking, you can simply make your variable of type KeyCode:

```
public KeyCode jumpKey;
...
jumpKey = KeyCode.Space;
...
Input.GetKey(jumpKey);

```

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


# Question
Title: How do I differentiate between the two Vive motion controllers?
I am working with a Vive Pre (devkit) and I have most everything working the way I want it to. However I am wondering how do I refer to or even know which motion controller is which? From what I can tell the headset is ALWAYS assigned first into a list, and the others are seemingly randomly assigned.

So how do I differentiate between the two or refer to one separately?

# Answer
> 5 votes
**C++ and OpenVR Solution:**

You can use `IVRSystem::GetTrackedDeviceProperty` for this exact purpose and everything you want to know about a tracked device/controller:

```
TrackedPropertyError error;
int32_t controllerRole;

for (auto i = 0; i < numTrackedControllers; i++)
{
    controllerRole = GetInt32TrackedDeviceProperty(i, ETrackedDeviceProperty::Prop_ControllerRoleHint_Int32, &error);

    if (controllerRole == ETrackedControllerRole::TrackedControllerRole_RightHand)
    {
        // right hand controller
    }
    else if (controllerRole == ETrackedCOntrollerRole::TrackedControllerRole_LeftHand)
    {
        // left hand controller
    }
    else
    {
        // neither
    }
}

```

**Unity and SteamVR Solution:**

For the absolute right and left controllers: The `SteamVR` class has the `string GetStringProperty(ETrackedDeviceProperty prop)` and `string GetStringProperty(ETrackedDeviceProperty prop)` methods in addition to the `ValveVR` methods in the `openvr_api.cs` file from OpenVR.

For the controllers currently in the right and left hands relative to the HMD using the Unity SteamVR scripts (pardon what may be inaccurate C#):

```
int rightIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Rightmost);
int leftIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);

SteamVR_Controller.Device rightDevice = SteamVR_Controller.Input(rightIndex);
SteamVR_Controller.Device leftDevice = SteamVR_Controller.Input(leftIndex);

```

# Answer
> 3 votes
At the time of writing, the other C++ solution is no longer correct; there is now a dedicated function for this:

```
vr::ETrackedControllerRole role = GetControllerRoleForTrackedDeviceIndex(device_index);

```

where `role` is one of `vr::TrackedControllerRole_Invalid`, `vr::TrackedControllerRole_LeftHand` or `vr::TrackedControllerRole_RightHand`.

Conversely if you want the id for the left or right controller, you can get it with

```
vr::TrackedDeviceIndex_t device_index = GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_LeftHand);

```

I'm sure it's the same in other language bindings.

---
Tags: unity, c#, virtual-reality, htc-vive
---


# Question
Title: How to handle edge cases for a cell divided multiplayer world?
The most common practice that I read about for overcoming floating point precision in video games with large worlds is by dividing the world into cells and load it with player's position and shift origin of objects with respect to player.

However this seems to be **only valid for single-player games**. As soon as you change to multiplayer with authoritative server scenario a lot of anomalies arises.

Since a authoritative server has to keep track of all of the world its not possible to base the origin off a single player

For a object that is halfway through two or more cell's co-ordinate system. which cell's part should it be ? and how should it react to it?

There seems to be extremely little to no information about supporting such worlds for multiplayer which are larger than what a common origin can support with enough precision.

Can anyone shed some light on the topic ?

# Answer
> 3 votes
It can work just as well in multiplayer games.

You can partition the world up into cells with integer coordinates and consider the center of each cell the origin for the floating point coordinates of the objects contained in that cell.

Ideally you choose a cell size that allows you to express the cellspace coordinates within a range of floating point values that won't exhibit too much question (due to accuracy away from zero) about when the object leaves one cell and enters another. But even if even if you have that problem you can solve it by choosing a suitable border size and essentially overlapping the cells slightly, so an object is reported in two cells while it's on the border.

Naturally you will want some form of uniquely identifying the object in this case, so even though there are two records for the objects in two different cells you don't double-process it in certain cases.

---
Tags: mathematics, multiplayer, maps, coordinates, world-design
---


title: Control SDL_Mix Sound Effect Volume

text:
# Question
Title: Control SDL_Mix Sound Effect Volume
My game (coded in c++) uses SDL Mixer for its sound. But how do I make certain sounds louder than others. In the game's Main menu, one button is not immediately unlocked, creating a sound if you try to click it. But I can't hear that sound over the game's theme playing in the main menu's background. How do I lower the volume of the game's main theme song in SDL Mixer so I can hear the button press sound?

# Answer
Use `Mix_Volume(channel, volume)` , or if you are using the special music-API, use `Mix_VolumeMusic(volume)`. You cannot make things louder, as volume always defaults to the maximum (128).
> 1 votes

---
Tags: c++, sdl2, visual-studio
---


# Question
Title: Unity Collaborate Error: "It looks like you don't have any data yet"
On the Unity Developer page, my partner has added me to his team. I can see his project. I clicked `Go to Collaborate`:

That brings me to the "Assets" tab, saying "It looks like you don't have any data yet."

Clicking on the provided link just brings me back to the main page, where no detailed instructions can be found.

Has anyone successfully used the new "Unity Collaborate" feature yet?

# Answer
In the top-right of Unity editor you should be able to check your current status with Collaborate.
> 1 votes

---
Tags: unity, tools
---


# Question
Title: Directx 12 Vertex buffer/shader question
Is there a way to process individual vertex that get pumped into the vertex shader.

I have a cube and pyramid.

I want to multiply a different world*view*proj matrix for the cube. So the first 8 vertex should be a differtent matrix.

Is is possible to do such a thing in the vertex shader?

# Answer
> 1 votes
In Shader Model 5.1 (required for DirectX 12), you certainly could use `SV_VertexID` in the vertex shader to address different matrices in your constant buffer(s) to transform some of the vertices uniquely, but it's unlikely that in your case the performance difference would be worth the complexity. Unless you are drawing millions of these things, you'd be better off just having distinct vertices for the two shapes: A simple no-branching shader that doesn't need system-generated values is going to be faster than a complex, dynamic branching shader that requires extra information, so the extra vertex count isn't a problem in practice.

See Using System-Generated Values

> `SV_VertexID` is also supported in Shadel Model 4 or later so you can use it with DirectX 11 with Direct3D Hardware Feature Level 10.0 or later. It's not supported for Direct3D Hardware Feature Levels 9.1, 9.2, or 9.3.

---
Tags: directx12
---


# Question
Title: Why aren't there game and physics engines with double precision?
Choice of game design and other human psychological factors aside

is the present hardware not capable of working with double precision floating point calculations with reasonable performance? It can ease all the complicated tricks involved to get large worlds working seamlessly in current single precision float setup.

Correct me if I'm wrong but shouldn't modern x64 processors more suited to this kind of task?

For the problem with gpu performance it should still be easier to work in double precision and translate co-ordinates to float on camera space

# Answer
There *are*, as has been pointed out to you in the comments.

Generally you don't see a lot of `double`-based engines in games because they aren't needed, and they might not be as fast as `float`-based ones.

The significant majority of games out there can work just fine using `float`s and the various techniques for doing world partitioning or readjustment that exist out there. They usually gain other advantages (or can gain them) by leveraging those kinds of partitioning techniques, as well, so there is some good synergy there.

Further, from a performance perspective, a game engine based on double-precision math (and thus double-precision matrix and vector APIs) can't take as much advantage of SIMD instruction sets, which are generally sized to allow for matrices and vectors that have 32-bit wide components. Those vector instructions can be a significant performance boost, and electing to use geometry representations that don't fit into the registers necessary for that instruction set means you don't get to leverage them.

The problem of interfacing with GPUs, which also generally want 32-bit component vectors, isn't *quite* as simple as you allude to in your question as well. Sure, you can recenter and downscale to floats relative to the render camera... but to get to view space you have to go through the graphics pipeline's transformation to *world* space, which means you have to have already submitted the geometry and coordinates as floats.

To do what you are suggesting there would involve short-circuiting the graphics pipeline by bringing all the coordinates into view space on the CPU, which is not nearly as well-suited to the task... especially if it cannot leverage the SIMD instruction set because the vectors don't fit.

You also have the problem of increasing the memory overhead of every coordinate *component*. This means a higher memory footprint overall, fewer such components fitting into cache at once, et cetera.

It's not a set of insurmountable problems. It's just that not very many games really benefit from doing so and thus the demand for middleware to support is proportionally low.
> 7 votes

---
Tags: hardware, floating-point
---


# Question
Title: Rigidbody or Character Controller for a momentum based sidescrolling shooter/platformer?
I'm working on a side scrolling game where among other movement options the player can perform a "bullet jump". The bullet jump fills a similar role to a double jump, but instead of just jumping in midair, it launches the player in the direction of the mouse cursor. Unfortunately, I can't seem to find any way of doing this using Character Controller, so I've turned to Rigidbody physics to handle the air launch of the player.

As I can't use both Rigidbody and Character Controller, I'm forced to pick one, and as I'm a novice, I decided I'd turn to Stack Exchange for help. I am aware that Character Controller was the given answer for this question on many other occasions, but due to the momentum focus of the game and the nature of the bullet jump mechanic, I feel it's worth asking this question in the context of my specific game.

# Answer
Neither.

Well, that depends. What are you trying to achieve? If you're looking for classic 90s era platformer physics, then absolutely not, you can't use anything that relies on the Unity physics engine, because 90s era platformer physics are not realistic.

A common method that's proven well for me is to use raycast based collision detection to determine whether or not your character will collide with a collision layer and adjust their Vector3 velocity accordingly.

Here's the code I've used for my platformer games, most recently, Demons with Shotguns.

```
public class RaycastCollisionDetection : IEntityCollisionDetection {
    private BoxCollider _collider;
    private Rect _collisionRect;
    private LayerMask _collisionMask;
    private LayerMask _playerMask;

    public GameObject ObjectCollidedWith { get; set; }

    public bool OnGround { get; set; }
    public bool SideCollision { get; set; }
    public bool PlayerCollisionX { get; set; }
    public bool PlayerCollisionY { get; set; }
    public Vector3 HitNormal { get; set; }

    public void Init(GameObject entityGo) {
        _collisionMask = LayerMask.NameToLayer("Collisions");
        _playerMask = LayerMask.NameToLayer("Player");
        _collider = entityGo.GetComponent<BoxCollider>();
    }

    public Vector3 Move(Vector3 moveAmount, GameObject entityGo) {
        float deltaX = moveAmount.x;
        float deltaY = moveAmount.y;
        Vector3 entityPosition = entityGo.transform.position;
        // Resolve any possible collisions below and above the entity.
        deltaY = YAxisCollisions(deltaY, Mathf.Sign(deltaX), entityPosition);
        // Resolve any possible collisions left and right of the entity.
        // Check if our deltaX value is 0 to avoid unnecessary collision detection.
        if (deltaX != 0) {
            deltaX = XAxisCollisions(deltaX, entityPosition);
        }
        if (deltaX != 0 && deltaY != 0 && !SideCollision && !OnGround) {
            DiagonalCollisions(ref deltaX, ref deltaY, entityPosition);
        }

        Vector3 finalTransform = new Vector2(deltaX, deltaY);
        return finalTransform;
    }

    private float XAxisCollisions(float deltaX, Vector3 entityPosition) {
        SideCollision = false;
        PlayerCollisionX = false;
        ObjectCollidedWith = null;
        // It's VERY important that the entity's collider doesn't change
        // shape during the game. This will cause irregular raycast hits
        // and most likely cause things to go through layers.
        // Ensure sprites use a fixed collider size for all frames.
        _collisionRect = GetNewCollisionRect();
        // Increase this value if you want the rays to start and end
        // outside of the entity's collider bounds.
        float margin = 0.04f;
        int numOfRays = 4;
        Vector3 rayStartPoint = new Vector3(_collisionRect.center.x,
            _collisionRect.yMin + margin, entityPosition.z);
        Vector3 rayEndPoint = new Vector3(_collisionRect.center.x,
            _collisionRect.yMax - margin, entityPosition.z);
        float distance = (_collisionRect.width / 2) + Mathf.Abs(deltaX);

        for (int i = 0; i < numOfRays; ++i) {
            float lerpAmount = (float) i / ((float) numOfRays - 1);
            Vector3 origin = Vector3.Lerp(rayStartPoint, rayEndPoint, lerpAmount);
            Ray ray = new Ray(origin, new Vector2(Mathf.Sign(deltaX), 0));
            Debug.DrawRay(ray.origin, ray.direction, Color.white);
            RaycastHit hit;
            // Bit shift the layers to tell Unity to NOT ignore them.
            if (Physics.Raycast(ray, out hit, distance, 1 << _collisionMask) ||
                Physics.Raycast(ray, out hit, distance, 1 << _playerMask)) {
                HitNormal = hit.normal;
                Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
                float x = Mathf.Sign(deltaX) == -1
                    ? _collisionRect.xMin
                    : _collisionRect.xMax;
                // Give a small amount of skin space to prevent snagging.
                float skinSpace = 0.005f;
                deltaX = (_collisionRect.center.x + hit.distance * ray.direction.x - x) + skinSpace;
                if (hit.transform.gameObject.layer == _playerMask) {
                    PlayerCollisionX = true;
                    deltaX = 0;
                    ObjectCollidedWith = hit.transform.gameObject;
                } else {
                    SideCollision = true;
                }
                break;
            }
        }

        return deltaX;
    }

    private float YAxisCollisions(float deltaY, float dirX, Vector3 entityPosition) {
        OnGround = false;
        PlayerCollisionY = false;
        ObjectCollidedWith = null;
        // It's VERY important that the entity's collider doesn't change
        // shape during the game. This will cause irregular raycast hits
        // and most likely cause things to go through layers.
        // Ensure sprites use a fixed collider size for all frames.
        _collisionRect = GetNewCollisionRect();
        // Increase this value if you want the rays to start and end
        // outside of the entity's collider bounds.
        float margin = 0.04f;
        int numOfRays = 4;
        Vector3 rayStartPoint = new Vector3(_collisionRect.xMin + margin,
            _collisionRect.center.y, entityPosition.z);
        Vector3 rayEndPoint = new Vector3(_collisionRect.xMax - margin,
            _collisionRect.center.y, entityPosition.z);
        float distance = (_collisionRect.height / 2) + Mathf.Abs(deltaY);

        for (int i = 0; i < numOfRays; ++i) {
            float lerpAmount = (float) i / ((float) numOfRays - 1);
            // If we are facing left, start the rays on the left side,
            // else start the ray rays on the right side.
            // This will help ensure precise castings on the corners.
            Vector3 origin = dirX == -1
                ? Vector3.Lerp(rayStartPoint, rayEndPoint, lerpAmount)
                : Vector3.Lerp(rayEndPoint, rayStartPoint, lerpAmount);
            Ray ray = new Ray(origin, new Vector2(0, Mathf.Sign(deltaY)));
            //Debug.DrawRay(ray.origin, ray.direction, Color.white);
            RaycastHit hit;
            // Bit shift the layers to tell Unity to NOT ignore them.
            if (Physics.Raycast(ray, out hit, distance, 1 << _collisionMask) ||
                Physics.Raycast(ray, out hit, distance, 1 << _playerMask)) {
                HitNormal = hit.normal;
                //Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
                float y = Mathf.Sign(deltaY) == -1
                    ? _collisionRect.yMin
                    : _collisionRect.yMax;
                // Give a small amount of skin space to prevent snagging.
                float skinSpace = 0.0005f;
                deltaY = (_collisionRect.center.y + hit.distance * ray.direction.y - y) + skinSpace;
                // Only flag player collision if we collide with them while traveling down.
                if (hit.collider.gameObject.layer == _playerMask && Mathf.Sign(deltaY) == -1) {
                    PlayerCollisionY = true;
                    ObjectCollidedWith = hit.transform.gameObject;
                }
                OnGround = true;
                break;
            }
        }

        return deltaY;
    }

    private void DiagonalCollisions(ref float deltaX, ref float deltaY, Vector3 entityPosition) {
        _collisionRect = GetNewCollisionRect();
        float distance = (_collisionRect.height / 2) + Mathf.Abs(deltaX);

        Ray ray = new Ray(_collisionRect.center, new Vector2(Mathf.Sign(deltaX), Mathf.Sign(deltaY)));
        Debug.DrawRay(ray.origin, ray.direction, Color.white);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, distance, 1 << _collisionMask)) {
            HitNormal = hit.normal;
            Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
            // Stop deltaX and let entity drop by deltaY.
            deltaX = 0;

            SideCollision = true;
        }
    }

    private Rect GetNewCollisionRect() {
        return new Rect(
            _collider.bounds.min.x,
            _collider.bounds.min.y,
            _collider.bounds.size.x,
            _collider.bounds.size.y);
    }
}

```

So for your game, you would need to determine when the player performed a "bullet jump" and adjust the movement and collision calculations accordingly based on your game's design.

For more info, visit Overdeveloped.
> 0 votes

# Answer
**Unity5** has a standard asset for a character controller script that works with a RigidBody. I recommend using it or making another such script and avoiding using the built-in character controller component because that one makes your character incompatible with the physics engine.

If you use Assets\>Import Package you should be able to find the standard one. It comes with a little robot sprite.

For your bullet jump effect, you will then be able to apply a force to your character and other, future characters using the same script.
> 1 votes

---
Tags: unity, physics, platformer, rigidbody
---


# Question
Title: Is it a good idea to perform all matrix operations on the GPU?
I was wondering if it is a improvement to use OpenGL for matrix calculations instead of using the CPU. And if it is a improvement, is it worth it to change the math class to use OpenGL?

# Answer
> 1 votes
It depends what you mean. The answer is generally no.

If you're talking about using OpenGL to leverage the GPU as a general-purpose parallel computation device, it can *potentially* be reasonable to offload matrix operations to the GPU *if* you're doing a *ton* of them. The GPU is good at lots of parallel math operations, especially math operations regarding matrices and vectors.

However it's not so great at getting the results of those operations back over to the CPU. There is overhead to read that data back, so generally you want to be doing thousands of parallel math operations at once to amortize the cost of that readback. Or you want to be doing those math operations in a context where you don't actually need to read the results back, but can continue to process them only on the GPU (as you would if you were simply rendering things or doing the matrix multiplies for hardware skinning, et cetea).

If you're just talking about multiplying one or two matrices at a time in a context where you also need those results on the CPU, it's definitely not worth it at that scale.

# Answer
> 1 votes
This is a misunderstanding on your part. glTranslate, glRotate, glScale, etc, **do not happen on the GPU**. Just because they're part of the OpenGL API you should not think that means they happen on the GPU.

What happens instead is that the matrix operations are performed on the CPU and the final calculated matrix is then uploaded to the GPU - in other words, very much the same as if you had used a matrix library instead of the OpenGL functions.

---
Tags: opengl, c++, performance
---


title: render text inside countries

text:
# Question
Title: render text inside countries
I have a map of the world and I want to place text on top of each country. The text can be anywhere from 0 to 1000 symbols long, and can often be changed.

I'm looking for an algorithm to layout text on top of each country "nicely":

* Text ideally should not go outside of the country borders
* Placed somewhere near poloygon's centroid
* Should be visible when possible

I can change font size, and I can split it into multiple lines.

Currently I'm using naive centroid approach, but it requires lots of manual tweaking, and with changing text it can result in suboptimal placement:

Interactive version of the USA map is available here: http://what-people-google.anvaka.com/ (so that you can see labels placement drawbacks and better understand my use case).

One solution I had in mind was to approximate each country by largest posible axis aligned rectangle that can be embedded inside country shape. But maybe there is a better way to do it?

# Answer
> 2 votes
I would do the following (there may be a better algorithm for this):

1. Split each string (country name) into words
2. Create a polygon for each country's outline (Can simplify this polygon fairly aggressively)
3. Given a starting font size, start at the top of the polygon, split the height of the polygon into the **font's height * 2** rows and measure how wide each row is.
4. Starting at the center row, find how many words you can fit into that row.
If you have to wrap, move up one row and break at that line, and continue trying on the line below.
5. If you have exausted all rows, shrink the font and go back to *step 3*
6. If you still cannot fit all rows at a lower bound font size, then treat the shape as a rectangle and just stretch it vertically until everything fits. (Maybe try something else here, I would look at each item on a case by case basis; you can also just hide at this point)
7. When drawing, make sure to center each line in its row

---
Tags: 2d, mathematics, graphics, algorithm
---


# Question
Title: How to render irregular sprite sheets in SDL2?
I have a sprite sheet that's 155 x 66 pixels that I use for my game's UI. I've seen many topics regarding rendering sprite sheets by using the number of pixels and dividing that by the number of sprites to figure out where the render the sprite from. The problem with this is that the buttons on the sprite sheet cannot perfectly aligned so I'm left with differently sized sprites on the sprite sheet.

How do I render an irregular sprite sheet in SDL2?

# Answer
> 0 votes
You basically have two options here:

1. You realign the sprites in the sheet, and use regular spritesheet loading methods to access the source rects that you want to use for rendering.
2. Hardcode the areas into your code or into a resource file. This way you won't have to realign the sprites, but you have to then manually maintain these values.

I would personally just go with option one, and try to always align the spritesheets on a grid.

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


# Question
Title: How to render a PNG-file on the screen with SDL?
I'm coding a 2D platformer in using C++ and SDL2. I've started by coding the GUI, however I'm unsure how to get the menu buttons onto the screen and in the right positions.

How do I load the PNG menu buttons onto the screen in a way that I can adjust them to get them in the right spots?

# Answer
> 2 votes
First, you need to load your image as a surface and convert the surface into a texture:

```
SDL_Surface* surface = IMG_Load("Path/To/Your/Image.png");
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);

```

Then, all you need to do is call `SDL_RenderCopy` with the destination rect adjusted accordingly. You most likely want to render the whole image unless you're creating a spritesheet.

```
SDL_Rect destination;
destination.x = xPos;
destination.y = yPos;
destination.w = yourImageWidth;
destination.w = yourImageHeight;

SDL_RenderCopy(renderer, texture, NULL, &destination);

```

If you need a dynamic way to get the image size, look into `SDL_QueryTexture` or get the size from the surface before destroying it.

Now, for a GUI system you probably want to wrap all this into a reusable class. Something like the following should allow you to nicely reposition the buttons, and later on add functionality to them.

```
class GuiElement
{
public:
    GuiElement(const std::string& path)
    {
        SDL_Surface* surface = IMG_Load(path.c_str());
        m_Texture = SDL_CreateTextureFromSurface(renderer, surface);

        m_Destination.w = surface->w;
        m_Destination.h = surface->h;
        SDL_FreeSurface(surface);
    }
    ~GuiElement()
    {
        SDL_DestroyTexture(m_Texture);
    }

    void Render(SDL_Renderer* renderer)
    {
        m_Destination.x = m_Position.x;
        m_Destination.y = m_Position.y;

        SD_RenderCopy(renderer, m_Texture, NULL, &m_Destination);
    }

    Vec2 m_Position;
protected:
private:
    SDL_Rect m_Destination;
    SDL_Texture* m_Texture;
}

```

I recommend picking up a basic SDL tutorial for stuff like this. They go into a lot more detail about this. LazyFoo's tutorial seems to be quite popular.

---
Tags: c++, gui, sdl2
---


# Question
Title: Jagged Edges Even With Anti Aliasing 8x Multi Sampling
I have an interior scene where I have imported a model for the apartment and many of the interior objects such as lamps, windows, etc. Unfortunately I have a lot of jagged edges on almost all the objects in my scene even on Fantastic Quality settings with Anti Aliasing pushed to its maximum. What else can I do to reduce the jaggies seen here:

Here are my quality settings:

And here are my model import settings:

# Answer
Hi i had the same problem, but i managed to solve it. The problem was in my GPU Settings. Currently an NVidia card. And in the Antialiasing settings the "Antialiasing - Mode" was set "Override any application setting" and i changed it to "Application-Controlled". In addition i changed the Deferred Rendering On. Afterwards i restarted Unity and the problem was gone.
> 3 votes

# Answer
Are you sure you are not using deferred rendering? MSAA is not available with it.
> 0 votes

# Answer
Use SMAA injector and downsample. Far superior. Multisampling is ancient garbage.
> -4 votes

---
Tags: unity, antialiasing
---


title: Softshadows create graphical errors

text:
# Question
Title: Softshadows create graphical errors
I have been implementing soft shadows into my game engine and it all looks ok in the beginning, but when I rotate the camera I get this...
https://puu.sh/rQ7yG/8cd692aaab.png
When I move around I also see that the shadow is offset from the model... https://puu.sh/rQ7B9/6f988749d9.png

Has anyone seen this before or would be able to find out what the issue is? I think it has something to do with the view matrix of the camera or something like that?

For my soft shadows I do 5 passes:

1. Render the scene from the cameras POV to a texture
2. Render that texture as black and white
3. Downscale the black and white texture to half its size
4. Blur the downscaled texture (blurring the shadows edges)
5. Upscale the blurred texture back to normal size

I have checked back and all the matrices get updated per frame

Please ask to see any code and I will gladly edit this post with it.

**EDIT: Added code**

Render Light To Texture

```
bool CGraphics::RenderToTexture()
{
    D3DXMATRIX worldMatrix,lightViewMatrix,lightProjMatrix;

    bool result;
    CMesh* tempMesh = nullptr;

    m_ToTexture->SetRenderTarget(m_Device->GetDeviceContext());
    m_ToTexture->ClearRenderTarget(m_Device->GetDeviceContext(), 0.0f,0.0f,1.0f,1.0f);

    m_PointLights[0]->GenerateViewMatrix();

    m_Device->GetWorldMatrix(worldMatrix);

    m_PointLights[0]->GetViewMatrix(lightViewMatrix);
    m_PointLights[0]->GetProjMatrix(lightProjMatrix);

    for(int i = 0;i<m_NumModels;i++)
    {
        D3DXVECTOR3 tempPos = m_Models[i]->GetPosition();
        D3DXMatrixTranslation(&worldMatrix,tempPos.x,tempPos.y,tempPos.z);

        result = true;//m_Frustrum->CheckSphere(position.x,position.y,position.z,2.0f);

        if(result)
        {
            m_Models[i]->GetMatrix(worldMatrix);
            tempMesh = m_Models[i]->GetMesh();
            tempMesh->Render(m_Device->GetDeviceContext());

            result = m_DepthShader->Render(m_Device->GetDeviceContext(),tempMesh->GetIndexCount(),
                worldMatrix,lightViewMatrix,lightProjMatrix);
            if(!result) return false;

            m_Device->GetWorldMatrix(worldMatrix);
        }
    }

    m_Device->SetBackBufferTarget();
    m_Device->ResetViewport();

    return true;
}

```

Render the shadows in black and white

```
bool CGraphics::RenderBW()
{
    D3DXMATRIX worldMatrix,viewMatrix,projMatrix,lightViewMatrix,lightProjMatrix;

    bool result;
    CMesh* tempMesh = nullptr;

    m_BWTexture->SetRenderTarget(m_Device->GetDeviceContext());
    m_BWTexture->ClearRenderTarget(m_Device->GetDeviceContext(),0.0f,0.0f,1.0f,1.0f);

    m_Cameras[0]->Update();

    m_PointLights[0]->GenerateViewMatrix();

    m_Cameras[0]->GetViewMatrix(viewMatrix);
    m_Device->GetWorldMatrix(worldMatrix);
    m_Device->GetProjMatrix(projMatrix);

    m_PointLights[0]->GetViewMatrix(lightViewMatrix);
    m_PointLights[0]->GetProjMatrix(lightProjMatrix);

    for(int i = 0;i<m_NumModels;i++)
    {
        D3DXVECTOR3 tempPos = m_Models[i]->GetPosition();
        D3DXMatrixTranslation(&worldMatrix,tempPos.x,tempPos.y,tempPos.z);

        result = true;//m_Frustrum->CheckSphere(position.x,position.y,position.z,2.0f);

        if(result)
        {
            m_Models[i]->GetMatrix(worldMatrix);
            tempMesh = m_Models[i]->GetMesh();
            tempMesh->Render(m_Device->GetDeviceContext());

            result = m_ShadowShader->Render(m_Device->GetDeviceContext(),tempMesh->GetIndexCount(),
                worldMatrix,viewMatrix,projMatrix,lightViewMatrix,lightProjMatrix,
                m_ToTexture->GetShaderResourceView(),m_PointLights[0]->GetPosition());
            if(!result) return false;

            m_Device->GetWorldMatrix(worldMatrix);
        }
    }

    m_Device->SetBackBufferTarget();
    m_Device->ResetViewport();

    return true;
}

```

Downscale the texture to half

```
bool CGraphics::DownScale()
{
    D3DXMATRIX worldMatrix,baseViewMatrix,orthoMatrix;
    bool result;

    m_DownScale->SetRenderTarget(m_Device->GetDeviceContext());

    m_DownScale->ClearRenderTarget(m_Device->GetDeviceContext(),0.0f,0.0f,0.0f,1.0f);

    m_Cameras[0]->Update();

    m_Device->GetWorldMatrix(worldMatrix);
    m_Cameras[0]->GetBaseViewMatrix(baseViewMatrix);

    // Get the ortho matrix from the render to texture since texture has different dimensions being that it is smaller.
    m_DownScale->GetOrthoMatrix(orthoMatrix);

    m_Device->ZBufferOff();

    m_DownSampleWindow->Render(m_Device->GetDeviceContext());
    result = m_TextureShader->Render(m_Device->GetDeviceContext(),m_DownSampleWindow->GetIndexCount(),
        worldMatrix,baseViewMatrix,orthoMatrix,m_BWTexture->GetShaderResourceView());

    m_Device->ZBufferOn();

    m_Device->SetBackBufferTarget();

    m_Device->ResetViewport();

    return true;
}

```

Blur Width

```
bool CGraphics::BlurTextureX()
{
    D3DXMATRIX worldMatrix,baseViewMatrix,orthoMatrix;
    float screenX;
    bool result;

    screenX = (float)(SHADOWMAP_WIDTH / 2);

    m_BlurTextureX->SetRenderTarget(m_Device->GetDeviceContext());

    m_BlurTextureX->ClearRenderTarget(m_Device->GetDeviceContext(),0.0f,0.0f,0.0f,1.0f);

    m_Cameras[0]->Update();

    m_Cameras[0]->GetBaseViewMatrix(baseViewMatrix);
    m_Device->GetWorldMatrix(worldMatrix);

    m_BlurTextureX->GetOrthoMatrix(orthoMatrix);

    m_Device->ZBufferOff();

    m_DownSampleWindow->Render(m_Device->GetDeviceContext());

    // Render the small ortho window using the horizontal blur shader and the down sampled render to texture resource.
    result = m_BlurShaderX->Render(m_Device->GetDeviceContext(),m_DownSampleWindow->GetIndexCount(),worldMatrix,baseViewMatrix,orthoMatrix,
        m_DownScale->GetShaderResourceView(),screenX);
    if(!result) return false;

    m_Device->ZBufferOn();

    m_Device->SetBackBufferTarget();
    m_Device->ResetViewport();

    return true;
}

```

Blur Height

```
bool CGraphics::BlurTextureY()
{
    D3DXMATRIX worldMatrix,baseViewMatrix,orthoMatrix;
    float screenY;
    bool result;

    screenY = (float)(SHADOWMAP_HEIGHT / 2);

    m_BlurTextureY->SetRenderTarget(m_Device->GetDeviceContext());

    m_BlurTextureY->ClearRenderTarget(m_Device->GetDeviceContext(),0.0f,0.0f,0.0f,1.0f);

    m_Cameras[0]->Update();

    m_Cameras[0]->GetBaseViewMatrix(baseViewMatrix);
    m_Device->GetWorldMatrix(worldMatrix);

    m_BlurTextureY->GetOrthoMatrix(orthoMatrix);

    m_Device->ZBufferOff();

    m_DownSampleWindow->Render(m_Device->GetDeviceContext());

    // Render the small ortho window using the horizontal blur shader and the down sampled render to texture resource.
    result = m_BlurShaderY->Render(m_Device->GetDeviceContext(),m_DownSampleWindow->GetIndexCount(),worldMatrix,baseViewMatrix,orthoMatrix,
        m_BlurTextureX->GetShaderResourceView(),screenY);
    if(!result) return false;

    m_Device->ZBufferOn();

    m_Device->SetBackBufferTarget();
    m_Device->ResetViewport();

    return true;
}

```

Rescale to full size

```
bool CGraphics::UpScale()
{
    D3DXMATRIX worldMatrix,baseViewMatrix,orthoMatrix;
    bool result;

    m_UpScale->SetRenderTarget(m_Device->GetDeviceContext());

    m_UpScale->ClearRenderTarget(m_Device->GetDeviceContext(),0.0f,0.0f,0.0f,1.0f);

    m_Cameras[0]->GetBaseViewMatrix(baseViewMatrix);
    m_Device->GetWorldMatrix(worldMatrix);

    // Get the ortho matrix from the render to texture since texture has different dimensions.
    m_UpScale->GetOrthoMatrix(orthoMatrix);

    m_Device->ZBufferOff();

    m_FullScreenWindow->Render(m_Device->GetDeviceContext());

    // Render the full screen ortho window using the texture shader and the small sized final blurred render to texture resource.
    result = m_TextureShader->Render(m_Device->GetDeviceContext(),m_FullScreenWindow->GetIndexCount(),
        worldMatrix,baseViewMatrix,orthoMatrix,m_BlurTextureY->GetShaderResourceView());
    if(!result) return false;

    m_Device->ZBufferOn();

    m_Device->SetBackBufferTarget();

    m_Device->ResetViewport();

    return true;
}

```

Here is also the camera functions

```
void CCamera::Update()
{
    D3DXVECTOR3 up, pos, lookAt;
    float yaw, pitch, roll;
    D3DXMATRIX rotationMatrix;

    //Setup upward vector
    up.x = 0.0f;
    up.y = 1.0f;
    up.z = 0.0f;

    //Set position
    pos.x = m_Pos.x;
    pos.y = m_Pos.y;
    pos.z = m_Pos.z;

    //Set default look direction
    lookAt.x = 0.0f;
    lookAt.y = 0.0f;
    lookAt.z = 1.0f;

    //Set rotations
    pitch   = m_Rot.x * 0.0174532925f;
    yaw     = m_Rot.y * 0.0174532925f;
    roll    = m_Rot.z * 0.0174532925f;

    //Create rotation matrix
    D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll);

    //Transform into rotation matrix
    D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
    D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);

    //Translate rotated camera to location of the viewer
    lookAt = pos + lookAt;

    //Create the view matrix
    D3DXMatrixLookAtLH(&m_ViewMatrix, &pos, &lookAt, &up);
}

void CCamera::RenderBaseViewMatrix()
{
    D3DXVECTOR3 up,position,lookAt;
    float radians;

    // Setup the vector that points upwards.
    up.x = 0.0f;
    up.y = 1.0f;
    up.z = 0.0f;

    // Setup the position of the camera in the world.
    position.x = m_Pos.x;
    position.y = m_Pos.y;
    position.z = m_Pos.z;

    // Calculate the rotation in radians.
    radians = m_Rot.y * 0.0174532925f;

    // Setup where the camera is looking.
    lookAt.x = sinf(radians) + m_Pos.x;
    lookAt.y = m_Pos.y;
    lookAt.z = cosf(radians) + m_Pos.z;

    // Create the base view matrix from the three vectors.
    D3DXMatrixLookAtLH(&m_BaseViewMatrix,&position,&lookAt,&up);
}

```

Anything else?

# Answer
It's not clear that in step 3) you're downscaling your shadow map or your shadowed scene.

The general process of soft shadows:

1. Render scene from the light's point of view into a texture (called shadow map)
2. Render the "shadowed scene" into a texture (now you have hard shadows)
3. Downscale the texture created in step 2)
4. Apply blur
5. Upscale the blurred image and render the final image using the blurred texture

You can find a better/longer description in gamedev.net. Also you can use different PCF functions which can produce acceptable results. (Another article with some tips & tricks).

**Edit**:

Anyway, based on your images, it seems to be a downscale/upscale problem. In addition with DirectX you have to use half-pixel offsets in your shaders.
> 1 votes

---
Tags: c++, directx, hlsl, shadows
---


# Question
Title: Using a single square sprite to create tetris-like objects
I'm currently working on a project in XNA, Visual Studio, where it is crucial I can create the classic tetris figures solely based on one square sprite (So I can return to each individual square at a later point, as I need individual squares highlighted at another point in the game).

I tried loading my square into my code, then use a matrix(Texture2D 2d-array) to draw one of my pieces:

```
centerPiece = new Texture2D[,] { { null, Content.Load<Texture2D>("square"), null }, { Content.Load<Texture2D>("square"), Content.Load<Texture2D>("square"), Content.Load<Texture2D>("square") }, { null, Content.Load<Texture2D>("square"), null } };

```

At first glance it seemed fine, but when I try to actually draw it using this method:

```
spriteBatch.Draw(centerPiece[,], screenView(), null, Color.White, 0f, IMGCenter(), 1f, SpriteEffects.None, 0f);

```

It can't draw it as an 2D array, or normal array for that matter. Neither is it able to draw the "nulls" I use in my first method, which also denies me of drawing it by the use of a nested for loop.

Am I completely on the wrong track, or am I just missing a slight detail?

# Answer
> 3 votes
Couple of things.

First and foremost you should only load your texture once like this:

```
Texture2D squareTex = Content.Load<Texture2D>("square");

```

And then you pass it into your array. There is no reason for the texture to occupy any more memory than that.

Secondly, no spritebatch does not take an array of textures - it takes a single one. So in your case you would loop over `centerPiece` like so:

```
foreach(Texture2D t in centerPiece) {
    spriteBatch.draw(t, ...);
 }

```

Now, if you want to improve on this and save some memory you wouldn't store a bunch of textures but maybe an array of booleans instead and on every loop where the boolean is true you draw a texture. This would change the code to something like:

```
bool[,] shape = new boolean[,] {false, true, false, .....}
Texture2D tex = Content.Load<Texture2D>("square");

...

foreach(bool b in shape) {
    if(b) {
      spriteBatch.draw(tex, ...);
    }
}

```

---
Tags: c#, xna, visual-studio
---


title: Unity 2D Bullet AddForce does not work

text:
# Question
Title: Unity 2D Bullet AddForce does not work
I got the following code :

```
public ParticleSystem PS;
public GameObject origin;
public float thrust = 1.0f;
public GameObject bullet;
private GameObject _bullet;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("Pressed left click.");
        PS.Play();
        _bullet = Instantiate(bullet, origin.transform.position, origin.transform.rotation);
        _bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust);
    }
}

```

Where everything is working except the AddForce, the bullet is just dropping out of my weapon. I've made some research and my script seems to be correct. The bullet has attached a circle collider and a rigidbody2D.

Update: This did not change anything :

```
_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust, ForceMode2D.Impulse);

```

And this neither :

```
_bullet.GetComponent<Rigidbody2D>().velocity = origin.transform.forward * thrust;

```

It's weird, because all of these should work actually.

# Answer
> 1 votes
There is just a minor mistake in this code which is `transform.forward`, which points to the z-axis which is obviously not working in a 2D game. So instead of this :

```
_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust);

```

use this and it should work just fine :

```
_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.right * thrust);

```

But at least the question is now a good summary of possible ways to give your object some speed. ( Force, velocity...)

---
Tags: unity, rigidbody
---


title: OpenGL threaded loading

text:
# Question
Title: OpenGL threaded loading
I'd like to introduce seamless level loading which means I need multiple threads. The main thread is for rendering the current scene (or for non-seamless level loading a progress bar) while the other thread is loading the resource files and sending data to the graphics card.

Now I have the following single threaded architecture: when the graphics device is initialized, a dummy window and a "shared context" is created. This is the only rendering context (HGLRC in Windows terms) I'm creating. Every time a new window is created and the graphics device is asked to create a "renderable surface" into that window, the same "shared rendering context" is used. I can do this because I set the same pixel format for each window, so there is no point to make multiple rendering contexts (that would just make my life harder than it should). Here is a small image representing the current design:

I've read some topics about this but now I'm confused since I read really different point of views, so I have some questions:

* As far as I know an OpenGL context can be active in a single thread only (at a time). This means that I need another "loading rc" which shares resources (through context creation or \*glShareList) with the "shared rc". Every time I create a new thread to load something, I have to set the "loading rc" active in that thread. Am I right?
* Can I use the same dummy device context (HDC) in the loading thread?
* Because I have a single GPU the commands sent to the graphics card are queued up. Right? Will this behaviour introduce switches between shared and loading contexts?
* Is there anything else I should take care of?

# Answer
> 5 votes
1. Each OpenGL context can only be "active" in a single thread at a time.

If you wish to be making OpenGL calls from two threads simultaneously (as in your example of one "loading thread" which is creating textures, VBOs, etc), and one "rendering thread", then as you say, you need to create a second context, with shared data between the two contexts.

Do note that shared contexts do not share *all* OpenGL data. Particularly notable exceptions are FBOs and VAOs, which will remain only in the context where they were created.

2. Yes, you can create multiple OpenGL contexts referring to a single window (HDCs, on Windows OS).
3. You are given no guarantees about what order the commands given to shared OpenGL contexts will be handled.

If you wish to make use of data inserted into one shared context from the other context, you'll need to put a fence in, to make certain that the data is definitely in sync between the two contexts before you try to use it. For example, if you want to draw something which has just finished loading, then you'd want the loading thread, after it has finished loading its data and pushing it into its shared context, to do something like this, before signalling the main thread that it's okay to draw the loaded data:

```
GLsync fenceId = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
while(true)
{
    result = glClientWaitSync(fenceId, GL_SYNC_FLUSH_COMMANDS_BIT, GLuint64(5000000000)); //5 Second timeout
    if(result != GL_TIMEOUT_EXPIRED) break; //we ignore timeouts and wait until all OpenGL commands have been processed!
}

```
4. The common wisdom is that you're generally a lot better off using only a single context, rather than two shared contexts.

Instead of making OpenGL calls directly from a second thread via a shared context, the usual advice is to instead simply prepare data from that second thread, but actually perform all the OpenGL calls from the main thread. Drivers, they say, are generally much better-optimised for the single-context case, and it's worth trying to fit the way the drivers want to work, rather than do anything complicated and weird, like shared contexts.

So it's worth considering whether you *really* want to go down this path. It gets complicated *fast*, and you pay a performance penalty for every extra shared context, even when you're not actually using them.

# Answer
> 3 votes
## The short answer: No!

Don't do that. Just, don't.

## The slightly longer answer

Unluckily, OpenGL does not truly (contrary to folklore) support multithreading. No, really, it does not.

You are of course aware that a context can be (must be) active for exactly one thread using that context, and making a context current between threads effectively causes lockstep behavior and is horribly expensive.

Now, sharing two contexts (with one context each bound to one thread) *sounds like* it would give you just what you want. However, this is an illusion.

Sharing contexts will significantly degrade overall performance due to internal synchronization and will be slower than just doing everything in one thread.
When I tried this some years ago, sharing contexts, even if there were no changes made (so, really nothing to synchronize!) would cause an approximate 8-10% performance drop compared to using a single context and a single thread. Maybe drivers have somewhat improved since then, but I would not rely on that since sharing contexts is not a very commonly used feature, and not a top priority.

## The somewhat less pessimistic answer

There is still a way to get *some* parallelism into that beast. You can map buffers in your render thread, pass a pointer to a worker thread, and have the worker thread fill the buffer with data. Then, signal a condition variable, causing the render thread to unmap the buffer again ready for use. You still have the mapping/unmapping on your render thread, but at least you can offload the shuffling around (and loading from disk, unpacking) of data.

Be sure to use a technique like buffer orphaning (or use the copy write buffer) and the unsynchronized bit to avoid unnecessary stalls on modifying buffers that are still being read from and client/server syncs. Unluckily, even unsynchronized maps will have some syncs that are unavoidable.

If updates are frequent (probably not the case in your example) and persistent mappings are supported, you may want to use these, making the repeated mapping/unmapping unnecessary. Just map once and pass a pointer. Be aware that persistent mapping is slightly slower overall, so it's only advantageous if you have frequent (every frame, or nearly so) updates where the cost of mapping/unmapping is dominating.

---
Tags: opengl, architecture, multithreading
---


title: OpenGL VAO Index Not Drawing Correctly

text:
# Question
Title: OpenGL VAO Index Not Drawing Correctly
I'm going insane trying to work out why I unable to draw a triangle using VAO and indexing. I have a bunch of redundant vertexes so that i can switch my index array up to test the drawing.

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

//bot left
vertices.push_back(glm::vec3(-0.75,0.9,1));     //0
vertices.push_back(glm::vec3(-0.5, 0.9, 1));    //1
vertices.push_back(glm::vec3(-0.25, 0.9, 1));   //2
vertices.push_back(glm::vec3(-0.0, 0.9, 1));    //3
//mid right
vertices.push_back(glm::vec3(0.75, 0, 1));  //4
vertices.push_back(glm::vec3(0.5, 0, 1));   //5
vertices.push_back(glm::vec3(0.25, 0, 1));  //6
vertices.push_back(glm::vec3(0.0, 0, 1));   //7
//top left
vertices.push_back(glm::vec3(-0.75, -0.9, 1));  //8
vertices.push_back(glm::vec3(-0.5, -0.9, 1));   //9
vertices.push_back(glm::vec3(-0.25, -0.9, 1));  //10
vertices.push_back(glm::vec3(-0.0, -0.9, -1));  //11

```

The indices are simple:

```
 GLuint indices[] = {0,5,11};

```

Here is how I am initialising everything:

```
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ivbo);

glBindBuffer(GL_ARRAY_BUFFER, vbo);

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),
    &vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,sizeof(glm::vec3), (void*)0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ivbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

```

I am rendering with:

```
glUseProgram(program);

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1.0, 0.0, 0.0, 1.0);//clear red

glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, (void*)0);

glutSwapBuffers();

```

Vertex shader is simple as they come:

```
#version 430 core
layout(location = 0) in vec3 in_position;

void main(void)
{
   gl_Position = vec4(in_position, 1);
}

```

Same with the fragment shader

```
#version 430 core
out vec4 color;

void main(void)
{
  color = vec4(0.0, 1.0, 0.0, 1.0);
}

```

---

EDIT: Switching the z coordinate in the vertices to a negative value fixes the problem. What is going on?

# Answer
First to ensure all vertices are rendered:

* Ensure that backface culling is disabled with `GlDisable(GL_CULL_FACE)`
* Disable depth testing `glDisable(GL_DEPTH_TEST)` OR ensure you are clearing the depth buffer bit before drawing `glClear(GL_DEPTH_BUFFER_BIT)`

---

Second

```
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),&vertices[0], GL_STATIC_DRAW);

```

is incorrect.

Second parameter to glBufferData is size of vertex array in bytes. Passing `sizeof(vertices)` will pass the 24 bytes (32 on debug) that indicate the pointer to the start location of the vector and the end location of the vector.

Instead you should use:

```
sizeof(glm::vec3) * vertices.size()

```

The same thing happens with the size you pass size to the ELEMENTS\_BUFFER .

---

glBufferData's second argument is the size in **Bytes** of the array you are passing. When it say's size in Bytes it means the whole size of *your* **vertices** vector.

So in this specific scenario you have stored 12 positions. Every one of those elements is a float number as we can see and every position consists of three float numbers.

"Coding" this would be

```
sizeof(float) * 3 * vertices.size();

```
* Normally sizeof(float) will return 4 which are the bytes for a float-number.
* vertices.size() will return 12 since you have 12 positions stored.
* and 3 is just a constant indicating that for every position you have 3 float-numbers.

So the size in bytes that you will have to pass as an argument to glBufferData is 4 * 3 * 12 = **144Bytes**.

You need to do the same for the Elements buffer.
> 2 votes

---
Tags: opengl, c++, index-buffer, vao
---


title: segmentation fault in glCreateBuffers

text:
# Question
Title: segmentation fault in glCreateBuffers
I am trying to run an example from the redbook 8th edition and I am receiving a segmentation fault in line:

`glCreateBuffers( NumBuffers, Buffers );`

file.cpp

```
//////////////////////////////////////////////////////////////////////////////
//
//  Triangles.cpp
//
//////////////////////////////////////////////////////////////////////////////

#include "vgl.h"
#include "LoadShaders.h"

enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0 };

GLuint  VAOs[NumVAOs];
GLuint  Buffers[NumBuffers];

const GLuint  NumVertices = 6;

//----------------------------------------------------------------------------
//
// init
//

void
init( void )
{
    glGenVertexArrays( NumVAOs, VAOs );
    glBindVertexArray( VAOs[Triangles] );

    GLfloat  vertices[NumVertices][2] = {
        { -0.90f, -0.90f }, {  0.85f, -0.90f }, { -0.90f,  0.85f },  // Triangle 1
        {  0.90f, -0.85f }, {  0.90f,  0.90f }, { -0.85f,  0.90f }   // Triangle 2
    };

    glCreateBuffers( NumBuffers, Buffers );
    glBindBuffer( GL_ARRAY_BUFFER, Buffers[ArrayBuffer] );
    glBufferStorage( GL_ARRAY_BUFFER, sizeof(vertices), vertices, 0);

    ShaderInfo  shaders[] =
    {
        { GL_VERTEX_SHADER, "triangles.vert" },
        { GL_FRAGMENT_SHADER, "triangles.frag" },
        { GL_NONE, NULL }
    };

    GLuint program = LoadShaders( shaders );
    glUseProgram( program );

    glVertexAttribPointer( vPosition, 2, GL_FLOAT,
                           GL_FALSE, 0, BUFFER_OFFSET(0) );
    glEnableVertexAttribArray( vPosition );
}

//----------------------------------------------------------------------------
//
// display
//

void
display( void )
{
    static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f };

    glClearBufferfv(GL_COLOR, 0, black);

    glBindVertexArray( VAOs[Triangles] );
    glDrawArrays( GL_TRIANGLES, 0, NumVertices );
}

//----------------------------------------------------------------------------
//
// main
//

int main( int argc, char** argv )
{
    if ( !glfwInit() )
    {
        exit(EXIT_FAILURE);
    }

    //glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    GLFWwindow* window = glfwCreateWindow(300, 300, "Triangles", NULL, NULL);
    if ( !window )
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glewInit();

    init();

    while (!glfwWindowShouldClose(window))
    {
        display();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
}

```

I am compiling :

`g++ -O2 -g -o run opengl.cpp LoadShaders.cpp -lGL -lGLU -lGLEW -lglut -lglfw -lX11 -lm`

# Answer
`glCreateBuffers` is an OpenGL 4.5 function but you are using OpenGL 2.0 context, you need to use `glGenBuffers` instead.
> 1 votes

---
Tags: opengl
---


# Question
Title: How do I load 100+, 480*800, 30KB PNGs into a frame by frame animation on Android without OOMs?
I'm an Android dev who's trying to get into game dev.

As the title says, I'm trying to load a hundred PNGs as an animation, fullscreen on Android, but no matter what I try, I always getting out of memory errors, ,or heavy lags.

I've tried different engines, as well as different approaches to loading assets, here's a list of what hasn't worked :

**1 - Libgdx :**

* Using Atlas textures, loaded in splash screen using the assets manager : Process killed with no errors after loading 20 2048\*2048 Atlas.
* Atlas Textures without Assets Manager : Huge Lag before the animation actually starts.
* Sequence of PNGs using Assets Manager : Crash with explicit OOM.

P.S : All Atlas files have been compressed to the Max. Average Final file size is about 1.5MB.

**2 - AndEngine :**

* Using Atlas Textures : So far I haven't been able to load multiple atlas pages. Seems like Andengine can only load single page atlases.
* Using createTiledFromAssetDirectory() and loading every single PNG from the assets directory to a BuildableBitmapTextureAtlas : Seems like I need to set a fixed size for the BuildableBitmapTextureAtlas, and again, it doesn't support multiple pages. So I'm stuck with loading all my 100s of assets, into a single 2048\*2048 atlas. Not what I'm looking for.

Please keep in mind all PNGs are exactly 480\*800px and I'm looking to play those in full screen android devices. Each PNG is about 20KB - 40KB after compression with PNGQuant.

# Answer
Don't.

It sounds like you're basically playing a full-screen movie. So one option is to *use a movie file*. Not only is this more straightforward, but since move movie file formats utilize compression it will save you a fair bit of space.

A second option is to break the scene you're trying to display up into smaller parts. If *every pixel* of the sequence you want to play changes *every frame*, this won't help you, but chances are that's not the case. If the background is mostly static, you can load one background frame, and a series of (smaller) frames for the animated components that sit on top of the background.

A third option is to stream the sequence in. Load the first few frames of the animation and play them, discarding them from memory immediately after displaying them and loading the pending frames in a background thread. If the animation is long enough and you can perform the IO fast enough (which is probably doable since you aren't doing anything else but playing this animation), it could work.
> 1 votes

---
Tags: android, libgdx, animation, andengine
---


title: Mobile OnMouseDown

text:
# Question
Title: Mobile OnMouseDown
I have a scene in my game with a bunch of colliders2D. The game is made for android. I want to be able to click on some colliders2D and execute some functions there. So I started with `OnMouseDown` on the gameobjects that I was clicking. Then I had to add a rigidbody2d so this would work. Recently though, the game crashes only when playing that scene once the apk is installed in the middle of the scene. The problem is that I can't get it to crash when on the editor or playing the game remotely with Unity Remote. So I haven't got a clue what the problem is

I think it may be the fact that there are a bunch of colliders2D with onmousedown functions attached to them. I got to that conclusion after some research on the forums. Do you think this maybe causing the random crashes? I can try to attach raycast functions to this objects instead of onmousedown but it seems much more complicated code than onmousedown. Plus it will be such a pain having to go to every single function where I wrote onMouse down, I have removed those on mousedown functions by writing #if UNITY\_EDITOR code #endif but the problems stays there, what can cause an only mobile crash and not on the editor, a performance issue?

# Answer
> 0 votes
Ok the problem was not onmousedown, but having around 10 canvas in a scene,it seems like mobiles cant handle this I solved it just by dragging all those ui objects into a canvas.

---
Tags: unity, android
---


# Question
Title: Does Game Maker use use intrinsic or extrinsic rotations?
I have a pretty difficult problem on my hands. My 3D character moves through space and rotates. I do not know the angle of rotation at any given time, but I do have three X, Y, Z unit vectors serving as basis vectors for the character's coordinate system.

I see that in the Euler angle page on Wikipedia there are three formula for extrinsic rotation. My problem is that they do not seem to work in any manner whatsoever. Either my reading of that page misled me, or game maker does not use extrinsic rotation.

Do Game Maker's rotation transformations always rotate globally in 3D space, or does it use the current set of transformations and rotate around the current X, Y, or Z axis?

# Answer
Game Maker Studio uses extrinsic rotations, as any 3D engine does. Intrinsic rotations are only functions which performs extrinsic transforms onto an object by moving it at the world origin and deleting any previous transform applied to the object.

In Game Maker Studio, any transformation is always relative to the `(0,0,0)` position. To perform transforms properly, you use the function `d3d_transform_set_identity()` to rotate and scale it, before translating it.
> 1 votes

---
Tags: rotation, game-maker
---


title: Apply Pixel Perfect by script in Unity?

text:
# Question
Title: Apply Pixel Perfect by script in Unity?
How can I apply Pixel Perfect by script in Unity? All I could find on the web is this which does help at all..

# Answer
You need to override pixel perfect inheritance first if the GameObject's Canvas component is not considered the root canvas.

```
myNewUIGameObject.GetComponent <Canvas> ().overridePixelPerfect = true;
myNewUIGameObject.GetComponent <Canvas> ().pixelPerfect = true;

```

or

```
myCanvas.overridePixelPerfect = true;
myCanvas.pixelPerfect = true;

```
> 1 votes

---
Tags: c#, unity, gui, pixel
---


# Question
Title: Sliding loose dirt shader/material/effect
Im sure there is some sort of technique with a name I don't know or didn't think to search, but how would I go about making an effect similar to loose dirt sliding down the face of a slope when something disturbs it? I guess I think of it as a mini avalanche or something.

I have attempted it a couple times with pretty poor results, but some of the properties i tried to replicate was: the sliding dirt spreads out the further it gets from its start position depending on the surface shape, angle of repose, rocks or larger pieces of debris causing even more dirt to slide(quasi-recursion?), loose dirt 'sliding' over other dirt, etc. I assume id need to combine the right ratio of shaders, particles and textures to look right but I cant seem to find any real info on this type of effect. Would something like this be too intensive to do real-time?

# Answer
You could try using an animated texture. I think that a gif file might possibly work but I'm not 110% sure
> -2 votes

---
Tags: physics, particles
---


# Question
Title: Delaying the game to restarts with Coroutine
I want to create some sort of delay for the game to restarts when the ball is stops moving but the game keeps restarting whenever the velocity reaches zero. I want use a timer where the game will restarts when the ball is stopping for too long but I don't know how. Here's the code. The Restart() will be called from another script when the game starts and the ball will starts moving. Any help would be appreciated.

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class BallCondition : MonoBehaviour {

    // Use this for initialization
    public bool isLose = false;
    public Rigidbody2D rb;

    void Awake () {

        rb = GetComponent<Rigidbody2D>();
    }
    public IEnumerator Restart()
     {
        Debug.Log(rb.velocity);
        if((rb.velocity.x)==0 && (rb.velocity.y) == 0)
        {
            //print(Time.time);
            Debug.Log("stopped");
            if((rb.velocity.x)==0 && (rb.velocity.y) == 0 && !isLose)
            {
                yield return new WaitForSeconds(3);
                Debug.Log("lose");
                isLose = true;
                SceneManager.LoadScene(0);
            }
        }
     }
}

```

This is the script where I call the Restart()

```
using UnityEngine;
using System.Collections;

public class Force : MonoBehaviour {

    public float moveSpeed = 5;
    public static bool isAlreadyClicked = false;

    void Start()
    {
       Reset();
    }

    void Update()
    {
        if(Input.GetMouseButton(1))
        {

            if(!isAlreadyClicked)
            {
                GetComponent<Rigidbody2D>().AddForce(new Vector2(moveSpeed,0));
                Debug.Log("clicked");
                isAlreadyClicked = true;
                BallCondition player = GetComponent<BallCondition>();
                StartCoroutine(player.Restart());
            }
        }

    }
    public void Reset()
    {
        isAlreadyClicked = false;
    }
}

```

# Answer
> 1 votes
Your code for `Restart` will only run once.

You could use something like:

```
public IEnumerator Restart()
{
    while (true)
    {
        Debug.Log("stopped");
        // if you want to limit the check by 1 per second
        yield return new WaitForSeconds(1f);
        if (rb.IsSleeping())
        {
            yield return new WaitForSeconds(3);
            Debug.Log("lose");
            SceneManager.LoadScene(0);
        }
    }
}

```

I've also changed the velocity check for `rb.IsSleeping()` (more info in Unity Docs)

I hope this helps! Good luck :)

---
Tags: unity, c#, timer, coroutines
---


# Question
Title: I need to move a sprite from point A to point B. I have objX1, objY1, frames, and X2, Y2
I have a custom sprite class in Unity and I'm trying to make a method in where it moves from one point to another. Instead of using an Enumerator for time, I'm using real time game frames using static void methods inside of classes which inherit from a MainGame.cs script attached to the Main Camera, and this is called inside of MainGame's Update() method.

So what I have in the end are the following values: SpriteID OriginalX OriginalY MoveToX MoveToY CurrentFrames TotalFrames

I'm not asking anyone to do the work for me, just that if there's a place I could be directed to in where I could find the math necessary to solve the problem that'd be a huge help. I'm not using any vectors here, just the raw math using only those variables. I don't know if someone has found an answer for calculating it based on update frames...

```
public class Sprite : MainGame {

public static int State = 0;
public static int CurrentFrames = 0;
public static int TotalFrames = 0;

 public static void Move(int SpriteID, int OriginalX, int OriginalY, int MoveToX, int MoveToY, int TotalFrames)
 {
    switch (State) {
    //init
       case 0:
       CurrentFrames = 0;

       State = 1;

       break;

       //run
       case 1:
       if (CurrentFrames < TotalFrames) {
       //do math here

          CurrentFrames++;
       }

       if (CurrentFrames >= TotalFrames) {
          State = 2;
       }
       break;

       //end
       case 2:
          //Reset values here
          //Shut off
          State = 3;
       break;
    }
 }
}

```

EDIT 10212016 456PM: What I've figured out so far, now...

```
if (CurrentFrames < TotalFrames) {
    DistanceX = MoveToX - OrigX;
    MoveForwardXFloat = (float)DistanceX / (float)Frames;
    OrigX += (int)MoveForwardXFloat;
}

```

# Answer
> 1 votes
It really depends on how you have the whole setup, but according to your code I'll use the `Mathf.MoveTowards` for moving the object.

The calculation should be something similar to this:

```
// in the Update method or something similar

currentX = Mathf.MoveTowards(currentX, targetX, (distanceX/duration) * Time.deltaTime),
currentY = Mathf.MoveTowards(currentY, targetY, (distanceY/duration) * Time.deltaTime),

// currentX/Y = current x/y position of the sprite
// targetX/Y = target x/y position for the sprite
// distanceX/Y = distance from start position to target position
// duration = duration in seconds for the movement

```

You could also use `Mathf.Lerp`

# Answer
> 0 votes
This worked for me. The math is within it down there. When I figured it out it seemed like it should be more obvious, Yvelocity and Xvelocity are added to it every frame until it's arrived, and it gets the velocity based on the frame number left (frame is counting down) and the distance.

The trick that I forgot was that everything has to be in floats.

using UnityEngine; using System; using System.Collections;

```
public class SpriteMoveTo : MG {

    public static int State;
    private static int SpriteID;
    private static float CurrentFrames;
    private static float TotalFrames;
    private static float DestinationX;
    private static float DestinationY;
    private static float CurrentX;
    private static float CurrentY;
    private static float DistanceX;
    private static float DistanceY;
    private static float MoveForwardXFloat;
    private static float Yvelocity;
    private static float Xvelocity;

    public static void Update (string SpriteIDstring, string DestinationXstring, string DestinationYstring, string TotalFramesString, string DoOrDontWait) {
        if (State == 0 && CurEcmd_Cmd == "SpriteMoveTo") {
            SpriteID = int.Parse (SpriteIDstring);
            TotalFrames = float.Parse (TotalFramesString);
            CurrentFrames = TotalFrames;
            DestinationX = float.Parse (DestinationXstring);
            DestinationY = float.Parse (DestinationYstring);
            CurrentX = MG_Sprites.MG_SpriteDatabase [SpriteID].X;
            CurrentY = MG_Sprites.MG_SpriteDatabase [SpriteID].Y;
            State = 1;
        }

        if (State == 1) {
            MG_Sprites.MG_SpriteDatabase [SpriteID].X = CurrentX;
            MG_Sprites.MG_SpriteDatabase [SpriteID].Y = CurrentY;

            if (CurrentFrames > 0) {

                DistanceX = DestinationX - CurrentX;
                DistanceY = DestinationY - CurrentY;
                Xvelocity = DistanceX / CurrentFrames;
                Yvelocity = DistanceY / CurrentFrames;
                CurrentY += Yvelocity;
                CurrentX += Xvelocity;
                MG_Sprites.MG_SpriteDatabase[SpriteID].Y = CurrentY;
                MG_Sprites.MG_SpriteDatabase [SpriteID].X = CurrentX;

                CurrentFrames--;
            }

            if (CurrentFrames <= 0) {
                State = 2;
            }
        }

        if (State == 2) {
            State = 0;
            //Next Ecmds command if list isn't empty, else set it to idle
            CurEcmd_Cmd = "";
            MG_Interpreter.State = 0;
        }
    }
}

```

---
Tags: unity, sprites
---


title: Rendering one pixel using DirectX11

text:
# Question
Title: Rendering one pixel using DirectX11
is it possible to render one pixel using DirectX 11? if its possible how to do it ?

# Answer
Your best option is to use a DYNAMIC 2D texture, and each 'frame' copy from a 2D array in system memory that your software renderer produces to the DYNAMIC 2D texture using `Map`/`Unmap`. You can then render a full-screen quad using your DYNAMIC 2D texture to get it into the render target backbuffer in the DXGI swapchain, and then `Present` to swap the buffers.

See How to: Use dynamic resources

> You can use `SpriteBatch` in the DirectX Tool Kit to do the 'full-screen quad render' trick of your DYNAMIC texture.
> 0 votes

---
Tags: c++, directx11
---