# Question
Title: Trying to load .json questions and answers into a multiple-choice quiz game in Unity
I am developing a Unity game which includes a multiple-choice quiz.

I've placed what I believe is a properly-formatted .json file (the quiz question, four answer choices, the correct answer, and an explanation for the answer) (which I checked with a .json formatter) in the StreamingAssets folder in the Unity project. I've created a custom class for the question, the four answer choices, the correct answer and the explanation of the answer.

I am trying to load the entire contents of the .json file into an array, "questions," then copy that array into another array, "questionsCopy." To avoid repeating questions, as a question is used during the gameplay, I will remove it (and its corresponding answer choices, correct answer and explanation) from the questionsCopy array. (I have not yet developed the GUI to show the question, answer choices and eventually the correct answer and its explanation.)

Here are relevant sections of what I've coded so far:

1) The custom class:

```
// This is the custom class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class QuestionChoicesAnswerHintExplanation : MonoBehaviour {

public string[] question; // An array of strings (rather than just a string) so that line spacing, which doesn't play well with .json, could be preserved
public string[] answerChoices;
public int correctAnswerIndex;
public string explanation;
}

```

2) From the GameController:

```
public QuestionChoicesAnswerExplanation[] questions; // This is the fixed size array of the questions, answer choices, answers, and explanations.
private static List<QuestionChoicesAnswerExplanation> questionsCopy; // This is the resizeable list (originally a copy of the array). The size of this list will diminish as we remove items after presenting each question.
private QuestionChoicesAnswerExplanation currentQuestion;

string path; // The path to the .json file storing the questions, answer choices, correct answer index, explanations.
string jsonString; // The contents of the .json file.

```

In the Start() in the GameController:

```
    path = Application.streamingAssetsPath + "/questionsAndAnswers.json";
    jsonString = File.ReadAllText(path);

    questions = JsonUtility.FromJson<QuestionChoicesAnswerExplanation[]>(jsonString);

    // Debug.LogWarning("Questions:");
    Debug.LogWarning(questions);

    if (questionsCopy == null || questionsCopy.Count == 0) // A list with zero elements isn't always null.
    {
        questionsCopy = questions.ToList<QuestionChoicesAnswerExplanation>();
    }

    PickRandomQuestion();

```

Further down in the GameController:

```
    public void PickRandomQuestion()
{
    int randomIndex = Random.Range(0, questionsCopy.Count);
    currentQuestion = questionsCopy[randomIndex];
    questionsCopy.RemoveAt(randomIndex);
}

```

3) Here are the contents of the .json file in the StreamingAssets folder:

```
{
"questions":

[

 {
 "question": ["Trinculo admits 'I have been in such a pickle...' in this comedy:"],
 "answerChoices": ["'The Tempest'", "'Henry 4, Part 1'", "'Henry 5'", "'The Merry Wives of Windsor'"],
 "correctAnswerIndex": 0,
 "explanation": "'Henry 4, Part 1,' and 'Henry 5, are both histories. To be in 'a pickle' usually means to be in a quandary. A broader view of this passage reveals Trinculo to be drunk: \n\nAlonso: \nAnd Trinculo is reeling ripe: where should they \nFind this grand liquor that hath gilded 'em? \nHow camest thou in this pickle? \n\nTrinculo: \nI have been in such a pickle since I \nsaw you last that, I fear me, will never out of \nmy bones: I shall not fear fly-blowing.' \n\n'The Tempest' 5.1."
 },
 {
 "question": ["In 'Hamlet,' this character remarks: 'Neither a borrower nor a lender be; \nFor loan oft loses both itself and friend, \nAnd borrowing dulls the edge of husbandry. \nThis above all: to thine own self be true,\nAnd it must follow, as the night the day,\nThou canst not then be false to any man:'"],
 "answerChoices": ["Fortinbras", "Gertrude", "Polonius", "The Ghost of Hamlet's Father"],
 "correctAnswerIndex": 2,
 "explanation": "The verbose Polonius is speaking to his son Laertes. 'Hamlet' 1.3."
 },
 {
 "question": ["Roger Daltrey, well into his career with The Who, played the roles for both Dromios, the twin servants, in a 1983 BBC production of:"],
 "answerChoices": ["'King John'", "'King Lear'", "'Coriolanus'", "'The Comedy of Errors'"],
 "correctAnswerIndex": 3,
 "explanation": "'The Comedy of Errors.'"
 }

 ]
}

```

BUT I'm getting an error:

> ArgumentOutOfRangeException: Argument is out of range. Parameter name: index
>
> Parameter name: index System.Collections.Generic.List\`1\[QuestionChoicesAnswerExplanation\].get\_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633) GameController.PickRandomQuestion () (at Assets/Scripts/Managers/GameController.cs:741) GameController.Start () (at Assets/Scripts/Managers/GameController.cs:99)

The error message points to problems (GameController.cs:741 and GameController.cs:99), but I don't see what's wrong there. I am UNSURE about the message regarding line 633.

And the Debug.Logwarning yields this:

> QuestionChoicesAnswerExplanation\[\] UnityEngine.Debug:LogWarning(Object) GameController:Start() (at Assets/Scripts/Managers/GameController.cs:92)

What need I do to fix this? Thank you.

# Answer
> 0 votes
Your problem is similar to the one we discussed recently here \- you're giving the JSON parser a different data type than you promised it.

This line:

```
questions = JsonUtility.FromJson<QuestionChoicesAnswerExplanation[]>(jsonString);

```

says "I promise the JSON text will be an array of question-choices-answer-explanation objects, something like..."

```
[
 {
 "question": ["Trinculo admits 'I have been in such a pickle...' in this comedy:"],
 "answerChoices": ["'The Tempest'", "'Henry 4, Part 1'", "'Henry 5'", "'The Merry Wives of Windsor'"],
 "correctAnswerIndex": 0,
 "hint": "Hint: Trinculo is stranded on an island.",
 "explanation": "'Henry 4, Part 1,' and 'Henry 5, are both histories. To be in 'a pickle' usually means to be in a quandary. A broader view of this passage reveals Trinculo to be drunk: \n\nAlonso: \nAnd Trinculo is reeling ripe: where should they \nFind this grand liquor that hath gilded 'em? \nHow camest thou in this pickle? \n\nTrinculo: \nI have been in such a pickle since I \nsaw you last that, I fear me, will never out of \nmy bones: I shall not fear fly-blowing.' \n\n'The Tempest' 5.1."
 },
 {
 "question": ["In 'Hamlet,' this character remarks: 'Neither a borrower nor a lender be; \nFor loan oft loses both itself and friend, \nAnd borrowing dulls the edge of husbandry. \nThis above all: to thine own self be true,\nAnd it must follow, as the night the day,\nThou canst not then be false to any man:'"],
 "answerChoices": ["Fortinbras", "Gertrude", "Polonius", "The Ghost of Hamlet's Father"],
 "correctAnswerIndex": 2,
 "hint": "Hint: This character is very talkative.",
 "explanation": "The verbose Polonius is speaking to his son Laertes. 'Hamlet' 1.3."
 }
 ...
]

```

But that's not what you're giving it. Instead, you're giving it an object *that contains* an array of question-choices-answer-explanation objects:

```
{
    "questions":
      [
        ...
      ]
}

```

In C#, this type would look something like this:

```
[System.Serializable]
public class QuestionCollection {
    public QuestionChoicesAnswerExplanation[] questions;
}

```

Which means your parsing should look like...

```
questionCollection = JsonUtility.FromJson<QuestionCollection>(jsonString);
questions = questionCollection.questions;

```

Now you should get a non-empty array.

---
Tags: unity, json
---


title: Why even use coroutines in Unity?

text:
# Question
Title: Why even use coroutines in Unity?
I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's `Update` method. By using a `IEnumerator` coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re-usability of the component using them.

Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?

# Answer
# You can do that if you want, but...

First, 10000 update calls are more expensive than one update call calling 10000 functions. This is due to the Magic Method indexing and querying logic Unity does for you.

Second, adding, removing, and fetching components has its own overhead. And it's not a cheap as you think. It isn't heavy, but you absolutely don't want to be calling `GetComponent` every game for dozens of objects.

Third, some methods you do not have control over return an `IEnumerator` (namely, Web requests) and the only sensible way to call these is in a coroutine.

Fourth, it can actually fragment your code *even more* than a coroutine seems to, because its now in a separate class chock full of timers and counters, other state machines and callbacks, plus even further calls out to more coroutine replacements when you have a coroutine that invokes further coroutines...

Fifth, coroutines can, in a single method, pick up and execute code in no less than four different places in the Update cycle loop, and sometimes you need the ability to wait until after LateUpdate, but before rendering, then wait again until just *before* Update...Admittedly a rare scenario, but plausible.

But in the end, coroutines are just another tool. It can be used well, it can be used poorly, or not at all.
> 3 votes

---
Tags: unity, component-based, coroutines
---


# Question
Title: Verifying that two words match — false negatives
In my first game, I am trying to validate whether two words match: whether an input word matches a reference word from an array.

Unfortunately the only word for which it finds a correct match is the last value in the array I created. All the other words report an incorrect match even when input correctly.

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

public class MatchLetters : MonoBehaviour {
    public string word = null;
    public int wordIndex = 0;
    public string alpha;
    public Text WordMatch;
    public Text Question;
    public string name;
    public static string[] quest;
    int num;
    public List<string> Words;

    void Start () {
        TextAsset wordText = Resources.Load<TextAsset> ("Words");

        quest = wordText.text.Split ("\n" [0]);
    }

    void Update () {
       //  Question.text = quest[Random.Range(0, quest.Length)];
    }
    public void AlphabeticFunction(string alphabet){
        wordIndex++;
        word = word + alphabet;
        WordMatch.text = word;
    }

    public void WordsGenerate (){
        name = Question.text = quest[Random.Range(0, quest.Length)];
    }

    public void ValidateAnswer (){

        if (name == WordMatch.text) {
            Question.color = Color.green;
            Debug.Log ("Correct");
        } else {
            Question.color = Color.red;
            Debug.Log ("Incorrect");
        }
    }

    public void ResetAnswer(){
        wordIndex = 0;
        word = "";
        WordMatch.text = word;
    }
}

```

# Answer
It sounds like you want do to some form of pattern matching. There's many ways to do that. I coded up a quick example. I left out the Unity specifics, but should be able to easily take what I wrote and put modify it for your project.

I created a class that contains a method called `CountOfInputThatExist` that does the matching. The method is more important. I think that is what you want.

