# Question
Title: Handling Back Button in Android without implementing InputProcessor
Please advice/clarifyon below issue in libgdx while handling back button in Screens.

I have already gone through these 2 threads,

https://stackoverflow.com/questions/7223723/in-libgdx-how-do-i-get-input-from-the-back-button

Is there a way to capture back button twice in same activity libgdx game

As per suggestion in above two threads, I have done something like this in 2 Screen of my Game,

```
public class MainMenuScreen implements Screen{
    //omitted unnecessary code
    @Override
    public void render(float delta) {
    if (Gdx.input.justTouched()) {
        game.setScreen(game.STS);   //Setting 2nd Screen
    } else if (Gdx.input.isKeyPressed(Keys.BACK)) {
        System.out.println("mms back");
        //if(Gdx.input.isKeyJustPressed(Keys.BACK))
        Gdx.app.exit();            // Exiting
    }
}

public class StageScreen implements Screen{
    //omitted unnecessary code
    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyPressed(Keys.BACK)) {
        System.out.println("backed to mms in android");
        //if(Gdx.input.isKeyJustPressed(Keys.BACK))
        game.setScreen(game.MMS);  //going back to Main screen
    }
}

```

Above code works fine, when I press BACK in Stage Screen to call Main Screen, it exits the app immediately, without stopping in my Main screen, which is as per my expectations because I am using Gdx.input.**isKeyPressed**(Keys.BACK) instead of Gdx.input.**isKeyJustPressed**(Keys.BACK).

But my problem is, when I use Gdx.input.**isKeyJustPressed**(Keys.BACK) method in my Screens, it does not (return true) catch BACK key.

I have already set **Gdx.input.setCatchBackKey(true)** for my Game.

Any idea, why does isKeyJustPressed not responds while isKeyPressed does?

Thanks in Advance.

# Answer
> 2 votes
After experimenting long time, I came to the conclusion that it is not possible to catch **isKeyJustPressed** method without implementing input processor. So I have used **isKeyPressed** method only, without implementing InputProcessor in my Screens.

I have used a boolean flag to get to know that if back button is kept pressed from last screen, it won't exit in first screen untill unless user push the BACK button again.

```
public boolean backpressed=false;  //defined in Game class

public class MainMenuScreen implements Screen {
    //omitted unnecessary code
    @Override
    public void render(float delta) {
        if (Gdx.input.justTouched()) {
            game.setScreen(game.STS);   //Setting 2nd Screen
        } else if (Gdx.input.isKeyPressed(Keys.BACK)){
            if(!game.backpressed) {
                game.backpressed=true;
            } else if (game.backpressed) {
                game.backpressed=false;
                Gdx.app.exit();
        }
    }
}

public class StageScreen implements Screen {
    //omitted unnecessary code
    @Override
    public void render(float delta) {
    ...........
    ............
    if (Gdx.input.isKeyPressed(Keys.BACK)) {
        game.backpressed=true;
        game.setScreen(game.MMS);
    }
}

```

# Answer
> 1 votes
```
protected boolean backTo(){
    boolean back = false;

    if(Gdx.input.isKeyPressed(KEY_BACK) && keyBack == false){
        System.out.println("KeyBack: "+Gdx.input.isKeyPressed(Input.Keys.BACK));
        keyBack = true;
        back = false;
    }
    if(Gdx.input.isKeyPressed(KEY_BACK) == false && keyBack){
        keyBack = false;
        back = true;
    }
    return back;
}

/**
 * @keyBack is a boolean variable that I use to handle the state if it
 * still pressing or not... It logics works like this:
 * If we press the back key it will not work because
 * @back value is set to false. However after the key back stop
 * pressing it will check if the
 * @keyBack is true and it will see Oh that's true because we used
 * to say it has to be true while pressing back key. Then it will set
 * @keyBack false then it will can't call this method again until the key
 * be pressed again.
 *
 * @KEY_BACK is a constant I made with the 4 value... It is the value of back.
 *
 */

```

Here an example how I used this function:

```
private void menuScene(){
   //Omitted unnecessary code
    if(backTo()){

        if(sceneID == MAIN){
            running = false;
            main.setSceneID(main.TRAVEL);
        } else {
            sceneID = MAIN;
            scene.setRunning(false);
        }
    }
}

```

In this case after press back my UI delivery the user to a menu and if the user press back again it will delivery to the MainMenu(Load Game and New Game) passing the constant TRAVEL because the MainMenu has also a map where displays where is the user char in currenty slot.

---
Tags: android, libgdx, input, screen
---


# Question
Title: How to use Resources.LoadAll<T>() to get derived classes
EDIT: Unity's Resources.LoadAll() does include all derived types. My mistake!

I noticed that the type filter in Unity's Resources.LoadAll() filters out only classes of type T. I would prefer it to include all derived types of T as well. Is there a good function to also get the derived types, or should I use reflection, or should I hard code two arrays and join them together? For reference, I only have one type derived from T right now, but it may expand to several later.

See:

https://docs.unity3d.com/ScriptReference/Resources.LoadAll.html

# Answer
Edit: Sorry, I made a mistake! Because I made wrapper classes, I forgot to derive one wrapper class from another. The Resources.LoadAll function does in fact find all derived types.
> 1 votes

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


# Question
Title: What algorithm should I use to laid out pre-made rooms into a level?
I want to have a semi-procedural level, where rooms are pre-made but the way they're connected are proc-gen. The connections need to really exist - you can walk between rooms in hallways - not just teleported between rooms like in old games.

Each map will have a set number of rooms. Rooms should be laid into a grid(not necessary fill it) - all rooms and hallways will have the same size. Every room must lead to the exit(no dead end), except for 0 to 2 "secret room"

There can be 1 to 3 paths from start to finish; these paths may intersect. They should be relatively straight(no 180 turn or more).

There can a few rare "secret room" that are dead-end, but can only be one room depth:

```
              +-----+                                +-----+
              |     |                                |     |
              | End |                                | End |
              +-----+                                +-----+
                | |                                    | |
   +------+   +-----+          +------+   +------+   +-----+
   |      +---+     |          |      +---+      +---+     |
   | This +---+     |          | Not  +---+ This +---+     |
   +------+   +-----+          +------+   +------+   +-----+
                | |                                    | |
              +-----+                                +-----+
              |     |                                |     |
              |Start|                                |Start|
              +-----+                                +-----+

```

---

Is there a popular algorithm can I use to accomplish this?

One that was recommended by some people here is BSP Tree. It doesn't fit my requirement since the path it creates is too spiral, and depend on the number of corridors, it either creates too much path or too many dead-end.

The only thing I can come up with is to just add rooms one after another in random directions. There are 2 problems I can see and don't know how to solve:

* How to create multiple natural paths(not just an L shape or straight line) that end up at the same location.
* How to make sure the path doesn't become a spiral and block it self from advance further

Edit: I found this that that kinda resembles the structure I need, but with diagonal hallway.

# Answer
> 2 votes
Begin with a straight path from start to finish

```
[S] - [1] - [2] - [3] - [E]

```

Pick a hallway at random. Imagine we choose the hallway 3-E (between room three and the end). Since the hallway runs left/right, we will look at choosing either up or down. There is nothing above or below either 3 or E, so either works. If neither worked, we would have to choose a different hallway. We randomly choose down.

```
[S] - [1] - [2] - [3]   [E]
                   |     |
                  [X] - [X]

```

This is a new possible path. We made this by replacing the hallway 3-E with a long path through two new rooms. Let's renumber our rooms.

```
[S] - [1] - [2] - [3]   [E]
                   |     |
                  [4] - [5]

```

Now repeat. We randomly choose hallway 2-3 next. There is a room below room 3, so we can only choose up. We add two rooms again and renumber our rooms:

```
            [3] - [4]
             |     |
[S] - [1] - [2]   [5]   [E]
                   |     |
                  [6] - [7]

```

So far so good. Since we are trying to get to a destination on the right, most new rooms will be added to the top and bottom, since adding left or right would mean a path that backtracks, but after enough iterations, it could still happen, like this:

```
            [3] - [4]
             |     |
[S] - [1] - [2]   [5]   [E]
                   |     |
                  [6]   [9]
                   |     |
                  [7] - [8]

```

Followed by:

```
            [3] - [4]
             |     |
[S] - [1] - [2]   [5]   [E]
                   |     |
            [7] - [6]   [11]
             |           |
            [8] - [9] - [10]

```

At every iteration, it meets the base requirement: a single random path with no dead ends that reaches a fixed destination. Once you have your path a sufficient length, you can stop. Now to add the secret room. First, get a list of all the possible branches. You can do this by looking one by one at each room (probably excluding S and E), and adding something to the list for each open spot. Our list might look like this:

```
1-up, 1-down,
3-up, 3-left,
4-up, 4-right,
7-left,
8-left, 8-down,
9-down,
10-down, 10-right,
11-right

```

We randomly choose one from this list. Let's say we choose 7-left. Our final path looks like this:

```
            [3] - [4]
             |     |
[S] - [1] - [2]   [5]   [E]
                   |     |
      [S] - [7] - [6]   [11]
             |           |
            [8] - [9] - [10]

```

If you want to add more secret rooms, remove 7-left and 1-down from the list, since they both would lead to the now-occupied space. Then pick another at random.

A few modifications you might want:

* Just disable adding to the path left or right if you want your paths more straight.
* Do the first part of the algorithm multiple times, then lay them one on top of another before adding the secret rooms. This way you could have multiple intersecting paths.

Alternatively, you could displace an entire section of a random width each iteration. For example, if we choose a length of two and there is enough space for it, you would remove the room between the two hallways and then add three new rooms, like this:

```
[1] - [2] - [3]    ->    [1]         [3]
                          |           |
                         [X] - [X] - [X]

```

---
Tags: algorithm, procedural-generation, level-design
---


# Question
Title: Box2d Javascript Disable Contact Between 2 Objects
I want two objects, when collided, to not effect each other in velocity or force.

I have looked up guides and they say to change the PreSolve so that b2Contact.SetEnabled is false... which in code is

```
b2Contact.SetEnabled(false);
```

However, SetEnabled is a prototypal method for b2Contact, which means I have to instantiate a new b2Contact each time in order to call SetEnabled.

This does not make any sense to me and the code is wrong as right now all the objects in my world still collide with each other, even though I set that every single object will not collide with every other object:

This is my modified PreSolve method:

