# Question
Title: UnityException: Transform child out of bounds (only in built APK)
In the Unity Editor, this code helps me to get the Fog GameObject:

```
//get the fog GameObject
//0 :day , 1:night
if (tzPlayInfo.Instance.ENV_01_IDX == 0)
{
      if (FogEffect == null)
      {
             FogEffect = this.transform.GetChild(0).GetChild(2).GetChild(0).GetChild(4).gameObject;
      }

} else
{
      if (FogEffect == null)
      {
             FogEffect = this.transform.GetChild(0).GetChild(2).GetChild(1).GetChild(5).gameObject;
      }
}

```

And here's what in my hierarchy (for the night case):

As you can see on the photo it successfully gets the Fog GameObject. But when i build it and run the apk it gives me

> UnityException: Transform child out of bounds at MC\_SettingBehaviour.Update () \[0x00000\] in :0

---

I tried what Arcane Engineer told me to do by using `Transform.Find()`

```
if (tzPlayInfo.Instance.ENV_01_IDX == 0)
{
      FogEffect = transform.Find("GO Root/day/01_Env_Lev01_test01/Fog01 (1)").gameObject;

} else{
      FogEffect = transform.Find("GO Root/night/01_Env_Lev01_night-test02/Fog01").gameObject;
}

```

But the problem when I build & run an APK, the error I get is replaced by:

> UnassignedReferenceException: The variable FogEffect of MC\_SettingBehaviour has not been assigned

This is how i load my `fog env`

```
// 4. fog env.
        data.GetFogEnv(ref env03_idx, out prefabs);
        Load(ref prefabs, ref weather_env_root);

```

and I created a Load function here it is

```
void Load(ref GameObject[] prefabs, ref Transform root)
{
    if (prefabs != null)
    {
        GameObject obj;
        for (int i = 0; i < prefabs.Length; i++)
        {
            if (prefabs[i] == null) continue;
            obj = Instantiate(prefabs[i], root);
            obj.name = prefabs[i].name;
        }
    }
}

```

And here is my `GetFogEnv`

```
public void GetFogEnv(ref int env03_idx, out GameObject[] prefabs)
{
    prefabs = (env03_idx == 2 || env03_idx == 3) ? fog : null;
}

```

# EDITTED:

```
[SerializeField] GameObject[] cameraGameObject = new GameObject[46];

[SerializeField] GameObject FogEffect;

bool foundobjects = false;
void Update()
{
    if (tzPlayInfo.Instance.BLOCK_GAME_FLOW == false)
    {
        //if the option is livestreaming lets disable this script because it's useless.
        if (PlayerPrefs.GetInt(OptionPopup.LiveStreaming_) == 1)
        {
            this.enabled = false;
        }
        else
        {
            //Find Objects
            if (!foundobjects)
            {
                StartCoroutine(FindObjects());
            } else
            {
                StopCoroutine(FindObjects());
            }
        }
        //if it is all found then execute this statement
        if (foundobjects)
        {
            //Save of Camera
            if (PlayerPrefs.GetInt(OptionPopup.CameraOptionSaving) == 1)
            {
                foreach (GameObject cameras in cameraGameObject)
                {
                    //lets check if theres a component
                    if (cameras.GetComponent<Bloom>() == null)
                    {

                    } else
                    {
                        cameras.GetComponent<Bloom>().enabled = true;
                    }

                    if (cameras.GetComponent<DepthOfField>() == null)
                    {

                    } else
                    {
                        cameras.GetComponent<DepthOfField>().enabled = true;
                    }

                    if (cameras.GetComponent<DepthOfFieldDeprecated>() == null)
                    {

                    } else
                    {
                        cameras.GetComponent<DepthOfFieldDeprecated>().enabled = true;
                    }
                }
            }
            else
            {
                foreach (GameObject cameras in cameraGameObject)
                {
                    //lets check if theres a component
                    if (cameras.GetComponent<Bloom>() == null)
                    {

                    }
                    else
                    {
                        cameras.GetComponent<Bloom>().enabled = false;
                    }

                    if (cameras.GetComponent<DepthOfField>() == null)
                    {

                    }
                    else
                    {
                        cameras.GetComponent<DepthOfField>().enabled = false;
                    }

                    if (cameras.GetComponent<DepthOfFieldDeprecated>() == null)
                    {

                    }
                    else
                    {
                        cameras.GetComponent<DepthOfFieldDeprecated>().enabled = false;
                    }
                }
            }
            //Start of Fog
            if (PlayerPrefs.GetInt(OptionPopup.FogOptionSaving) == 1)
            {
                FogEffect.SetActive(true);
            }
            else
            {
                FogEffect.SetActive(false);
            }
        }
    }
}

IEnumerator FindObjects()
{
    //AIR
    cameraGameObject[0] = transform.Find("GO Root/Camera/AIR_1(Clone)/GameObject/Camera").gameObject;
    cameraGameObject[1] = transform.Find("GO Root/Camera/AIR_2(Clone)/Camera").gameObject;

    //Paddock
    cameraGameObject[2] = transform.Find("GO Root/Camera/Paddock_1(Clone)/CameraPos/GameObject/Camera").gameObject;

    //TV
    cameraGameObject[3] = transform.Find("GO Root/Camera/TV_1_far(Clone)/Poss/Camera").gameObject;
    cameraGameObject[4] = transform.Find("GO Root/Camera/TV_1_lead(Clone)/Poss/Camera").gameObject;
    cameraGameObject[5] = transform.Find("GO Root/Camera/TV_2_far(Clone)/Poss/Camera").gameObject;
    cameraGameObject[6] = transform.Find("GO Root/Camera/TV_2_lead(Clone)/Poss/Camera").gameObject;

    //LAST_SPURT && Test 30
    cameraGameObject[7] = transform.Find("GO Root/Camera/LAST_SPURT_1(Clone)/Pos/Camera").gameObject;
    cameraGameObject[8] = transform.Find("GO Root/Camera/Test30(Clone)/Poss/Camera").gameObject;

    //Tests
    cameraGameObject[9] = transform.Find("GO Root/Camera/Test01(Clone)/Poss/Camera").gameObject;
    cameraGameObject[10] = transform.Find("GO Root/Camera/Test02(Clone)/Poss/Camera").gameObject;
    cameraGameObject[11] = transform.Find("GO Root/Camera/Test03(Clone)/Poss/Camera").gameObject;
    cameraGameObject[12] = transform.Find("GO Root/Camera/Test04(Clone)/Poss/Camera").gameObject;
    cameraGameObject[13] = transform.Find("GO Root/Camera/Test05(Clone)/Poss/Camera").gameObject;
    cameraGameObject[14] = transform.Find("GO Root/Camera/Test06(Clone)/Poss/Camera").gameObject;
    cameraGameObject[15] = transform.Find("GO Root/Camera/Test07(Clone)/Poss/Camera").gameObject;
    cameraGameObject[16] = transform.Find("GO Root/Camera/Test08(Clone)/Poss/Camera").gameObject;
    cameraGameObject[17] = transform.Find("GO Root/Camera/Test09(Clone)/Poss/Camera").gameObject;
    cameraGameObject[18] = transform.Find("GO Root/Camera/Test10(Clone)/Poss/Camera").gameObject;
    cameraGameObject[19] = transform.Find("GO Root/Camera/Test11(Clone)/Poss/Camera").gameObject;
    cameraGameObject[20] = transform.Find("GO Root/Camera/Test12(Clone)/Poss/Camera").gameObject;
    cameraGameObject[21] = transform.Find("GO Root/Camera/Test13(Clone)/Poss/Camera").gameObject;
    cameraGameObject[22] = transform.Find("GO Root/Camera/Test14(Clone)/Poss/Camera").gameObject;
    cameraGameObject[23] = transform.Find("GO Root/Camera/Test15(Clone)/Poss/Camera").gameObject;
    cameraGameObject[24] = transform.Find("GO Root/Camera/Test16(Clone)/Poss/Camera").gameObject;
    cameraGameObject[25] = transform.Find("GO Root/Camera/Test17(Clone)/Poss/Camera").gameObject;
    cameraGameObject[26] = transform.Find("GO Root/Camera/Test18(Clone)/Poss/Camera").gameObject;
    cameraGameObject[27] = transform.Find("GO Root/Camera/Test19(Clone)/Poss/Camera").gameObject;
    cameraGameObject[28] = transform.Find("GO Root/Camera/Test20(Clone)/Poss/Camera").gameObject;
    cameraGameObject[29] = transform.Find("GO Root/Camera/Test21(Clone)/Poss/Camera").gameObject;
    cameraGameObject[30] = transform.Find("GO Root/Camera/Test22(Clone)/Poss/Camera").gameObject;
    cameraGameObject[31] = transform.Find("GO Root/Camera/Test23(Clone)/Poss/Camera").gameObject;
    cameraGameObject[32] = transform.Find("GO Root/Camera/Test24(Clone)/Poss/Camera").gameObject;
    cameraGameObject[33] = transform.Find("GO Root/Camera/Test25(Clone)/Poss/Camera").gameObject;
    cameraGameObject[34] = transform.Find("GO Root/Camera/Test26(Clone)/Poss/Camera").gameObject;
    cameraGameObject[35] = transform.Find("GO Root/Camera/Test27(Clone)/Poss/Camera").gameObject;
    cameraGameObject[36] = transform.Find("GO Root/Camera/Test28(Clone)/Poss/Camera").gameObject;
    cameraGameObject[37] = transform.Find("GO Root/Camera/Test29(Clone)/Poss/Camera").gameObject;
    cameraGameObject[38] = transform.Find("GO Root/Camera/Test30(Clone)/Poss/Camera").gameObject;
    cameraGameObject[39] = transform.Find("GO Root/Camera/HORSE_JOCKEY(Clone)").gameObject;

    //CommonEnv (follow_camera's_focus)
    cameraGameObject[40] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_1(Clone)/Pos/Camera").gameObject;
    cameraGameObject[41] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_2(Clone)/Pos/Camera").gameObject;
    cameraGameObject[42] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_3(Clone)/Pos/Camera").gameObject;
    cameraGameObject[43] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/FRONT_1(Clone)/Pos/Camera").gameObject;
    cameraGameObject[44] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/SIDE_1(Clone)/Pos/Camera").gameObject;
    cameraGameObject[45] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/SIDE_2(Clone)/Pos/Camera").gameObject;

    //get the fog GameObject
    //0 :day , 1:night
    if (tzPlayInfo.Instance.ENV_01_IDX == 0)
    {
        //Find GameObject Fog Effect
        FogEffect = transform.Find("GO Root/day/01_Env_Lev01_test01/Fog01 (1)").gameObject;
    }
    else
    {
        //Find GameObject Fog Effect
        FogEffect = transform.Find("GO Root/night/01_Env_Lev01_night-test02/Fog01").gameObject;
    }

    foreach (GameObject cams in cameraGameObject)
    {
        if (cams != null && FogEffect != null)
        {
            foundobjects = true;
            Debug.Log("All of the GameObjects have been found!!!!");
        }
    }
    yield break;
}

```