```
public class WordMatchMaking
{
    // this is the list of words you load from your asset
    // that you called WordText in your code
    public List<string> PossibleWords = new List<string>();

    public int CountOfInputThatExist(string input)
    {
        int matchesFound = 0;

        foreach(string validWord in PossibleWords)
        {
            if (input.Contains(validWord))
                matchesFound++;
        }

        return matchesFound;
    }
}

```

And here's the code being used:

```
class Program
{
    static void Main(string[] args)
    {
        WordMatchMaking matchTest = new WordMatchMaking();

        // this is how I initialize my example.  Its similar to
        // your Resources.Load call
        matchTest.PossibleWords.AddRange(new string[] { "cat", "dog", "bird", "fish" });

        string test = "my cat is hungry.";
        Console.WriteLine($"testing '{test}' found {matchTest.CountOfInputThatExist(test)} occurrences.");

        test = "I have a cat and a dog.";
        Console.WriteLine($"testing '{test}' found {matchTest.CountOfInputThatExist(test)} occurrences.");

        test = "The snake ate the fish.";
        Console.WriteLine($"testing '{test}' found {matchTest.CountOfInputThatExist(test)} occurrences.");

        Console.WriteLine("\r\n\r\ntest done...press any key to end application");
        Console.ReadKey();
    }
}

```

And here's the output:

```
testing 'my cat is hungry.' found 1 occurrences.
testing 'I have a cat and a dog.' found 2 occurrences.
testing 'The snake ate the fish.' found 1 occurrences.

```

If you have any questions about this, please ask. I hope it helps. Please remember to mark this as an answer, if you find this helpful.
> -1 votes

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


title: Pygame platformer - Making sprite jump

text:
# Question
Title: Pygame platformer - Making sprite jump
I am currently trying to make a Mario-type platformer using pygame and the MVC design pattern. My progress as of right now is getting a character on screen and having it move left and right.

My goal is to have this character have the ability to jump when spacebar is pressed. It is definitely recognizing that spacebar is pressed, but the character just stops in place instead of jumping. Here is the code for the character that I currently have:

```
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, name, x, y, img_file):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load(img_file).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.falling = True
        self.onGround = False
        self.v = 0
        self.speed = 2

    def moveLeft(self):
        self.rect.x -= self.speed
    def moveRight(self):
        self.rect.x += self.speed
    def jump(self):
        if self.onGround == False:
            return
        self.velocity = 8
        self.onGround = False

```

and here is the controller part corresponding to this:

```
if event.type == pygame.KEYDOWN:
    if(event.key == pygame.K_SPACE):
        self.player.jump()

```

Thanks

# Answer
I have never worked with Pygame, but are you not defining on init self.onGround = false?

> ```
>     self.falling = True
>     self.onGround = False
>     self.v = 0
>
> ```

That would mean that if jump is called, nothing happens.

> ```
> def jump(self):
>     if self.onGround == False:
>         return
>     self.velocity = 8
>     self.onGround = False
>
> ```

Maybe there is something else you dont show in your code, but if you dont set onGround to true in the meantime, you can't jump.
> 1 votes

# Answer
You didn't increased the y-position of the sprite when it is jumping

```
self.rect.y -= self.velocity

```

Also, add a gravity function in your game beforehand so that your sprite stopped jumping at some point

```
def gravity(self):
    if self.vy == 0:
        self.vy = 1
    else:
        self.vy += .45

    if self.rect.y >= (Screen_Height - 5) - self.rect.height and self.vy >= 0:
        self.vy = 0
        self.rect.y = (Screen_Height - 5) - self.rect.height
        self.OnGround = True

```
> 0 votes

---
Tags: sprites, python, pygame
---


# Question
Title: Can I have a scene graph translation node with multiple parent nodes?
I am trying to write a C++ scene graph structure. While designing the node classes I am facing the below issue.

I have a scene graph to represent a house.

I would like to have another house next to the one I have but I would like to reuse the nodes from the existing graph. In order to do that, I create another house (House 2) as a child of the original house (House 1). Although this leads to a situation where the base node in the following graph has 2 parent nodes.

I would like to know, is it a good idea to have a scene graph node (intermediate translation node) to have multiple parents? I would like to reuse my sub-graph as much as possible.

# Answer
> 1 votes
Sure, you *can*, but a monolithic scene graph where nodes have multiple actual parents sounds complicated and cumbersome.

Instead, it sounds like what you'd want to do is allow nodes in the graph to *reference other complete graphs*. This sort of mechanism is often called a "prefab," "template" or "blueprint" system.

In this sort of solution, you'd package what is currently the sub-graph representing the house up into it's own "prefab" graph. It has a root at the origin, and all the pieces of the house placed relative to that root.