```
 B2.b2ContactListener.prototype.PreSolve = function (contact) {
        var a = contact.GetFixtureA().GetUserData();
        var b = contact.GetFixtureB().GetUserData();

        if (a instanceof Entity.Rock && b instanceof Entity.Player) {
            new B2.b2Contact.SetEnabled(false);
        }

        if (a instanceof Entity.Rock) {
            new B2.b2Contact.SetEnabled(false);
        }

    }.bind(this);
```

Any tips on how to use this API would be much appreciated!

# Answer
> 1 votes
Ok, I'm pretty stupid, but yeah the answer is to PUT THE CONTACT:

contact.SetEnabled(false).

I keep reading box2d docs for C++ and the like and keep getting tripped up on how these methods work.

this is pretty much a DUH thing once I understand it though, sorry for asking/

---
Tags: collision-detection, javascript, box2d
---


# Question
Title: Restrict the rotation of the camera using button
I've been trying to limit the Y-axis of the camera rotation but I'm out of depth until now. I'd looked up many tutorials and I found the clamping method, but I seem can't get it to work on my code, and all the tutorials I found is using them in Update(), while I'm using a button to rotate the camera. Here's the code:

```
public void RotateLeft()
{
    cameraY = Mathf.Clamp(cameraY, minAngle, maxAngle);
    if(cameraY >= minAngle)
    {
        Camera.main.transform.Rotate(0,-cameraY,0);
    }
}
public void RotateRight()
{
    cameraY = Mathf.Clamp(cameraY, minAngle, maxAngle);
    if(cameraY <= maxAngle)
    {
        Camera.main.transform.Rotate(0,cameraY,0);
    }
}

```

Does clamping works outside an Update()? What am I missing?

Thank you in advance.

# Answer
> 0 votes
I finally solved it. Thanks to this Unity Question though..

```
public void RotateLeft()
{
    myRotation.y = Mathf.Clamp(myRotation.y - 1f, -45f, 45f);
    Camera.main.transform.rotation = Quaternion.Euler(myRotation);
}
public void RotateRight()
{
    myRotation.y = Mathf.Clamp(myRotation.y + 1f, -45f, 45f);
    Camera.main.transform.rotation = Quaternion.Euler(myRotation);
}

```

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


# Question
Title: How to get a translation vector in a certain direction? SAT
I'm using the seperating axis thereom for discrete collision detection. I have code to find the minnimum translation vector (or distance) to seperate two shapes but how can I adjust it to get a vector in a certain direction that seperates the shapes? For example: If a box A is overaping box B 10 pixels horizontaly and 40 pixels vertically the MTV would calculate to move the box horizontally 10 px or so but I want to seperate the boxes vertically (move 40px up). How can I adjust my code to calculate a MTV in a direction of my choosing?

```
    const Vector2 ShapeImpl::CalcDisplacement(const AxesVec &axes, const Shape &a, const Shape &b) const
{
    Vector2 displacement;
    Precision_t Overlap = std::numeric_limits<Precision_t>::infinity();
    Axis smallest;

    for (auto && axis : axes)
    {
        const Projection pA = b.Project(axis);
        const Projection pB = a.Project(axis);

        // No Collision
        if (!pA.IsOverlap(pB))
            return Vector2(0, 0);

        else
        {
            const Precision_t o = pA.GetOverlap(pB);

            if (std::abs(o) < std::abs(Overlap))
            {
                Overlap = o;
                smallest = axis;
            }
        }

}

    displacement = smallest * Overlap;

    return displacement;
}

```

# Answer
> 1 votes
When you know there's a collision, you can just use an arbitary axis (e.g. (0, 1) if you want to separate them upwards), then project the points onto this axis. The distance you need to move the objects to separate them in this direction is the overlap between the projections.

---
Tags: c++, mathematics, collision-resolution, separating-axis-theorem
---


# Question
Title: How can i make a list or maybe some kind of dictionary of distances and positions of gameobjects?
```
private void FindDistances()
    {
        List<float> distances = new List<float>();
        List<Vector3> positions = new List<Vector3>();

        for (int i = 0; i < objects.Count; i++)
        {
            distances.Add(Vector3.Distance(EndStartPoints[0].transform.position, objects[i].transform.position));
            positions.Add(objects[i].transform.position);
        }
        distances.Sort();
    }

```

For example in distances the first 3 indexes are:

```
0 = 10
1 = 10
2 = 10

```

But in the positions List every object have another position. So distance 10 in index 0 is not in the same position as distance 10 in index 2. S o i want somehow to merge the Lists so i know that index 0 distance 10 is at position...x,y,z and index 2 distance 10 is at position...x,y,z

Like keys and values ? Not sure.

Then i want to get from the first 3 distance random of one distance and his position. For example if i in the List distances i have cases of same distance pick random distance and it's position.

If it's only one distance then just get his position.

Last thing i will want then to destroy or color the object at the position of the distance. So i have a List called objects.

So if i picked for example distance index 1 then destroy or color the object on the distance position.

What i tried so far:

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class TestGenerator : MonoBehaviour
{
    [System.Serializable]
    public class PosDisPair //Name the pair however you like
    {
        public float Distance;
        public Vector3 Pos;
    }

    public GameObject Node;
    public Vector3 nodeScale = new Vector3(4, 1, 4);
    [Range(3, 100)]
    public int mapSize = 10;
    public float Spacing = 10;
    public float spawnSpeed = 5;
    private List<GameObject> objects = new List<GameObject>();
    private List<GameObject> EndStartPoints = new List<GameObject>();
    private int currentMapSize;
    private List<PosDisPair> pairList = new List<PosDisPair>();

    private void Start()
    {
        currentMapSize = mapSize;
        Generate();
        GenerateRandom(mapSize);
    }

    private void Generate()
    {
        if (objects.Count > 0)
            objects = new List<GameObject>();

        if (Node == null)
            Node = UnityEngine.GameObject.FindGameObjectWithTag("Main Node");

        for (int x = 0; x < mapSize; x++)
        {
            float positionWidth = Spacing * (float)x;

            for (int z = 0; z < mapSize; z++)
            {
                float positionHieght = Spacing * (float)z;
                GameObject block = Instantiate(Node, Vector3.zero, Node.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(positionWidth, 0, positionHieght);
                block.transform.localScale = new Vector3(nodeScale.x, nodeScale.y, nodeScale.z);
                block.tag = "NodeDestroyable";
                objects.Add(block);
            }
        }
    }

    public void GenerateNew()
    {
        currentMapSize = mapSize;

        DestroyNodes();

        Node = UnityEngine.GameObject.FindGameObjectWithTag("Main Node");
        Generate();
        GenerateRandom(mapSize);

        FindDistances();
    }

    public void DestroyNodes()
    {
        GameObject[] nodes = UnityEngine.GameObject.FindGameObjectsWithTag("NodeDestroyable");

        if (nodes.Length == 0)
        {
            //Debug.Log("No nodes to destroy found");
        }
        else
        {
            for (int i = 0; i < nodes.Length; i++)
            {
                DestroyImmediate(nodes[i]);
            }
        }
    }

    private void Update()
    {
        Erase();
    }

    private void Erase()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "NodeDestroyable")
                {
                    Destroy(hit.collider.gameObject);
                }
            }
        }
    }

    private void GenerateRandom(int gridSize)
    {
        List<int> selectedIndexes = new List<int>();

        //Create an array for indexes of the TOP side
        var arr = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr[i] = i;
        }
        int mynum = arr[Random.Range(0, arr.Length)];
        GameObject Top = objects[mynum];
        selectedIndexes.Add(mynum);

        //Create an array for indexes of the LEFT side
        int mynum1 = 0;
        var arr1 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr1[i] = i * gridSize;
        }
        do
        {
            mynum1 = arr1[Random.Range(0, arr1.Length)];
        }
        while (selectedIndexes.Contains(mynum1));
        GameObject Left = objects[mynum1];
        selectedIndexes.Add(mynum1);

        //Create an array for indexes of the BOTTOM side
        int mynum2 = 0;
        var arr2 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr2[i] = (gridSize * (gridSize - 1)) + i;   //Reach the last row and iterate with i.
        }
        do
        {
            mynum2 = arr2[Random.Range(0, arr2.Length)];
        }
        while (selectedIndexes.Contains(mynum2));
        GameObject Bottom = objects[mynum2];
        selectedIndexes.Add(mynum2);

        //Create an array for indexes of the RIGHT side
        int mynum3 = 0;
        var arr3 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr3[i] = (i * gridSize) + gridSize - 1;
        }
        do
        {
            mynum3 = arr3[Random.Range(0, arr3.Length)];
        }
        while (selectedIndexes.Contains(mynum3));
        GameObject Right = objects[mynum3];
        selectedIndexes.Add(mynum3);

        /*DestroyImmediate(Right);
        DestroyImmediate(Left);
        DestroyImmediate(Top);
        DestroyImmediate(Bottom);*/

        EndStartPoints = new List<GameObject>();
        EndStartPoints.Add(Left);
        EndStartPoints.Add(Right);

        selectedIndexes.Clear();
    }

    private void OnValidate()
    {
        if (currentMapSize != mapSize)
        {
            UnityEditor.EditorApplication.delayCall += () =>
            {
                GenerateNew();
            };
        }
    }

    private void FindDistances()
    {
        for (int i = 0; i < objects.Count;)
        {
            PosDisPair pairToAdd = new PosDisPair();
            pairToAdd.Distance = Vector3.Distance(EndStartPoints[0].transform.position, objects[i].transform.position);
            pairToAdd.Pos = objects[i].transform.position;
            pairList.Add(pairToAdd);
        }

        pairList.Sort(delegate (PosDisPair a, PosDisPair b) {
            return (a.Distance.CompareTo(b.Distance));
        });
    }

    private void MoveInPath(List<float> distances, List<Vector3> positions)
    {
        for (int i = 0; i < pairList.Count; i++)
        {

        }
    }
}

```

In the method GenerateNew i'm calling the method: FindDistances(); And inside FindDistances i'm doing:

```
private void FindDistances()
        {
            for (int i = 0; i < objects.Count;)
            {
                PosDisPair pairToAdd = new PosDisPair();
                pairToAdd.Distance = Vector3.Distance(EndStartPoints[0].transform.position, objects[i].transform.position);
                pairToAdd.Pos = objects[i].transform.position;
                pairList.Add(pairToAdd);
            }

            pairList.Sort(delegate (PosDisPair a, PosDisPair b) {
                return (a.Distance.CompareTo(b.Distance));
            });
        }