I build an apk using this code now it has this error

> 02-14 13:14:47.306 1828-1958/system\_process W/InputDispatcher: channel '4ecb0710 com.x.x.x/com.unity3d.player.UnityPlayerActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
>
> 02-14 13:14:47.306 1828-1958/system\_process E/InputDispatcher: channel '4ecb0710 com.steet383.rh.google/com.unity3d.player.UnityPlayerActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
>
> 02-14 13:14:47.306 1828-1846/system\_process W/InputDispatcher: Attempted to unregister already unregistered input channel '4ecb0710 com.x.x.x/com.unity3d.player.UnityPlayerActivity (server)'
>
> 02-14 13:14:47.306 1828-1846/system\_process I/WindowState: WIN DEATH: Window{4ecb0710 u0 com.x.x.x/com.unity3d.player.UnityPlayerActivity}
>
> 02-14 13:14:47.306 1828-1846/system\_process W/WindowManager: Force-removing child win Window{4ebbdfa0 u0 SurfaceView} from container Window{4ecb0710 u0 com.x.x.x/com.unity3d.player.UnityPlayerActivity}
>
> 02-14 13:14:47.306 1828-2020/system\_process W/ActivityManager: Force removing ActivityRecord{4ea0bc74 u0 com.x.x.x.UnityPlayerActivity t8}: app died, no saved state

# Answer
> 1 votes
Use `Transform.Find(string name)` instead. Or keep public references that you can populate via inspector, e.g.

`public Transform myLightSource;`

You should never, EVER be using magic numbers in your code to retrieve various elements as that inevitably leads to the sort of problems you are having right now. Always use string names/IDs or symbolic references e.g. a constant like `MY_LIGHT_SOURCE` where that would be defined as `const int MY_LIGHT_SOURCE = 7;` or `#define MY_LIGHT_SOURCE 7`.

Moreover, in your specific case, `Transform` order is not guaranteed at runtime, so you are requesting an invalid index when running as APK. This will not happen if you `Find` by name.

---
Tags: unity, c#, transformation, gameobject
---


# Question
Title: Animating a sprite character with Multiple Parts
I'm trying to animate a 2D character with interchangable parts. Right now, I have each part nested in a general part that is in turn nested in an overall parent like so; Player-\>Heads-\>Head1. I have a Controller for each part made and I feel like I should be able to pass the parameters from the Player's animator all the way to Head1's animator as they have the same parameters. I'm not quite sure how to tackle this. Using C#

# Answer
My own personal way of handling this would be having the Player contain each directly connected part of the body, and so when the player is called to update, you then update each part of the body within that.

A quick example, lets assume that your objects will handle their own rendering.

```
RenderPlayer()
{
//Player Render code here
this.Arm.RenderArm(PlayerX,PlayerY);
}

```

With this each Object only needs to know its location compared to the player, and add that to the location information the player passes on. You can also continue to nest this even farther down.

```
RenderArm(X,Y)
{
//Arm Render code here
this.Hand.RenderHand(ArmX + X, ArmY + Y);
}

```

The player does not need to know the arm has a hand, so you could add even more, like if the hand has a weapon or the like. You have to factor in offsets of course, but hopefully this will help your creation of something "Rayman like"

It also means that if you swap one head for another, it doesn't need anything special to work, since it fills the same mold.
> 2 votes

---
Tags: unity, c#, animation, sprites, character
---


title: Font Changes in WebGL Build

text:
# Question
Title: Font Changes in WebGL Build
I'm attempting to make a game for WebGL. However, everytime I export a build, the font always changes on everything, just like below.

Original

WebGL

My default font is Arial and I have made a separate Arial font file with which I've replaced all instances of Arial font in my game, but it's still turning out like this. Why?

# Answer
> 1 votes
I just managed to solve the problem in a very weird way.

I initially brought an Arial font file into the project and replaced all text object fonts with this. It didn't work. To make sure it was accessing that font file and not the default font, I renamed it "\_Arial". Still didn't work.

Then while looking at the Unity Documentation, I noticed this:

> **Font Names:** A list of fallback fonts to use when fonts or characters are not available (see below).

So I got an idea. I duplicated my \_Arial Font, which was my original Arial font, and renamed it back to simply "Arial". Built my project and it worked. I don't have a solid reason why it works, but I highly suspect it's because it can't ever find a "\_Arial" font, so it uses the Font Names section as a fallback, which in this case is "Arial". If there's a separate font with that name, Arial, it just runs to that instead since it's already listed on \_Arial's Font name reference. As to why this didn't work normally when I tried to just run the regular "Arial" font file, I have no idea, but that seems to be how it works from what I can tell and it solved the issue. This seems exclusive to Arial though. Other fonts work just fine.

Hopefully anyone with this problem can see this and try that solution, as nonsensical as it is.

---
Tags: unity, fonts, unity-webgl
---


# Question
Title: UNIT_SPELLCAST_START event, spell names, localization issues?
I have created a small addon for myself, SheepWhisperer which listens for me casting Polymorph on my mage or Shackle Undead on my priest.

When it detects this, and I'm in a party, it will check if I'm targetting a mob that one of the other party members are also targetting. If so then it will send them a whisper telling them about my incoming spell.

So far the addon works for me, but I'd like to publish this addon for others to use.

The event gets called with the spell names, not the spell id's, which means that my code currently looks for the following two spells by their names:

* Polymorph
* Shackle Undead

The question is this: If someone is running the German client (or any of the other clients, other than the English one), will they get different names or will this event still be called with "Polymorph"?

I have checked Wowhead: Polymorph but it doesn't tell me the German (as an example) name for that spell. Perhaps there is none? Perhaps all the clients use Polymorph so this is a non-starter?

# Answer
> 2 votes
The answer is yes, this will be a problem.

I found files from many addons that contains localized spell names, here's one such example - https://github.com/laytya/Libs2/blob/master/Babble/Babble-Spell-2.3/Babble-Spell-2.3.lua

Example:

```
...
["Shackle Undead"] = "Сковывание нежити",
...
["Shackle Undead"] = "Untote fesseln",
...

```

so yes, this has to be solved.

---
Tags: modding, world-of-warcraft-modding
---


title: Java ConcurrentModificationException

text:
# Question
Title: Java ConcurrentModificationException
Hey guys i am trying to solve the problem for 2 days now and dont know how to handle it. i tried to use an iterator also a copy ArrayList but it didnt solved my problem, below are my two relevant classes.I wanna check if my player is colliding with a gem and ig it is colliding then add the gem to item ArrayList and delete it from objects ArrayList.

public class Player extends GameObject {

```
// bereite und höhe des Rechtecks der das Object umhüllt für Collisin in
// getBounds
private float width = 32, height = 64;
private float gravity = 0.02f;
Handler handler;
Texture tex = Game.getInstance();
private Animation playerA, playerD, playerW, playerS;

public Player(float x, float y, Handler handler, ObjectID id) {
    super(x, y, id);
    this.handler = handler;
    playerW = new Animation(10, tex.playerW.get(1), tex.playerW.get(2));
    playerS = new Animation(10, tex.playerS.get(1), tex.playerS.get(2));
    playerA = new Animation(10, tex.playerA.get(1), tex.playerA.get(2));
    playerD = new Animation(10, tex.playerD.get(1), tex.playerD.get(2));
    score = 0;

}

public void playerMovement() {
    x += velX;
    y += velY;

    if (jumping || falling) {
        velY += gravity;

    }

}

@Override
public void tick(ArrayList<GameObject> object) {
    facingFigur();
    playerMovement();
    collision(object);
    playerW.runAnimation();
    playerS.runAnimation();
    playerA.runAnimation();
    playerD.runAnimation();

}

@Override
public void render(Graphics g) {
    g.setColor(Color.BLUE);
    if ((this.x > -Camera.getX() + Game.WIDTH) || (this.x < -Camera.getX() - 32)
            || (this.y > -Camera.getY() + Game.HEIGHT) || (this.y < -Camera.getY() - 32)) {
    } else {
        if (velX != 0 || velY != 0) {
            switch (facing) {

            case 1:
                playerD.drawAnimation(g, (int) x, (int) y, 24, 32);
                break;
            case -1:
                playerA.drawAnimation(g, (int) x, (int) y, 24, 32);
                break;
            case 2:
                playerW.drawAnimation(g, (int) x, (int) y, 24, 32);
                break;
            case -2:
                playerS.drawAnimation(g, (int) x, (int) y, 24, 32);
                break;
            }
        } else {

            switch (facing) {

            case 1:
                g.drawImage(tex.playerD.get(0), (int) x, (int) y, null);
                break;
            case -1:
                g.drawImage(tex.playerA.get(0), (int) x, (int) y, null);
                break;
            case 2:
                g.drawImage(tex.playerW.get(0), (int) x, (int) y, null);
                break;
            case -2:
                g.drawImage(tex.playerS.get(0), (int) x, (int) y, null);
                break;
            }

        }
    }

}

// Collision

private void collision(List<GameObject> object) {

    for (GameObject objectt : handler.objects) {

        if (objectt.getID().equals(ObjectID.Tree) || objectt.getID().equals(ObjectID.Block)) {

            if (getBoundsTOP().intersects(objectt.getBounds())) {
                y = objectt.getY() + (height / 2);
                velY = 0;

            }

            if (getBounds().intersects(objectt.getBounds())) {
                y = objectt.getY() - height;
                velY = 0;

            } else {

            }

            if (getBoundsRIGHT().intersects(objectt.getBounds())) {
                x = objectt.getX() - width;

            }
            if (getBoundsLEFT().intersects(objectt.getBounds())) {
                x = objectt.getX() + width;

            }

        }

    }

    for (GameObject objectt : handler.objects) {
        if(objectt.getID().equals(ObjectID.Gem)) {
            if(getBoundsTOP().intersects(objectt.getBounds())) {
                handler.collectedItems.add(objectt);
            }
        }

    }
    handler.objects.removeAll(handler.collectedItems);

}

public void facingFigur() {
    if (velX < 0) {
        facing = -1;
    } else if (velX > 0) {
        facing = 1;
    }

    if (velY < 0) {
        facing = 2;
    } else if (velY > 0) {
        facing = -2;
    }

}

public Rectangle getBounds() {
    return new Rectangle((int) ((int) x + (width / 2) - width / 4), (int) ((int) y + (height / 2)), (int) width / 2,
            (int) height / 2);
}

public Rectangle getBoundsTOP() {
    return new Rectangle((int) ((int) x + (width / 4)), (int) y, (int) width / 2, (int) height / 2);
}

public Rectangle getBoundsRIGHT() {
    return new Rectangle((int) ((int) x + width - 5), (int) y + 5, (int) 5, (int) height - 10);
}

public Rectangle getBoundsLEFT() {
    return new Rectangle((int) x, (int) y + 5, (int) 5, (int) height - 10);
}

```

}