The main world graph would contain two nodes, with appropriate world transforms, which then *reference* the house graph (but aren't duplicating its contents). At runtime you can walk from the nodes in the main graph to the nodes in the referenced graph *as if* they were duplicated into the main graph, but you have the advantage of only having the house prefab graph in memory once, and that when you change the prefab graph, all instances of references to that graph inherit those changes.

(The main difference, in case it's not obvious, is that there's no "parent" link from the root of the prefab subgraph back to the node(s) in the main graph; the relationship is only from the main graph into the subgraph, and so avoids a lot of the complication that comes from instead treating the same *logical* relationship of nodes as equal peers in one single graph.)

---
Tags: architecture, design-patterns, scene-graph
---


# Question
Title: Scrolling Camera in Pygame is not working properly
I implemented a camera with edges in 2D side scrolling game using Pygame, it is working but sometimes it will scroll for more than it should have, and in case of using different moves that involved movement, sometimes the value will be in float number and it will cause the level to be buggy. I have tried different methods of camera, but none of them worked for me so far. Is there any other way to implement camera, or at least make this one work as intended?

Below is the code for scrolling at x-axis:

```
   if self.rect.right >= 500 and self.in_level.world_shift_x >= -((self.in_level.total_level_width - (Screen_Width + 32))):
        diff = self.rect.right - 500
        self.rect.right = 500
        self.in_level.shift_world_x(round(-diff, 0))

    if self.rect.left <= 200 and self.in_level.world_shift_x <= -((self.speed / 2)):
        diff = 200 - self.rect.left
        self.rect.left = 200
        self.in_level.shift_world_x(round(diff, 0))

```

# Answer
> 1 votes
I think there might be some weirdness with using round(diff, 0). That always results in a floating number as a result, even with the 0. If you desire to round to an integer, just use round(diff)

---
Tags: pygame
---


# Question
Title: DirectX11 - CreateInputLayout() Vertex shader linkage problem
I keep getting the same error every time, I really have tried everything to fix the problem but it's still not working. Basically I'd like to draw a simple cube.

The error(s):

```
D3D11 ERROR: ID3D11DeviceContext::Draw: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (COLOR,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND]
D3D11 ERROR: ID3D11DeviceContext::Draw: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (TEXCOORD,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND]
D3D11 ERROR: ID3D11DeviceContext::Draw: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (SV_Position,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND]

```

The vertex shader, pos.hlsl:

```
float4 main(float3 pos : POSITION) : SV_POSITION
{
    float4 finalPos = { pos.x, pos.y, pos.z, 1.0f };

    return finalPos;
}

```

The vertex layout:

```
const D3D11_INPUT_ELEMENT_DESC d[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

struct Vertex
    {
        XMFLOAT3 poz;
    };

```

The actual code:

```
Vertex vertex_list[] =
{
    { XMFLOAT3{-1.0f, -1.0f, -1.0f} },
    { XMFLOAT3{-1.0f, +1.0f, -1.0f} },
    { XMFLOAT3{+1.0f, +1.0f, -1.0f} },
    { XMFLOAT3{+1.0f, -1.0f, -1.0f} },
    { XMFLOAT3{-1.0f, -1.0f, +1.0f} },
    { XMFLOAT3{-1.0f, +1.0f, +1.0f} },
    { XMFLOAT3{+1.0f, +1.0f, +1.0f} },
    { XMFLOAT3{+1.0f, -1.0f, +1.0f} }
};

/* First, setup the vertex buffer */
D3D11_BUFFER_DESC o;
o.ByteWidth = sizeof(Vertex) * ARRAYSIZE(vertex_list);
o.Usage = D3D11_USAGE_IMMUTABLE;
o.BindFlags = D3D11_BIND_VERTEX_BUFFER;
o.CPUAccessFlags = 0;
o.MiscFlags = NULL;
o.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA d;
d.pSysMem = vertex_list;

if FAILED(pRenderer->GetDevice()->CreateBuffer(
    &o,
    &d,
    &m_pBuffer
))
    return R_BUFFER_ERROR;

/* Now, setup the vertex layout */
long size = pFileManager->ReadShaderFile("pos.cso", m_bytes);

if FAILED(m_pD3DDevice->CreateInputLayout(
    d,
    ARRAYSIZE(d),
    m_bytes,
    size,
    &m_pInputLayout
))
    return R_SETUP_VERTEX_LAYOUT;

m_pD3DKontekst->IASetInputLayout(m_pInputLayout);

```

Then I'm using m\_pD3DContext-\>Draw() to draw the scene. Nothing shows up, just the usual gray background color using ClearRenderTargetView()

Thanks a lot for any help.

# Answer
> 0 votes
After struggling I found an answer: I was calling IASetInputLayout() only once (when initializing D3D11), and actually I needed to call it every frame. That's why I was seeing a colored cube for a fraction of a second just before all these errors came up.

# Answer
> 1 votes
These errors are telling you that you have the wrong vertex shader set when you issue your draw calls.

If we look at the errors and break them down, it can assist in finding the cause.

First of all, the errors all start with this:

> Input Assembler - Vertex Shader linkage error

This tells us that the problem is with passing data from the Input Assembler (IA) stage to the Vertex Shader (VS) stage, which is confirmed by the next part:

> Signatures between stages are incompatible.

The error then goes on to tell us what data formats the input stage expects (lower-case 'i' here; in this case the input stage is the Vertex Shader, because it's the one which the data is going *to*). Based on the content of the errors we can reconstruct this signature. So, the errors in full are:

> The input stage requires Semantic/Index (COLOR,0) as input...
> The input stage requires Semantic/Index (TEXCOORD,0) as input...
> The input stage requires Semantic/Index (SV\_Position,0) as input...

Meaning that somewhere in your code, you have a vertex shader that looks something like this:

```
struct VS_INPUT
{
    float4 Position : SV_Position;
    float2 Texcoord : TEXCOORD;
    float4 Color : COLOR;
};

VS_OUTPUT MyVertexShader (VS_INPUT vs_in)
{
    ...

```

And that's the shader that's active when you issue your draw calls.

In order to track this down, you can begin as follows:

* Check your IASetInputLayout call and make sure that it has the input layout you intend when issuing your draw calls.
* Check your VSSetShader call and make sure that it has the vertex shader you intend when issuing your draw calls.
* Make sure that the contents of your "pos.cso" file are what you think they are (and likewise for any other .cso files you use).
* Make sure that your shaders and input layouts are all compiled/created successfully.

If this is modified tutorial code then it's possible that any of the above may be at fault.

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


title: Map generator sometimes doesn't work

text:
# Question
Title: Map generator sometimes doesn't work
I am making a dungeon map generator and am currently trying to make it place empty rooms. It first checks if the space is empty and then places a room. The problem is that most of the times it compiles and I get a map/2d array printed, but sometimes it compiles but doesn't print the map. I don't get an error.

```
public class Mapa {

public static void main(String[] args) {
     // Create a 2D array map filled with floors

    char map1[][] = new char[100][100];
    for (int i = 0; i < map1.length; i++) {
        for (int j = 0; j < map1[i].length; j++) {
            map1[i][j] = tiles.wall();

        }
    }
    char mapFinal[][] = roomPlacement(map1);
    for (int i = 0; i < mapFinal.length; i++) {
        for (int j = 0; j < mapFinal[i].length; j++) {
            System.out.print(mapFinal[i][j] + " ");
        }
        System.out.println();
    }

}

public static char[][] roomPlacement(char map1[][]) {
     // this method places rooms into the 2D array map

    char mapReplacement[][] = map1;

    int roomNumber = (int) (10 + (Math.random() * 10));
    int roomLength = (int) (10 + (Math.random() * 10));
    int roomWidth = (int) (10 + (Math.random() * 10));

    int startPositionX = (int) (Math.random() * (mapReplacement.length - roomLength));
    int startPositionY = (int) (Math.random() * (mapReplacement.length - roomWidth));

    int counter = 0;

    while (roomNumber > counter  ) {
        if (position(startPositionX, startPositionY, roomLength, roomWidth, mapReplacement)) {

            if (roomSpace(mapReplacement, startPositionX, startPositionY, roomLength, roomWidth) == true) {
                for (int i = startPositionX; i < (startPositionX + roomLength); i++) {
                    for (int j = startPositionY; j < (startPositionY + roomWidth); j++) {
                        mapReplacement[i][j] = tiles.floor();
                    }
                }
            }
            if (roomSpace(mapReplacement, startPositionX, startPositionY, roomLength, roomWidth) == false) {
                startPositionX = (int) (Math.random() * (mapReplacement.length - roomLength));
                startPositionY = (int) (Math.random() * (mapReplacement.length - roomWidth));

            }

            counter++;
        }

        roomLength = (int) (10 + (Math.random() * 10));
        roomWidth = (int) (10 + (Math.random() * 10));

    }

    return mapReplacement;
}

public static boolean roomSpace(char map1[][], int startPositionX, int startPositionY, int roomLength,
        int roomWidth) {
    // this method checks if there is enough free space

    boolean isFreeSpace = false;
    char mapCheck[][] = map1;

    int counter = 0;
    for (int i = startPositionX; i < (startPositionX + roomLength); i++) {
        for (int j = startPositionY; j < (startPositionY + roomWidth); j++) {
            if (mapCheck[i][j] == tiles.wall()) {
                counter++;
            }
        }
    }

    if (counter == (roomLength * roomWidth)) {
        isFreeSpace = true;
    }

    if (isFreeSpace == true) {
        System.out.println("true");
    } else if (isFreeSpace == false) {
        System.out.println("false");
    }

    return isFreeSpace;

}

public static boolean position(int startPositionX, int startPositionY, int roomLength, int roomWidth,
        char mapReplacement[][]) {
    boolean position = false;
    // checks if the room is out of bounds
    if (startPositionX > 0 && startPositionX < mapReplacement.length && startPositionX + roomLength > 0
            && startPositionX + roomLength < mapReplacement.length && startPositionY > 0
            && startPositionY < mapReplacement.length && startPositionY + roomWidth > 0
            && startPositionY + roomWidth < mapReplacement.length) {
        position = true;
    }

    return position;
}

  }

```

Sorry for the long code but wanted to let you see the whole code to better understand it

# Answer
> 5 votes
You get an infinite loop. The statement that increases your counter in the while loop is inside an if statement that checks if the position is in bounds. Else it just sets `roomLength` and `roomWidth` to new values. To fix this you could move the `counter++` statement at the end of the while block so that it is guaranteed to be executed. Note that this means that you could sometimes get 0 rooms if you're unlucky. You probably also want to set `startPositionX` and `startPositionY` to fresh random values at that point instead of only if `roomSpace` is `false`. You can see that this is happening, since your program never actually finishes ("returns"). That means it's still computing, so for simple programs an infinite loop is the likely culprit.

Some other minor stuff: You don't need an `== true` or `== false` check. `if (a == true)` is the same as `if (a)` (as long as a is a boolean or can automatically be casted to one, im not sure ad hoc what the rules are for this in Java), and `if (a == false)` is equal to `if (!a)`. Similarly you can change your `position` method to simply be

```
return startPositionX > 0
       && startPositionX < mapReplacement.length
       && startPositionX + roomLength > 0
       && startPositionX + roomLength < mapReplacement.length
       && startPositionY > 0
       && startPositionY < mapReplacement.length
       && startPositionY + roomWidth > 0
       && startPositionY + roomWidth < mapReplacement.length;

```

Lastly, I'd recommend you try reading up on some development practices, like SOLID - your code is a bit hard to read. One easy thing that I mean is simply renaming methods: Methods are actions, so their name should be a verb. If I see `public static boolean position()`, I have no idea what this method does. If I instead see `public static boolean isValidPosition()` I know that I have to give it a position and it will check if it is valid in some sense.

---
Tags: java, procedural-generation, tilemap, rpg
---


# Question
Title: unity how to automate changing sprite editor setting
I have a bunch of hex tiles that I want to import into a tile palette. However their pivot point needs to be set to y 0.35 when the default is 0.5

I could edit the import settings in the sprite inspector or change the pivot point in the sprite editor but that takes forever with hundreds of tiles.

Is there any way I could automate that?

# Answer
this can be done with an Editor script and the AssetImporter:

1. Start by creating a TextureImporter

`// spritesheetPath with Assets folder as root
TextureImporter importer = AssetImporter.GetAtPath( spritesheetPath ) as TextureImporter;`

2. Get the SpriteMetaData array using `importer.spritesheet`
3. Edit the pivot properties (pivots are relative to sprite's rect, in \[0-1\] range as shown in the inspector), set the alignment to Custom and replace/re-assign the spritesheet array.
4. Flag the asset using `EditorUtility.SetDirty ( importer )`.
5. Commit your changes with `importer.SaveAndReimport ()`

Here's a complete script with all the bells and whistles:

```
using UnityEditor;
using UnityEngine;

public class SpritesToolsWindow : EditorWindow {

    [MenuItem ( "Window/My Utilities/Sprites Tools" )]
    public static void SpriteTools () {
        SpritesToolsWindow spriteTools = GetWindow<SpritesToolsWindow> ( "Sprites Tools", true );
        spriteTools.Show ();
        if ( Selection.activeObject != null && Selection.activeObject.GetType () == typeof ( Texture2D ) )
            spriteTools.spritesheet = ( Texture2D ) Selection.activeObject;
    }

    public Texture2D spritesheet;

    private Vector2 m_CommonPivot;
    private string m_Log;
    private void OnGUI () {

        spritesheet = EditorGUILayout.ObjectField ( "Spritesheet", spritesheet, typeof ( Texture2D ), allowSceneObjects: false ) as Texture2D;
        m_CommonPivot = EditorGUILayout.Vector2Field ( "Pivot", m_CommonPivot );
        using ( new EditorGUI.DisabledGroupScope ( spritesheet == null ) )
            if ( GUILayout.Button ( "Edit sprites" ) )
                EditSprites ();

        m_Log = EditorGUILayout.TextArea ( m_Log );
    }

    private void EditSprites () {
        if ( spritesheet != null ) {
            string spritesheetPath = AssetDatabase.GetAssetPath( spritesheet );

            if ( !string.IsNullOrEmpty ( spritesheetPath ) ) {

                TextureImporter importer = AssetImporter.GetAtPath( spritesheetPath ) as TextureImporter;

                if ( importer != null && importer.spritesheet != null && importer.spriteImportMode == SpriteImportMode.Multiple ) {
                    SpriteMetaData[] spritesMetaData = importer.spritesheet;
                    for ( int i = 0; i < spritesMetaData.Length; i++ ) {
                        SpriteMetaData metaData = spritesMetaData [ i ];
                        metaData.pivot = m_CommonPivot;
                        metaData.alignment = ( int ) SpriteAlignment.Custom;
                        spritesMetaData [ i ] = metaData;
                    }

                    importer.spritesheet = spritesMetaData; // seems like this setter internally change stuff (needed)
                    EditorUtility.SetDirty ( importer );
                    importer.SaveAndReimport ();

                    m_Log += string.Format ( "Edited {0} sprites in {1}\n", spritesMetaData.Length, spritesheetPath );
                    return;
                }

                m_Log += "Texture is not a spritesheet.\n";
            }
        }

        m_Log += "Could not complete action.\n";
    }
}

```

Cheers!
> 2 votes

---
Tags: unity, sprites, tiles, pivot
---


# Question
Title: How do I remove the window border in Godot?
I want to show my Godot engine game in a borderless window, but not fullscreen. I want to just have the game view visible on screen with no title bar or window chrome.

# Answer
A quick search for "Godot bordeless window" turns up some useful hits, including this official documentation about Godot's `OS` class:

> `bool window_borderless` \- If `true` removes the window frame.
> 0 votes

---
Tags: godot, window-management
---


# Question
Title: OnMouseEnter() function stops working when I set the canvas render mode to: Camera Overlay
Basically the title says it all. I have a OnMouseEnter() function that works fine when I have the canvas render mode on Worldspace but stops working when I change it to Camera Overlay.

Before, it would work with just the script with the mouse functions on it attached to the image object. Now to work I need to use an event trigger and add the script to another object to put it into the trigger.

Any idea why?

# Answer
OnMouseEnter is a MonoBehaviour message that's fired by rays cast in the 3D game world (including hit-testing 2D colliders in that 3D game world too).

Once you set your UI to Overlay, it's no longer *in* the 3D game world. It exists as a pure UI layer painted over-top by a separate pass at the end.

To catch mouse events in this pure UI world, you need to use the UI's event system approach:

```
public class UIMouseOverExample : MonoBehaviour, IPointerEnterHandler {

    public void OnPointerEnter(PointerEventData eventData)
    {
        // Do your stuff.
    }
}

```
> 3 votes

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


# Question
Title: AssetBundles with shaders that contain #include to cg/hlsl
I have a shader that contains some #includes to other cg/hlsl scripts. If i put that shader into an AssetBundle, how am i suppose to handle the cg/hlsl scripts?

Are they not necessary anymore because they are compiled into the shader during the AssetBundle build process? Unity version is 5.6.6f2

Or do i have to put the cg/hlsl scripts into the AssetBundle too? If that is the case, how do I load them during runtime such that the Shader finds them?

Someone suggested me to inline them, but I would like to avoid it if possible.

# Answer
Every shader ends up self-contained, actually (besides the fallback directives). The include directive is processed by the compiler and goes away in the compiled shader, whether it’s in an AssetBundle or not.
> 0 votes

---
Tags: unity
---


title: A lot of memory taken by meshes

text:
# Question
Title: A lot of memory taken by meshes
In the Unity Profiler, it says my meshes are taking over 200 mb memory. Thing is, I don’t have meshes in my scene. The only place they exist is in my list. Would that be it? Do prefabs on a list take memory?

I tried clearing the list, turning it to null, doing = new List. Yet they still exist in the profiler. My list derives from another class, which is serializable if that matters. Like List();

I hope I can get some help!

# Answer
> 0 votes
You can avoid using up the memory by loading only the one mesh you want from an AssetBundle or Resources by name. This will keep the meshes you are not using from ever taking up memory.

Alternatively, if you don’t mind taking up large amounts of memory on scene load and clear it up after picking one, you can just instantiate the one you want from your list, then unload all the other ones using `Resources.UnloadAsset`. Note that you should not call this on the instantiated mesh, as it may remove the one used in the scene.

You can also try using `Resources.UnloadUnusedAssets` after emptying the list, although that may take some time to look through the entire GameObject hierarchy.

---
Tags: unity
---


# Question
Title: NullReferenceException when using GetComponent
I have a script that is attached to all the NPCs in my game.

Here's what the variable declarations and Awake() function look like:

```
Dialogue dialogue;
TextMeshProUGUI UIText;
GameObject textBox;
Image portrait;
AudioSource audioSource;

private void Awake()
{
    audioSource = GameObject.Find("Audio Source").GetComponent<AudioSource>();
    UIText = GameObject.Find("Canvas").GetComponentInChildren<TextMeshProUGUI>();
    textBox = GameObject.Find("TextBox");
    portrait = GameObject.Find("Portrait").GetComponent<Image>();

    textBox.SetActive(false);
}

```

All of this works fine, until it gets to

```
portrait = GameObject.Find("Portrait").GetComponent<Image>();

```

For some reason, it throws a NullReferenceException on that line.

Two things about this confuse me:

* The GetComponents above (for the audioSource and UIText) appear to work fine, despite being called for each of the NPCs. I'd assume it'd either work for all or none of them.
* The portrait variable is used to show a portrait of the NPC when the player is talking to them, and even with the errors, one of the NPCs still has their portrait. It's like one NPC grabs the Image component, and none of the others can snag it or something...?

Anyway, very grateful for any wisdom y'all may provide, and happy to provide any other info that could lead to a resolution. Thanks! Hope your new year is going well!

EDIT: There is a Portrait GameObject in my scene under the Canvas, with an Image component attached to it. This I can confirm.

# Answer
```
portrait = GameObject.Find("Portrait").GetComponent<Image>();

```

There is exactly one way for this line to throw a null reference exception, and that is if no game object named "Portrait" was found in your scene *at the time this script ran*.

Things to check:

* Does the "Portrait" object or anything in its parent chain get spawned dynamically at runtime? If so, it might not be in the scene by the time your NPC script gets its `Awake()` message.

You can try delaying this initialization to `Start()` or a manual initialization routine, or change the order you spawn content to ensure the portrait has fully loaded before the NPC goes looking for it.
* Does the spelling of your "Portrait" game object's name differ in any tiny detail from the string you're looking for? Double-check capitalization, or leading/trailing whitespace. To be extra-sure, paste both strings into a Unicode character checker to reveal any non-printing characters. And note that if the portrait is spawned dynamically, it might get the string " (copy)" automatically appended to its name during instantiation.

(This minefield is the risk we run with stringly-typed code, and one reason why it's often recommended to avoid looking up objects by name)

If these assets are often requested by various NPCs or other scripts, it might make more sense to expose them via a Service Locator, eg...

```
public class DialogueSystem : MonoBehaviour {
    public AudioSource audio;
    public Image portrait;
    public GameObject textBox;
    public TextMeshProGUI uiText;

    static DialogSystem _instance;
    public static DialogueSystem instance {
        get {
            return _instance;
        }
    }

    public void Awake() {
        if(_instance != null)
            Debug.LogError("You somehow have two dialogue systems in your scene at once");
        _instance = this;
    }
}

```

You can set this up as part of the same structure/prefab that holds your portrait and the like, and wire up the references in advance.

Then, instead of searching your whole scene for named objects four times every time you spawn an NPC, you can instead just ask the DialogueSystem whenever you want to show some dialogue:

```
DialogueSystem.instance.portrait.sprite = foo;

```
> 0 votes

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


title: Sorting a list of objects by distance

text:
# Question
Title: Sorting a list of objects by distance
I have an issue with a script the community helped with previously. If an enemy enters the player's ring, it is assigned to the player's list of enemies to combat. However, if a group of enemies gets inside this ring I need to sort them by distance from player, so that the first one in the list will be the closest enemy from player, and so on. If an enemy dies, the next closest enemy should be promoted. Will my GameObject list allow me to do this? Or I need to make new Vector3 list? I'm using System.Linq.

```
        public List<GameObject> enemiesInRange = new List<GameObject>();
        public int hox;

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

        hox = enemiesInRange.Count;
        if (hox == 3)
            print("Frist enemy near you is " + enemiesInRange[0] + ", " + enemiesInRange[1] + ", " + enemiesInRange[2]);
        //   enemiesInRange[0].GetComponent<enemypath>().enemey_checker = true;
        //   enemiesInRange[1].GetComponent<enemypath>().enemey_checker = true;
        //   enemiesInRange[2].GetComponent<enemypath>().enemey_checker = true;

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("enemy") && hox < 3)
            enemiesInRange.Add(other.attachedRigidbody.gameObject);
    }

    void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("enemy"))
            enemiesInRange.Remove(other.attachedRigidbody.gameObject);
    }

```

I really hope to solve this issue and finish from this point.

# Answer
> 5 votes
When in doubt, I recommend consulting the documentation for the types you're using. Even using Intellisense to browse the members of `List<T>` would let you discover `List.Sort()`.

This lets you sort a list using any Comparison method you choose, like for instance this one:

```
int CompareDistanceToMe(GameObject a, GameObject b) {
    float squaredRangeA = (a.transform.position - transform.position).sqrMagnitude;
    float squaredRangeB = (b.transform.position - transform.position).sqrMagnitude;
    return squaredRangeA.CompareTo(squaredRangeB);
}

```

Then you can simply call:

```
enemiesInRange.Sort(CompareDistanceToMe);

```

This is a quick & dirty solution that does strictly more vector calculations than necessary, but for a handful of enemies that won't be a problem. If you want to run this on hundreds of enemies then you'll want to pre-compute your distances first, then find the ranked/sorted order of that collection.

---
Tags: unity
---


# Question
Title: Huge input delay although framerate is stable - possibly related to the DirectX Tool Kit?
I'm in the process of learning how to use the DirectX 11 API and came upon the following problem:
Although my rendering function executes quite fast at around 150 fps (as one expects considering how little geometry is rendered), the mouse and keyboard input is massivly delayed. Sometimes the "game" reacts several seconds too late or doesn't react at all; looking around is a pain.
When I increase the framerate even further to, let's say, 400 (by reducing the rendering resolution/rendering less objects), the effect vanishes and the every keystroke is detected precisely.

My update() function (see code below) is called by the StepTimer class of the DirectX Tool Kit from the main message handling loop. I tried both fixed and variable timestep mode.

Main loop calling update() and render()

```
while (msg.message != WM_QUIT)
{
    if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    static DX::StepTimer stepTimer;
    stepTimer.Tick([&]() { update(stepTimer); });
    render();
}

```

The update() function:

```
void update(DX::StepTimer const &timer)
{
    static Keyboard::KeyboardStateTracker keyboardTracker;
    static Mouse::ButtonStateTracker mouseTracker;
    Keyboard::State keyboardState = keyboard->GetState();
    Mouse::State mouseState = mouse->GetState();
    keyboardTracker.Update(keyboardState);
    mouseTracker.Update(mouseState);
    fps = timer.GetFramesPerSecond();

    if (keyboardState.Escape) PostQuitMessage(0);

    static float pitch = 0.0f;
    static float yaw = 0.0f;

    if (mouseState.positionMode == Mouse::MODE_RELATIVE)
    {
        pitch = std::max(std::min(pitch - float(mouseState.y) * 0.001f, XM_PI / 2.0f - 0.01f), -XM_PI / 2.0f + 0.01f);
        yaw -= float(mouseState.x) * 0.001f;
        if (yaw < -XM_PI) yaw += XM_PI * 2.0f;
        if (yaw > XM_PI) yaw -= XM_PI * 2.0f;
    }
    if(mouseTracker.leftButton == Mouse::ButtonStateTracker::RELEASED) mouse->SetMode(mouseState.positionMode == Mouse::MODE_ABSOLUTE ? Mouse::MODE_RELATIVE : Mouse::MODE_ABSOLUTE);

    Vector3 cameraDir(-sin(yaw) * cos(pitch), sin(pitch), cos(yaw) * cos(pitch));

    Vector3 motionVec = { 0.0f, 0.0f, 0.0f };
    float speed = 4.2f;
    if (keyboardState.W || keyboardState.Up)
    {
        motionVec.x += cameraDir.x;
        motionVec.z += cameraDir.z;
    }
    if (keyboardState.S || keyboardState.Down)
    {
        motionVec.x -= cameraDir.x;
        motionVec.z -= cameraDir.z;
    }
    if (keyboardState.A || keyboardState.Left)
    {
        motionVec.x -= cameraDir.z;
        motionVec.z += cameraDir.x;
    }
    if (keyboardState.D || keyboardState.Right)
    {
        motionVec.x += cameraDir.z;
        motionVec.z -= cameraDir.x;
    }
    if (keyboardState.Space || keyboardState.PageUp)
    {
        motionVec.y += 1.0f;
    }
    if (keyboardState.LeftShift || keyboardState.PageDown)
    {
        motionVec.y -= 1.0f;
    }
    motionVec *= speed;

    static Vector3 cameraPos = { 0.0f, 2.0f, 0.0f };
    if (keyboardState.R)
    {
        cameraPos = { 0.0f, 2.0f, 0.0f };
        pitch = 0.0f;
        yaw = 0.0f;
    }
    cameraPos += motionVec * float(timer.GetElapsedSeconds());
    matrixCamera = XMMatrixLookToLH(cameraPos.XMVECTOR(), cameraDir.XMVECTOR(), { 0.0f, 1.0f, 0.0f });
}

```

Is there any hint you can give me? Or might this even by a bug in the StepTimer class?

# Answer
Your main Win32 message pump is only ever processing a single Win32 message per frame. You need to empty the message queue between each render frame since there are usually dozens or more messages queued up in a single frame time.

Here's a common pattern. Notice that here I'm only doing the tick/update/render cycle if there is no Win32 message to process:

```
while (WM_QUIT != msg.message)
{
    if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else // <---- This is the key part you are missing.
    {
        stepTimer.Tick([&]() { update(stepTimer); });
        render();
    }
}

```

See GitHub for complete basic Direct3D render loops for various Microsoft platforms.

> Note that `StepTimer` is not my invention or strictly a part of the *DirectX Tool Kit*. It was created by Shawn Hargreaves (MSFT) for the Visual Studio DirectX templates for Windows Store 8.1 to replace the somewhat less robust `BasicTimer` class that was shipped in the Visual Studio DirectX templates for Windows Store 8.0. As Shawn was one of the original engineers on *XNA Game Studio*, that team really deserves the credit as the creators of the `StepTimer` design as talked about on his blog.
>
> I have made sure that `StepTimer` has gotten more adoption and use in various other templates, samples, etc. and I use it for the *DirectX Tool Kit* tutorials extensively per my blog post.
> 1 votes

---
Tags: c++, directx, directx11, timestep, timing
---


# Question
Title: Getting grid coordinates of cells bordering a square region
I have a board that is 4x4 ( the blue cells) with the origin (0 , 0) being in the bottom left for example, how can I get the coords which are adjacent to the board (the red cells) to store them in an array?

# Answer
> 1 votes
For any given square (or rectangle) with the upper left hand corner at (Px, Py) with a width of m and a height of n the border will be (Px-1 \<= x \<= Px+m+1, {Py-1, Py+n+1}) and ({Px-1, Px+m+1}, Py-1 \<= y \<= Py+n+1).

# Answer
> 0 votes
Loop through the positions between (-1;-1) and (4;4), and if the position is less, than 0 or larger, than 3 on any axis, then add that to a list.

There are definitely more performant options, but unless you're working with boards thousands of cells wide, you won't run into problems.

# Answer
> 0 votes
I would suggest you to just include those red cells in array, so it won't be a problem to store them.

If you want to set bottom left cell exactly as (0, 0), you can something like this:

```
private Vector2Int greenCellsStartPoint;

public Vector2Int GetGreenCellOnGrid(Vector2Int position) // position from the bottom left cell
{
    return greenCellsStartPoint + position;
}

```

In this case you can store as many red cells as you want in array, this is doesn't really a problem, position in Unity is relative.

---
Tags: unity
---


title: How can I add an in-game level editor?

text:
# Question
Title: How can I add an in-game level editor?
I have 200 prefabs and a scene with an infinite flat plane.

I want to allow user to edit the scene - add, remove, rotate, place that prefabs and save/load resulting "scene" in some custom format.

How can I implement this?

# Answer
You need to make a movable camera and implement a raycast that can select gameobjects, then implement a way to edit that selected gameobject modifying it's transform or even more components through either a simple UI with slider, text or buttons o a similar tool to the one that Unity is using.

Then the last thing you'll have to implement is a save system, you can either go for binary (not readable but better performance) or xml/json (readable but less performant).

If you have any question about how to do any of these just ask away.
> 1 votes

---
Tags: unity, scene, world-editor, user-generated-content
---


# Question
Title: How can I seamlessly animate textures across tiles like in Civilization 6?
I am trying to make a much simpler version of the graphic effects we see in the game Civilization 6. This question applies to the graphics on land and ocean tiles. But I first noticed this effect on the ocean tiles.

So you will see the waves effect (fairly near centre of the image), if you ever played the game you'll know that these waves roll into the coast and are there to let you know its an ocean tile and not a lake.

But these waves span several hex tiles, appearingly seamless. But the map is procedurally generated and so land tiles and ocean can appear in any random formations.

How does it know which animated texture to play for each tile?

I already have made the hex tile map.
I have NOT yet learnt how to add my own custom material/shader to make the texture animate, but I believe I can learn this on my own

But I really am at a loss of how the tile 'knows' what its neighbours are doing and is able to join the texture so nicely). Is there a name for this process of which i can do further research? Any tips on where to start making this effect. (I only want it to look very basic to start with , I'm not expecting to be able to recreate Civ6 any time soon :P

Many thanks!

# Answer
> 2 votes
I don't know how Civ6 does it. But this is how I would do it:

A height map is generated based on the tile information; this could be a simple version (a tile could be represented by 1 pixel in that heightmap). This is then used by a shader as a regular water-foam shader works. The heightmap could be more intricate and have a flow map (so each pixel has an X/Y vector in the rgb coded in)- for more advanced shaders with flowing water or different lapping waves.

The water is not rendered tile-by tile but as one 3D plane using the generated heightmap as source of information. Deeper parts of the ocean could be darker etc.

In fact I suspect the rest of the gameworld is also rendered as terrain using such technique (considering the mountain ranges are similar seamless and unique). The 'undiscovered' areas on the map have a distinct perlin noise look to them... Remember that game visuals and gamelogic are two separate entities- so how the world is represented can be completely different from how the world is displayed. So using heightmaps and 3D meshes that line up with the hex grid are completely valid strategies- the world is simply not drawn hex-by-hex tile.

---
Tags: graphics-programming, graphic-effects, hexagonal-grid
---


title: Modern Techniques of Drawing Pixels?

text:
# Question
Title: Modern Techniques of Drawing Pixels?
How do game engines efficiently handle and draw pixels within a given display?

As a personal project / exercise, I had begun developing a simple game engine written in Java, but came across the issue of figuring a way to efficiently and quickly update the pixels within the game window.

Since I had decided to model this engine after the NES' (which maintains a resolution of 256x240 at 60hz, if i recall correctly) 6502 chip, I had quickly created an array of pixels at that resolution.

Though already thinking that looping through the array and drawing the pixels within that loop was not the best way to handle this task, it performed worse that what I had thought.

My method was only able to produce 100 frames a second at 30% CPU usage, and 40% GPU.

How did the early programmers of the NES / 6502 chip accomplish this task of drawing the display, given the limited power of systems back then, or is this really the most efficient method of going about this problem?

# Answer
Setting pixels is a task best left to specialized graphic hardware. This is how 8bit and 16bit generation hardware worked and this is still how modern PCs work. 2d graphic APIs usually reflect this separation.

The usual way to draw tiles and sprites with a 2d graphics API is to load a couple of bitmaps into dedicated video memory and then provide function calls which just tell the graphic hardware "draw the bitmap `a` at screen coordinates `x`:`y`".

Why do most systems work that way?

1. Because the connection between CPU and GPU only has a limited capacity. So you want to minimize the amount of data exchanged between them. This makes it far more efficient to load bitmaps into GPU memory and let the GPU use those images than to send pixels from CPU to GPU each frame.
2. Because the video hardware and CPU often run at different clock speeds. This means they can not communicate all the time. When the CPU wants to give instructions to the video hardware but the video is currently in a state where it can not receive instructions, the CPU has to wait.

But why separate the graphics hardware from the CPU in the first place? Wouldn't it be more simple and logical to just have one CPU which does everything instead of having a separate CPU and GPU with separate RAM and VRAM? Because it allows to specialize the graphics hardware. The CPU is supposed to execute many different programs, so it needs to be flexible. A GPU, on the other hand, does repeated instructions in bulk (in older hardware that was little more than "copy bitmap to screen location", modern GPUs are far more complex).
> 0 votes

# Answer
Most of the 2D graphics in modern engines are actually 3D graphics in disguise. The modern GPU is optimized for drawing in 3D; but a 3D rectangle viewed from the right angle is simply a picture in a 2D perspective.

So in the end, most engines treat 2D sprites as 3D objects with no depth and are drawn using the GPU with no depth coordinate (Orthogonal projection). This means the pixel artwork is loaded in the GPU's memory as a texture, and then drawn as a textured quad on the screen. All hard work of the drawing to the display is handled by the GPU.

Most frameworks (example Monogame) or engines (Unity) abstract this 3D translation- so the programmers only have to work in a 2D space.

Even in old systems like the NES or C64 there was an area in the memory called the 'video memory'. Writing in that memory space would result in direct results on the screen. The NES had it's own GPU (Ricoh RP2C07) that provided the graphic capabilities of the NES- so it's not just the MOS6502 doing the graphics. Likewise the C64 had a VIC-II chip next to the MOS6510.

These chips added also special graphic capabilities- such as hardware sprites; small graphics that could be placed anywhere on the screen, with some limitations (usually size, number of colors and number of sprites in total or per y-coordinate). Other systems had specific hardware to move pieces of memory around to the video memory (like blitting)- software sprites.

So even in 'old' computers/consoles there were things in place to draw graphics.
> 1 votes

---
Tags: 2d, pixel
---


title: 2D walled map generation

text:
# Question
Title: 2D walled map generation
I want to make a 2D walled map. the walls must be L,T,+,-,| shaped. (made from vertical and horizontal lines) There must not be a complete closed block (i.e. all parts of the map must be connected). Also the map is actually not tile based. All the data I should generate for the map must be in form of x1,y1,x2,y2. which indicates start and endpoint of a horizontal or vertical line.

One idea was using a DFS maze generation algorithm on different parts of my map in order to get a non-perfect maze that has a lot of entrances and exits. But I think it is not a very good solution. Can Anyone help me to get a working algorithm that results wall in forms of x1,y1,x2,y2 of a horizontal or vertical line start and endpoints.

I think I could say it is a pacman like map but it is not tile based.

For example see this picture:

I drew this with paint and is not a perfect map but I want some algorithm that generates a better looking map like this. this map don't have any closed block.

I should say that I don't really need any graphics. I just need an algorithm that generate start and endpoint x,y of a line.

# Answer
I'd solve this using a disjoint-set data structure. This lets you group walls into clusters.

Start with one cluster, consisting of the 4 border walls of your map.

Now, take turns choosing a random place to put a wall of random size & orientation. (You could also randomly place `T`, `L`, or `+` corners, or just let those emerge organically from placing walls)

Before you place the new wall(s), check to see what other walls the new structure would touch (a spatial partition data structure can help you accelerate this check if you have hundreds of walls or more, but for a few dozen a brute force check is probably fine). You might want to add some range tolerance to this check, so walls that pass so close that nothing can fit between them still count as touching.

Now we have a set of walls that we would connect together if we placed this new wall structure. Here's where we use the clustering technique: check whether any two of these walls are already from the same cluster. If so, they're already connected somewhere else, and making a new connection here will create a closed loop. This disqualifies our candidate wall placement, so we try again with a new random choice of placement/size/shape.

If all of the walls we're touching are from different clusters (including the case where we're not touching anything at all), then we can proceed to place this new wall structure, and merge all the clusters we're touching into one (including making a new cluster for the new walls if they're not touching any existing ones).

This guarantees you never create a closed loop of walls.
> 1 votes

# Answer
You can use a modified recursive division maze algorithm. The regular algorithm works like this:

1. Begin with an (empty) rectangular area.
2. Bisect the area randomly with a horizontally or vertical wall. Note this generates two new rectangular sub areas.
3. Cut a door in the wall at a random location.
4. If they are big enough, repeat the process on each of the sub areas generated in step 2.

Side note: while this algorithm is typically described recursively, it can be implemented with a regular loop & a dynamically sized list. Also, while this algorithm is typically applied to cells, you can just as easily apply it to decimal coords.

As for the modifications, you need to make the following changes:

1. When a vertical wall meets a horizontal wall (or vice versa) check it to see if there are any other walls on that same side. If so, then cut the new wall so that it is an acceptable distance from the existing wall.
2. Apply modification 1 whenever a new wall would meet the outside perimeter.
> 0 votes

---
Tags: algorithm, procedural-generation, maps
---


# Question
Title: Lighting in Unreal is not fluid, lighting changes drastically at object "borders"?
I used the starter content's wall objects, an atmospheric fog, a directional light and this is the result:

As you can see, it's obvious where the new object starts.

Why?

# Answer
> 2 votes
Answering as of **4.21.1**, one reason for problems with fluid lighting may be due to issues with UV maps of model. Check if:

* UV map present or not.
* Any faces overlapping in UV map

In this image:

* *Upper Left*: No UV, light placed in editor
* *Upper Right*: No UV, after building lighting
* *Lower Left*: Non overlapping UV, light placed in editor
* *Lower Right*: Non overlapping UV, lighting built

Lights are static 2cd intensity, 300 attenuation, enough to cover a single building. Materials are default material.

Good Luck.

---

Thank you Mr. Gregory for reminding about overlapping UV case. So, in case of overlapping UV, we get jagged lighting like this.

* *New Left*: Overlapping UV, light placed in editor
* *New Right*: Overlapping UV, lighting built

Ideally, we dont want corners to be lit up. Most low poly textures have baked ambient lighting which is least costly. If you absolutely want dynamic lighting, use ambient occlusion and proper texture/normal maps to remove corner effects.

Should look like this:

* Upper part: In engine Ambient Occlusion 0.0
* Lower part: In engine Ambient Occlusion 1.0

More customization(for low poly lighting) available if you make texture not light using by custom greyscale map from 3d modelling software.

---
Tags: lighting, unreal-4, unreal
---


# Question
Title: Blender to Unreal Material workflow....?
I'm new to game development and the Unreal Engine and I have a general question.

I model my objects in Blender and import them into Unreal Engine. My question is, is it better to create and apply your materials and textures within Blender and then import them? Or is it better to save that work for Unreal?

Also does it matter which rendering engine I use in Blender? I use Cycles by default.

# Answer
> 0 votes
As per my knowledge, as of **4.21.1**, unreal engine does not support texture painting.

For a simple 3d game, you would want either

* **Vertex Painting** for very high poly models in scene. Used in realistic graphics and creating terrains.
* **Texture Painting** for low poly models for transparency, normal maps, bump maps, occlusion maps, roughness, metallic.

If you are working on low poly models with large surfaces, you can go for

# Blender -- Export with UV -- Substance -- Blender -- FBX to Unreal

some good practices would be:

* Use same mesh model multiple times with same base texture and different decals.
* Reuse similar meshes(such as doors, roof which nobody usually notices) in multiple assets to reduce gpu workload. You can have different materials/decals/textures in each of them.
* Make textures in high quality(2048x2048) but reduce size as much as permissible in game. When at a distance from player view, reduce map quality even further to improve performance.

If you are working on high poly models with small surfaces, you can go for

# Blender -- Substance -- Blender(redcue poly) -- remap textures -- unreal

In this case, you would:

* Use high poly blender model to create all the maps.
* Use medium poly mesh and maps in game itself
* When farther from player, use Level Of Detail settings to use low poly models and maps.

Good Luck.

---
Tags: blender, unreal-4, materials
---


# Question
Title: In Unity unable to find second github branch
I'm using github for unity asset and for some reason I can't find new branch that was created on a different PC. I tried refreshing, fetching, reinstalling asset, reinstalling asset and recloning repository.

Strangely, my laptop shows the branch, but not my personal home computer.

Any ideas why is this happening?

# Answer
Open your project root folder in a command line and try this :

```
git branch -r

```

To view all available branches on remote.

```
git checkout --track origin/remote_branch_name

```

To checkout the branch and track it from the remote repository.

See this question for more details.
> 1 votes

---
Tags: unity, git
---


# Question
Title: Resetting The object scale to it's original size!
I have this sprite renderer in unity. I have made so that it increases it's scale. The Object is:

This object is a child of empty gameObject and I have resized the parent gameObject rather than this one and added the script to parent rather than this object. The code I have written is:

```
Scaler = transform.localScale;
Scaler.x += 3f;
transform.localScale = Scaler;
if(Scaler.x > MaximumPoint){
Scaler.x -= 3f;
transform.localScale = Scaler;
}

```

This code doesn't work because if the object decrease by 3f, it isn't greater than MaximumPoint anymore. So, this code stops.

Another Code , I have tried is:

```
void OnCollisionTrigger2D(Collision2D col){
if(col.gameObject.name == "Collider"){
Scaler --;
}
}

```

This one throws a null pointer exception because I am not sure why?

Another thing I have tried is raycasting but the ray doesn't move with the increased scaled object.

# Answer
> 0 votes
Why don't you just use a bool that determines whether you're increasing the size or decreasing? Could use something like this:

```
bool increasing = true;
Vector3 Scaler;
float maximumX;
float minimunX;

void Start()
{
    minimunX = transform.localScale.x;
    maximumX = "Whatever you want the max to be";
    Scaler = transform.localScale;

}
public void DoNothing()
{
    if(Scaler.x >= maximumX)
    {
        increasing = false;
    }
    else if(Scaler.x <= minimunX)
    {
        increasing = true;
    }

    if (increasing)
    {
        Scaler.x += 3f;
    }
    if (!increasing)
    {
        Scaler.x -= 3f;
    }

    transform.localScale = Scaler;
}

```

Hope this helps :)

---
Tags: c#, transformation
---


title: How to rotate a pixmap (LIBGDX)

text:
# Question
Title: How to rotate a pixmap (LIBGDX)
In my game I have a world with randomly generated islands. My islands are based on the pixel information of the LibGDX Pixmap class.

Now I need to rotate the islands. For this I need to rotate the Pixmaps. Not for drawing, but for reading the pixel data of the rotated Pixmap afterwards.

My problem is, that I don't know how to rotate the Pixmap, so I can read the pixel data of the rotated Pixmap.

Drawing a rotated Pixmap works well, but I need the rotated data persisted, so I can read it.

My code I started with, which doesn't work:

```
public Pixmap rotatePixmap(Pixmap pixmap, int angle){
    Sprite sprite = new Sprite(new Texture(pixmap));
    sprite.setRotation(angle);
    return sprite.getTexture().getTextureData().consumePixmap();
}

```

How can I rotate the Pixmap, so the pixels are altered to the desired rotation?

# Answer
As taken from this post on stack overflow, you can manually build a new Pixmap by sampling from rotated position in the original Pixmap data:

```
public static Pixmap rotatePixmap (Pixmap src, float angle){
    final int width = src.getWidth();
    final int height = src.getHeight();
    Pixmap rotated = new Pixmap(width, height, src.getFormat());

    final double radians = Math.toRadians(angle);
    final double cos = Math.cos(radians);
    final double sin = Math.sin(radians);

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            final int centerX = width/2;
            final int centerY = height / 2;
            final int m = x - centerX;
            final int n = y - centerY;
            final int j = ((int) (m * cos + n * sin)) + centerX;
            final int k = ((int) (n * cos - m * sin)) + centerY;
            if (j >= 0 && j < width && k >= 0 && k < height){
                rotated.drawPixel(x, y, src.getPixel(j, k));
            }
        }
    }
    return rotated;
}

```

Note: this solution returns a Pixmap with the same dimensions as the target. If you have a rectangular rather than a square Pixmap, this might not be quite what you want. Also, depending on your data, it's possible that some of the image will get clipped. If that's a problem, you'll need to do a little bit of math to adjust the size of the destination Pixmap to make it big enough to accommodate the result.
> 2 votes

# Answer
Calling `Sprite.setRotation` is realized when calling `Sprite.getVertices` or `Sprite.set`. These functions do not transform the underlying texture.

One option is to write your own code to preform the rotation. This website is an excellent resource for learning how to do so and what the pitfalls (and solutions) are.
> 0 votes

---
Tags: libgdx
---


# Question
Title: How do you make a particle system collision add a force to an object towards the particle system?
I have a lightning particle that gets shot at the ground. I want the particles to collide with the object they hit and add an upward force. I tried just entering a negative force in the Collider Force tab but it defaults to 0. If anyone knows a way to do this it would be greatly appreciated!

Edit: I want to send the cube in the photo upwards by adding a force on its y-axis. The Particles should remain as they are.

# Answer
> 2 votes
After searching and searching it turns out I needed to toggle the Send Collision Message bool. If anyone is wondering how to get this to work, toggle on this bool in the inspector:

and this is the code I used to get it moving:

```
void OnParticleCollision(GameObject other)
{
    if(other.GetComponent<Rigidbody>() != null)
    {
        other.GetComponent<Rigidbody>().AddForce(transform.up * 160);
    }
}

```

# Answer
> 1 votes
I hope that what you are trying to achieve is to make the particles bounce back from a surface. I do not think we need collider force for that. Just set bounce value to non zero. That should work.

**Simple Reflection**

**Strictly Upward**

If you want the particle rebound to go upward only, use the trigger section just like you would use BoxCollider2D. Use another particle system to send particle upwards.

**rebound and upward**

I would guess you have to write a script for particle system to fire whenever a collision is detected on the plane. The second alternative sounds cleaner. Just cover up the ground with a lot of light, nobody will notice :)