```

And it keep adding to pairList all the time. Then it's raising the memory usage to 2.3GB and stuck/freezing everything i need to shut down the pc.

And the List objects contain only 100 items but i see in pairList over 2 million items i could debug it for a second.

Not sure why it keep adding items to pairList.

The script is working on editor mode so once i'm opening the project it's executing the script and stuck everything.

I also have another script i'm using for buttons:

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

[CustomEditor(typeof(TestGenerator))]
public class GenerateButton : Editor
{
    public override void OnInspectorGUI()
    {
        TestGenerator Generate = (TestGenerator)target;

        if (GUILayout.Button("Generate New"))
        {
            Generate.GenerateNew();
        }

        DrawDefaultInspector();

        if (GUILayout.Button("Destroy Nodes"))
        {
            Generate.DestroyNodes();
        }
    }
}

```

# Answer
I could not understand the operations you want to perform but I can also modify the answer for those needs if you clarify it more (The part after your "Like keys and values ? Not sure." sentence). For the solution I suggest you to create a little class for holding the position and the distance as pairs (Can also be struct I guess):

```
[Serializable]
public class PosDisPair           //Name the pair however you like
{
      public float Distance;
      public Vector3 Pos;
 }

```

Create a list from that pairs as follows:

```
List<PosDisPair> pairList = new List<PosDisPair>();

```

Modify your for loop to set the elements of the list:

```
for (int i = 0; i < objects.Count; i++){
     PosDisPair pairToAdd = new PosDisPair();
     pairToAdd.Distance = Vector3.Distance(EndStartPoints[0].transform.position, objects[i].transform.position);
     pairToAdd.Pos = objects[i].transform.position;
     pairList.Add(pairToAdd);
}

```

And finally sort the list with a custom mehtod:

```
pairList.Sort(delegate(PosDisPair a, PosDisPair b) {
     return (a.Distance.CompareTo(b.Distance));
});

```

Now you can easily access and modify the items you desire, and manipulate the list according to your needs.
> 0 votes

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


title: Multiple Textures in Shader?

text:
# Question
Title: Multiple Textures in Shader?
I have this (pseudo) code:

```
unsigned int TextureLoc = glGetUniformLocation(programID, "objectTexture");
for(int i = 0; i < object->texturesCount; i++)
{
    glActivateTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, object->textures[i]->textureID);
    glUniform1i(TextureLoc, 0);
}

```

And Fragment Shader code:

```
in vec2 UV;
out vec3 color;
uniform sampler2D objectTexture;
void main()
{
    color = texture2D(objectTexture, UV).rgb;
}

```

My example is that of a house model that composes a single object, but the house walls are of Texture#1 and the roof is of Texture#2.

At first I coded that each object had it's own material/textures, but then I noticed it's a waste of memory if I'm using the same texture in multiple places, so now I have a list of objects and a list of textures. An object can have ***n*** textures.

**1.** How can I get a "new" in GLSL for dynamic textures count? Some objects might have 1, some might have 10, etc... How can I control that?

**2.** I have an array specifying which textureID each triangle in the object uses, but how can I use this information to properly draw the object? I send the array in the **glEnableVertexAttribArray(int)** function, but how can I know which texture I'm supposed to use when I'm in the shader code?

Another option I thought of was to divide all objects into smaller objects if they don't have the same texture, but I'm not sure what's the best approach to this.

# Answer
> 7 votes
> How can I get a "new" in GLSL for dynamic textures count? Some objects might have 1, some might have 10, etc... How can I control that?

You don't.

> I have an array specifying which textureID each triangle in the object uses, but how can I use this information to properly draw the object? I send the array in the glEnableVertexAttribArray(int) function, but how can I know which texture I'm supposed to use when I'm in the shader code?

Again, you *don't*.

The correct way to handle this is to create a distinction between "object" and "mesh". An "object" is a house. An object can be composed of multiple "mesh"es. Each mesh represents a single rendering command. Thus, it is the vertex data, shader, and texture(s) needed to render that mesh.

So your house would have a mesh for the roof and a mesh for the walls.

# Answer
> 0 votes
You can probably have up to 16 activated textures in a shader program. And from the application, they should each be bound to their own texture unit, that is

```
glActivateTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, object->textures[i]->textureID);
glUniform1i(TextureLoc, 0);

glActivateTexture(GL_TEXTURE1);
...

glActivateTexture(GL_TEXTURE2);
...

```

You can also use a Uniform Buffer Object so you don't have to rebind all the textures every time you run the shader program.

---
Tags: opengl, textures, shaders
---


# Question
Title: Space Ship Move Left and right side but its not stop (stable or like vibrate) in the corner
I made the game space shooter. In my space shooter its move left and right but not stop in the corner( Stable or vibrate). I don't know how it will be stopped.

Player Movement. cs

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speedMove = 3;
    public float bonusTime;
    private Rigidbody rb;
    private float _limit = 0;

    // 1 for right and -1 for left.
    private float _direction = 1;

    // You can call it as speed
    private float _speed = 0.01f;

    private bool toLeft = true;
    private bool toRight = true;

    public GameObject shield;
    public GUIText bonustimeText;

    private bool counting = true;
    private float counter;

    private Weapon[] addWeapons;

    public Sprite strongShip;
    public Sprite normalSprite;
    public Sprite shieldSprite;

    private SpriteRenderer sRender;
    private Weapon weaponScript;

    void Start () {

        counter = bonusTime;
        rb = GetComponent<Rigidbody>();

        sRender = GetComponent<SpriteRenderer> ();
        addWeapons = GetComponentsInChildren<Weapon> ();
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }

        weaponScript = GetComponent<Weapon>();
        weaponScript.enabled = true;
    }

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

        transform.position = Vector3.MoveTowards (transform.position, new Vector3 (transform.position.x + _direction, transform.position.y, transform.position.z), _speed);

        if (Input.GetMouseButtonDown (0))
            _direction *= -1;
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "StrongMode") {
            Destroy (coll.gameObject);
            counting = true;
            StrongMode();
            Invoke ("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "ShieldMode") {
            Destroy (coll.gameObject);
            counting = true;
            ShieldMode();
            Invoke("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "Life") {
            GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
            gui.AddHealth();
            SendMessage("AddHp");
            SoundHelper.instanceSound.PickUpSound();
            Destroy(coll.gameObject);
        }

        if (coll.gameObject.tag == "Enemy") {
            SendMessage("Dead");
        }
    }

    void Downgrade()
    {
        SoundHelper.instanceSound.BonusDownSound ();
        counting = false;
        bonustimeText.text = "";
        counter = bonusTime;

        sRender.sprite = normalSprite;
        weaponScript.enabled = true;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }
        weaponScript.enabled = true;
        shield.SetActive (false);
    }

    void StrongMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = strongShip;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = true;
        }
        weaponScript.enabled = false;
    }

    void ShieldMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = shieldSprite;
        shield.SetActive (true);
    }

//  void OnDestroy()
//  {
//      bonustimeText.text = "";
//  }
}

```

# Answer
From what I understand, you did not reset \_direction and so it will always move to the right based on the Update function. You had a GetMouseButtonDown but it would just set \_direction to be -1 so your spaceship will move left as it is now going in the negative x axis.

I think what you need is a way to set \_direction to be 0 to stop it from moving.
> 1 votes

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


# Question
Title: 2D Game : How do I draw my entities (player, etc.) by their Y position?
I am using C# with MonoGame 3.6

A picture of what I mean: https://i.stack.imgur.com/jvPf3.png You see, the little black box is drawn over the red box, because it is drawn before the red box gets drawn. Our view is diagonally forward, which means the red box should get drawn over the red one.

Now, I of course could loop through all entities and sort them by their Y coordinate, but I wanted to know if there was a faster way, as this would be totally inefficient if I had to do it on every game tick / every entity move.

Thank you!

# Answer
Yes there is a way, You have set the SpriteSortMode in SpriteBath.Begin() to BackToFront or FrontToBack. Then use the SpriteBatch.draw() method that includes layer depth (https://msdn.microsoft.com/en-us/library/ff433989.aspx). They will be drawn in the proper order.

Note Layer Depth should be between 0 (front) and 1 (back).
> 0 votes

---
Tags: c#, xna, monogame
---


# Question
Title: Can't deserialize parameters from JSON in LibGDX
I am quite new to JSON and I have been having trouble with this data-driven asset manager (not my code). I have been trying to deserialize parameters for my TmxMapLoader object from JSON. It takes the parameters of TmxMapLoader.Parameters type.

Here is the Asset.class file that's responsible for deserializing JSON:

```
public class Asset implements Json.Serializable  {
public Class<?> type;
public String path;
public AssetLoaderParameters parameters;

@Override
public void write(Json json) {
    json.writeValue("assetType", type.getName());
    json.writeValue("path", path);
    json.writeValue("parameters", parameters);
}

@Override
public void read(Json json, JsonValue jsonData) {
    try {
        type = ClassReflection.forName(jsonData.get("type").asString());
    } catch (Exception e) {
        type = null;
    }

    path = jsonData.get("path").asString();

    JsonValue parametersValue = jsonData.get("parameters");
    parameters = parametersValue != null ? json.fromJson(AssetLoaderParameters.class, parametersValue.toString()) : null;
}
}

```

And here is my JSON file:

```
{
"base" : [
{
    "type" : "com.badlogic.gdx.graphics.Texture",
    "path" : "data/background.jpg"
},

{
    "type" : "com.badlogic.gdx.graphics.Texture",
    "path" : "data/player.png"
},

{
    "type" : "com.badlogic.gdx.maps.tiled.TiledMap",
    "path" : "data/map.tmx",
    "parameters": [{
        "flipY": true
    }]
}
]}