public class Handler {

```
public ArrayList<GameObject> objects = new ArrayList<GameObject>();
public ArrayList<GameObject> bullets = new ArrayList<GameObject>();
public ArrayList<GameObject> collectedItems= new ArrayList<GameObject>();
private GameObject tempObject;

public void tick() {

    for (GameObject objectt : objects) {
        objectt.tick(objects);
    }

    for (GameObject bulletss : bullets) {
        bulletss.tick(bullets);
    }

    for (GameObject element : new ArrayList<GameObject>(bullets)) {
        if (element.isVisible() == false) {

            bullets.remove(element);
        }
    }

}

public void render(Graphics g) {

    for (GameObject o : objects) {
        o.render(g);

    }

    for (int i = 0; i < bullets.size(); i++) {
        tempObject = bullets.get(i);
        tempObject.render(g);

        /**
         * andere variante for(GameObject o: object){ o.render(g);
         */

    }

}

public void addObject(GameObject object) {

    this.objects.add(object);
}

public void addBullet(GameObject object) {

    this.bullets.add(object);
}

public void removeObject(GameObject object) {
    this.objects.remove(object);
}

public void removeAll() {
    this.objects.clear();
}

public int sizeOfObject(ObjectID id) {
    int count = 0;
    for (GameObject object : objects) {
        if (object.getID().equals(id)) {
            count++;
        }
    }
    return count;
}

// public void createLevel() {
//
// for (int xx = 0; xx < Game.WIDTH + 32; xx += 32)
//
// addObject(new Tree(xx, Game.HEIGHT - 32, ObjectID.Tree));
// for (int yy = 0; yy < Game.WIDTH + 32; yy += 32)
// addObject(new Tree(Game.HEIGHT + 166, yy, ObjectID.Tree));
// for (int zz = 0; zz < Game.WIDTH + 32; zz += 32)
// addObject(new Tree(Game.HEIGHT - 609, zz, ObjectID.Tree));
// for (int ww = 192; ww < Game.WIDTH - 256; ww += 32)
// addObject(new Tree(ww, Game.HEIGHT - 192, ObjectID.Tree));
//
// }

/*
 * for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
 * String value = iterator.next(); if (value.length() > 5) { iterator.remove();
 * } }
 */

```

}

```
Exception in thread "Thread-2"
java.util.ConcurrentModificationException
    at
java.util.ArrayList$Itr.checkForComodification(Unknown  Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at window.Handler.tick(Handler.java:19)
    at window.Game.tick(Game.java:96)
    at window.Game.run(Game.java:76)
    at java.lang.Thread.run(Unknown Source)

```

# Answer
Don't modify you structures as you are iterating over them.

Instead collect the planned modifications into a collection and apply them afterwards.

So in `addObject` you instead add to a secondary `objectToAdd` list and then do a `this.objects.addAll(objectToAdd);objectToAdd.clear();` at the end of `tick`. You do the same with every other method that would change the datastructure.
> 0 votes

---
Tags: java
---


# Question
Title: Unity 5.. How to Block interaction below panel?
New to Unity...Is there an easy way to block all interaction underneath a panel that I would have stationary at top of my game. There will be a pause button in that panel and some game info. Just don't want the mouse input or clicks to go through the panel and interacting with game below.

# Answer
You're looking for;

```
if(!EventSystem.current.IsPointerOverGameObject())

```

Place this line before your code that handles mouse click on any non-UI componenets to stop their functionality when clicking on the UI; the method will return `true` whilst over UI components.
> 7 votes

# Answer
If you are trying to block interation on other UI elements (for example if this panel is a pop-up submenu or notification, which is overlayed on top of the actual menu, which is also made up of UI elements), then you can tick the "Raycast target" checkbox on the panel's Image component. This will prevent all clicks on the panel from going through the panel and interacting with UI components (such as buttons, checkboxes, input fields, sliders, etc.) underneath the panel.

If, however, you are trying to block interaction with game objects (and not ui elements), then there are also two cases I can think of:

If this panel is meant to stop interaction with the entire game (such as a "Game Options" panel, then you can do what Vadim Tatarnikov suggested and simply have a boolean which tracks whether or not the panel is open. Alternatively, since you mention pausing, you can also use the Time.timeScale static variable to determine whether the game is paused or not and use that to decide how to process clicks.

If this panel is however a screen overlay, where the player can interact with the panel, but also the game (for example a "Unit details" panel in a strategy game), then you can use what MrDiVolo suggested:

```
if(!EventSystem.current.IsPointerOverGameObject())

```

With this method, you however need to be very diligent in disabling transparent ui elements, setting the raycast target checkbox properly for all visible ui elements (meaning ticking for elements which should block clicks and unticking for overlays which should not block clicks)
> 3 votes

# Answer
You can make a Boolean variable that is true when the game is paused, and make other objects check if it this variable is true, in addition to the check for Input.
> 0 votes

# Answer
I had a similar issue and I found this video to be very helpful, all credit to kiwasi.com. It's showing 3 possible solution approaches, from the simplest to most complex (and least to most recommended):

1. Use `EventSystem.current.isPointerOverGameObject()` from `UnityEngine.EventSystems` just as MrDiVolo explains
2. Event Triggers (check also here)
3. Event System Interfaces (IPointerClickHandler etc.)
> 0 votes

---
Tags: unity
---


# Question
Title: How can I know if my puzzle game is always possible?
I've made a sort of a puzzle game where the goal is to get rid of all of the white tiles. You can try it at the end of the question.

Each time, the board is randomly generated with white tiles in random places on a 5\*5 grid. You can click any tile on that grid and it will toggle the color of it and all of the tiles touching it on its sides. My dilemma is the fact that I don't know if it will generate an impossible board. What is the best way to check things like this?

```
function newgame() {
 moves = 0;
    document.getElementById("moves").innerHTML = "Moves: "+moves;

  for (var i = 0; i < 25; i++) {
   if (Math.random() >= 0.5) {
$(document.getElementsByClassName('block')[i]).toggleClass("b1 b2")
   }
}
}
newgame();
function toggle(a,b) {
  moves += 1;
  document.getElementById("moves").innerHTML = "Moves: "+moves;
$(document.getElementsByClassName('block')[a+(b*5)]).toggleClass("b1 b2");

if (a<4) {$(document.getElementsByClassName('block')[(a+1)+(b*5)]).toggleClass("b1 b2")}

if (a>0) {$(document.getElementsByClassName('block')[(a-1)+(b*5)]).toggleClass("b1 b2")}

if (b<4) {$(document.getElementsByClassName('block')[a+((b+1)*5)]).toggleClass("b1 b2")}

if (b>0) {$(document.getElementsByClassName('block')[a+((b-1)*5)]).toggleClass("b1 b2")}
}
```

```
body {
  background-color: #000000;
}

.game {
  float: left;
  background-color: #000000;
  width: 300px;
  height: 300px;
  overflow: hidden;
  overflow-x: hidden;
  user-select: none;
  display: inline-block;
}

.container {
  border-color: #ffffff;
  border-width: 5px;
  border-style: solid;
  border-radius: 5px;
  width: 600px;
  height: 300px;
  text-align: center;
}

.side {
  float: left;
  background-color: #000000;
  width: 300px;
  height: 300px;
  overflow: hidden;
  overflow-x: hidden;
  user-select: none;
  display: inline-block;
}

.block {
  transition: background-color 0.2s;
  float: left;
}

.b1:hover {
  background-color: #444444;
  cursor: pointer;
}

.b2:hover {
  background-color: #bbbbbb;
  cursor: pointer;
}

.row {
  width: 300px;
  overflow: auto;
  overflow-x: hidden;
}

.b1 {
  display: inline-block;
  height: 50px;
  width: 50px;
  background-color: #000000;
  border-color: #000000;
  border-width: 5px;
  border-style: solid;
}

.b2 {
  display: inline-block;
  height: 50px;
  width: 50px;
  background-color: #ffffff;
  border-color: #000000;
  border-width: 5px;
  border-style: solid;
}

.title {
  width: 200px;
  height: 50px;
  color: #ffffff;
  font-size: 55px;
  font-weight: bold;
  font-family: Arial;
  display: table-cell;
  vertical-align: middle;
}

.button {
  cursor: pointer;
  width: 200px;
  height: 50px;
  background-color: #000000;
  border-color: #ffffff;
  border-style: solid;
  border-width: 5px;
  color: #ffffff;
  font-size: 25px;
  font-weight: bold;
  font-family: Arial;
  display: table-cell;
  vertical-align: middle;
  border-radius: 5px;
  transition: background-color 0.3s, color 0.3s;
}

.button:hover {
  background-color: #ffffff;
  color: #000000;
}

.sidetable {
  padding: 30px 0px;
  height: 200px;
}

#moves {
  width: 200px;
  height: 50px;
  color: #aaaaaa;
  font-size: 30px;
  font-weight: bold;
  font-family: Arial;
  display: table-cell;
  vertical-align: middle;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
  <div class="container">

  <div class="game"><div class="row"><div onclick="toggle(0,0);" class="block b1"></div><div onclick="toggle(1,0);" class="block b1"></div><div onclick="toggle(2,0);" class="block b1"></div><div onclick="toggle(3,0);" class="block b1"></div><div onclick="toggle(4,0);" class="block b1"></div></div><div class="row"><div onclick="toggle(0,1);" class="block b1"></div><div onclick="toggle(1,1);" class="block b1"></div><div onclick="toggle(2,1);" class="block b1"></div><div onclick="toggle(3,1);" class="block b1"></div><div onclick="toggle(4,1);" class="block b1"></div></div><div class="row"><div onclick="toggle(0,2);" class="block b1"></div><div onclick="toggle(1,2);" class="block b1"></div><div onclick="toggle(2,2);" class="block b1"></div><div onclick="toggle(3,2);" class="block b1"></div><div onclick="toggle(4,2);" class="block b1"></div></div><div class="row"><div onclick="toggle(0,3);" class="block b1"></div><div onclick="toggle(1,3);" class="block b1"></div><div onclick="toggle(2,3);" class="block b1"></div><div onclick="toggle(3,3);" class="block b1"></div><div onclick="toggle(4,3);" class="block b1"></div></div><div class="row"><div onclick="toggle(0,4);" class="block b1"></div><div onclick="toggle(1,4);" class="block b1"></div><div onclick="toggle(2,4);" class="block b1"></div><div onclick="toggle(3,4);" class="block b1"></div><div onclick="toggle(4,4);" class="block b1"></div></div></div>

    <div class="side">
      <center class="sidetable">
        <div class="title">Tiles</div>
        <br>
        <div class="button" onclick="newgame()">New Game</div>
        <br><br>
        <div id="moves">Moves: 0</div>
      </center>
    </div>

  </div>
    </center>
```

# Answer
> 164 votes
This is the type of game where the same move performed twice reverses the board to its previous state. So to ensure a board is solvable, generate it by playing in reverse. Start with a solved (blank) board, then start programmatically "clicking" randomly either a certain number of times, or until the board has the desired number of white squares. One solution is then to simply perform the same moves in the reverse order. Other shorter solutions may exist, but you are guaranteed to have at least one.

Another, much more complex solution, is to define a solving algorithm that goes through all possible game states from your starting position to try to find the solution. This would take much longer to implement and run, but would allow the boards to be truly randomly generated. I won't go into specifics of this solution, because it's just not as good an idea.

# Answer
> 95 votes
While the above answers are clever (and probably how I would do it anyway), this particular game is very well known. It's called Lights Out, and has been mathematically solved. There is a solution if and only if two sums of various elements (given on the wikipedia page) add to zero mod 2 (i.e. an even number). In general a little linear algebra should give similar solution conditions for games on any board.

# Answer
> 12 votes
Go the other way around when generating your puzzle.

Instead of randomly selecting the tiles and turning them from white to black, start from a blank slate, then select the tiles but instead of turning *that* tile to black, make it as if the user selected it, resulting in flipping all of the other tiles around it.

This way you'll be guaranteed to have *at least* one solution: the user will have to undo what you "AI" player did to create the level.

# Answer
> 7 votes
Ed and Alexandre have the right of it.

But if you *do* want to know if every solution is possible, there are ways.

# There are a finite number of possible puzzles

Clicking on the same square twice produces the same result as not clicking on it at all, no matter how many clicks were made between them. That means that every solution can be described by giving each square a binary value of 'clicked' or 'not clicked'. Similarly, each puzzle can be described by giving each square a binary value of 'toggled' or 'not toggled'. That means that there are 2^25 possible puzzles, and 2^25 possible solutions. If you can prove that each solution solves a unique puzzle then there must be a solution to every puzzle. Similarly, if you find two solutions that solve the same puzzle then there cannot be a solution to every puzzle.

Also, 2^25 is 33,554,432. That's quite a lot, but it's not an unmanageable number. A good algorithm and a decent computer could probably brute force that in a couple of hours, especially when you consider that half the puzzles are inverses of the other half.

# Answer
> 4 votes
Generalized answer:

1. Create a matrix of size (# moves) x (# lights).
2. Put a 1 in a cell if making the move corresponding to that row toggles that light corresponding to that column, 0 otherwise.
3. Perform Gauss-Jordan elimination (modulo 2) on the matrix.
4. If the matrix that results has a single 1 in each column, and every row has at most a single 1, then every grid in solvable.

# Answer
> 1 votes
Others have already mentioned ways to find whether your randomly generated puzzle is solvable. the question you should also be asking though, is whether you actually want randomly generated puzzles.

Randomly generated puzzles all have the same core flaw: Their difficulty is pretty much unpredictable. The possible puzzles you might get can range from already solved, to trivial (solution is obvious) to hard (solution is not obvious) to impossible (the puzzle is not solvable at all). Because the difficulty is unpredictable, it makes for an unsatisfactory experience for the player, especially if they do multiple puzzles in a row. They're highly unlikely to get a smooth difficulty curve, which can make them bored or frustrated depending on what puzzles they get.

Another problem of random generation is that the time it takes for the puzzle to initialize is unpredictable. Generally speaking, you're going to get a solvable puzzle (almost) immediately, but with some bad luck, your randomly generated puzzles might end up on a streak of unsolvable puzzles.

One way to solve both of these is by having predefined vectors of every solvable puzzle available, arranged into difficulty groups, and then selecting a random puzzle from the solvable puzzles based on the difficulty. This way, you will be certain that every puzzle is solvable, that the difficulty is predictable and that the generation will be done in constant time.

---
Tags: game-design, logic, puzzle, playtesting
---


# Question
Title: Unity: Set new Origin using empty GameObject
You used to be able to set a GameObject with your Mesh as a child of an Empty GameObject. By rotating the Empty the Mesh would rotate around the position of the Empty. Now after the update it seems it's auto calculating a Median Point.

Here's the problem: https://www.youtube.com/watch?v=gxB\_6c75oP0

I should be able to keep the original Origin of the empty GameObject no matter what children it gets. What happened to Unity?

This is how it used to be: https://answers.unity.com/questions/609267/how-to-change-the-origin-of-a-gameobject.html

# Answer
> 5 votes
Next to the `RectTransform` tool, you will find a toggle that has two states "Pivot" or "Center".

This **Gizmo handle position toggle** is used to define the location of the Transform tool Gizmo of the selected objets, and the handles use to manipulate the Gizmo itself.

* When set to **Pivot**, the Gizmo is positionned at the actual pivot point of a Mesh.
* When set to **Center**, the Gizmo is positionned at the center of the GameObject’s rendered bounds.

According to your problem, the toggle is set to **Center**. Click on the toggle to set it to **Pivot**. Now, you have the correct pivot point of your empty.

Source: https://docs.unity3d.com/Manual/PositioningGameObjects.html

---
Tags: unity, 3d, pivot
---


# Question
Title: How do you create a circular room on a 2D Plane(Similar to Odin Sphere)?
I'm trying to figure out an optimal solution to creating the illusion of a circular room within a 2D world.

Odin Sphere(Video Example) does this well. As you walk along the X axis the room will eventually wrap around and you'll be back at your original location.

My thought process was to have the level separated into sections and if the player passes a certain point on the X Axis have the initial sections position move to the opposite side.

I'm not sure how to handle enemy or other objects within the section though, if the level section is moved and they're active I'm worried they might fall through the world or other strange behaviors.

Anyone have experience implementing something similar to this?

# Answer
One solution is to mod the character/camera position by the dimensions of the room. For example if the room is 2000 units large & the character is at position 1995 & tries to walk in the +X direction 8 units, then you would have the following:

```
xPosition = xPosition + update;   // apply the update
xPosition = xPosition % roomSize; // use mod to wrap around
// xPosition is now at position 3

```

The other consideration is how to visually transition across the edge of the room. Using just the above, the character would teleport from one location to the other. If the room fits on a single screen, that's probably fine as the background would stay in place. If it doesn't fit on the same screen, then I would divide the room into chunks & again use mod to determine which sections to render. For example, let's say you have the following:

* screen is 1280px wide
* full room is 6000px wide
* the sections of the room are 750px wide
    + note: this means that it takes 8 sections (indexed 0 to 7) to represent the entire room
* the character is at position 5900
* the view should be centered on the character
* the coordinates start with 0 on the left & increase as you move to the right

First you'll need to find the left & right extents of the viewing area:

```
screenLeft  = xPosition - (screenWidth / 2);  // 5260
screenRight = xPosition + (screenWidth / 2);  // 6540

```

Next, determine which sections would need to render. Note, we only need the integer part, so you can either use integer division, the floor function or a cast to remove the decimal portion. In my example, I'm assuming integer division:

```
leftmostSection  = screenLeft  / sectionWidth; // 7.013333 -> start at section 7
rightmostSection = screenRight / sectionWidth; // 8.72     -> go up to section 8

```

But there's no section 8! What we really need to do is wrap around to the section 0 (the first section). Rather than using a bunch of conditional logic, you can again use the % operator:

```
leftmostSection  = (screenLeft  / sectionWidth) % sectionCount; // 7
rightmostSection = (screenRight / sectionWidth) % sectionCount; // 0

```

Now you have enough info to know which sections (and enemies thereof) to draw to get a wrap around room. Visually, it would be something like this:

For future reference: When dealing with positive numbers, mod (often represented with the % symbol) gives the remainder after applying division. However, there's more than one way to interpret the notion of modulus & remainders when negative numbers are involved. The C# documentation for % explains their implementation; note that it does not give the canonical modulus, it gives the remainder & there's a difference between the two.
> 1 votes

---
Tags: unity
---


# Question
Title: C++ Storing Mass Data Sets for Future Use
I didnt know how to title this...

**Background:** I am currently trying to develop a windows command console game with C++ for a final project. The game is text based. I have only been programming C++ for a semester. My game is basically a racing simulation game where you can buy and equip different cars.

I have created a bunch of different cars with stats similar to the Forza 7 racing game. The stats are as followed: car model and year, car ID, top speed (float), handling (float), acceleration (float), braking (float), as well as some hidden attributes like ride height(enum) and others.

**Goal:** I am basically trying to find a way to store this data in large amounts while being able to edit and access this data very easily. I want to be able to print these out in large amounts (possibly using a loop to print based on car IDs) and be able to set the equipped cars stats equal to an int that is always being changed to the equipped car's stats.

I was thinking placing these statistics inside of a structure and then initializing each car and its attributes individually, but this would be a very long process. Example of what I think I should do:

```
struct carData {
   string Year;
   string Manufacturer;
   string Model;
   int iCarID;
   double iCost;
   float fSpeed;
   float fHandling;
   float fAccel;
   float fBraking;
   float fMidRange;
};
//Every car, the number represents the car id

carData C01;
C01.iCarID = 01;
C01.Year = "2001";
C01.Manufacturer = "Volkswagen";
C01.Model = "Golf";
C01.fSpeed = 9.9;

//Would be continued for all stats for all cars

```

Would it be possible to then print this data (cars name, number and stats) using a loop rather than printing it individually when needed? I want to be able to change car's stats without having to redo entire sections of code and I want to keep my code as efficiently as possible.

Any resources or ideas would be greatly appreciated. If you find links to similar questions, please let me know. I had no idea what to search to find a question like mine... Thanks.

# Answer
Store the individual instances of your data in a `std::vector` (`std::vector<carData> allTheCars`).

You can then use `resize()` to pre-allocate a bunch of entries in the array, and refer to individual entries with `operator[]` (for example, `allTheCars[0]` or `allTheCars[21]`).

You can also use `reserve()` to reserve storage without actually adding elements, and then use `push_back()` or `emplace_back()` to add them on at a time (particularly if you are reading the data from a file, for example).

Regular C++ for loops can be used to iterate over the data in a loop (`for (auto i = 0; i < allTheCars.size(); ++i) { ... }`). You can also use range for loops, as well.
> 1 votes

---
Tags: c++, game-design, data-structure, statistics
---


# Question
Title: How the sharpdx set vertices by reading the vertex information files instead of coding the vertices?
During my developing, I always spend much time to fill up my vertex array by coding every vertex information when I have to create some complex models. It's quite inconvenient. It's will be very helpful if there is a method which can load the whole vertex information by reading the related files. For instance, there is a vertex file with 78 vertex-information in it such as:

```
Vertex Count: 78

Data:

4 -0.5 -4 0.998008 0.998008 0 1 -0
-4 -0.5 4 0.001992 0.00199199 0 1 -0
4 -0.5 4 0.998008 0.00199199 0 1 -0
4 -0.5 -4 0.998008 0.998008 0 1 -0
-4 -0.5 -4 0.001992 0.998008 0 1 -0
-4 -0.5 4 0.001992 0.00199199 0 1 -0
4 1 4 0.187127 0.998008 0 0 -1
-4 -0.5 4 0.000374 0.00199199 0 0 -1
-4 1 4 0.187127 0.00199199 0 0 -1
4 -0.5 4 0.000374 0.998008 0 0 -1
-4 -0.5 4 0.000374 0.00199199 0 0 -1
4 1 4 0.187127 0.998008 0 0 -1
4 1 -4 0.187126 0.998008 -1 0 -0
4 -0.5 4 0.000373 0.00199199 -1 0 -0
4 1 4 0.187126 0.00199199 -1 0 -0
4 -0.5 -4 0.000373 0.998008 -1 0 -0
4 -0.5 4 0.000373 0.00199199 -1 0 -0
4 1 -4 0.187126 0.998008 -1 0 -0
-4 1 -4 0.000374 0.00199199 0 0 1
4 -0.5 -4 0.187127 0.998008 0 0 1
4 1 -4 0.000374 0.998008 0 0 1
-4 1 -4 0.000374 0.00199199 0 0 1
-4 -0.5 -4 0.187127 0.00199199 0 0 1
4 -0.5 -4 0.187127 0.998008 0 0 1
-4 1 4 0.187127 0.998008 1 0 -0
-4 -0.5 -4 0.000374 0.00199199 1 0 -0
-4 1 -4 0.187127 0.00199199 1 0 -0
-4 -0.5 4 0.000374 0.998008 1 0 -0
-4 -0.5 -4 0.000374 0.00199199 1 0 -0
-4 1 4 0.187127 0.998008 1 0 -0
-5 1 5 0.199602 0.00199199 -1 0 -0
-5 -1 -5 0.000398 0.998008 -1 0 -0
-5 -1 5 0.000398 0.00199199 -1 0 -0
-5 1 -5 0.199602 0.998008 -1 0 -0
-5 -1 -5 0.000398 0.998008 -1 0 -0
-5 1 5 0.199602 0.00199199 -1 0 -0
5 1 -5 0.199602 0.00199199 1 0 -0
5 -1 5 0.000398 0.998008 1 0 -0
5 -1 -5 0.000398 0.00199199 1 0 -0
5 1 5 0.199602 0.998008 1 0 -0
5 -1 5 0.000398 0.998008 1 0 -0
5 1 -5 0.199602 0.00199199 1 0 -0
-5 -1 5 0.199602 0.00199199 0 0 1
5 1 5 0.000398 0.998008 0 0 1
-5 1 5 0.000398 0.00199199 0 0 1
5 -1 5 0.199602 0.998008 0 0 1
5 1 5 0.000398 0.998008 0 0 1
-5 -1 5 0.199602 0.00199199 0 0 1
-5 1 5 0.001992 0.00199199 0 1 -0
-4 1 -4 0.101594 0.898406 0 1 -0
-5 1 -5 0.001992 0.998008 0 1 -0
-5 1 5 0.001992 0.00199199 0 1 -0
-4 1 4 0.101594 0.101594 0 1 -0
-4 1 -4 0.101594 0.898406 0 1 -0
-4 1 -4 0.101594 0.898406 0 1 -0
5 1 -5 0.998008 0.998008 0 1 -0
-5 1 -5 0.001992 0.998008 0 1 -0
4 1 -4 0.898406 0.898406 0 1 -0
5 1 -5 0.998008 0.998008 0 1 -0
-4 1 -4 0.101594 0.898406 0 1 -0
4 1 -4 0.898406 0.898406 0 1 -0
5 1 5 0.998008 0.00199199 0 1 -0
5 1 -5 0.998008 0.998008 0 1 -0
4 1 4 0.898406 0.101594 0 1 -0
5 1 5 0.998008 0.00199199 0 1 -0
4 1 -4 0.898406 0.898406 0 1 -0
4 1 4 0.898406 0.101594 0 1 -0
-5 1 5 0.001992 0.00199199 0 1 -0
5 1 5 0.998008 0.00199199 0 1 -0
-5 1 5 0.001992 0.00199199 0 1 -0
4 1 4 0.898406 0.101594 0 1 -0
-4 1 4 0.101594 0.101594 0 1 -0
-5 1 -5 0.199602 0.00199199 0 0 -1
5 -1 -5 0.000398 0.998008 0 0 -1
-5 -1 -5 0.000398 0.00199199 0 0 -1
5 1 -5 0.199602 0.998008 0 0 -1
5 -1 -5 0.000398 0.998008 0 0 -1
-5 1 -5 0.199602 0.00199199 0 0 -1

```

There are there information in each vertex, which are position, texture, normal. So how could I set my vertex array by reading this file instead of coding these 78 verteces in my program?

My code is such as:

```
verts = new PositionTextureNormalVertex[]
            {
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,-4.0f),new Vector2(0.998008f,0.998008f), new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,4.0f),new Vector2(0.001992f,0.00199199f), new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,4.0f),new Vector2(0.998008f,0.00199199f), new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,-4.0f),new Vector2(0.998008f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,-4.0f),new Vector2(0.001992f,0.998008f), new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,4.0f),new Vector2(0.001992f,0.00199199f), new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.187127f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,4.0f),new Vector2(0.187127f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,4.0f),new Vector2(0.000374f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.187127f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,-4.0f),new Vector2(0.187126f,0.998008f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,4.0f),new Vector2(0.000373f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.187126f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,-4.0f),new Vector2(0.000373f, 0.998008f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,4.0f),new Vector2(0.000373f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,-4.0f),new Vector2(0.187126f,0.998008f),new Vector3(-1.0f,0.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,-4.0f),new Vector2(0.187127f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,-4.0f),new Vector2(0.000374f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,-4.0f),new Vector2(0.187127f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,-0.5f,-4.0f),new Vector2(0.187127f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),

                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f, 4.0f),new Vector2(0.187127f,0.998008f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,-4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.187127f,0.00199199f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,4.0f),new Vector2(0.000374f,0.998008f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,-0.5f,-4.0f),new Vector2(0.000374f,0.00199199f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f, 4.0f),new Vector2(0.187127f,0.998008f),new Vector3(1.0f,0.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.998008f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,5.0f),new Vector2(0.000398f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.998008f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.998008f),new Vector3(-1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(-1.0f,0.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.00199199f), new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,5.0f),new Vector2(0.000398f,0.998008f), new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.00199199f), new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.199602f,0.998008f),new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,5.0f),new Vector2(0.000398f,0.998008f), new Vector3(1.0f,0.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.00199199f), new Vector3(1.0f,0.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.000398f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.000398f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,5.0f),new Vector2(0.199602f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.000398f,0.998008f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(0.0f,0.0f,1.0f)),

                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.001992f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.101594f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,-5.0f),new Vector2(0.001992f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.001992f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,4.0f),new Vector2(0.101594f,0.101594f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.101594f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.101594f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.998008f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,-5.0f),new Vector2(0.001992f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,-4.0f),new Vector2(0.898406f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.998008f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,-4.0f),new Vector2(0.101594f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f, -4.0f),new Vector2(0.898406f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.998008f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.998008f,0.998008f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.898406f,0.101594f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.998008f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f, -4.0f),new Vector2(0.898406f,0.898406f),new Vector3(0.0f,1.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.898406f,0.101594f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.001992f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,5.0f),new Vector2(0.998008f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,5.0f),new Vector2(0.001992f,0.00199199f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(4.0f,1.0f,4.0f),new Vector2(0.898406f,0.101594f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionTextureNormalVertex(new Vector3(-4.0f,1.0f,4.0f),new Vector2(0.101594f,0.101594f),new Vector3(0.0f,1.0f,0.0f)),

                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(5.0f,-1.0f,-5.0f),new Vector2(0.000398f,0.998008f),new Vector3(0.0f,0.0f,-1.0f)),
                new PositionTextureNormalVertex(new Vector3(-5.0f,1.0f,-5.0f),new Vector2(0.199602f,0.00199199f),new Vector3(0.0f,0.0f,-1.0f)),
}

```

# Answer
this is the wavefront obj file loader that will allow you to load your models into memory. You need to add this as a part of your project as another solution. using Blender, you can export your models to .OBJ format. This loader is for very static models only.

included is some old code which I used to load files in with. See below. You will need to adapt the code and fill in the spaces in your code. This is working with Sharpdx and my project. Formatting is broken.

```
  public bool LoadMeshFromOBJ(string a_filename, string a_filepath, D3D11.DeviceContext2 a_context, D3D11.Device3 a_device)
    {
        FileStream fileStream = null;
        try
        {
            int vertexIndexCount = 0;

            var objLoaderFactory = new ObjLoaderFactory();
            IObjLoader objLoader = objLoaderFactory.Create();

            if (!File.Exists(a_filepath + a_filename))
            {
                throw new Exception("Mesh not found: " + a_filepath + a_filename);
            }

            fileStream = new FileStream(a_filepath + a_filename, FileMode.Open);
            LoadResult result = objLoader.Load(fileStream, a_filepath);

            m_masterVertexList.Clear();
            m_indexList.Clear();
            m_indiceBased = false;

            m_assetFileName = a_filepath + a_filename;
            m_assetExtension = Path.GetExtension(a_filename);
            m_assetName = a_filename.Substring(0, a_filename.Length - Path.GetExtension(m_assetExtension).Length).ToUpper();
            VertexPointMaster vp;

            for (int GroupCount = 0; GroupCount < result.Groups.Count; GroupCount++)
            {
                int texture = GlobalStatics.RenderManager.TextureFactory.GetTextureIndexByMaterialName(result.Groups[GroupCount].Material.Name, TextureGroup.Asset, true, a_device, a_context);

                if (!m_textureList.ContainsKey(texture))
                    m_textureList.Add(texture, result.Groups[GroupCount].Material.Name);

                for (int faceCount = 0; faceCount < result.Groups[GroupCount].Faces.Count; faceCount++)
                {
                    var Face = result.Groups[GroupCount].Faces[faceCount];

                    for (int i = 0; i < Face.Count - 1; i+=2)
                    {

                        for (int j = 0; j < 3; j++)
                        {
                            var FaceVertex = Face[(i + j) % Face.Count];

                            int vertexindex = (FaceVertex.VertexIndex - 1);  // should not use shorts, may need to be improved
                            int TextureIndex = (FaceVertex.TextureIndex - 1);  // should not use shorts, may need to be improved
                            int VertexNormal = (FaceVertex.NormalIndex - 1);

                            vp = new VertexPointMaster();
                            vp.m_vertex.X = result.Vertices[vertexindex].X;
                            vp.m_vertex.Y = result.Vertices[vertexindex].Y;
                            vp.m_vertex.Z = result.Vertices[vertexindex].Z;

                            if (TextureIndex >= 0)

                                vp.SetTextureUV(result.Textures[TextureIndex].X, -result.Textures[TextureIndex].Y);

                            vp.m_normal = (new Vector3(result.Normals[VertexNormal].X, result.Normals[VertexNormal].Y, result.Normals[VertexNormal].Z));
                            vp.m_normal.Normalize();

                            vp.TexturePrimary = texture;
                            vp.TextureSecondary = 0;
                            vp.SetTextureBlend(1.0f);

                            m_masterVertexList.Add(vp);
                        }
                        //  vertexIndexCount = vertexIndexCount + Face.Count;
                        vertexIndexCount += 3;
                    }
                }
            }

            RewindMesh(false, a_context, a_device);

            CreateDefaultBufferList(m_masterVertexList, m_indexList);
            CreateD3DBufferFromData(a_device, a_context, false);

            m_boundingBox.RegenerateBoundingBoxExtents(m_masterVertexList);

            return true;
        }
        catch (Exception ex)
        {
            ErrorHandler.DoErrorHandling(ex, ErrorHandler.GetCurrentMethod(ex), Environment.StackTrace);

        }
        finally
        {
            fileStream.Close();
        }

        return false;
    }

```
> 0 votes

---
Tags: c#, sharpdx, vertex-arrays
---


title: Proper way to update pixel array data

text:
# Question
Title: Proper way to update pixel array data
For a game that updates a board every frame I am calculating the next arrangement of board, updating pixel array data and render board as 2D texture to quad the size of the screen using OpenGL. I use:

```
glTexImage2d(GL_TEXTURE_2D,0,GL_RGBA,tex_width,tex_height,0,GL_BGRA,GL_UNSIGNED_INT_8_8_8_8_REV, &pixel_data.front())

```

to initialize the texture object and

```
glTexSubImage2d(GL_TEXTURE_2D,0,0,0,tex_width,tex_height, BGRA,GL_UNSIGNED_INT_8_8_8_8_REV, &pixel_data.front())

```

to update the texture.

The slowest part of the code is `update_pixels()` (below) Taking 256x128 elements input array and creating four component pixel array based on that. This function is very slow(45ms) and it seems it should be done differently. What would be the proper way to implement this function?

Update pixel data per frame:

```
void  update_pixels() {
//update pixels
//std::vector <unsigned char> pixel_data
float state = 0;
size_t it = 0;

for (size_t y = 0; y < board.getWorldHeight(); ++y) {
    for (size_t x = 0; x < board.getWorldWidth(); ++x) {
        state = board.get_state(y * golf_board.getWorldWidth() + x);

        pixel_data[y * board.getWorldWidth() + x + it ] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(1 * 255);

    }

}
return;
}

```

Time measurement:

```
void render(){
render_frame() //glDrawElements() for quad and scale uniform update takes 0.2ms
generate_states() //new states for board takes 1.3ms
auto t1 = std::chrono::high_resolution_clock::now();
update_pixels(); // create new pixel array, takes 32 ms
auto t2 - std::chrono::high_resolution_clock::now();
float update_time = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count() /1000.0f;
//cout <<updae_time
glfwSwapBuffers() //from update pixels to swap takes 13ms
}

```

# Answer
The first thing to speed up would be to use the smallest texture format for the job.

Since your `Alpha` is always 1 and all three components `RGB` are the same value you should use `GL_RED` (OpenGL 3.0 and later) or `GL_LUMINANCE` (up to OpenGL 3.0).

This creates a single-component texture so you do not need to copy the value 3 times and add a constant alpha value of 1.0 (255).

Up to OpenGL 3.0:

```
glTexImage2d(GL_TEXTURE_2D, 0, GL_LUMINANCE, tex_width,tex_height, 0,GL_LUMINANCE,　GL_UNSIGNED_BYTE, pixel_data.data());

```

or OpenGL 3.0 onward:

```
glTexImage2d(GL_TEXTURE_2D, 0, GL_RED, tex_width,tex_height, 0, GL_RED,　GL_UNSIGNED_BYTE, pixel_data.data());

const GLint swizzleMask[] = {GL_RED, GL_RED, GL_RED, GL_ONE};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);

```

This makes your texture a series of single bytes, one per pixel. Reducing CPU memory bandwidth, CPU\<-\>GPU bus transfer, and GPU memory bandwidth requirements.

The texture is returned by the sampler as `{RED, RED, RED, 1}` or `{LUMINANCE, LUMINANCE, LUMINANCE, 1}` (same thing, older OpenGL).

This way only 1 byte per pixel need to be written.

Also reduce the two loops to a single continuous loop of width\*height and avoid calculating the loop limit on every iteration:

```
//GLubyte *pixels = &pixel_data.front();
GLubyte *pixels = pixel_data.data(); // C++11

for (size_t i=0, count=board.getWorldHeight()*board.getWorldWidth(); count--; ) {
    *pixels++ = static_cast<GLubyte>(board.get_state(i++) * 255);
}

```

The post-decrement/post-increment operators helps modern CPUs do out-of-order execution.

To speed things up further you should also consider storing your board state as fixed points or a copy of it as a bytes to avoid the costly float to integer conversion multiple times every redraw.

If you maintain a copy of the state as bytes whenever modifying your states you can directly update the texture when something change.

And look into avoiding updating the texture when no state have effectively changed if this is a frequent occurrence.
> 1 votes

# Answer
One way to speed it up would be to access the arrays directly rather than doing a monstrous number of indexed look-ups into them when you're accessing the sequentially. It could look something like this:

```
unsigned char* nextPixel = &pixel_data [ 0 ];
const int boardHeight = board.getWorldHeight();
const int boardWidth = board.getWorldWidth();
const int numPixels = boardHeight * boardWidth;
for (int i = 0; i < numPixels; ++i)
{
    const float state = board.get_state(i);
    const unsigned char channel = static_cast<unsigned char>(state * 255.0);

    // red
    *nextPixel = channel;
    nextPixel++;

    // green
    *nextPixel = channel;
    nextPixel++;

    // blue
    *nextPixel = channel;
    nextPixel++;

    // alpha
    *nextPixel = 255;
    nextPixel++;
}

```

I also recommend using the appropriate types for your data. An OpenGL texture is not a series of individual `unsigned char`s. It's a 2 dimensional array of RGBA pixels. You should make a structure for them:

```
struct RGBAPixel {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char alpha;
};

```

Then your code wouldn't need the comments I added. But this isn't Code Review, so I'll stop here.
> 0 votes

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


# Question
Title: How to create a depth-recording shader for shadow mapping?
I am attempting to implement shadow maps.

I am first going to implement spotlights over directional lights (I am aware this is harder).

Since I was already rendering the geometry, my attempt was to recycle my old shaders and modify them to make shaders to create the depth maps.

This created the following vertex shader:

```
#version 450

layout(location = 0) in vec3 position; //(x,y,z) coordinates of a vertex

layout(std430, binding = 3) buffer data_buffer
{
    vec4 cubes_info[];//first 3 values are position of object
};

uniform mat4 view = mat4(1); //Camera orientation and position
uniform mat4 proj = mat4(1); //The projection parameters (FOV, viewport dimensions)

void main()
{
    gl_Position = proj*view*(vec4(position, 1.0) + vec4(vec3(cubes_info[gl_InstanceID]),0));
}

```

And fragment shader:

```
#version 450

layout(location = 0) out float fragmentdepth;

void main()
{
    fragmentdepth = gl_FragCoord.z;
}

```

As you can see, both shaders are pretty basic, they are a little more complex than they would otherwise be since they are using instancing, but overall they are simple.

However the output of these shaders is:

Where the original image is:

As you can see, the depth is being lost.

I think this is because my perspective, projection and model matrices are identical for both shaders.

In other words, I think that the camera I use for rendering the second image does not store the depth information. I wanted to know how can you generate a similar projection matrix to store the depth?

# Answer
One of the things you need to understand that the red component is actually visually correct. The Z Depth is being embedded in values close to 1.

If you want to just see a colour change to see the depth values more visually, you can either shorten the back plane to allow a greater range of values (not tracking close 1.0f).

I usually use the trick of depth = saturate((depth - 0.95f) * 20.0f);

What this does is stretch that part of the z buffer out (when im replaying the buffer back through a Pixel shader).

You may find what you have is working perfectly fine. Z Depth is not written in a linear fashion btw most of the time.

Sample of what you should see in your shadow buffer
> 2 votes

---
Tags: shaders, fragment-shader, shadows, shadow-mapping
---


# Question
Title: How to make an irregular shape that displays how far a unit can move through the map?
I'm still new to programming, and I was wondering if there is a way to make an irregular shape that displays how far a unit can move through the map taking in account pathing around obstacles. For example, as shown in the overworld of Total War:

I do not want to brute force it by checking every pixel that is in range as that's probably too slow to do in the game maker engine.

The pathing uses the `mp_grid` of game maker which I heard is A\* (but I don't really know what that means or how it affects what I want to accomplish).

Is there a way to get a similar thing in a 2D space, but not necessarily as precise?

# Answer
> 1 votes
After plenty of trial an error i came to get to the closest i could get to the desired result. I did indeed bruteforce it by checking the area around the player object whenever it entered the "Movement Phase", but i tried to optimize it to the best of my ability creating something that emulates the movement display of Total War, in a more rudamentary and imprecise way.

Maybe because Total War may have a more powerful engine and/or much more optimized algorithms, but this is the best i could get (because making it more precise may require a better engine or more math knowledge)

Here is the code i use to get the cordinates in order to draw the primitive.

```
//Basically this code works by checking the length of the path every 5 degrees
//And then checks from the max length of the radious inwards, and comparing
//the length of the path with the maximum movement range, if the length of
//the path is lower than the max range, then the cordinates are stored in two
//arrays (one for x, the other for y), else it will start decreasing the movement
//x and y goal cordinates of the path until the path lenght is equal or lower
//than the max range.(it cuts a lot of calculations by simply substracting
//the diference between the path length and the max range from the search radious
//This created some problems if the path was too long (because it will substrac to
//from the radious) so i conditioned it to only do that if the result of the substraction
//didn't made the the shorter than the max range + a threshold.
//so here are the variables

//m = the maximum range (usually called from the object that holds the stats
//search_maxrange = is basically m but easier to call
//search_x = Gets the cordinate X from the furthes point in the radious
//search_y = same but for Y
//origin_x = the point of origin of the radious origin_y = same but for Y
//border_x = array that stores the furthes point the path can get without being longer than max range
//border_y = same but for Y
//distance_lookout = stores the substranction of the difference between max range and
//path length to the radious(used to check if the search radious inst being cut too much
//if not distance_lookout is used as the starting point of the search
//search_extended = is the search radious from where start looking if the path is
//longer than max range
// search_x_extended && search_y_extended = have the same porpouse as search_y
// and search_x, but for the extended search

{
var i;
distance_path = path_add();
for(i = 0; i < 72; i += 1)
{
search_maxrange = m;
search_x = origin_x + lengthdir_x(search_maxd,i*5)
search_y =  origin_y + lengthdir_y(search_maxd,i*5);
mp_grid_path(grid,distance_path,origin_x,origin_y,origin_x + lengthdir_x(search_maxrange,i*5),origin_y + lengthdir_y(search_maxrange,i*5),true);
if path_get_length(distance_path) <= point_distance(origin_x,origin_y,search_x,search_y)
{
border_x[i] = search_x;
border_y[i] = search_y;
if border_x[i] < 0
{
    border_x[i] = 0;
}
if border_y[i] < 0
{
    border_y[i] = 0;
}
if border_x[i] > room_width
{
    border_x[i] = room_width;
}
if border_y[i] > room_height
{
    border_y[i] = room_height;
}
}
if path_get_length(distance_path) > search_maxrange
{
distance_lookout = (path_get_length(dpath) - (path_get_length(dpath) - search_maxd))
distance_lookout_path = path_add();
mp_grid_path(global.grid,dlpath,origin_x,origin_y,origin_x + lengthdir_x(distance_lookout,i*5),origin_y + lengthdir_y(distance_lookout,i*5),true)
if path_get_length(distance_lookout_path) < search_maxrange - 200
{
   search_extended = search_maxrange;
}
if path_get_length(distance_lookout_path) > search_maxrange - 25
{
    search_extended = distance_lookout;
}
var c;
for (c = search_extended;c > 0;c -= 10 )
{
    search_x_extended = origin_x + lengthdir_x(c,i*5);
    search_y_extended = origin_y + lengthdir_y(c,i*5);
    mp_grid_path(global.grid,distance_path,origin_x,origin_y,search_x_extended,search_y_extended,true);
    if path_get_length(distance_path) <= search_maxrange
    {
        border_x[i] = search_x_extended;
        border_y[i] = search_y_extended;
        if border_x[i] < 0
        {
            border_x[i] = 0;
        }
        if border_y[i] < 0
        {
            border_y[i] = 0;
        }
        if border_x[i] > room_width
        {
            border_x[i] = room_width;
        }
        if border_y[i] > room_height
        {
            border_y[i] = room_height;
        }
        break
    }
}
}
}
}

```

---
Tags: game-maker, turn-based
---


title: Transform.LookingAt() does nothing

text:
# Question
Title: Transform.LookingAt() does nothing
To get used to how Godot transforms work, I am attempting to write an orbit control. The goal is for it to behave similarly to the Godot viewport.

So far I have the positioning of my camera working. However, when I try to point it at the center of orbit (0,0,0), the `LookingAt()` function doesn't seem to work. I have printed the values to the console and just proves beyond a doubt that there isn't any change.

I've tried moving the camera around and using different values for the up-axis, but it still doesn't work.

Here are the pertinent functions from my Camera node's script:

```
private Vector2 rotateStart;
private Vector2 rotateEnd;
private Spherical spherical = new Spherical();
private Vector3 target = new Vector3();

public void HandleRotation(float delta)
{
    var transform = GetGlobalTransform();
    var viewportSize = GetViewport().GetVisibleRect().Size;

    rotateEnd = GetViewport().GetMousePosition();
    Vector2 RotateDelta = rotateEnd - rotateStart; //Change in rotation
    spherical.SetFromVector(transform.origin); //Spherical = current location

    //Calculate changes to equatorial and vertical rotations.
    spherical.theta += 2 * (float)Math.PI * RotateDelta.x / viewportSize.x;
    spherical.phi += 2 * (float)Math.PI * RotateDelta.y / viewportSize.y;
    var final_transform = new Vector3();

    spherical.CopyToVector3(ref final_transform);
    transform.Translated(final_transform - transform.origin); //Apply position change
    GD.Print(transform);

    //Point at origin (point of orbit)
    transform.LookingAt(target, new Vector3(0, 1, 0));
    GD.Print(transform);
    SetGlobalTransform(transform);

    rotateStart = rotateEnd;
}

public override void _Process(float delta)
{
    if (Input.IsMouseButtonPressed((int)ButtonList.Middle))
    {
        HandleRotation(delta);
    }
    else
    {
        rotateStart = GetViewport().GetMousePosition();
    }
}

```

# Answer
Okay, it turns out the issue was that `Transform.LookingAt()` is not self modifying (I completely missed the bit that specified there was a return value). so the fix is as simple as `transform = transform.LookingAt(...,...)`.
> 3 votes

# Answer
Maybe you're misunderstanding how the method works?

You can't *look at* the zero vector i.e. `(0,0,0)`, if the method needs a direction, since that means it has to have some length in order to be normalized and used to re-orient the camera.

You could *look at* the difference between the position of object you want to view, and the camera's position: This would make sense as such a non-zero vector describes a direction.

`transform.LookingAt(target, object.position - camera.position);`

Or am I mistaken? - on this note, best find someone else's code using the same method, and put it to the test in a minimal example. If it works in *theirs*, there's problem some simple problem in *yours*.
> 2 votes

---
Tags: 3d, transformation, godot
---


# Question
Title: What is Clash of Clans projection called?
What is the Clash of Clans projection (it doesn't seem to be isometric Image )

Image from here

# Answer
> 11 votes
It's basically an isometric projection. Your second image is closer to a dimetric projection.

Both projections are kinds of axonometric projections. The differentiating factor between them is the mainly the angle between the projected axes.

(The above images are a subset of this image from Wikipedia).

As you can see above, an isometric projection has angles that measure 120 degree between any pair of axes. If you look at the tile containing the flagpole in your image

you can see that the angles between the tile borders (X and Y axes) and the flagpole (Z axis) don't *quite* form even 120 increments (they're somewhere between an isometric projection and an oblique one, it looks like). But it's close enough for government work.

# Answer
> 3 votes
It's isometric.

How can you tell? When things get bigger the closer they are to your point of view, that's "perspective," because your *perspective* matters in the view. When things appear to be the same size no matter how you move the view around, that's "isometric" (Greek for "equal measure").

Since the objects at the bottom (what should be the near edge) of the screen are the same size as objects at the top (what should be the far edge), we know it's isometric.

If this were 3D and we were looking at models, we would use Perspective and Orthographic projection, respectively, which are two mathematical models of how we map coordinates in 3D space onto a 2D surface for display.

# Answer
> 3 votes
I wanted to mimic this projection as well and there is next to none good information on this topic, which I find very strange. A oblique projection like Clash of Clans creates a more downward/angled look over a basic 2:1 isometric projection and buildings for example do not obscure as many tiles. This projection is helpful when the player is allowed to build on each individual tile and thus needs vision of it in the first place. The individual buildings still have a "height" constrained but since the angle of a oblique projection is much steeper a building automatically look higher then a isometric 2:1 projection.

So I have fiddled around with a tile and Clash of Clans does a 4:3 projection. This tile can be tiled using 32:24 (4:3 ratio) increments.

To generate sprites from 3D assets in the correct projection you need to angle your orthographic camera 47.5 degree downward when it is facing your model. I am not the best in matrix math and it would be nice if someone could add an explanation for this but it creates a perfect 4:3 render when rendering without AA. Here is a little map mockup with a stunning building I modeled and rendered.

The tile picking remains the same as in a isometric perspective as long as you use the proper tile dimensions (64, 48 in the case of the I linked).

```
// From flat index/coordinate to the oblique projections
int ox = (ix - iy) * Tile.width / 2;
int oy = (ix + iy) * Tile.height / 2;

// From world position to index/coordinate
int ix = (int)(wx / (Tile.width / 2f) + wy / (Tile.height / 2f)) / 2;
int iy = (int)(wy / (Tile.height / 2f) - wx / (Tile.width / 2f)) / 2;

```

This does expect the bottom corner of the bottom tile to be at 0.0. an Easy way to do this is to just offset drawing by half the tile width.

---
Tags: projection, terminology
---


# Question
Title: Drawing an isometric characters: solutions for aiming
I decided to implement an isometric 2D game for iPhone, using SpriteKit and GameplayKit, and Inkscape/GIMP as graphic tools. I prefer vectorial graphics because as a iOS programmer I am required to create multiple versions of my assets, each one of different size in order to adapt to different screen resolutions. I use GIMP just rarely, in the case that I need to adjust the images created with Inkscape.

I draw my hero using Inkscape, and this is the result:

Now since it's an isometric game, the hero needs to move in all the four directions, and he also needs to aim the shotgun to different directions. I will also need to draw the hero with more weapons, but for now I have this one. Now the question is: should I draw a new version of the hero for all the possible directions in which the shotgun could be pointed, or there is a smarter way?

The only options that come to my mind are:

* Drawing the hero aiming the shotgun only in the main directions (maybe 0°, 15°, 30°, etc...)
* Drawing the hero aiming in 3 directions (0°, 45°, -45°) and then finding a way to interpolate the images in order to draw the hero aiming in the intermediate directions
* Using two separate layers, the top layer to draw the arms and the shotgun of the hero, and rotating it in the desired direction

Clearly the best way would be to redraw the hero for each aiming direction, but it requires too much work. If instead I choose the 3rd option I think I'd get not so much realistic results. What do you suggest? or maybe there is a smarter way?

# Answer
> 1 votes
Drawing each position takes an incredible amount of time and I believe the old isometric games just did that. Nowadays developers use 3D assets to render all possible directions. Once you have created a character you setup a simple scene with a orthographic camera and a light. For each character you render each frame for each animation in as many directions you want by rotating the character so the light source stays the same.

So Inkscape is certainly not the tool for what you want. You can cut corners here and there but even with 4 directions, 4 frames of walking and 4 frames shooting you need 32 images and 4 frames look very jumpy. And if you want to add another weapon you need to have another 32 images where in 3D you would just replace the gun (and alter the pose and animation depending on the weapon). If you want things to play smoothly you need at least 8 directions and 16 frames for a walk cycle and 8 frames for a shot. That is 192 images for just walking and shooting and that amount of vector/spriting work is insane.

---
Tags: 2d, graphics, isometric, spritekit
---


# Question
Title: Using a rule engine for a text-based web game
I have a database table that stores basic player data for the game.

It looks like this:

```
_________________________________________________________
player_id | player_level | player_class_ref | player_exp
    P1            8              W1            68349518
_________________________________________________________
level | required_exp
  1         100
 ...
  8         80000000
____________________

```

The game itself is text and browser based.

I decided to use a rule engine to adjust player data when needed.

It executes after every player event - for example, killing a monster or finishing a quest.

The sample rule looks like this

```
when
    player_exp > closest_level_exp
then
    player_level + 1
    player_exp = abs (closest_level_exp - player_exp)

```

There might be a lot of similar rules - for example, quest accepting.

So my question is - **Is my approach viable for a web and text based game?**

I am not sure how such things are usually implemented in games, such rules be hard coded, or they are stored another way?

# Answer
> 1 votes
I've successfully built a game where the main content and gameplay were implemented via rules similar to this.

It was a visual novel/narrative game where most of the logic hinged on when to trigger particular scenes, so I wanted this to be exposed in data and easy for the narrative designers/writers on my team to control.

I used a fuzzy pattern matching system based on this Valve talk to select the next event to fire.

Each event was a short script (containing dialogue, variable updates, basic conditional logic, or triggers for chaining to the next rule) written in a simple scripting language. The scripts and rules would be compiled to bytecode and run in a fairly basic virtual machine.

This let my core game code stay very lean:

1. Initialize state variables to new game state
2. Fire rule matching "new game" event to let writers add to the startup state
3. Based on the state following the last event, update state variables

(simple things like advancing a time counter that I might want to happen automatically, rather than write into every single event, or advancing the phase of play between intro - action - result stages)
4. Look for the next rule to match based on the current state, and fire its event
5. Loop 3 & 4 until the victory or game over states are hit

This approach gave the writers a ton of flexibility, but also a ton of responsibility to ensure their rules & events supported the game structure & all contingencies. We needed to include a few very permissive rules to ensure the game would never stall with no further matching events to play. And reasoning about the possibility space of the game, or how often/how soon particular scenes might fire became quite complicated.

So far the system has been reasonably successful for its goals, I would say, but it's not a universal solution or ideal for every game.

Based on this, I can say that a rule-matching core works for at least some class of game. Whether it's the right choice for your game is something you'll need to evaluate based on your own plans & goals.

---
Tags: architecture
---


title: How can I move two couple of objects?

text:
# Question
Title: How can I move two couple of objects?
Now it will move all the objects of allLines and instancesToMove at the same time. But I want to take each time one object from the allLines and one from the instancestoMove and move this two together then the next two objects and so on.

```
if (animateLines)
        {
            counter++;
            for (int i = 0; i < allLines.Count; i++)
            {

                endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);

                if (Vector3.Distance(instancesToMove[i].transform.position, endPos) < 0.1f)
                {
                    DestroyImmediate(instancesToMove[i]);
                    instancesToMove.RemoveAt(i);
                    DestroyImmediate(allLines[i]);
                    allLines.RemoveAt(i);
                }
            }
        }

```

Both allLines and instancesToMove are List

# Answer
> 0 votes
```
int index = 0; //you must persist index state
Vector3 endpos;
bool isMoving = false; //same as your "animateLines"

void BeginMove(int i)
{
    endPos = allLines[i].GetComponent<EndHolder>().EndVector; //init
    isMoving = true;
}

void Move(int i )
{
    Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
    Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

    allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

    instancesToMove[i].transform.position =
        Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);

    if (Vector3.Distance(instancesToMove[i].transform.position, endPos) < 0.1f)
    {
        EndMove(i); //deinit
        isMoving = false;
    }
}

void EndMove(int i)
{
    DestroyImmediate(instancesToMove[i]);
    instancesToMove.RemoveAt(i);
    DestroyImmediate(allLines[i]);
    allLines.RemoveAt(i);

    index++;
}

void Update()
{
    if (isMoving)
    {
        Move(index);
    }
    else //(try to) start moving the next pair
    {
        if (Input.GetKeyDown(KeyCode.Space)) //comment this line if you want it to proceed automatically
            if (index < allLines.Count)
                BeginMove(index);
    }
}

```

Maybe not perfect, but that should give you the idea.

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