Good Luck.

---

Particle system has a list of collision events. This script checks collisions and matches tags. If tags match, then action is executed. Uncomment flag= true if you want only one collisions.

---
Tags: unity, physics, collision-resolution, particles
---


# Question
Title: Unity - Bool doesn't change to false anymore
I got into a Unity-Tutorial and halfway-through I face this weird problem. I used this code so that my player may attack if he pressed a leftShift. When the player attacks, the animation starts playing in a loop - he never stops attacking and debugging show that attack is never false after the first "leftShift"-Input.

I removed the loops from the animator etc. - but that doesn't seem to be the problem because "attack" never get's to false anyways. I tried different approaches. If I set "attack = false" immediately after attacking, he doesn't attack at all.

Sorry for asking such a beginner question but I can't seem to find my error.

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

public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;

[SerializeField]
private float movementSpeed;

private bool facingRight = true;

private Animator myAnimator;

private bool attack = false;

// Start is called before the first frame update
void Start()
{
    myRigidbody = GetComponent<Rigidbody2D>();
    myAnimator = GetComponent<Animator>();
}

void Update()
{
    HandleInput();
    Debug.Log(attack);

}

// Update is called once per frame

void FixedUpdate()
{
    float horizontal = Input.GetAxis("Horizontal");
    HandleMovement(horizontal);
    Flip(horizontal);
    HandleAttacks();
    ResetValues();

}