```

Everything works fine and loads properly if I don't add the "parameters" element. Whenever I add the "parameters" element into the JSON file, the map fails to load. Am I adding the parameters wrong or missing something? Please help!

**EDIT:** Whenever I add the "parameters" element in .json file, the assets are being loaded. Here is my .json loading method:

```
private void loadGroups(String assetFile) {
    groups = new ObjectMap<String, Array<Asset>>();

    Gdx.app.log(TAG, "loading file " + assetFile);

    try {
        Json json = new Json();
        JsonReader reader = new JsonReader();
        JsonValue root = reader.parse(Gdx.files.internal(assetFile));

        JsonIterator groupIt = root.iterator();

        while (groupIt.hasNext()) {
            JsonValue groupValue = groupIt.next();

            if (groups.containsKey(groupValue.name)) {
                Gdx.app.log(TAG, "group " + groupValue.name + " already exists, skipping");
                continue;
            }

            Gdx.app.log(TAG, "registering group " + groupValue.name);

            Array<Asset> assets = new Array<Asset>();

            JsonIterator assetIt = groupValue.iterator();

            while (assetIt.hasNext()) {
                JsonValue assetValue = assetIt.next();

                Asset asset = json.fromJson(Asset.class, assetValue.toString());
                assets.add(asset);
            }

            groups.put(groupValue.name, assets);
        }
    }
    catch (Exception e) {
        Gdx.app.log(TAG, "error loading file " + assetFile + " " + e.getMessage());
    }
}