private void HandleMovement(float horizontal)
{
    if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    {

        myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
        myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
    }
}

private void HandleAttacks()
{
    if (attack)
    {
        myAnimator.SetTrigger("attack");

    }
}

private void HandleInput()
{
    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        attack = true;

    }
    attack = false;
}

private void Flip(float horizontal)
{
    if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

private void ResetValues()
{
    attack = false;
}
}

```

# Answer
> 3 votes
The issue was that only the bool "attack" was being changed, not the animation parameter "attack. After lots of testing this code finally works if anyone is interested:

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

public class Player : MonoBehaviour
{
    private Rigidbody2D myRigidbody;

    [SerializeField]
    private float movementSpeed;
    private bool attack = false;

    private float attackTimer;

    private bool facingRight = true;

    private Animator myAnimator;

    // Start is called before the first frame update
    void Start()
    {
        myRigidbody = GetComponent<Rigidbody2D>();
        myAnimator = GetComponent<Animator>();
    }

    void Update()
    {
        HandleInput();
        if (attack)
        {
            Debug.Log(attack);
        }

        float horizontal = Input.GetAxis("Horizontal");

        HandleMovement(horizontal);
        Flip(horizontal);
        HandleAttacks();
        //ResetValues();

    }

    // Update is called once per frame

    void FixedUpdate()
    {

    }

    private void HandleMovement(float horizontal)
    {
        if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
        {

            myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
            myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
        }
    }

    private void HandleAttacks()
    {
        if (attack)
        {
            myAnimator.SetTrigger("attack");

            attack = false;
            myAnimator.ResetTrigger("attack");

        }
    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift))
        {

            attack = true;
            HandleAttacks();

        }

    }

    private void Flip(float horizontal)
    {
        if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
        {
            facingRight = !facingRight;
            Vector3 theScale = transform.localScale;
            theScale.x *= -1;
            transform.localScale = theScale;
        }
    }

    private void ResetValues()
    {
        attack = false;
    }

}

```

---
Tags: unity
---


# Question
Title: Rendering Tilemap Tile Layer Side by Side for Infinite/Endless Runner Game
I was strugeling this for days how to implement tilemap into libgdx and box2d with infinite/endless scheme. I can load a single map and display everything on screen. But placing 2 or more tilemap side by side got me headache. I know currently not possible to offset/add x value position of tilemap. What I do right now is use setview for camera of it's render method. This is my map helper and currently I works with 3 renderer for 3 tilemap as a test...

```
public class MapHelper {
private Array<OrthogonalTiledMapRenderer> renderer = new Array<OrthogonalTiledMapRenderer>();
private int number;
private float oldDistance, currentDistance;
private String layer = "world";

public MapHelper(Callback callback) {
    this.callback = callback;
    number = 0;
    item = new ItemMap[3];
}

public void render(CamHandler cam) {
    for(int r = 0; r < renderer.size; r++) {
        if(item[r] != null) {
            renderer.get(r).setView(cam.getCam().combined, item[r].distance, 0, item[r].getWidth(), item[r].getHeight());
            renderer.get(r).render();
        }
    }
}

public void updateMap(CamHandler cam) {
    if(mapOut(cam)) {
        number++;
        if(number > 2)
            number = 0;
        loadMap(number);
    }
}

/**
 * Check if camera reach the current distance, then build new map
 * @param cam
 * @return
 */
private boolean mapOut(CamHandler cam) {
    float x = cam.getCam().position.x + cam.getCam().viewportWidth / 2;
    Utils.log("pos cam x "+x+" current distance "+currentDistance);
    return x >= currentDistance;
}

private void loadMap(int map) {
    AssetsManager.loadMap(map);
    if(item[map] != null) {
        renderer.set(map, new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map].set(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    } else {
        renderer.add(new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map] = new ItemMap(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    }

    oldDistance = currentDistance;
    currentDistance += TileHelper.getMapWidth(AssetsManager.map, layer);
    callback.onLoad();
    Utils.log("load new map "+map+" distance "+currentDistance);
}

public Array<OrthogonalTiledMapRenderer> getRenderer() {
    return renderer;
}

public Array<Body> getBodies(World world) {
    return new MapBodyBuilder().buildShapes(AssetsManager.map, world, oldDistance);
}

private ItemMap[] item;

private class ItemMap {
    private float distance, mapWidth, mapHeight;

    ItemMap(float w, float h, float distance) {
        mapWidth = w;
        mapHeight = h;
        this.distance = distance;
    }

    private void set(float mapWidth, float mapHeight, float distance) {
        this.mapWidth = mapWidth;
        this.mapHeight = mapHeight;
        this.distance = distance;
    }

    private float getWidth() {
        return mapWidth * Constants.WORLD_TO_SCREEN;
    }

    private float getHeight() {
        return mapHeight * Constants.WORLD_TO_SCREEN;
    }
}

private Callback callback;

public interface Callback {
    void onLoad();
}

public void startOver() {
    clear();
    currentDistance = number = 0;
    loadMap(number);
}

private void clear() {
    for (OrthogonalTiledMapRenderer render : renderer) {
        render.dispose();
    }
}

```

}