```

And the console output is:

```
Assets: loading file data/assets.json
Assets: registering group base
Assets: error loading file data/assets.json Error parsing JSON on line 2     near: parameters: {
*ERROR*flipY: false

```

}

# Answer
> 0 votes
You have to access the data inside of the `{ }` brackets of your array before you can do anything with it. To do this simply make this simple change:

```
JsonValue parametersValue = jsonData.get("parameters").child;

```

The `.child` will access the first child of the `JsonValue` (if any). In this case the child is the `{ }` brackets.

Note that you also will probably have to change `json.fromJson(AssetLoaderParameters.class, ...)` to `json.fromJson(TmxMapLoader.Parameters.class, ...)` since otherwise it will throw the exception:

> Field not found: flipY (com.badlogic.gdx.assets.AssetLoaderParameters)

---
Tags: libgdx, json
---


# Question
Title: Predicting the route a rigid body will take when force is applied
I'm learning 3D game development with some kind of mini golf game.

It is working well so far: I have a sphere, and I am using `AddForce` on its `RigidBody` to launch it in the desired direction.

One feature I'd like to add is to show a preview line that predicts the trajectory of the ball. Like telling the player that if he uses this direction and this force, the ball is going to follow this route, collide here, bounce, and end up there etc.

I know how to use a line renderer alright, but I don't know how to calculate the array of points from which to draw the line.

It has to be updated in realtime, and the player can quickly change the potential direction and force at any time - it has to consider that there are various objects with different bounciness/friction etc.

That seems like a lot of work. The only thing that occurs to me is to use dummy invisible balls that will be constantly firing using the potential direction/force and then recording their route, but I'd need to figure out some way to make them 'move faster' so I can get the array of points instantly.

What would be my best approach for this?

# Answer
> 1 votes
Your simplest approach would be to simply run the physics math yourself. The term to google would be "projectile motion". Its not to much more complex than algebra and vector math. You would simulate the initial condition and then iterate over the path to create points to then graph.

If that is not your cup of tea, you could send the invisible ball and graph it as it goes. I would build over time so it actually might be a cool effect.

# Answer
> 1 votes
A physics simulation is not (should not be) bound to real-world time in any way. I don't know how Unity does it, but a physics solver should have a function like "Simulate \[timedelta\]". Nothing should prohibit one from calling that a thousand times from within one single visual frame (main loop, game frame), with an estimated (average?) future time delta. It's a computer, it is able to execute a thousand physics simulation cycles in practically zero time.

Between each game frame, reset all relevant physics bodies (copies of them?) to their original, static positions and redo the (hidden, parallel) simulation as the user aims. No need to record all intermediate positions of that single ball (nm the others), every 10th should be enough - this means 6 recorded positions per second if 60 fps - will make a smooth curve to paint.

Having said that, i wonder if your idea is good. First, it removes the challenge - what's the point if the user sees the result all time? Second, the ball (its recorded path) will probably be weird as it will make unexplained turns from upcoming collisions that you cannot show the user without showing a complete pre-simulation of the entire game board.

At least limit the simulation/hint to the first or second hit with another ball, or 1-2 seconds, or whatever feels right.

The determinism of physics simulations is popular discussion subject. For various reasons, assume it is not deterministic, ie. as you launch the visual simulation, the balls will not always move as shown in the pre-simulated preview. This is another reason to not make the preview too long.

Also to note, a pre-simulation calculated in another way will not match the result of your current physics solver. A solver is not exact. It presents something that looks good enough but another solver/method will probably disagree. Hence, you must use your current solver, the same that eventually does the final, visual simulation, so handle this task.

# Answer
> 0 votes
Unity usually treats one unit of world space as one meter. Also, gravity should be close to actual Earth gravity, -9.81 m/s^2. To be sure, you can check in the Physics Manager. Assuming you know the initial x and y velocity of your projectile, you can trace its parabolic path like so:

```
//x0 and y0 are the initial position components, in meters
//vx0 and vy0 are the initial velocity components, in m/s.
//t is the time from the initial launch, in seconds
//g is gravity, probably -9.81 m/s^2
x = x0 + vx * t
y = g*t*t/2 + vy0*t + y0

```

Now, loop through this plugging in different values of t and you should get your path. The problem, though, is that this doesn't account for bouncing off obstacles. One possibility, although I'm not sure if it will have perfect accuracy, is to check with each iteration of your path tracing if the point lies within a surface. If it is horizontal, invert the y velocity, multiply by a scale for its bounciness, and the set that x and y as the new x0 and y0 for the next iteration. If the wall is vertical, do the same, but inverting and scaling vx. It might get a little trickier if some of the obstacles have diagonal surfaces, but you could still do it using dot products.

If this still doesn't work, you could always send a test ball through at an increased timescale to gather the needed data.

---
Tags: unity, physics, 3d
---


# Question
Title: Sprite changes colour when imported into Unity
I create some simple geometrical shapes in Inkscape, then export it to PNG and import into Unity.

Positive example: I make a rectangle of colour hsva(0, 0, 32, 255), export it as a 32x32 PNG image and import to Unity. Then I put it into the scene. When I check its rendered colour with a probe tool it's perfectly correct: hsva(0, 0, 32, 255).

Negative (problematic) example: I create a **right triangle** of colour **hsva(0, 0, 32, 255)**, export it as a 32x32 PNG image. Effect: half of the image is transparent and the triangle edge is "anti-aliased", but the main triangle's area in the PNG file still conserves its original colour.

Then I import it into Unity and I put it into the same scene and check its rendered colour with a probe tool. It's actually **hsva(299, 8, 33, 255)** \- very dark purple, but still distinguishable from the (0, 0, 32, 255).

What am I doing wrong? Why is the rendered colour of the sprite different? How can I solve this problem?

Thanks in advance for your help :)

PD

Adding my import settings, as requested in on of the comments (now I'm experimenting with larger images 512x512, but the effect is the same):

# Answer
> 2 votes
Thanks @DMGregory and @Draco18s for help with this one!

The problem turned out to be the compression algorithm which Unity automatically applied for the imported image. The DXT5 compression reduced colour precision, provoking the subtle change in the rendered colour of the sprite.

The solution to the problem was changing Compression Quality from "Normal Quality" to "High Quality" in the default import settings for the image.

This could be also solved by explicitly overriding the compresison algorithm in the build-specific settings of the image, selecting BC7 compression algorithm for instance.

---
Tags: unity, 2d, graphics, sprites, color
---


# Question
Title: Why rendered objects to cubemap are larger than they should be?
I am trying to render a scene to a cubemap, so I can later use it as environment map for another object. The object I want to use the environment map with is a surface, I am trying to render water. But I have an issue, when the refraction index is set to 1.0 (air), the skybox is shown correctly, however the other object is not.

The circled area is where the cube made out of air is, in these images:

But when I position my camera so it includes a part of the stone platform, the stone platform appears much more larger than it should be:

I render to cubemap as follows:

```
glm::mat4 translateInfoMat = x.model - glm::mat4(glm::mat3(x.model));
glm::vec3 position = glm::vec3(translateInfoMat[3][0], translateInfoMat[3][1], translateInfoMat[3][2]);//gets the view position of the cubemap from the object's model matrix.

glm::mat4 _projection = glm::perspective(glm::radians(90.0f), 1.f, 0.1f, 2000.0f);

for(int j = 0; j < 6; j++)// for each face it renders the scene
{
    envMap.bindRenderToFace(j); //sets the current face to draw to.
    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glm::mat4 _view = glm::lookAt(position, position + targets[j], ups[j]);

    //renders skybox
    glDepthMask(GL_FALSE);
    if(skybox != NULL)
    {
        skybox->setVP(_projection * glm::mat4(glm::mat3(_view)));
        skybox->draw(&skyboxShader);
    }
    glDepthMask(GL_TRUE);

    for(int i = 0; i < renderQueue.size(); i++)//renders the objects that doesn't need environment map (the stone platform)
    {
        RenderableElement object = renderQueue[i];
        if(!y.renderInfo.m_needsEnvironmentMap)
        {
            lighting.SetMVP(_projection * _view  * y.model);
            lighting.SetModel( object.model);
            lighting.SetViewPos(viewPos);

            lighting.Use();

            object.mesh->Draw(lighting.GetShader());
        }
    }
}

```

And the shader that does the refraction is:

```
#version 330 core

in vec3 FragPos; //the position of the current fragment in world space
in vec3 Normal; //normal in world space

out vec4 FragColor;

uniform vec3 viewPos;
uniform samplerCube skybox;

vec3 refraction(vec3 normal, vec3 viewPos, vec3 fragPos, float n1, float n2)
{
    vec3 i = normalize(fragPos - viewPos);
    vec3 r = refract(i, normalize(normal), n1 / n2);

    return texture(skybox, normalize(r)).rgb;
}

void main()
{
    vec3 normal;

    normal = normalize(Normal);

    vec4 refr = vec4(refraction(normal, viewPos, FragPos, 1.0, 1.0), 1.0);

    FragColor = refr;
}

```

I have verified my code with multiple sources, and they are doing approximately the same way as I have done. The data fed to the shader is correct (normals, vertex position, model matrix, view position, etc.).

# Answer
(My answer originally from: Reddit.)

The problem you're having is not caused by your cubemap rendering or setup (didn't go through your code, but seems to work just fine from the images), but a parallax issue.

It is caused when the position where you calculate the reflection/refraction vector doesn't correspond to the position of the camera where you took the image. This works fine for the environment but cause issues for objects that are not very far away.

I've been there (exactly same issue with water reflection/refraction :)) and there are two ways to go:
> 0 votes

---
Tags: opengl, glsl, cubemap
---


# Question
Title: How do I fix my material texture rendering issue in Unity?
I am very new to Unity and was just testing out a few things to make my first ever game. I tried to make a material for my obstacle and I noticed that there is some texture issue. It shows pink lines and all other colors when at a close look. This can also be seen when the material color is brighter. How would I fix this?

My Unity version is Unity 2017.1.0f3.

# Answer
> 1 votes
Here are some clues :

## GPU

Make sure your GPU can handle the version of DirectX Unity is using (example : Unity running with DX11 and GPU was only capable of DX10). `Build Settings PC, Mac & Linux Standalone -> Other Settings -> Rendering` : Disable `Automatic Graphics API` and reorder the list of Graphics APIs for Windows that appears so that DX11 is at the bottom.

## Lightning

Go to the top menu: `Window -> Lighting -> Scene`. Uncheck `Auto` at the bottom of the panel and click on `Clear baked data` in the dropdown menu next to the `Build` button.

Also, in the `Lightning` panel, under the `Environment Lightning` section, set to `Uncompressed` the `Reflection Source -> Compression` field.

## Shader

Try to download the shaders assets of Unity and use the downloaded Standard shader

## Reflections

Turn off the HDR in Cubemap capture settings for the reflection probe

---
Tags: unity, textures, rendering
---


# Question
Title: 3d complex collision and trigger detection
I'm a Unity developer and I use monobehavior functions to dot things like collision detection. I have read about articles about collision detection. Most of them work with geometrical structures like sphere or boxes.

How are complex collisions with no formal and geometrical structures calculated?

# Answer
> 1 votes
Unity uses those exact same geometric structures under the hood. You just don't see the native code (written in C++) that does those operations. *That doesn't mean they aren't there.* Unity purposely obscures these from you so you don't have to think about them, and you can just use what they've provided "under the hood". Like a driving a car - you need not know how the engine works - you just use the pedals, gears, brakes and steering wheel.

---

`How are complex collisions with no formal and geometrical structures calculated?`

If you're asking about the real world: every atomic nucleus repels other atomic nuclei (except in special cases). Atoms form bonds, thereby creating molecules and ultimately, macro-scale physical objects. As you try to push atoms closer together, they repel each other. This (at least in current physics) is described in the Pauli exclusion principle.

If you coded to replicate that effect, you could create objects without need for a large-scale geometric description, since they would likewise just be described as a point in space and a given influence / force around that point. The combination of those point fields would create the greater field which could handle close range repulsion (impenetrability) for you. The problem then becomes simulating *enough* of these particles to make a working world without very coarse collision fields. *That limitation* is why we do not do physics that way, at least in games. Collision geometries are typically cheaper.

---

P.S. You should know that collision systems consist of two sets of actions: **detection** & **resolution**.

Let's look at a simple example describing 1D collisions.

First, **detection** in 1D. Imagine 2 carriages, A & B, on a train-track. If the front of the first carriage is at the same position, or further along than the back of the second trailer, then there is a collision. Here is your track and two carriages overlapping:

`---[A [AB] B]--->`

If we found they are overlapping, we need **resolution**. This can occur in many different ways. One of the simplest is to say, "In real life two carriages cannot be overlapping on a train track. So we must move one or both carriages so that they are no longer overlapping." So we go from the above, to this:

`---[A ][ B]--->`

Now there is potentially a lot more to that, than meets the eye. If you are writing a very *simple* game, this resolution may suffice. But if you need more accurate physics, then you may need to calculate bounce force using the force formula `f=mv` with restitution co-efficient, and then reverse or reduce the velocity of A, increase that of B, or whatever. Realistic computation of physics is a field all on its own.

You can see that it's simple enough to extend this to 2D or 3D. Exactly the same principles apply. First, geometrically describe the object (in the case of carriages using a min and max extent), then check for overlap (**detection**), then **resolve** the collision in whatever way is accurate enough for you.

---
Tags: collision-detection, 3d, mathematics, collision-resolution
---


title: Isometric tile map rotation

text:
# Question
Title: Isometric tile map rotation
Is it possible to rotate an isometric tile map, either in LibGDX or Tiled map editor? My problem is that LibGDX renders the (0, 0) position from Tiled at bottom-left corner like it usually does (see the attachments), however that introduces awkwardness when editing the map as you have to keep in mind that the top corner of the map will be the left corner when rendered in game. Is there any workaround for this?

# Answer
> -1 votes
It was my mistake, I was passing "flipY = false" as a parameter into my TmxMapLoader!

EDIT:

My bad. Here's a better explanation:

```
TmxMapLoader.Parameters param = new TmxMapLoader.Parameters();
param.flipY = false;
map = loader.load("data/maps/tiled.tmx", param);

```

I was passing these parameters when loading my map. I did this because otherwise LibGDX would return different Y coordinates of objects than the ones that are set in .tmx file. However, by passing those parameters, the map loader also changes a few more things, including map rotation. I am not sure why exactly it does that but if you analyze BaseTmxMapLoader class you can see where that parameter is used.

---
Tags: libgdx, isometric, tiled
---


# Question
Title: Best way to store player actions and movements and repeat them
I am developing a tile based game to help improve my skills, there will be an entity spawning and following the player, to get around the various obstacles around the map i think that the best way would be for the entity to simply shadow the players movements.

What is the best way to store the players action e.g. jump, move left/right etc.

Would there be an alternative better way for the entity to hunt down the player?

# Answer
> 1 votes
Use the Command pattern and a circular or regular buffer.

The former encapsulates all the information you need to store a command (of your general design) as a single class instance, while the second allows you to limit the length of your history of commands so that you don't run out of memory.

---
Tags: libgdx, movement
---


# Question
Title: Does TCP slow down server and other clients for MMO game
hi guys i made a server and client for mmorpg game of course very amateurish. i am using UDP to send coordinates if the packet is lost doesnt matter i am already sending 10 times in a second. UDP doesn't slow down server and server doesn't slow down other clients. But i also want to use TCP for ID PW and attack skill because when i use attack skill he needs to go absolutely to server. If i use TCP for them, Will client1 slow down Server ? or Will Server slow down other clients ?

i am using c++,opengl,SDL 1.2 and SDL\_net 1.2

I will be grateful for your help :)

EDIT I ADD VIDEO :D : youtu.be/J7Ulh4vUBu0 when only udp server loop 658982 in a second like at the end of the video if i add tcp this valuse slow down ?

# Answer
TCP is generally viewed as being slow because of the guarantee of delivery, and the guarantee of delivery *in order*. When the packet is not received, it has to be resent. It seems that the delay to resend the packet is implementation dependant. If a packet is missing, the software will have to wait for that packet to continue it's process, even if the following packets have arrived.

This represents a potentially high delay.

So to answer your question: I guess it depends on how you implement your transmission layer (blocking vs non-blocking sockets), and I think this is independent of whether you used TCP or UDP.

The TCP vs UDP is not about *slowing down* the server or the client, it's about having the user experience lag or not.

IMHO, you could use TCP for ID and PW if you want, but I'd suggest to find another way using UDP to transmit your attack commands.

---

Disclaimer: I'm not an expert on the topic, I've just been reading a lot on it lately.
> 2 votes

---
Tags: mmo, server, client
---


# Question
Title: What is the origin of the term "AAA game?"
One often hears the term "AAA" thrown around when talking about top production value games and big releases, but where does the term come from? How was it coined and popularized?

# Answer
The term was used at Electronic Arts prior to 1995. While I was a technical director there, I recall first hearing the term used at a meeting where we were discussing sales data with marketing. The context was that--based on sales data--building anything other than AAA games was a bad business move. The "anything other" were referred to as B games, reflecting the movie industry use of "B movies" for low budget films. Although I hadn't heard the term before, it seemed quite natural and everyone understood what it meant. Triple A was associated with high quality and in the game industry high quality was always expensive.

I don't remember the exact numbers, but the data we were looking at showed that of the over 2000 games made during the previous year, only a very small percentage of them were "hits" (e.i. made huge profits). A larger percentage--but not large--broke even or made small profits. The majority lost money. No low or medium budget game was a hit. And very few low budget games broke even or made a small profit. EA and the other big game publishers focused on AAA games after that. . .at least until "Deer Hunter" proved low budget games--in the right market--could make very good profits. The casual mobile game market drove the final nail into the rule of thumb that to make a large profit you had to spend a lot of money.
> 7 votes

# Answer
The term is based on the academic grading scale of the United States (where "A" is a top mark) or similar letter-based grading scales.

The "triple" aspect is somewhat hyperbolic, mainly intended to demonstrate how much "better" the games in question are relative to others; there are no "BBB" or "AA" or similar intermediary ratings, generally speaking (in part, perhaps, because there's no really solid *definition* of what it means to be "AAA").

The genesis of the expression can be found, allegedly, in the 90s, when it was bandied about internally by members of the industry.

"Better" is highly subjective, of course, and can often just mean "had a very large budget," especially today.
> 5 votes

---
Tags: terminology
---


title: Convert Quaternion to Matrix4x4

text:
# Question
Title: Convert Quaternion to Matrix4x4
I'm trying to set `Gizmos.matrix` which is a 4x4 by matrix such that the gizmos drawn match the rotation of the object. However, I'm not sure how to convert the `transform.rotation` quaternion to a `Matrix4x4`. The Unity documentation points to a function called `Matrix4x4.Rotate()`, but Unity 5.6 does not seem to recognize any such function under `Matrix4x4`

# Answer
> 0 votes
You need to use the Matrix4x4.TRS function. It takes a position vector, rotation quat, and a scale vector and outputs a Matrix 4x4.

```
public static Matrix4x4 TRS(Vector3 pos, Quaternion q, Vector3 s);

```

to draw the gizmo in the scene, use

```
//Just as one color assignment applies to every gizmo,
//You must be sure to assign the correct matrix
Gizmos.matrix = Matrix4x4.TRS(transform.position,transform.rotation,transform.localScale);
Gizmos.DrawWireCube(Vector3.zero,Vector3.one);

```

Or alternatively:

```
Gizmos.matrix = transform.localToWorldMatrix;

```

Link to unity docs: https://docs.unity3d.com/ScriptReference/Matrix4x4.TRS.html

---
Tags: unity, rotation, matrix, quaternion
---


# Question
Title: How can I switch between starting a coroutine vs running the routine all at once?
I'm generating a level, and I have an optional delay to show the steps level generation one by one.

If my `generationDelay` boolean is true, I want to use StartCoroutine to spread the generation out over time. If it's false, I want to call the same method but without StartCoroutine.

The problem is that the method is type IEnumerator.

I can make two methods one type of IEnumerator and one not. But I wonder if there is a way to use one method.

In the first script top i did:

```
public bool generationDelay = false;

```

Then in a method:

```
private void BeginGame()
    {
        mazeInstance = Instantiate(mazePrefab) as Maze;

        if (generationDelay == true)
        {
            StartCoroutine(mazeInstance.Generate(generationDelay));
        }
        else
        {
            mazeInstance.Generate(generationDelay);
        }
    }

```

Then the other script where the method Generate is: In the top:

```
public float generationStepDelay = 0.01f;

```

Then the method Generate:

```
public IEnumerator Generate (bool generationDelay) {

        if (generationDelay == true)
            WaitForSeconds delay = new WaitForSeconds(generationStepDelay);
        cells = new MazeCell[size.x, size.z];
        List<MazeCell> activeCells = new List<MazeCell>();
        DoFirstGenerationStep(activeCells);
        while (activeCells.Count > 0) {
            yield return delay;
            DoNextGenerationStep(activeCells);
        }
    }

```

I'm getting an error on the line:

```
WaitForSeconds delay = new WaitForSeconds(generationStepDelay);

```

> "Embedded statement cannot be a declaration or labeled statement"

And an error on the line:

```
yield return delay;

```

> "The name 'delay' does not exist in the current context"

The reason I want to use a bool variable is that when i'm using StartCoroutine it's kind of slow, even if I change the value of `generationStepDelay` to 0 it's kind of slow. And if I'm not using StartCoroutine and not using the Generate method as IEnumerator it will work fast.

So i wonder what should I do and how?

# Answer
> 1 votes
**First of all:** The errors you cite have nothing to do with the problem you're solving - they're just syntax mistakes.

When you define `delay` inside an `if` like that, the definition isn't visible to the rest of the code - it exists only inside the scope of the `if` itself (which is just that line defining the variable alone - not very useful, which is why the compiler tells you not to do that)

To conditionally assign a value, you first need do define a spot it can live in, unconditionally. Then fill that slot based on your condition:

```
WaitForSeconds delay = null;
if (generationDelay == true)
    delay = new WaitForSeconds(generationStepDelay);
// If we fail out of the if, delay still has a well-defined value of null.

```

---

**Secondly**, if you want to complete the whole operation in a single frame, you don't need to conditionally define your `WaitForSeconds` at all - you can simply ignore the `IEnumerator's` current yield value, like so:

```
void RunCoroutine(IEnumerator routine, bool allAtOnce) {
    if(allAtOnce == false) {
        // Start the coroutine normally, and let the Unity
        // engine handle scheduling it with appropriate waits.
        StartCoroutine(routine);
    } else {
        // Race through all steps of the coroutine until MoveNext()
        // returns false when the method finishes / yields break,
        // and don't wait for anything in between!
        while(routine.MoveNext());
    }
}

```

Note that this is **not safe** to use for coroutines that do things like...

* Wait on a `WWW` or `ResourceRequest` object until some data is loaded from the disc/network (you'll skip this wait and try to use the data before it's loaded)
* Chain control to a nested coroutine (you'll ignore this new coroutine and resume the parent routine immediately)
* Expect other game systems to do work between yields (eg. yielding `WaitForFixedUpdate` to let the physics step ahead)

It will also block the main thread until the coroutine finishes ALL of its work, which can cause your game to stutter or become non-responsive if the coroutine takes a long time.

**To avoid these problems**, you could just as easily stick to using vanilla `StartCoroutine` all the time, and just set your `WaitForSeconds` value to 0.0f if you don't want to delay. That way you'll wait the minimal amount of a single frame before resuming, giving the engine a chance to still run its other updates so the game remains responsive and you can show things like progress bars. And then you can still wait on file access/other coroutines/etc. without breaking anything.

If one step per frame is too slow, you can use a loop counter so you only `yield` every 5th or 10th or 100th loop. eg.

```
int batchIndex = 0;
while (activeCells.Count > 0) {
    if(++batchIndex > stepsPerBatch) {
        yield return delay;
        batchIndex = 1;
    }
    DoNextGenerationStep(activeCells);
 }

```

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


# Question
Title: How to make Sword disable when I walk into different scene
So I have a sword animation and it attacks enemies and stuff but whenever I walk into a house scene I want it to disable. So it only is enabled in outdoors scenes

# Answer
Create some kind of scene controller and put it on a GameObject in every scene. In this controller you could set a variable which the sword (e.g.) can check on load and disables or enables itself depending on that.

```
public SceneController : MonoBehaviour
{
    public bool enableSword = true;
}

public Sword : MonoBehaviour
{
    private SceneController sceneController;

    public void Start()
    {
        sceneController = GameObject.FindGameObjectWithTag("SceneController") // You need to create and set this tag in this case
        if (sceneController.enableSword)
        {
            // Do stuff
        }
    }
}

```
> 1 votes

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


# Question
Title: How can I make the Player animation appear smooth?
I'm using GLFW for my window and input related work. I'm calculating delta time and multiplying it with my player speed and then finally adding it to the current position of the player. The thing is that, though it makes my motion frame independent the player movement appears to slow and speed up interchangeably. Well the reason would be the different values of delta time at each frame. What should I do to smooth out this animation?

Here is the relevant code, and a capture of what's going on:

```
float deltaTime = 0;
float oldTime = 0;

//The direction in which the player will move
int playerX = 0;
int playerY = 0;

//callback method for keyboard events
void keyboard_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_W && action == GLFW_REPEAT) {
        playerX = 0; playerY = 1;
    }
    if (key == GLFW_KEY_S && action == GLFW_REPEAT) {
        playerX = 0; playerY = -1;
    }
    if (key == GLFW_KEY_D && action == GLFW_REPEAT) {
        playerX = 1; playerY = 0;
    }
    if (key == GLFW_KEY_A && action == GLFW_REPEAT)
    {
        playerX = -1; playerY = 0;
    }
}

//update player's position
void update() {
    player->move(playerX, playerY, TIME_PER_FRAME);
}

//set up glfw keyboard callback function and other stuff
void init() {
    glClearColor(0, 0, 0, 0);
    player->bindVertexAttributes(shader.getAttributeLocation("position"));
    glfwSetKeyCallback(window->getGLFWWindow(), keyboard_callback);
}

//wait logic
float expected_frame_end = glfwGetTime() + TIME_PER_FRAME;
void wait() {
    while (glfwGetTime() < expected_frame_end) {

    }
    expected_frame_end += TIME_PER_FRAME;
    playerX = playerY = 0;
}

//rendering function
void render() {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    player->setUniformMatrixLocation(shader.getUniformLocation("projectionMatrix"), shader.getUniformLocation("transformationMatrix"));
    shader.useProgram();
    update();
    player->render();
    wait();
    shader.stopProgram();
}

//main function
int main(int argc, char** argv) {
    init();
//main loop
    while (!glfwWindowShouldClose(window->getGLFWWindow())) {
        render();
        window->swapBuffers();
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

# Answer
> 0 votes
> I'm calculating delta time and multiplying it with my player speed and then finally adding it to the current position of the player.

This is variable timestep, which contradicts how you currently tagged the question: .

If your game can currently run at sky high frame rates like 300hz, this is expected.

This is often fixed by actually fixing the time-step: make sure you run your game at a fixed framerate (like 60hz). This means that you have 1/60th of a second to simulate and draw everything. If your loop takes less time than that, *wait*. (As in, don't put your thread to sleep.)

I usually like to do something like (pseudo-code):

```
expected_frame_end = getCurrentTime() + FRAME_TIME

while( true ) {

  update( FRAME_TIME ) // frame time is your delta time, i.e. 1/DESIRED_FRAME_RATE, which is
                       // constant.

  while ( getCurrentTime() < expected_frame_end )
  {
    // do nothing;
  }
  expected_frame_end += FRAME_TIME

}

```

Generally, `sleep` methods guarantee that the thread will be suspended for *at least* the time you requested, not *at most*, which results in frames taking longer than expected, and variation in your actual frame rate.

I suggest a nice read: Fix Your Timestep!.

---

> Is it has to the way keyboard input is processed or something else?*\[sic\]*

Maybe!

The input received by an application largely depends on what the OS decides to send it. And if the app runs at 60Hz, it's most probably too fast for the OS, as in: the OS will not send input 60 times per second, but less often.

To work around that, when you expect the keys/mouse buttons to be held down, you have to register when the key is pressed down, and when it's released. Your code that acts on "key down" will only check your local variable "isKeyDown".

So you need a software layer that checks the state changes sent by the OS, and your code interacts with that layer instead of interacting directly with the raw input sent by the OS.

---
Tags: animation, game-loop
---


title: FixedUpdate() Not Being Called

text:
# Question
Title: FixedUpdate() Not Being Called
I'm following a tutorial for making a simple shooter in Unity, but I have a problem. FixedUpdate() is never being called. I tested Update(), and it was being called as it should be. Normally I would usually just use Update(), but everyone says FixedUpdate() should be used. This is my script:

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 6f;

    Vector3 movement;
    Animator anim;
    Rigidbody playerRigidbody;
    int floorMask;
    float camRayLength = 100f;

    void Awake()
    {
        floorMask = LayerMask.GetMask("Floor");
        anim = GetComponent<Animator>();
        playerRigidbody = GetComponent<Rigidbody>();
    }

    void FixedUpate()
    {
        Debug.Log("fixedUpdate hit");
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        Debug.Log(h);
        Debug.Log(v);

        Move(h, v);
        Turning();
        Animating(h, v);
    }

    void Move(float h, float v)
    {

        movement.Set(h, 0f, v);
        movement = movement.normalized * speed * Time.deltaTime;
        playerRigidbody.MovePosition(transform.position + movement);
    }

    void Turning()
    {
        Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit floorHit;
        if(Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
        {
            Vector3 playerToMouse = floorHit.point - transform.position;
            playerToMouse.y = 0f;

            Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
            playerRigidbody.MoveRotation(newRotation);
        }
    }

    void Animating(float h, float v)
    {
        bool walking = h != 0f || v != 0f;
        anim.SetBool("IsWalking", walking);
    }
}

```

Thanks in advance!

# Answer
As addressed in the comments, you *must* use correct spelling, when calling these methods. They are called, internally, so miss-spelt methods will not be called.

Your calling FixedUpate; you need to call FixedUp**d**ate.
> 0 votes

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


# Question
Title: How to write testable MonoBehaviour and test scripts in Unity?
I had problems with decoupled scripts and exposing interfaces in Unity, and these answers helped me a lot. But now, since I don't have hard-coded references in my scripts, I wanted to write unit tests for my code.

This presented a problem - I can't instantiate MeonoBehaviours using `new` because of how the engine works. What is more, I can't mock out anything from the Unity API.

I found a great blog post by Tomek Paszek. He suggests using the Humble Object pattern, and it seems reasonable. Still, maybe thats just me, because I haven't used that pattern too much, when using the Humble Object pattern even simple code seems to be very complex.

Are there other ways to write testable MonoBehaviors?

# Answer
Use the unit test framework 'Unit Test Tools' provided by Unity.

You're right you can't create new MonoBehaviours on their own, but why not use an empty GameObject and use `AddComponent<MyMonoBehaviour>()` and then run your tests?

Alternatively you can create the bulk of your logic inside your own classes. Then your MonoBehaviour scripts will just use composition to have a local instance of the class that represents their functionality. Your unit testing can also just make a local instance of the class. Though, this sounds more messy than the Humble Object pattern suggested in the blog post.

Yes, creating a testing framework and implementing unit tests can be complex. But once you have things in place, adding additional unit tests is fairly trivial.
> 6 votes

# Answer
There's another option to Unit test MonoBehaviours without calling the constructor (using FormatterServices). Here's a small helper class that creates testable MonoBehaviours:

```
public static class TestableObjectFactory {
    public static T Create<T>() {
        return FormatterServices.GetUninitializedObject(typeof(T)).CastTo<T>();
    }
}

```

Usage:

```
var testableObject = TestableObjectFactory.Create<MyMonoBehaviour>();
testableObject.Test();

```
> 1 votes

---
Tags: unity, c#, testing, unit-testing
---


# Question
Title: How do I make camera follow player only in a certain scene?
In my other scenes I made it so the camera doesn't follow the player, I only want the camera to follow the player in one scene. How do I do that? This is my follow cam script:

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

public class CamFollowPlayer : MonoBehaviour {

    [SerializeField]
    GameObject player;

    // Use this for initialization
    void Start () {

    }

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

        transform.position = new Vector3(transform.position.x,
GameObject.Find("Shrump").transform.position.y,
transform.position.z);

    }
}

```

# Answer
You're pretty close here. You just need to...

* Capture the reference to the player in Start, rather than searching every frame
* Apply the follow effect on all axes, not only on the y axis
* Apply an offset so your camera doesn't embed inside the player object, but sits at a controllable distance & direction away

Like so:

```
public class CamFollowPlayer : MonoBehaviour {

    // Control where the camera wants to position itself relative
    // to the player in worldspace (other spaces are available too)
    public Vector3 offset = new Vector3(0, 1, -10);

    [SerializeField]
    GameObject player;

    // Caching the player reference in Start saves search costs later.
    void Start () {
        player = GameObject.Find("Shrump");
    }

    // LateUpdate is called after all Updates
    // (so the camera can move in response to the player's movement this frame)
    void LateUpdate () {
        transform.position = player.transform.position + offset;
    }
}

```

Note that looking up gameobjects by name can be fragile, leading to obscure bugs if the naming or spawning structure of your game ever changes. A better alternative is to `FindObjectOfType` to search for the player control script or something similar that is uniquely attached to the player.

---

Also, for future reference, please note that abusive language like this is generally not a good way to make people want to help you. If you want free help from users here, you should be prepared to treat them with respect, and be patient when your question does not get answered immediately.
> 0 votes

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


title: Why are voxels used for landscape?

text:
# Question
Title: Why are voxels used for landscape?
According to Wikipedia many games have been using so far voxel engines for modelling landscape. Why is it only used for landscape and not characters etc?

# Answer
> 1 votes
First of all, it was used for characters sometimes (mostly the cube based version). Just look at the majority of voxel based games (Cube World, Trove, etc.).

Voxels are so powerful, because they allow for complex 3d shapes with overhangs and holes and it makes the model destructable. You usually don't need these options for a character model. It's also very hard to render.

---
Tags: architecture, graphics, voxels
---


# Question
Title: Camera and Wall collision - is it possible?
I have seen a couple questions on similar subjects but none of the answers am I satisfied with.

I have a camera which follows a game object; the problem is that it can pass through walls and because of this, has the potential to show some areas that aren't meant to be seen.

I have my walls built using a mesh exported by Sketchup. So there aren't clean barriers that I can write in code. I'd much rather do it using the same physics system that correctly prevents my player object from moving through the wall.

Yet this doesn't seem to work. I try to put a collider on the camera, and also a rigid body, but it has no effect.

*edit*

here is a image of my camera's collider bounds - see how it is partly inside the wall?

The walls are imported from FBX and I generated colliders upon import, so it's a mesh collider.

I am using cinemachine for the camera script.

# Answer
Perform a linecast from the player to your default camera position. When you have a collision, move the camera to the point of the collision. When there is none, move the camera back to the default position.

This requires that all objects which are supposed to block the camera have a collider. If you would like to have objects with colliders which affect either the gameplay or the camera but not both, put these on different layers and use the layer masks flags.

Please note that this is just a very basic solution. Good 3rd person cameras are tricky, and many good games got ruined by bad camera handling. But the "best" solution depends on the game, because you will have to make tradeoffs between practical, aesthetic and ergonomic concerns.
> 2 votes

---
Tags: unity
---


# Question
Title: Admob for Unity: clarification on use needed
I'm following this documentation by Google on how to integrate Admob ads into my game and I'm confused because of the following:

This documentation says I build by game and then I mess around with ads. (Section Unity plugin API tells me how to add ads and that's after the build instruction). Shouldn't it be vice versa? That I place those ads and build last?

Or, if I really do build first, where do I add those ads?

# Answer
It's actually a mess.

`Unity Ads` and `Google Ads` are two different systems and it's still recommended (from my and other users experience) to use `Google Admob`, because it simply gives you more money.

In order to have working ads, you have to:

1. Add them through the code
2. Add the app to `Google Play` without testing the ads (app may be in alpha-beta phase, don't worry, it won't be public)
3. Add the app to the `AdMob` console (https://apps.admob.com/v2/home)
4. Create ads in the `AdMob` console (video, static, banners) and get their keys.
5. Put ads keys into the code (see below)

When you have ad ID's, you put them here:

```
using GoogleMobileAds.Api;
…
private void RequestBanner()
{
    #if UNITY_EDITOR
        string adUnitId = "unused";
    #elif UNITY_ANDROID
        string adUnitId = "INSERT_ANDROID_BANNER_AD_UNIT_ID_HERE";
    #elif UNITY_IPHONE
        string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
    #else
        string adUnitId = "unexpected_platform";
    #endif
}

```

as mentioned on the website you provided.

Then, you can test your app, even by building in `Unity` and uploading directly to the phone/tablet. Remember to put ad's ID's to the code. You'll have your ads working.
> 1 votes

---
Tags: unity, scripting, plugin, advertisements, admob
---


# Question
Title: How can I get N random objects from array?
```
[Range(5, 50)]
    public int waypointsCount = 10;

    private System.Random random = new System.Random();

    // Use this for initialization
    void Start ()
    {
        var Nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");
    }

```

I want to get a random number of `gameobjects` from `Nodes` according to the number in `waypointsCount`. So if for example the number is `10` then I want to get `10` random `gameobjects` from the array nodes. And the `gameobjects` should not be duplicates.

# Answer
Use the greatest tricks of all time:

```
using System.Collections.Generic;

[Range(5, 50)]
public int waypointsCount = 10;

void Start ()
{
    var Nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");

    HashSet<GameObject> randomObjects = new HashSet<GameObject>();

    while(randomObjects.Count < waypointsCount){
        randomObjects.Add(Nodes[UnityEngine.Random.Range(0, Nodes.Length)]);
    }

    // use randomObjects
}

```

Here are `HashSet` docs. When you add an objects to a `HashSet`, the system checks if the object is already there. Only if it isn't - the object is added. That's why sets are used to maintain uniqueness in programming languages.

The script will choose a random `GameObject` from `nodes`, until `randomGameobjects` `HashSet`'s size is equal to `waypointsCount`. Even if it chooses an already existing waypoint/node - it won't add it to the collection (because it's a `HashSet` \- it does what it does).
> 0 votes

# Answer
You can do this faster than a Hashset with a simple linear scan:

```
var randomObjects = new GameObject[waypointsCount];

for(i = 0; i < waypointsCount; i++) {
    // Take only from the latter part of the list - ignore the first i items.
    int take = Random.Range(i, Nodes.Length);
    randomObjects[i] = Nodes[take];

    // Swap our random choice to the beginning of the array,
    // so we don't choose it again on subsequent iterations.
    Nodes[take] = Nodes[i];
    Nodes[i] = randomObjects[i];
}

```

This is effectively a Fisher-Yates shuffle (also called a Knuth shuffle) that terminates early.

Doing it this way has a couple of advantages:

* we can build the output array in-place (even just using the same memory as the input `Nodes` array if we want to), without setting aside extra memory for the hash structure for membership tests.
* if we want 49 items from a list of 50, we finish in exactly 49 iterations, every time. The Hashset method will take on average 3-4 times longer in this scenario, because its probability of choosing a duplicate and retrying goes up the longer our output list gets in proportion to the input. To pick the last random item in this scenario, the Hashset would need to try 25 times on average, since the list only contains 2 valid non-duplicate choices out of 50. The linear scan guarantees that we pick each item in a single try while avoiding duplicates through the re-ordering trick.
> 7 votes

---
Tags: unity, c#, algorithm, random
---


# Question
Title: Why when destroying objects when quitting the game it's destroying the objects only in hierarchy?
In one script i did:

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

public class GameManager : MonoBehaviour
{
    public LevelGenerator levelGenerator;

    // Use this for initialization
    void Start ()
    {

    }

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

    }

    private void OnApplicationQuit()
    {
        levelGenerator.DestroyNodes();
    }
}

```

Then in the other script:

```
public void DestroyNodes()
    {
        GameObject[] nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");

        if (nodes.Length == 0)
        {
            //Debug.Log("No nodes to destroy found");
        }
        else
        {
            for (int i = 0; i < nodes.Length; i++)
            {
                DestroyImmediate(nodes[i]);
            }
        }
    }

```

But the Nodes still exist in the Hierarchy and in the Game and Scene views.

I used a breakpoint it's getting to the OnApplicationQuit

And it's getting to the line:

```
DestroyImmediate(nodes[i]);

```

There are 100 objects and it's doing the line for each object. But then when i make continue they are still exist.

I want that when i quit the game stop the play all the gameobjects to be destroyed.

# Answer
If the nodes were there before you hit play, they will reappear when you hit stop even if you delete them. The scene state is restored after stop playing
> 1 votes

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


# Question
Title: Rotate from Current Rotation to Another using Angular Velocity
I am attempting to calculate an angular velocity that will get me from the current gameObject.transform.rotation to a given Quaternion rotation using angular velocity. I've tried several methods but all of them seem to cause oscillation (maybe due to the gimbal nature of Vector3 for angular velocity).

Here are the pieces of code that I have tried:

```
Quaternion rotationDelta = Quaternion.Inverse(gameObject.transform.rotation) * remoteRotation;
return (rotationDelta.eulerAngles / PlayerMovement.BROADCAST_INTERVAL);

```

Another attempt using toAngleAxis:

```
rotationDelta.ToAngleAxis(out angleInDegrees, out rotationAxis);
Vector3 angularDisplacement = rotationAxis * angleInDegrees * Mathf.Deg2Rad;
return angularDisplacement / PlayerMovement.BROADCAST_INTERVAL;

```

Using Eulers:

```
 Vector3 difference = new Vector3(Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.x, remoteRotation.eulerAngles.x),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.y, remoteRotation.eulerAngles.y),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.z, remoteRotation.eulerAngles.z));

 Vector3 differenceInRadians = new Vector3(difference.x * Mathf.Deg2Rad,
                                           difference.y * Mathf.Deg2Rad,
                                           difference.z * Mathf.Deg2Rad);

 return differenceInRadians / PlayerMovement.BROADCAST_INTERVAL;

```

# Answer
"maybe due to the gimbal nature of Vector3 for angular velocity" ...using Vector3 for angular velocity does not entail gimbals, but converting it to Euler angles does.

Angular velocity is not an Euler angle where each axis is a rotation rate about that axis. It's a vector pointing in the direction of the axis of rotation, with length proportional to the speed of rotation.

Treating it this way, we can get much more stable and intuitive results:

```
// Rotations stack right to left,
// so first we undo our rotation, then apply the target.
var delta = remote.rotation * Quaternion.Inverse(body.rotation);

float angle; Vector3 axis;
delta.ToAngleAxis(out angle, out axis);

// We get an infinite axis in the event that our rotation is already aligned.
if (float.IsInfinity(axis.x))
    return;

if (angle > 180f)
    angle -= 360f;

// Here I drop down to 0.9f times the desired movement,
// since we'd rather undershoot and ease into the correct angle
// than overshoot and oscillate around it in the event of errors.
Vector3 angular = (0.9f * Mathf.Deg2Rad * angle / interval) * axis.normalized;

body.angularVelocity = angular;

```
> 7 votes

---
Tags: unity, rotation, quaternion
---


# Question
Title: How can i set a Range values min/max according to another variable value?
In one script:

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class LevelGenerator : MonoBehaviour
{
    public GameObject Node;
    public Vector3 nodeScale = new Vector3(4, 1, 4);
    [Range(3, 100)]
    public int mapSize = 10;
    public float Spacing = 10;

    private List<GameObject> Nodes = new List<GameObject>();
    private List<GameObject> EndStartPoints = new List<GameObject>();
    private int currentMapSize;

    private void Start()
    {
        currentMapSize = mapSize;
        GenerateNew();
        GenerateRandom(mapSize);
    }

    public void Generate()
    {
        if (Nodes.Count > 0)
            Nodes = new List<GameObject>();

        if (Node == null)
            Node = UnityEngine.GameObject.FindGameObjectWithTag("Main Node");

        for (int x = 0; x < mapSize; x++)
        {
            float positionWidth = Spacing * (float)x;

            for (int z = 0; z < mapSize; z++)
            {
                float positionHieght = Spacing * (float)z;
                GameObject Node = Instantiate(this.Node, Vector3.zero, this.Node.transform.rotation) as GameObject;
                Node.transform.parent = transform;
                Node.transform.localPosition = new Vector3(positionWidth, 0, positionHieght);
                Node.transform.localScale = new Vector3(nodeScale.x, nodeScale.y, nodeScale.z);
                Node.tag = "Node";
                Node.name = "Node";
                Nodes.Add(Node);
            }
        }
    }

    public void GenerateNew()
    {
        currentMapSize = mapSize;
        DestroyNodes();

        Node = UnityEngine.GameObject.FindGameObjectWithTag("Main Node");
        Generate();
        GenerateRandom(mapSize);
    }

    public void DestroyNodes()
    {
        GameObject[] nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");

        if (nodes.Length == 0)
        {
            //Debug.Log("No nodes to destroy found");
        }
        else
        {
            for (int i = 0; i < nodes.Length; i++)
            {
                DestroyImmediate(nodes[i]);
            }
        }
    }

    private void Update()
    {
        Erase();
    }

    private void Erase()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Node")
                {
                    Destroy(hit.collider.gameObject);
                }
            }
        }
    }

    private void GenerateRandom(int gridSize)
    {
        List<int> selectedIndexes = new List<int>();

        //Create an array for indexes of the TOP side
        var arr = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr[i] = i;
        }
        int mynum = arr[Random.Range(0, arr.Length)];
        GameObject Top = Nodes[mynum];
        selectedIndexes.Add(mynum);

        //Create an array for indexes of the LEFT side
        int mynum1 = 0;
        var arr1 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr1[i] = i * gridSize;
        }
        do
        {
            mynum1 = arr1[Random.Range(0, arr1.Length)];
        }
        while (selectedIndexes.Contains(mynum1));
        GameObject Left = Nodes[mynum1];
        selectedIndexes.Add(mynum1);

        //Create an array for indexes of the BOTTOM side
        int mynum2 = 0;
        var arr2 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr2[i] = (gridSize * (gridSize - 1)) + i;   //Reach the last row and iterate with i.
        }
        do
        {
            mynum2 = arr2[Random.Range(0, arr2.Length)];
        }
        while (selectedIndexes.Contains(mynum2));
        GameObject Bottom = Nodes[mynum2];
        selectedIndexes.Add(mynum2);

        //Create an array for indexes of the RIGHT side
        int mynum3 = 0;
        var arr3 = new int[gridSize];
        for (int i = 0; i < gridSize; i++)
        {
            arr3[i] = (i * gridSize) + gridSize - 1;
        }
        do
        {
            mynum3 = arr3[Random.Range(0, arr3.Length)];
        }
        while (selectedIndexes.Contains(mynum3));
        GameObject Right = Nodes[mynum3];
        selectedIndexes.Add(mynum3);

        /*DestroyImmediate(Right);
        DestroyImmediate(Left);
        DestroyImmediate(Top);
        DestroyImmediate(Bottom);*/

        EndStartPoints = new List<GameObject>();
        EndStartPoints.Add(Left);
        EndStartPoints.Add(Right);

        selectedIndexes.Clear();
    }

    private void OnValidate()
    {
        if (currentMapSize != mapSize)
        {
            UnityEditor.EditorApplication.delayCall += () =>
            {
                GenerateNew();
            };
        }
    }
}