With above class, I can display and load new map on screen when camera reaching the map end. But the tile layer texture keeps wrong position. Please give me an advice.

# Answer
if i understand right , you missed to check this.

* if, your *MAP\_PIECE* is 2nd you must add(if moving right) previous *MAP\_PIECE's* width
* if, your *MAP\_PIECE* is 3rd you must add *MAP\_PIECE's* width x2
* if, your *MAP\_PIECE* is 3rd you must add *MAP\_PIECE's* width x3

For example you can have variable like *delta/difference* or something.

```
difference = 0,

```

each time you load new "map/chunk" you just:

```
difference += map's width

```

and each time you draw add *differecne* to map's position on x\_axis

Below is your code (not fixed, just copy-past) i think it could be integrated here

```
if(item[map] != null) {
        renderer.set(map, new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map].set(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    } else {
        renderer.add(new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map] = new ItemMap(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    }

```
> 1 votes

---
Tags: libgdx, box2d, tilemap, side-scroller
---


# Question
Title: How to use GLM Simd using GLM version 0.9.8.2?
I am new user for GLM, can somebody guide me how to use GLM SIMD using its version 0.9.8.2.

According to its Manual using #define GLM\_FORCE\_SSE2

For example, if I write:

```
#define GLM_FORCE_SSE2

#ifdef GLM_FORCE_SSE2

glm::vec3 v(1.0f);

#endif

```

I am unable to notice any difference if I write this now:

```
glm::vec3 v(1.0f);

```

unlike older version of GLM where I can use different function like

```
#include <GLM\GTX\simd_mat4.hpp>
glm::detail::fvec4SIMD v(1.0f); //for simd
glm::vec3 v(1.0f); //for non simd

```

but with version 0.9.8.2 I am confused.

# Answer
The good news is that simd support is now part of the standard GLM types (GLM\GTX\simd\_mat4.hpp is deprecated), the bad news is that its activation looks broken. Here is how I managed to enable the use of simd intrinsics in GLM.

First, before any inclusion of a glm header, define:

```
#define GLM_FORCE_SSE2 // or GLM_FORCE_SSE42 if your processor supports it
#define GLM_FORCE_ALIGNED

```

And then in glm/detail/precision.hpp, replace the following lines:

```
highp = packed_highp,
mediump = packed_mediump,
lowp = packed_lowp,

```

By

```
highp = aligned_highp,
mediump = aligned_mediump,
lowp = aligned_lowp,

```
> 2 votes

# Answer
It also depends on your OS and compiler. I'm testing GLM-0.99, and this is the behavior I observe. Note that I have the following macros defined before including `glm` headers:

```
#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#define GLM_FORCE_SIMD_AVX2

```
* On MacOS 10.14 with `clang++` compiler, I get executable with SIMD right away.
* On Ubuntu 16.04 with `g++` compiler, I will have to use the compiler flag `-mavx2` to generate a SIMD executable. There are other compiler options for other SIMD instructions here. Without the compiler flag, I still get a serial executable.

P.S. I used the following test program to time the executable and know if it's SIMD enabled. Without SIMD, it takes ~12s, and with SIMD, it's ~2s (on a Core i7 processor).

```
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sys/time.h>

#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#define GLM_FORCE_SIMD_AVX2
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#define NUM_VERT 1000000000
#define PI 3.14159f

int main()
{

    float* buf = new float[ NUM_VERT + 4 ];

    std::srand( std::time(nullptr) );
    for( size_t i = 0; i < NUM_VERT + 4; i++ )
        buf[i] = float(std::rand() % 100) * PI;

    glm::mat4 Model = glm::translate( glm::mat4(1.0f), glm::vec3(1.0f));
    Model[3][2] = 0.11f;
    Model[2][0] = -0.1f;
    Model[0][1] = 0.04f;
    Model[1][3] = -0.2f;

    double sum = 0.0;
    struct timeval start, finish;
    glm::vec4 Pos, Trans;
    gettimeofday( &start, NULL );

    for( size_t i = 0; i < NUM_VERT; i++ )
    {
        Pos.x = buf[ i ];
        Pos.y = buf[ i + 1 ];
        Pos.z = buf[ i + 2 ];
        Pos.w = buf[ i + 3 ];
        Trans = Model * Pos;
        sum += glm::length( Trans );
    }

    gettimeofday( &finish, NULL );
    double sec = (finish.tv_sec - start.tv_sec) + ((finish.tv_usec - start.tv_usec)/1000000.0);
    std::cout << "total time = " << sec << std::endl;
    std::cout << "  sum = " << sum << std::endl;

    delete[] buf;

    return 0;
}

```
> 3 votes

---
Tags: c++, glm, simd
---


# Question
Title: Unreal Android game crashes after google play integration
I'm fairly new to android game dev but after some months of work I finished making my game in ue4. However, when uploading it to google play on an alpha track and then trying to launch the app, it crashes.

The error itself might be connected to either gradle or proguard (from what I gathered in information over the past 2 days), but as the build.gradle file in unreal projects gets a reset with every fresh build, I can't just edit that.

I've also read in the forums by one unreal dev how you are supposed to add dependencies to the build.gradle by using an "additions.gradle" file, but there was no further documentation about that.

I have already looked up every thread online with a similar problem - yet none of those could solve my problem.

Crash logs:

```
java.lang.NoClassDefFoundError:

 at com.google.android.gms.c.c.<clinit> (Unknown Source)

  at com.epicgames.ue4.GameActivity.onCreate (GameActivity.java:2785)

  at android.app.Activity.performCreate (Activity.java:7383)

  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1218)

  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3250)

  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3405)

  at android.app.ActivityThread.-wrap12 (Unknown Source)

  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1994)

  at android.os.Handler.dispatchMessage (Handler.java:108)

  at android.os.Looper.loop (Looper.java:166)

  at android.app.ActivityThread.main (ActivityThread.java:7523)

  at java.lang.reflect.Method.invoke (Native Method)

  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:245)

  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:921)

```

build.gadle in Intermediate\Android\APK\gradle

```
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
    apply from: 'buildscriptAdditions.gradle', to: buildscript
}

apply from: 'baseBuildAdditions.gradle'

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

```

build.gradle in Intermediate\Android\APK\gradle\permission\_library

```
apply plugin: 'com.android.library'
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        minSdkVersion 13
        targetSdkVersion 23
    }
}
dependencies {
    implementation 'com.android.support:support-v13:25.0.0'
}

```

build.gradle in Intermediate\Android\APK\gradle\downloader\_library

```
apply plugin: 'com.android.library'
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        minSdkVersion 4
        targetSdkVersion 15
        versionCode 2
        versionName "1.1"
    }
}

```

buildAdditions.gradle in Intermediate\Android\APK\gradle\app

```
 apply from: 'aar-imports.gradle'
    apply from: 'projects.gradle'
    android {
        defaultConfig {
            ndk {
                abiFilter "arm64-v8a"
            }
        }
        signingConfigs {
            release {
(Keystore removed)
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
            debug {
                debuggable true
            }
        }
    }
    dependencies {
        implementation('com.android.support:support-v13:27.1.0')
    }
    dependencies {
        implementation('com.google.android.gms:play-services-gcm:11.8.0')
    }

```

# Answer
> 3 votes
so I fixed the problem. I had to go into C:\Program Files\Epic Games\UE\_4.21\Engine\Build\Android\Java and edit the aar-imports file. After adding all missing dependencies and updating the others (as many were super outdated) the problem was fixed.

(also make sure the dependencies are the same as those in your plugins build.gradle files.

---
Tags: android, unreal-4, google-play-services
---


# Question
Title: Aligning rotation from a imu9250 to a game object
I am experimenting with interfacing unity with real world inputs, specifically I have an imu9250, connected to an arduino clone providing rotation inputs ( either quaternion or pitch/yaw/roll) to unity. (I’m using the DMP functionality of the 9250 to calculate orientation).

The connectivity (over serial for now) works fine, rotating my sensor rotates my game object but I can’t work out how to align my input (programmatically) so that the rotation of the game object rotates in the same direction (in game space).

Any tips/pointers appreciated.

Additional information:

My understanding is that the DMP only uses the Gryo and Accelerometer, not the magnetometer.

I can’t find any other references to the coordinate system used outside of the images above. Not mentions in the data sheet as far as I could see http://www.invensense.com/wp-content/uploads/2015/02/PS-MPU-9250A-01-v1.1.pdf

# Answer
In case anyone comes across this, here is how I solved it (for my needs at least).

This solution requires the target object have an parent GameObject (child position offset 0,0,0). Both must be specified as parameters to the script.

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

public class playerController : MonoBehaviour {

    public string COMPort = "COM3";
    public int baudRate = 115200;

    //rotate input - X by 90, Y by 90
    private Quaternion offset = new Quaternion();
    public Vector3 offsetEuler = new Vector3(90, 90, 0);

    public Transform target;
    public Transform targetParent;

    public bool calibrate = true;
    private Quaternion calibrationAngle = new Quaternion();
    public bool reverse = false;

    SerialPort stream;

    void Start () {
        stream = new SerialPort(COMPort, baudRate); //Set the port and the baud rate
        stream.Open();

        // Set the offset
        offset = Quaternion.Euler(offsetEuler);
    }

    private void Update()
    {
        Quaternion rawInput;
        string value = stream.ReadLine(); //Read the information
        string[] vec3 = value.Split(','); //Arduino returns a Quaternion, note however the order is different to Unity
        if (vec3[0] != "" && vec3[1] != "" && vec3[2] != "" && vec3[3] != "") //Check if all values are recieved
        {

            rawInput = new Quaternion(float.Parse(vec3[1]), float.Parse(vec3[2]), float.Parse(vec3[3]), float.Parse(vec3[0]));

            if (calibrate)
            {
               // resets the child oritentation so that it remains consistent with world
               // needs to be sampled prior to setting parent and set afterwards.
               // this could be probably be done cleaner in the Start function
               calibrationAngle = target.transform.rotation ;
               calibrate = false;
               targetParent.transform.rotation = offset * rawInput;
                target.transform.rotation = calibrationAngle;
            }
            targetParent.transform.rotation = offset * rawInput;
        }
    }
}

```
> 1 votes

---
Tags: unity, orientation, arduino
---


# Question
Title: Detect collision with bullet physics, to make a character controller
I inherited from `btCollisionWorld::ContactResultCallback` but I really have no idea how to use this virtual function:

```
btScalar addSingleResult(btManifoldPoint& cp,
        const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0,
        const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)

```

I thought about using `btCollisionWorld::ConvexResultCallback` instead but there is no method in btCollisionWorld to use it.

For now my only goal is to move a btCollisionObject around and detect collision with walls, to adjust the position and movement.

I would just need the collision normal, some collision point, or anything else...

# Answer
Ok so in

```
btScalar addSingleResult(btManifoldPoint& cp,
    const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0,
    const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)

```

btManifoldPoint& cp contains everything I'd need.

https://www.pybullet.org/Bullet/BulletFull/classbtManifoldPoint.html

My native language is not french and I still have quite some trouble understanding the meaning of the word manifold.
> 2 votes

---
Tags: opengl, collision-detection, physics, bullet-physics, control
---


# Question
Title: Convert a direction vector (normalized) to rotation?
Say i have something like this:

```
pos += glm::normalize(target - pos) //PLEASE NOTE: pos is a glm::vec3 and so is target

```

This makes "pos" translate towards "target", but what if i want to make my object to ***face*** "target"?

# Answer
> 4 votes
Making a model always face a point is trickier in 3d than it is in 2d: the added dimension makes one wonder "what about the UP?".

This here assumes that you want your model to stay vertical as much as possible, and it uses the following coordinate system.

```
// z+    y+
// |    /
// |   /
// |  /
// | /
// |/
//  ¯¯¯¯¯¯¯¯¯¯¯¯ x+

```

This also assumes that the 'front' vector of your model is in x+ and that the 'side' vector is y+ (and of course, 'up' is z+).

```
glm::vec3 dirglm( dir.x(), dir.y(), dir.z() ); // dir is normalized

// find the angle about world-frame-z-axis
double angle = std::atan2( dir.y(), dir.x() );

// Make the rotation matrix around the vertical (z) axis, adjusts the 'yaw'
glm::mat4 glmrotXY = glm::rotate( angle, glm::tvec3<double>( 0.0, 0.0, 1.0 ) );

// Find the angle with the xy with plane (0, 0, 1); the - there is because we want to
// 'compensate' for that angle (a 'counter-angle')
double angleZ = -std::asin( (dir).z() );

// Make the matrix for that, assuming that Y is your 'side' vector; makes the model 'pitch'
glm::mat4 glmrotZ = glm::rotate( angleZ, glm::tvec3<double>( 0.0, 1.0, 0.0 ) );

object->setRotationMatrix( glmrotXY * glmrotZ );

```

This will cause a behaviour similar to the one of a camera in a 3rd person view kind of game (I'm thinking MMORPG style). It has the caveat that you can't have 'pos' *directly* above or below.

# Answer
> 2 votes
You just need the standard `lookat` function.

```
#include <glm/gtc/matrix_transform.hpp>

glm::vec3 const up(0.f, 0.f, 1.f);
object->setRotationMatrix(glm::lookAt(pos, target, up));

```

That’s all! Replace `(0.f, 0.f, 1.f)` with whatever you want your “up” vector to be.

# Answer
> 0 votes
If direction and up vectors are collinear, then you're in trouble. I think direction by itself is not enough to describe orientation in 3D space. So the answer is no, you can't just convert direction into rotation matrix.

---
Tags: c++, glm
---