```

Then i'm creating a grid of gameobjects and it will be always 10x10 if it was 11 then 11x11 or 9x9.

In another script:

```
using UnityEngine.UI;
using System;

public class WayPoints : MonoBehaviour
{
    public GameObject[] wayPoints;

    [Range(5, 50)]
    public int waypointsCount = 44;

    private System.Random random = new System.Random();

    // Use this for initialization
    void Start ()
    {
        var Nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");

    }

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

    }
}

```

I set the Range min to 5 and max to 50 But i know that the map size is 10 so there will be 100 gameobjects. So the range should be min 5 max 90 or maybe min 5 and max 50.

The problem is how can i make sure i will not set the Range max to be more then the map size ? If the map size will be 5 so it's 25 gameobjects i can't set the Range max to 50.

# Answer
Usually I do it something like this:

```
[Range(0, 1)]
public float proportionToPick;

public int maxItems = 50;

int _numberToPick;

void Start() {
     _numberToPick = Mathf.FloorToInt(maxItems * proportionToPick);

     ...
}

```

This way you can tune `proportionToPick` to 0.2 if you want to grab about a fifth of the items in the collection, no matter if that collection is 50 items or 5 or 5000. It will automatically scale in proportion to your count.

If you need to be able to set the number of items more explicitly, you can do this with a Custom Editor, where you can manually control every detail of how the script looks & works in the Inspector. This is a fair bit of extra code though so I usually work around it with what I can do in a single script unless I need something complicated.
> 2 votes

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


# Question
Title: Strange patterns on models with Unity Lightmap
To save performance and increase the details of static shadows I marked all static objects as static in my Unity Scene. Unfortunately there are now strange patterns on some of my models and I have no clue why. Execpt the sun every light source in my scene uses the mode "Baked".

I'm using Unity 2017.1.0f3 with DX11 on Windows 10 Home x64 and a NVidia GTX 780 Ti.

This is one of the affected models:

My Lightmapping Settings are the following:

```
Lightmapper: Enlighten
Indirect Resolution: 8 texels per unit
Lightmap Resolution: 80 texels per unit
Lightmap Padding: 2 texels
Lightmap Size: 2048
Compress Lightmaps: false
Ambient Occlusion: false
Final Gather: true
    Ray Count: 256
    Denoising: true
Directional Mode: Directional
Indirect Intensity: 1
Albedo Boost: 1
Lightmap Parameters: Default-HighResolution

```

The models were made with Blender 1.78c and the issue does not appear if I use only Realtime lights. Does anyone know this behavior and is there a way to fix it?

Thank you very much in advance! :)

# Answer
> 1 votes
I just found the issue. For models without Lightmap UVs it's required to generate them. This can be done directly in Unity where you just have to tick "Generate Lightmap UVs" in the Model tab of the imported model.

Don't forget to apply the changes made to the import settings! I did this with all of the affected models and it solved the problem.

---
Tags: unity, blender, lightmap
---