# Question
Title: Display loading screen after scene change but wait for coroutine to finish
I thought I'd understood how coroutines work but I'm still experiencing problems getting them to run when I want them to run:

There are two scenes in my game: The main menu one and a game one. The main menu consists of a couple of buttons that let you choose a txt file and if you click on one of them, the "game" scene is loaded (`SceneManager.LoadScene("Game");`), which first thing reads the chosen txt file from HDD. Afterwards there's some other stuff that has to be finished (`FinishRest()`) but it's pretty quick anyway.

I want to display a loading screen while it's reading the file (no need to update it), which can take a while. Clicking on the button freezes the game in the main menu while the txt file is being read and it never displays the loading screen. That's why I put the actual reading part inside a coroutine and start it as soon as the "game" scene is loaded:

```
//In SciptA (derives from MonoBehaviour, is on the main camera)
void Awake() {
    loadingOperationReadTxt = StartCoroutine(ClassB.ReadTxtCoroutine());
    FinishRest();
}

//In ClassB (derives from ScriptableObject)
public IEnumerator ReadTxtCoroutine() {
    loadingPanel.SetActive(true);
    loadingPanel.GetComponentInChildren<Text>().text = "Reading txt file...";
    output = ClassC.ReadTXT(); //ClassC derives from nothing
    loadingPanel.SetActive(false);
    yield return null;
}

```

The problem is that it never displays the loading screen like this (I'm guessing because I don't let it tick until after I'm already done), so I tried to fix it by putting another `yield return null;` right before `output = ClassC.ReadTXT();`. Now it does display the loading screen but skips the rest of the coroutine and goes right to `FinishRest()`, which fails, of course, because it's missing the data from the txt file.

I want to display a loading screen but I also have to wait for the coroutine to finish before actually calling `FinishRest()` (I miss Tasks...). How can I accomplish this?

# Answer
> 1 votes
There are a couple of errors here:

1. `StartCoroutine` does just that - it *starts* the coroutine, running it up to its next `yield` statement and queuing it up to resume at the appropriate time.

It does not *wait* until the coroutine finishes completely before proceeding up to the next line of your `Awake` method, otherwise your game would freeze if you tried to start a long-running coroutine.

If you want to delay some work like `FinishRest()` until a coroutine has finished, you can either put that work at the end of the coroutine itself, or yield within an outer coroutine:

```
IEnumerator DoThisThenThat() {
    // Start doing "this" work, possibly spread across several frames.
    Coroutine thisWork = StartCoroutine(DoThisWork());
    // Let the game loop keep running normally
    // until "this" work has finished, before proceeding to the next line.
    yield return thisWork;
    // Now "this" work is done, and we can start "that" work.
    DoThatWork();
}
```
2. You're missing a `yield` somewhere inside your text-reading coroutine.

Remember, coroutines aren't threads. They're not running in parallel with the game's main loop, but taking turns within it.

So when you call `StartCoroutine(ReadTxtCoroutine())`, it's going to do all the work up to its first `yield` statement before returning control to the main game loop.

Since your only `yield` statement is at the very end, that means everything that `ReadTxtCoroutine()` does happens immediately, back-to-back, without a chance for the game loop to tick or display a frame in between.

If your `ReadTXT()` does some work asynchronously, you'll want to `yield` until that work is done before proceeding. Otherwise `loadingPanel.SetActive(true)` and `loadingPanel.SetActive(false)` will get called back-to-back in the same game frame, and you won't see the active state because it's been switched off again before the frame gets rendered.

If `ReadTXT()` does its work synchronously (ie. a blocking call), then your game will stall until it's done, because you haven't given the main game loop a chance to take its turn in-between by `yield`ing back to it. In cases like this we'll usually want to either run the blocking task on a thread instead, so it can happen in parallel, or chop it into small steps that we can `yield` in between so we don't impact the framerate or responsiveness.

---

Q&A:

> Isn't there some way to make some work wait until after the coroutine finishes?

Yes. The way I showed above, where you make another coroutine call the first coroutine, yield it until it's done, then do the work that's supposed to wait.

> I tried putting a yield right before ReadTXT(), which showed the loading screen but then didn't wait of course.

It sounds ReadTXT might be finishing its work asynchronously. In that case, you'll need to instrument it in some way so that your coroutine can detect when it's done and keep yielding to the game loop until then. To show you how to do that, we'll need you to show us what it's doing by including *all* relevant code in your question.

> It's not that easy to get coroutines to return stuff according to other posts.

Programming by hearsay will get you into trouble in Unity - there's a lot of flat-out wrong advice out there.

It's not hard to get data out of a coroutine, but because they don't execute synchronously, you need to not think of it as a return value.

Instead, you could pass in a status object or callback delegate when you start the coroutine, and the coroutine can store values into that for your code elsewhere to read them, or fire callback methods as needed.

Or you can have your coroutine fire an event or set flag variables when it gets data it wants to pass on to somewhere else.

> If ReadTXT throws an exception, then FinishRest and anything after the `yield` isn't called. Why is that?

Remember that the `StartCoroutine` call synchronously runs the coroutine up to its first `yield` statement.

So when your first `yield` is after `ReadTXT`, this is what your callstack looks like when the exception is thrown:

```
...Unity game loop stuff
    ScriptA.Awake
       StartCoroutine
          IEnumerator.MoveNext (ie. ClassB.ReadTextCoroutine)
             ClassC.ReadTXT

```

If none of those levels catches the exception, then the whole callstack is unwound up into the Unity game loop where it's finally output as an error message in your console log. Note that all this happens before `Awake` has had a chance to move on to the line after `StartCoroutine`, so it's aborted before it can `FinishRest()`.

# Answer
> 0 votes
This is what I ended up with (with DMGregory's help):

```
//In SciptA (derives from MonoBehaviour, is on the main camera)
void Awake() {
    waitingCoroutine = StartCoroutine(WaitForTxtToFinishCoroutine());
}
private IEnumerator WaitForTxtToFinishCoroutine() {
    Coroutine waitingForTxt = StartCoroutine(ClassB.ReadTxtCoroutine());
    yield return waitingForTxt;
    FinishRest();
}

//In ClassB (derives from ScriptableObject)
public IEnumerator ReadTxtCoroutine() {
    loadingPanel.SetActive(true);
    loadingPanel.GetComponentInChildren<Text>().text = "Reading txt file...";
    yield return null;
    output = ClassC.ReadTXT();
    loadingPanel.SetActive(false);
    yield return null;
}

//In ClassC (derives from nothing and isn't static)
public String ReadTXT() {
    StreamReader reader = new StreamReader(path);
    String line;
    int ii = 0;

    while((line = reader.ReadLine()) != null) {
        error = ProcessLine(line.Trim(),ii);

        if(!error.Equals("")) {
            return error;
        } else {
            ii++;
        }
    }
}

```

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


# Question
Title: how to set the length of a control point without changing its direction
Considering the image above, I want to manually increase the length of a bezier curve control point (`C3` to `newC3`) by a certain value (say 0.5f) while preserving it’s original direction. How can I do this?

# Answer
> 2 votes
You normalize the vector "C4\_C3" and multiply it by the new length it should have. Subtracting the coordinates of C4 with the coordinates of C3 (or the other way around) gives you the gradient between those two points. Normalizing it scales this gradient down so its length is 1. Multiplying with the new length results in a new gradient that you can add to your C4 coordinates.

normalization:

```
l = sqrt(x²+y²)
x = x / l;
y = y / l;

```

so in total:

```
x = c4.x - c3.x;
y = c4.y - c3.y;
l = sqrt(x²+y²)

x = c4.x + (x / l) * newLength;
y = c4.y + (y / l) * newLength;

```

---
Tags: unity
---


# Question
Title: The game is running but it gives me Object reference not set to an instance of an object error on console
When I play the game it works perfectly fine but it shows an error in the console when pressing buttons but it is still working just causing a bit of lag.

This is the error: NullReferenceException: Object reference not set to an instance of an object uiManager.Update () (at Assets/Scripts/uiManager.cs:31)

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

public class uiManager : MonoBehaviour {

public Button[] buttons;
public Button resume;
public Button pause;
public Text scoreText;
public Text hiScore;
public Text newHighScore;
public Text optionsResetPrompt;
int score;
bool gameOver;

// Use this for initialization
void Start () {
    pause.gameObject.SetActive(true);
    resume.gameObject.SetActive(false);
    gameOver = false;
    score = 0;
    InvokeRepeating("scoreUpdate", 0.5f, 0.25f);
    hiScore.text = PlayerPrefs.GetInt("highscore").ToString();
}

// Update is called once per frame
void Update () {
    scoreText.text = "" + score;
}

void scoreUpdate(){
    if (gameOver == false) {
        score += 1;
    }
}
public void gameOverActivated(){
    gameOver = true;
    pause.gameObject.SetActive(false);
    resume.gameObject.SetActive(false);
    foreach (Button button in buttons) {
        button.gameObject.SetActive(true);
    }
    int highestScore = PlayerPrefs.GetInt("highscore", 0);
    if (score > highestScore){
        PlayerPrefs.SetInt("highscore", score);
        newHighScore.gameObject.SetActive(true);
        }

}

public void Play() {
    SceneManager.LoadScene("level1");
}

public void Menu()
{
    SceneManager.LoadScene("Menu");
    if (Time.timeScale == 0)
    {
        Time.timeScale = 1;
    }
}

public void Reset()
{
    PlayerPrefs.DeleteKey("highscore");
    optionsResetPrompt.gameObject.SetActive(true);
}

public void Options()
{
    SceneManager.LoadScene("Options");
}

public void Retry()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    if (Time.timeScale == 0){
        Time.timeScale = 1;
    }
}

public void Pause() {

    if (Time.timeScale == 1) {
        Time.timeScale = 0;
        pause.gameObject.SetActive(false);
        resume.gameObject.SetActive(true);
        foreach (Button button in buttons)
        {
            button.gameObject.SetActive(true);
        }
    }

}
public void Resume() {

     if (Time.timeScale == 0) {
        Time.timeScale = 1;
        pause.gameObject.SetActive(true);
        resume.gameObject.SetActive(false);
        foreach (Button button in buttons)
        {
            button.gameObject.SetActive(false);
        }
    }
}
}

```

# Answer
> 0 votes
Such an error is caused, because the object: Text scoreText , is not assigned. I suppose you have an empty object in your scene, where you have placed the uiManager Script as a component. There, you will see all of your public variables and you will have to assign a value to them.

In this case, in the variable scoreText of uiManager script component, you will need to assign(drag n drop) your actual text object in your editor.

Cheers

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


# Question
Title: 2d sprite topples over due to circle collider
I am completely new to unity nd was trying to create a simple 2d platformer. I a trying to use a box collider and a circle collider for my Player. I am using circle collider because I have heard it helps more accurate collision detection for a player. The problem is that my player topples over when it falls to ground. Please tell me if there is any fix for my problem.

# Answer
> 1 votes
On the `RigidBody2D` component of your character, expand the `Constraints` dropdown. Here you can freeze your character's rotation around the Z-axis to prevent your character from falling.

---
Tags: unity, rigidbody
---


# Question
Title: How to paint regions of a map with visually different colors
I'm learning some concepts of procedural content generation. Now I'm generating a map with regions and each region has a diferent colors generated in a pseudo-random way.

My problem right now is that most of times (more probably when more regions exists), some regions has colors that are visually similar.

I want to control that adjacent colors are visually different, but still with some random component. What make colors different?

# Answer
> 5 votes
You could now go really deep into color theory to answer the question of what exactly makes two colors visually distinct. RGB is a color system for machines which doesn't map linearly to human perception. So if you want a *really good* formula, then it can get amazingly complex. And if you want your game to be accessible for people with various forms of color blindness, then you might have to offer some completely different alternative formulas.

But a quick-and-dirty solution could be to simply look at their respective difference of their R, G and B components and add them up. So if you have the colors `col1` and `col2`, then you could calculate their difference with

```
abs(col1.r - col2.r) +
abs(col1.g - col2.g) +
abs(col1.b - col2.b)

```

But now that we have this formula, what do we do if our algorithm placed two very similar colors next to each other? We could change one of them to a random other color, but now it might be too similar to one of its *other* neighbors. So changing one color could cause a ripple effect affecting all the other colors.

One solution I could think of would be to create four different color palettes 1 to 4. Make sure that none of the colors in one palette is visually close to a color in a different palette (you can have visually close colors in the same palette, though). Then pick colors from these palettes at random according to this schema:

```
12121212
34343434
12121212
34343434

```

Or in technical terms:

* If X is even and Y is even, use palette 1
* If X is odd and Y is even, use palette 2
* If X is even and Y is odd, use palette 3
* If X is odd and Y is odd, use palette 4

This means that all neighbors of a tile will be from a different palette. And because no color has a similar color in a different palette, you will never have two visually similar colors next to each other.

---
Tags: procedural-generation, color
---


# Question
Title: How do 3d game engines draw this pattern?
I am doing a small project, where there is a 3d engine, however I do not know how to draw something if it is like the image below. Usually I would draw from farthest back to closest. But here there is no order? How would modern 3d Engines draw this?

# Answer
The keyword you are looking for is z-buffering.

When a polygon-based rendering engine calculates the pixels covered by a triangle, it doesn't just calculate its x- and y-coordinates on the screen for each pixel, but also it's z-coordinate. The z-coordinate is its distance from the screen.

The engine also creates a z-buffer for each frame it renders. The z-buffer remembers if the engine already drew something to each x/y coordinate, and if it did, what z-coordinate that pixel had. Before the engine calculates the color of a new pixel, it checks if there is already a value in the z-buffer for these coordinates with a lower value than that of the current pixel. When there is, the pixel gets skipped. When there is not, both z-buffer and the image on the screen get overwritten by the current pixel.
> 4 votes

---
Tags: 3d
---


title: Unity and arduino processing

text:
# Question
Title: Unity and arduino processing
This question relates to this link: https://www.freetronics.com.au/blogs/news/6537043-experimenting-with-unity-processing-and-arduino#.W2-SFs4zbIU Does anyone have any idea how I would begin doing this? I cannot find the tutorial or code that relates to this. I have a cube on unity that changes colour and texture according to the input from a force sensing resistor. How would I get the cube to react in this way (as in the video)? Any assistance will be appreciated

In this video, a flexiforce sensor is housed in a cube. When the user presses the sensor, a cube on Unity reacts in the same manner that the real cube is squeezed; its basically a virtual version of what is happening to the cube in real life

# Answer
> 0 votes
This works well:

```
     using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.IO;
public class arduino : MonoBehaviour
{

    public SerialPort sp = new SerialPort("\\\\.\\COM5", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake()
    {
        Sphere = GameObject.FindWithTag("Player");
        m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
    }
    void Start()
    {
        if (!sp.IsOpen)
        {
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading

    }

    // Update is called once per frame
    void Update()
    {
        if (sp.IsOpen)
        { // Check to see if the serial port is open
            try
            {

                //string portreading = sp.ReadLine(); // get the string output of the serial port
                //float amount = int.Parse(portreading);
                string value = sp.ReadTo("EOL"); //Read the information
                float amount = float.Parse(value);

                if ((amount > 251f))
                {
                    m_Material.color = Color.red;
                    Renderer _rend = Sphere.GetComponent<Renderer>();
                    Sphere.GetComponent<Renderer>().material = _rend.material;
                    _rend.material.mainTexture = Resources.Load("face1") as Texture;
                    Sphere.transform.localScale = new Vector3( 2f, 0.03f*amount, 2f);
                    //Sphere.transform.position = new Vector3(2f, 2f , 2f);
                }
                else
                {
                    m_Material.color = Color.white;
                    Sphere.transform.localScale = new Vector3(2f, 10f, 8f);

                }
            }
            catch (System.Exception)
            {

            }
        }
    }

```

---
Tags: unity, input, processing, arduino
---


# Question
Title: How to constrain a ball and chain like object?
Following up on this question, I have created a snakelike enemy which consists of a head followed by segments. I get the segments to follow the head by constraining each segment's position relative to the segment in front of it. I get the difference between the actual distances between the segments and the desired distance, and correct that error 30% per frame.

The GDScript code looks like this:

```
for segment in [segment1, segment2, segment3, segment4, segment5, segment6]:
    # get actual distance between segment and its target
    var distance = segment.global_position.distance_to(segment.target.global_position)
    # find difference with desired distance
    var error = distance - desired_distance
    # move segment a percentage of the error toward its target segment
    var vector_to_target = (segment.target.global_position - segment.global_position).normalized()
    segment.global_position += vector_to_target * error * 0.30

```

I am happy with the result.

Now I want to create a similar enemy also composed of segments, but whose final segment is a kind of base, rooted to one position. Similar to the Chain Chomp from Mario.

I then want to code movement of the head, but for everything to be constrained. I'm guessing all intermediate segments would be doubly constrained by *both* of their neighbor segments, and the head itself would also have to be constrained by its neighbor segment, even though I'd be coding movement for it.

**I'm not sure how to set up constraints like these which have to look in both directions, and would appreciate any advice?**

Although I work in Godot, an engine-neutral explanation of the technique would suffice.

# Answer
> 1 votes
Assuming you are interested in having an enemy that behaves roughly like the Chain Chomp from Mario, rather than one that respects real-world rope physics, I can think of an approach that might work for you. To start with, consider the two possible cases:

1) The head of the snake is at the maximum distance, D, from the rooted point. That is, the chain is extended out as far as it can go.

2) The head of the snake is not at the maximum distance from the rooted point.

The first is the simple case, because when the chain/rope is fully extended, we can use linear interpolation to place each body segment. For example, if you have three body segments, you might do something like:

```
FirstSegment.X = (Base.X - Head.X) * 0.25
SecondSegment.X = (Base.X - Head.X) * 0.50
ThirdSegment.X = (Base.X - Head.X) * 0.75

```

This will space them out evenly, stretching them from the base, to the head. Just be mindful that this assumes Base.X is greater than Head.X. You will have to switch the order of the subtraction if this is not true.

The second case is the more interesting one. You can start by defining a distance, r, that constrains how far each segment can be from the one in front of it. That is, the first body segment must be within distance r from the head. The second body segment must be within distance r from the first segment, etc.

Then, each frame, starting at the first segment and proceeding backwards, you check whether that constraint is being met. If it's not met, that body segment should move towards. Consider how this will play out as the head of the snake moves:

From your post, I believe this is the effect you desire. For completion, in the Mario games, I believe gravity is applied to the body segments of the chain chomp any time it is not at maximum distance from its post. That is, the segments are either on the ground, or they are stretched out towards the chomp. I don't believe they ever "dangle" loosely in the air (unlike how a rope would behave in real life.) If I am mis-remembering, I apologize.

---
Tags: 2d, movement, joints, rope-physics
---


# Question
Title: How to access coordinates of objects in bullet physics (libGDX)?
I need to access the x, y and z coordinates of a bullet physics object. I'm assuming this is done via the transform matrix, but I have no idea which values mean what. There doesn't seem to be any information about it on the internet. How is this done? Is there a better was of doing it that I'm not aware of?

# Answer
> 0 votes
To access the x, y and z coordinates of a physics object, use the following code. Obj in this case is an instance of the class RigidBody, and a Vector3 containing the coords is being returned.

```
obj.getWorldTransform().getTranslation(new Vector3(0, 0, 0))

```

The Vector3 here is simply where the coords are stored. Bullet doesn't want to give you direct access to the vectors it uses so you don't mess them up, so you have to supply it with one.

# Answer
> 1 votes
*Note that this is only from reading the doc. I haven't actually tested anything of it.*

---

For some reasons, it appears that *Bullet Physics* uses the term "origin" for "translation".

I guess that once you've found the transform matrix you're after (`btTransform`), you'll need to use the `getTransform()` method to retrieve the translation vector.

There seems to be complete doc of Bullet Physics used in libGDX here.

Also, with the little knowledge I have of Bullet Physics, I think the proper approach to have your objects updated is to use the concept of *motion states*. From what I remember, it is the mechanism used to link your model's world's position and orientation to the physics world simulated by Bullet Physics. You supply Bullet with a reference to your matrix via the motion state, so whenever bullet updates the world, it updates the matrix automatically so you don't have to do it yourself.

I'm not familiar with Java/libGDX, and the last time I used Bullet was long ago, so I'll link to the documentation I found about it.

---
Tags: libgdx, matrix, coordinates, bullet-physics
---


# Question
Title: How to make sure an object NEVER passes through an edge collider (2D)?
In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right.

On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent.

How can I make sure that the ball always registers the collision?

Here's my setup:

The script I use to move the ball:

```
void Update () {
    switch (direction)
    {
        case 'u':
            transform.Translate(0f, ballSpeed * Time.deltaTime, 0f);
            break;
        case 'd':
            transform.Translate(0f, ballSpeed * -1 * Time.deltaTime, 0f);
            break;
        case 'l':
            transform.Translate(ballSpeed * -1 * Time.deltaTime, 0f, 0f);
            break;
        case 'r':
            transform.Translate(ballSpeed * Time.deltaTime, 0f, 0f);
            break;
    }
}

```

Additional info:
\- every wall is it's own object with it's own edge collider.
\- the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note: I had issues with the ball passing through walls even before I implemented the centering.

# Answer
This is happening because collisions happen in fixed update and you are moving the ball by its transform in the update. You should instead use Rigidbody.MovePosition, or apply a force to it instead or make it kinematic and move the transform but in Fixed update. Take a look at the rigidbody manual and this.
> 1 votes

---
Tags: unity
---


# Question
Title: Error: not all code paths return a value
I'm new to unity, so I've been having problems with my code here:

```
public bool FindItem(GameObject item)
{
    for (int i = 0; i < MyInventory.Length; i++)
    {
        if (MyInventory[i] == item)
        {
            //we found the item
            return true;
        }
        //if item not found
        return false;
    }
}

```

it shows this error : Assets/Script/Items/InventoryScript.cs(35,17): error CS0161: \`InventoryScript.FindItem(UnityEngine.GameObject)': not all code paths return a value

I've been looking for answers on the internet but nothing seems to give me solution to this problem. so I was hoping you could help me, thanks again in advance ! :)

# Answer
"Not all code paths return a value" means that inside a function that's supposed to explicitly return something (ie. it's not `void` or a constructor/IEnumerator), the compiler found a way to hit the end of the function without a `return` statement telling it what it's supposed to return.

In this case, this happens if `MyInventory.Length` is zero. What happens:

* We enter the for loop and set `i = 0`
* We check the for loop's test, is `i < MyInventory.Length`? No, zero is not less than zero.
* Since we failed the test, we exit the for loop immediately, without visiting any of the code inside (not the `if MyInventory[i] == item`, not the `return true`, not the `return false`
* Since there's nothing after the for loop, we hit the end of the function, but the compiler doesn't know what `bool` value the function should return because we haven't encountered a `return` statement.

Thus, the error.

To fix this in this case, you want to move the `return false` statement *outside* your for loop to the end of the function. When you put it inside the loop, the loop will check whether the item is in `MyInventory[0]`, and if not, it will always return false before it gets a chance to check `MyInventory[1]`. You want to `return true` if and only if we get through the *whole* array and don't find the item, not immediately after a single mismatch.

Or you can replace the whole thing with

```
public bool FindItem(GameObject item) {
    return System.Array.IndexOf(MyInventory, item) >= 0;
}

```

`IndexOf` returns -1 if the item isn't found in the array.

As Mikael says, this is a pure programming question that doesn't need game-specific expertise, so you can find answers to this elsewhere too.
> 5 votes

# Answer
If MyInvenyory does not contain any items the for loop will never execute, therefore it will skip the entire block of code.

To fix you should add a return statement after your loop.

Usually these kinds of questions are not encouraged since it's not directly related to gamedev and are more of a "debug my code" question, but since you are a new contributor I figured I might answer it anyway.
> 1 votes

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


# Question
Title: Turning on Vertex Attribute Divisor With Instanced Rendering Renders Nothing
When I render with glDrawArraysInstanced with the vertex attribute divisor set to zero, the triangle appears as expected. But when the divisor is set to any value other than zero, the triangle disappears. This is the code I am using to render:

```
static const u32 NUM_TRIANGLES = 1;
struct Vertex
{
    f32 x;
    f32 y;
 };
 static const Vertex g_triangles[NUM_TRIANGLES*3] =
 {
    {0.125f, 0.125f},{-0.125f,0.125f},{-0.125f,-0.125f},
 };
 glGenVertexArrays(1, &g_vao);
 glBindVertexArray(g_vao);

 glGenBuffers(1, &g_vbo);
 glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
 glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangles), nullptr,
             GL_DYNAMIC_DRAW);
 glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(g_triangles),
                reinterpret_cast<const void*>(&g_triangles));
 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0,
                       reinterpret_cast<void*>(0));
 glEnableVertexAttribArray(0);
 glVertexAttribDivisor(0, 1); // Setting this to 0 renders the triangle

 // This is the draw call
 glDrawArraysInstanced(GL_TRIANGLES, 0, 3, NUM_TRIANGLES);

```

Here are my shaders:

```
#version 420 core
layout (location = 0) in vec2 v;
void main()
{
    gl_Position = vec4(v, 0.0f, 1.0f);
}

#version 420 core
out vec4 out_color;
void main()
{
    out_color = vec4(1.0f,0.0f,0.0f,1.0f);
}

```

My problem is similar to OpenGL 2D instancing: glDrawArraysInstanced with a divisor renders nothing, but that question wasn't resolved.

# Answer
Setting the attrib divisor means that each instance gets 1 copy of the attribute.

In your case it's easier to do

```
glDrawArrays(GL_TRIANGLES, 0, 3*NUM_TRIANGLES);

```

Otherwise you need to make the offset a second attribute and then add them together in the vertex shader:

```
#version 420 core
layout (location = 0) in vec2 v;
layout (location = 1) in vec2 instance_offset;

void main()
{
    gl_Position = vec4(v+instance_offset, 0.0f, 1.0f);
}

```

and to bind it:

```
 static const Vertex g_triangles[3] =
 {
    {0.125f, 0.125f},{-0.125f,0.125f},{-0.125f,-0.125f},
 };
 static const Vertex g_offsets[NUM_TRIANGLES] =
 {
    {0f,0f},//...
 };
 glGenVertexArrays(1, &g_vao);
 glBindVertexArray(g_vao);

 glGenBuffers(1, &g_vbo);
 glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
 glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangles), nullptr,
             GL_DYNAMIC_DRAW);
 glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(g_triangles),
                reinterpret_cast<const void*>(&g_triangles));
 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0,
                       reinterpret_cast<void*>(0)); glGenBuffers(1, &g_vbo);

 glGenBuffers(1, &g_offset_vbo);
 glBindBuffer(GL_ARRAY_BUFFER, g_offset_vbo);
 glBufferData(GL_ARRAY_BUFFER, sizeof(g_offsets), nullptr,
             GL_DYNAMIC_DRAW);
 glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(g_offsets),
                reinterpret_cast<const void*>(&g_offsets));
 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
                       reinterpret_cast<void*>(0));
 glVertexAttribDivisor(1, 1);

```
> 1 votes

---
Tags: opengl, rendering, vertex-attribute
---


# Question
Title: Need help deciding on an ability system in Unity
I'm making an RPG and got to the point where I want a player to be able to use abilities. I decided to use a command pattern to keep keybindings flexible and now I've arrived with the following dilemma:

Command is an abstract class with an abstract method called Execute(). Every ability has a command class (for example FireBallCommand). I have a PlayerInput class. All buttons and the abilities that belong to it are defined there:

```
public class PlayerInput : MonoBehaviour {

private Command buttonF;
private Command buttonQ;

private PlayableCharacter character;

void Awake () {
    character = GetComponent<PlayableCharacter>();
    Initialize();
}

void Initialize()
{
    //Setup controls here
    //TODO: Get user's saved controls from db

    //Temporarily hardcoded
    buttonF = new BasicAttackCommand();
    buttonQ = new FireBallCommand();
}

void Update () {
    if (Input.GetKeyDown(KeyCode.F))
    {
        buttonF.Execute(character);
    }
    if (Input.GetKeyDown(KeyCode.Q))
    {
        buttonQ.Execute(character);
    }
}
}

```

The FireBallCommand class looks like this, (atm it creates a GameObject because Command does not derive from MonoBehaviour because I read you should/cant create object using 'new' with MonoBehaviours, in code):

```
public class FireBallCommand : Command {

public override void Execute(PlayableCharacter character)
{
    GameObject go = new GameObject();
    go.AddComponent<FireBall>();
    go.name = go.GetComponent<FireBall>().Name;
    go.GetComponent<FireBall>().Execute(character);
}
}

```

Next, the abstract class Ability contains an abstract method Execute() as well. It also contains some properties such as name and cooldown. The actually ability derives from Ability and actually executes the ability:

```
public class FireBall: Ability {

PlayableCharacter character;

public override void Execute(Character character)
{
    this.character = character as PlayableCharacter;
    StartCoroutine(Fire());
}

IEnumerator Fire()
{
    //Here it fires the fireball but there's no need to post that here.
}
}

```

This is the first time I am making a system like this. The dilemma is that I am not sure whether this is a right way to do it. It feels like casting one ability or spell is passing way to many classes and taking too much code in general. I thought of creating an AbilityManager that is always in the scene, which could be called to cast any spell/ability and takes a player as parameters.

In short: Do you think this would be a fine and fairly clean way to create an ability system? What other way(s) do you suggest? What could I change/remove/add to improve it?

P.S if anyone feels like answering this. I'm not sure where and how to implement cooldowns for the abilities in this system. Got an idea? :)

Thanks a lot in advance guys, if there's anything I should provide please let me know.

# Answer
A very "unity" solution which I am using in one of my project would be to **use prefabs to represent abilities**. When the `PlayerCharacter` class uses an ability, it does nothing but instantiate a prefab which was previously assigned through the inspector. The prefab is then responsible for doing everything else about the ability. The prefab either *is* a fireball projectile with Renderer, ParticleSystem, Rigidbody, Collider, scripts, etc., or it is just an invisible game object which just does its job and then immediately destroys itself.

To implement cooldowns you could create a class like this:

```
[System.Serializable]
public class AbilitySlot {
      public GameObject abilityPrefab;
      public float cooldownTime;
      [HideInInspector] public float cooldownTimeLeft;
      public int manaCost;
      public KeyCode hotkey;

}

```

and then have a `public AbilitySlot[] abilitySlots` in your player class to keep track of all the abilities available to the player. You should then be able to edit this array in the inspector to assign the ability prefabs, set the cooldown time, the mana cost and assign a hotkey.

When the MonoBehaviour which handles the movement and damage mechanics of your fireball is also sufficiently data-driven, then this architecture should allow you to add a new ability without writing a single line of code.
> 4 votes

# Answer
I agree that @Philipp's answer is a very "Unity approach" and isn't inherently bad, however I've found that I strongly dislike having prefabs lying around in wait.

You can, however, instantiate a prefab without having it already present and waiting. I tend to use a controller class for things like this (one for abilities/spells, one for maybe loot or the like, etc). The controller sits on a Controller prefab that doesn't destroy as scenes are switched, and can be called to generate anything anywhere in the scene as needed. It also allows for some interesting and quick changes - say using a fireball spell as a trap that originates from a rune or some mechanical spout.

Conversely, if you use this approach it may be worthwhile to use a object pool in the event that you need more than one of a given gameObject at once.
> 2 votes

---
Tags: unity, c#, architecture, rpg, combat
---


title: Unity - SpriteAtlas memory consumption

text:
# Question
Title: Unity - SpriteAtlas memory consumption
I'm in the process of optimizing my application memory consumption. To do so, I'm using Unity profiler while connecting to an Android device, which runs a development build of the application.

The application is using two types of sprite containers:

1. Sprite sheets created by the Texture packer.
2. Sprite Atlases created by unity.

Using the profiler, it is observed that while the sprite sheets (created by the Texture packer) take the expected amount of RAM, the sprite atlases created by unity consume DOUBLE the expected amount of RAM.

For example, the sprite atlas UIATLAS, whose size is 4096x4096 is supposed to consume 16MB of RAM:

But looking at the profiler, after running "Take Sample", you see the value 32MB:

My sprite atlas settings are:

Any help is welcome here.

One more comment (please review): UIAtlas belongs to an asset bundle called "atlas\_ui". It is defined on several directories containing its sprites, all of which belong to the same asset bundle, atlas\_ui. Is that the correct way to define it?

Thanks in advance!

# Answer
I'm not 100% certain, but I think your texture setting "Read/Write Enabled" may be the root cause. The texture on the GPU cannot be written to (it can be replaced, but not written to), so a writable copy is kept on the CPU (which also requires memory).

I apologize for a less than certain answer, but it's an easy thing to test and I think it may resolve your issue.
> 1 votes

---
Tags: unity, optimization, spritesheet, memory-efficiency, profiler
---


# Question
Title: Using multiple textures in Monogame HLSL Effect shader?
My Monogame HLSL shaders only successfully sample one texture (besides the screen). Any additional textures I try to sample end up with the same texture data as the screen.

I've found people with similar issues as me, such as this thread. However, I'm unsure of what they've done to remedy the problem. Any solutions I've seen in other threads don't work.

**C#**

```
Lighting.Parameters["NightTexture"].SetValue(night);
Lighting.Parameters["SunsetTexture"].SetValue(sunset);

```

**HLSL**

```
float4x4 World;
float4x4 View;
float4x4 Projection;

Texture2D NightTexture;
sampler2D NightSampler = sampler_state
{
    Texture = <NightTexture>;
};

Texture2D SunsetTexture;
sampler2D SunsetSampler = sampler_state
{
    Texture = <SunsetTexture>;
};

sampler TextureSampler : register(s0);

float4 main(float4 position : SV_Position, float4 color : COLOR0, float2
texCoord : TEXCOORD0) : COLOR0
{
    // Different Grading
    float4 day = tex2D(TextureSampler, texCoord);
    float4 night = tex2D(NightSampler, texCoord);
    float4 sunset = tex2D(SunsetSampler, texCoord);

    float4 col = lerp(day, night, .5);
    col = lerp(sunset, col, .5);

    return col;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_5_0  main();
    }
}

```

Note: The code is abbreviated to show the issue. When executed, the SunsetTexture and TextureSampler both have correct data, but the NightTexture copies the TextureSampler's data.

Any ideas how to fix this?

# Answer
> 1 votes
Looks like it's just a matter of using textures in the right order.

```
float4x4 World;
float4x4 View;
float4x4 Projection;

sampler TextureSampler : register(s0);

Texture2D NightTexture;
sampler2D NightSampler = sampler_state
{
    Texture = <NightTexture>;
};

Texture2D SunsetTexture;
sampler2D SunsetSampler = sampler_state
{
    Texture = <SunsetTexture>;
};

float4 main(float4 position : SV_Position, float4 color : COLOR0, float2
texCoord : TEXCOORD0) : COLOR0
{
    float4 day = tex2D(TextureSampler, texCoord);
    float4 night = tex2D(NightSampler, texCoord);
    float4 sunset = tex2D(SunsetSampler, texCoord);

    float4 col = lerp(day, night, .5);
    col = lerp(sunset, col, .5);

    return col;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_5_0  main();
    }
}

```

I moved TextureSampler to the top.

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


title: Health and Medicine

text:
# Question
Title: Health and Medicine
I want to have a health system in my game and I was thinking that every character should have the following

* Health (HP basically) - when it reaches 0 it dies
* Wounds - physical injuries, can have multiple levels of severity (minor to lethal)
* Illness - same as wounds, but require a different type of medicine to heal
* Nutrition - they require food

The wounds will require bandages to heal and a medic to apply them. There are multiple tiers of bandages, from basic cloth bandages to sterilized bandages. Each tier of bandages are effective up to a certain severity of wounds, after the severity passed that threshold their effectiveness should decrease. The medic's skill should affect the effectiveness, "advanced" bandages should require higher skill to apply. If the medic's skill is not enough, they can still apply it, but it's effectiveness should be decreased.

The illnesses are exactly the same, but require antibiotics for treatment instead of bandages.

I want the behavior to be something in the lines of

* Low severity wounds or illnesses can heal on their own
* The severity can get worse if untreated
* The chances of recovery to be affected by the HP and the nutrition

The rest of the game is tick based, and I can update a character's state every tick.

I know "This War of Mine" has a really similar behavior, but I just can't wrap my head around on how this should be designed in a tick-based game. I came up with an idea, but it seems needlessly complicated to do.

## My Idea in a Nutshell

Represent Wound's and Illnesses' severity as a double ranging from \[0.0, 1.0\] where 1.0 is the worst possible illness.

The characters will also have a recovery chance, that will change every tick based on their state (severity, bandage/meds eff, HP, nutrition)

A bandage efficiency and meds efficiency will also be present on the character's state, again from \[0.0, 1.0\] where 0.0 means no bandage/meds and 1.0 means top tier bandage/meds applied by a skillful medic.

After a set number of ticks the recovery chance will "proc" and either completely heal the character or make the disease worse and remove any applied bandages/meds.

The problem with my approach is that I think it's way too complicated to fit into a math formula that computes the delta recovery chance.

Is there a better approach? Is my idea too complicated and I should simplify it a bit?

# Answer
> 1 votes
It is difficult to judge how a specific mechanic is going to work in the context of a larger game. It depends on how many other mechanics you have which compete for the player's attention, how well your UI informs the player about all the information required to understand the mechanic and how many opportunities your game gives to the player to make meaningful decisions based on your mechanics.

But my gut instinct says that you are overcomplicating game mechanics just for the sake of complicating them. It is usually a better approach to design and implement a very simple solution first, do some testplaying to see how it works, and then see if adding more complexity will make the mechanics more interesting or just make your game harder to understand.

---
Tags: game-design
---


title: How to eliminate roll rotation?

text:
# Question
Title: How to eliminate roll rotation?
Let's say I have Rotation(0, 0, 180) \[pitch, yaw, roll\]. How to do it that I would have Rotation(180, 180, 0) which is exactly the same?

# Answer
To keep track of orientation, and orientation changes, you are often better off using two perpendicular vectors, as opposed to three angles.

* A "look-at" or "forward" vector.
* An up-vector.

Taking the cross product of these two will give you a vector perpendicular to both, and can be used for your transformation matrix.

To derive the basis, remember:

```
X = Y × Z
Y = Z × X
X = X × Y

```

If you were to switch the order of the product's arguments, you switch between LH and RH coordinate systems.

Using three angles is called "Euler Angles."

There are also Quaternions that can be used to keep track of orientation and orientation changes. But I find two vectors to be more intuitive.

To summarize: two perpendicular unit vectors uniquely describe an orientation.
> 1 votes

---
Tags: rotation
---


title: Unity: Draw a trench onto a terrain

text:
# Question
Title: Unity: Draw a trench onto a terrain
I am making an RTS game and want to add the ability to dig a trench without redrawing the whole terrain as that is causing lag. The solution would need to allow a user to build a trench on the map and have a unit able to stand in the trench. The game is using 3d models at the moment.

My first thought was to have the trench on a layer that is rendered on top of the layer with the terrain but that would give the problem that a trench would be seen even if it was behind a hill.

Is there an alternative or a solution?

# Answer
> 1 votes
Divide the terrain into sections, then replace only the section where the trench is dug. This technique speeds up the game.

---
Tags: unity
---


# Question
Title: Help with the calculation of the usage of my speed stat
I am working on a freeroam, action RPG (before you read further, I am not noobish to programming, plus have friends to help with actual content rather than the base code). Anyway, I am trying in Skills to the game. I decided the movement-based skills and animations should be a priority, so I began integrating it in. The animations work fine, but alas my movement skill Athleticism is making the character move unrealistically fast at a higher skill. The skill ranged from 1 to 100. After realising I should do some calculations to make you go from normal to Sonic the Hedgehog, I am using this formula currently:

(Athleticism / Mathf.Sqrt(Athleticism)) * 0.05f * runMod;

This has helped, but it still looks weird. I need some help to make a formula that **makes that the skill doesn't have such of a linear effect on the movement.**

EDIT:

Trying to be specific. The player moves, currently about 0.05 walking units per second at Athleticism 10, which is nice. However, the movement rate at Athleticism 100 cranks up to 0.15 units, which is a little too fast. I am aiming for 0.1 instead.

# Answer
If you want athleticism to improve the movement rate from 0.05 by another 0.05 to a total of 0.1, then there is a very easy formula for that:

```
speed = 0.05f + 0.05f * (Athleticism / 100.0f);

```

or more generally expressed:

```
value = minimum + possibleImprovement * (currentLevel / maximumLevel);

```

If you want the increase to be some form of non-linear progression, then you might want to toy with the `(currentLevel / maximumLevel)` part. Just make sure you end up with some function which returns values between 0.0 and 1.0 so the result still hits into the range between your desired minimum and maximum speed.
> 3 votes

---
Tags: unity, mathematics
---


# Question
Title: How can I write a dots effect shader when the character is behind an object?
I watched an interesting effect while I was playing Super Mario Odyssey: when Mario or another character was behind an obstacle (walls, etc), a tiny gray silhouette mesh appears.

I tried to build something similar using an amplify shader with Unity but I could not achieve it.

How could I write this?

Here is an example from the game:

# Answer
In Amplify forum I found this shader:

> We've performed some changes to the XRay sample in order to allow for the effect that you've requested.
>
> Here's a package that contains updated shaders, together with materials and \>sample scene:
>
> XrayWithIntersections.unitypackage
>
> http://amplify.pt/forum/viewtopic.php?f=8&t=710

you can easily make this effect by using `ZTEST Operators`:

render first pass by unlit gray color and `ZTEST Greater` ,`ZWrite Off`.

as you can see when mario is behind of something it will be gray:

then render second pass Albedo by `ZTest Default(ZTEST LEqual)`:

to making dots effect you can sample your texture by screen space-mapped texture sample or dithering.

I wrote this shader without Amplify:

```
Shader "Custom/Mario/DotsBehindWall" {
    Properties {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Dots("Dots",2D) = "white"{}
        _Size("Size",Vector) = (1,1,1,1)
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        GrabPass
        {
            "_BackgroundTexture"
        }

        ZWrite Off
        ZTest Greater

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float4 grabPos : TEXCOORD1;
            };

            sampler2D _MainTex,_Dots;
            float4 _MainTex_ST;
            float4 _Size;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float2 screen = i.vertex.xy/_ScreenParams.xy;
                float4 tex = tex2D(_Dots, screen /_Size);
                return tex;
            }
            ENDCG
        }
        ZWrite On
        ZTest LEqual

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows

        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

another way to make this effect is using stencil buffer that I explained In this post
> 1 votes

---
Tags: unity, shaders, cg
---


# Question
Title: Making a Java Swing game a browser based game
I have made a game in Java using Swing for the GUI.
It is a network game relying on the client-server model.
Basically the game is a turned-based chess-like game. It has a connection menu, game searching screen and a game screen.
Graphics are simple, it's just rendering a board with pieces in 2D.

I want to make this game a browser game.
At first I thought of Java EE. Making the game an applet and embed it in a JSP but it doesn't seem to be a good solution.
So I did some research looking for open source solutions.
I came across the Play Framework that allow to write web apps in Java. Play seems good but I dont know if I can reuse my Swing GUI with it.
I also encountered the libGDX framework.
Finally, some say that HTML5 is the way to god for a 2D browser games, combined with the framework Phaser.

Which technology would fit for this kind of game and should I go for ?
I would like to stick with Java if possible.

Any advice or solution suggestion would be appreciated
Thank you

# Answer
It used to be possible to deploy Java applications on the web in form of java applets. But several security holes were found in the technology. So the browser vendors no longer support it.

If you want to turn your game into a browser game, then you won't get around to reimplement it from scratch as a HTML5/Javascript application. Phaser is just one of many game development frameworks on top of Javascript. Which one is the best for you and your game is a matter of personal preference.
> 1 votes

---
Tags: java, browser-based-games, swing
---


# Question
Title: Too many if statements, How can i take a whole bunch if statements that check 13 separate lists more optimally?
I have a 13 if statements that check 13 separate lists to check if a value is in that particular list. Now surely there's a better way of doing this because I'm going to have to do this 12 more times and that'll get messy.

```
  void Start()
{
    spline = GameObject.Find("Spline");
    SplinePath = spline.GetComponent<PathGenerator>();
    splineSplices = SplinePath.slices;
    Player = GameObject.FindGameObjectWithTag("Player").transform;
    splineMesh = spline.GetComponent<MeshFilter>().mesh;
    trisLenght = splineMesh.triangles.Length;
    blocksObjects = new GameObject[trisLenght];

    //Lane 1
    for (int i = 0; i < trisLenght; i += 26)
    {
        lane1Index.Add(i);
    }

    for (int i = 2; i < trisLenght; i += 26)
    {
        lane2Index.Add(i);
    }

    //Lane 3
    for (int i = 4; i < trisLenght; i += 26)
    {
        lane3Index.Add(i);
    }

    for (int i = 6; i < trisLenght; i += 26)
    {
        lane4Index.Add(i);
    }

    //Lane 5
    for (int i = 8; i < trisLenght; i += 26)
    {
        lane5Index.Add(i);
    }

    for (int i = 10; i < trisLenght; i += 26)
    {
        lane6Index.Add(i);
    }

    for (int i = 12; i < trisLenght; i += 26)
    {
        lane7Index.Add(i);
    }

    for (int i = 14; i < trisLenght; i += 26)
    {
        lane8Index.Add(i);
    }

    for (int i = 16; i < trisLenght; i += 26)
    {
        lane9Index.Add(i);
    }

    for (int i = 18; i < trisLenght; i += 26)
    {
        lane10Index.Add(i);
    }

    for (int i = 20; i < trisLenght; i += 26)
    {
        lane11Index.Add(i);
    }

    for (int i = 22; i < trisLenght; i += 26)
    {
        lane12Index.Add(i);
    }

    for (int i = 24; i < trisLenght; i += 26)
    {
        lane13Index.Add(i);
    }
}
  void Update()
{
    Vector3 prev_up = Player.transform.up;
    RaycastHit hit;

    if (Input.GetKey(KeyCode.W))
    {
        //raycast down to get the triangle index that were currently on
        if (Physics.Raycast(Player.transform.position, -prev_up, out hit) && !GameObject.Find("TriParentA") && !GameObject.Find("TriParentB"))
        {
            CreateBlockOnLane13(hit.triangleIndex);
            CreateBlockOnLane1(hit.triangleIndex);

            if (audioPeer.audioBand64[2] > oldFrequency && audioPeer.audioBand64[2] > .5f)//Creates a new block to the beat
            {
                //pick a random index from 0 - 12
                int randomLane = Random.Range(1, 12);
                ChooseRandomLane(randomLane, hit.triangleIndex);

            }
             oldFrequency = audioPeer.audioBand64[2];
         }
    }
}

void ChooseRandomLane(int randomLane, int triangleIndex)
{
    switch (randomLane)
    {

        case 0://every other space
            CreateBlockOnLane13(triangleIndex);
            CreateBlockOnLane11(triangleIndex);
            CreateBlockOnLane9(triangleIndex);
            CreateBlockOnLane7(triangleIndex);
            CreateBlockOnLane5(triangleIndex);
            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane1(triangleIndex);
        break;
        case 1://every other space
            CreateBlockOnLane12(triangleIndex);
            CreateBlockOnLane10(triangleIndex);
            CreateBlockOnLane8(triangleIndex);
            CreateBlockOnLane6(triangleIndex);
            CreateBlockOnLane4(triangleIndex);
            CreateBlockOnLane2(triangleIndex);
            break;
        case 2://5 gap in middle
            CreateBlockOnLane13(triangleIndex);
            CreateBlockOnLane12(triangleIndex);
            CreateBlockOnLane11(triangleIndex);
            CreateBlockOnLane10(triangleIndex);

            CreateBlockOnLane4(triangleIndex);
            CreateBlockOnLane2(triangleIndex);
            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane1(triangleIndex);
            break;
        case 3://3 gap in middle
            CreateBlockOnLane13(triangleIndex);
            CreateBlockOnLane12(triangleIndex);
            CreateBlockOnLane11(triangleIndex);
            CreateBlockOnLane10(triangleIndex);
            CreateBlockOnLane9(triangleIndex);

            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane4(triangleIndex);
            CreateBlockOnLane2(triangleIndex);
            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane1(triangleIndex);
            break;
        case 4:
            CreateBlockOnLane13(triangleIndex);
            CreateBlockOnLane12(triangleIndex);
            CreateBlockOnLane11(triangleIndex);
            CreateBlockOnLane10(triangleIndex);
            CreateBlockOnLane9(triangleIndex);

            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane4(triangleIndex);
            CreateBlockOnLane2(triangleIndex);
            CreateBlockOnLane3(triangleIndex);
            CreateBlockOnLane1(triangleIndex); break;
        case 5:
            CreateBlockOnLane7(triangleIndex);
            break;
        case 6:
            CreateBlockOnLane8(triangleIndex);
            break;
        case 7:
            CreateBlockOnLane9(triangleIndex);
            break;
        case 8:
            CreateBlockOnLane10(triangleIndex);
             break;
        case 9:
            CreateBlockOnLane11(triangleIndex);
            break;
        case 10:
            CreateBlockOnLane12(triangleIndex);
        break;

    }
}
    void CreateBlockOnLane13(int triangleIndex)
{
    if (lane1Index.Contains(triangleIndex))
    {
        currentLane = 1;
        SpawnBlockAtIndex(triangleIndex + 1168); //+=26
    }

    if (lane2Index.Contains(triangleIndex))
    {
        currentLane = 2;
        SpawnBlockAtIndex(triangleIndex + 1166); //+=26
    }

    if (lane3Index.Contains(triangleIndex))
    {
        currentLane = 3;
        SpawnBlockAtIndex(triangleIndex + 1164); //+=26
    }

    if (lane4Index.Contains(triangleIndex))
    {
        currentLane = 4;
        SpawnBlockAtIndex(triangleIndex + 1162); //+=26
    }

    if (lane5Index.Contains(triangleIndex))
    {
        currentLane = 5;
        SpawnBlockAtIndex(triangleIndex + 1160); //+=26
    }

    if (lane6Index.Contains(triangleIndex))
    {
        currentLane = 6;
        SpawnBlockAtIndex(triangleIndex + 1158); //+=26
    }

    if (lane7Index.Contains(triangleIndex))
    {
        currentLane = 7;
        SpawnBlockAtIndex(triangleIndex + 1156); //+=26
    }

    if (lane8Index.Contains(triangleIndex))
    {
        currentLane = 8;
        SpawnBlockAtIndex(triangleIndex + 1154); //+=26
    }

    if (lane9Index.Contains(triangleIndex))
    {
        currentLane = 9;
        SpawnBlockAtIndex(triangleIndex + 1152); //+=26
    }

    if (lane10Index.Contains(triangleIndex))
    {
        currentLane = 10;
        SpawnBlockAtIndex(triangleIndex + 1150); //+=26
    }

    if (lane11Index.Contains(triangleIndex))
    {
        currentLane = 11;
        SpawnBlockAtIndex(triangleIndex + 1148); //+=26
    }

    if (lane12Index.Contains(triangleIndex))
    {
        currentLane = 12;
        SpawnBlockAtIndex(triangleIndex + 1146); //+=26
    }

    if (lane13Index.Contains(triangleIndex))
    {
        currentLane = 13;
        SpawnBlockAtIndex(triangleIndex + 1144); //+=26
    }
}
 void CreateBlockOnLane12(int triangleIndex)
{
    distribution = 5;

    if (lane1Index.Contains(triangleIndex))
    {
        currentLane = 1;
        SpawnBlockAtIndex(triangleIndex + 1166); //+=26
    }

    if (lane2Index.Contains(triangleIndex))
    {
        currentLane = 2;
        SpawnBlockAtIndex(triangleIndex + 1164); //+=26
    }

    if (lane3Index.Contains(triangleIndex))
    {
        currentLane = 3;
        SpawnBlockAtIndex(triangleIndex + 1162); //+=26
    }

    if (lane4Index.Contains(triangleIndex))
    {
        currentLane = 4;
        SpawnBlockAtIndex(triangleIndex + 1160); //+=26
    }

    if (lane5Index.Contains(triangleIndex))
    {
        currentLane = 5;
        SpawnBlockAtIndex(triangleIndex + 1158); //+=26
    }

    if (lane6Index.Contains(triangleIndex))
    {
        currentLane = 6;
        SpawnBlockAtIndex(triangleIndex + 1156); //+=26
    }

    if (lane7Index.Contains(triangleIndex))
    {
        currentLane = 7;
        SpawnBlockAtIndex(triangleIndex + 1154); //+=26
    }

    if (lane8Index.Contains(triangleIndex))
    {
        currentLane = 8;
        SpawnBlockAtIndex(triangleIndex + 1152); //+=26
    }

    if (lane9Index.Contains(triangleIndex))
    {
        currentLane = 9;
        SpawnBlockAtIndex(triangleIndex + 1150); //+=26
    }

    if (lane10Index.Contains(triangleIndex))
    {
        currentLane = 10;
        SpawnBlockAtIndex(triangleIndex + 1148); //+=26
    }

    if (lane11Index.Contains(triangleIndex))
    {
        currentLane = 11;
        SpawnBlockAtIndex(triangleIndex + 1146); //+=26
    }

    if (lane12Index.Contains(triangleIndex))
    {
        currentLane = 12;
        SpawnBlockAtIndex(triangleIndex + 1144); //24
    }

    if (lane13Index.Contains(triangleIndex))
    {
        currentLane = 13;
        SpawnBlockAtIndex(triangleIndex + 1142); //24
    }
}

```

# Answer
Given your construction, you don't need to search your lists at all. You can compute the lane number directly by examining the index:

```
int TriangleIndexToLane(int triangleIndex) {
    return (triangleIndex >> 1) % 13 + 1;
}

```

Then your creation method simplifies to:

```
void CreateBlock(int triangleIndex, int laneOffset) {
    currentLane = TriangleIndexToLane(triangleIndex);
    int offset = 1144 + 2 * (laneOffset - currentLane);
    SpawnBlockAtIndex(triangleIndex + offset);
}

```

And your various switch cases become:

```
void ChooseRandomLane(int randomLane, int triangleIndex)
{
    switch (randomLane)
    {
    case 0://every other space
        CreateBlock(triangleIndex, 13);
        CreateBlock(triangleIndex, 11);
        CreateBlock(triangleIndex, 9);
        CreateBlock(triangleIndex, 7);
        CreateBlock(triangleIndex, 5);
        CreateBlock(triangleIndex, 3);
        CreateBlock(triangleIndex, 1);
    break;
    case 1://every other space
        CreateBlock(triangleIndex, 12);
        CreateBlock(triangleIndex, 10);
        CreateBlock(triangleIndex, 8);
        CreateBlock(triangleIndex, 6);
        CreateBlock(triangleIndex, 4);
        CreateBlock(triangleIndex, 2);
        break;
    case 2://5 gap in middle
        CreateBlock(triangleIndex, 13);
        CreateBlock(triangleIndex, 12);
        CreateBlock(triangleIndex, 11);
        CreateBlock(triangleIndex, 10);

        CreateBlock(triangleIndex, 4);
        CreateBlock(triangleIndex, 3);
        CreateBlock(triangleIndex, 2);
        CreateBlock(triangleIndex, 1);
        break;
    ...

```
> 6 votes

# Answer
May be have list of LaneXIndex itself and use foreach or for loop
> 1 votes

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


# Question
Title: Is there any way to detect cpu/battery temperature on Android 7.0+ platform in Unity?
I tried WeTest but it's not working because my test device is Android 8.1. Also, I tried Emmagee however it's just working on Android 6.0 and below. Is there any other thing?

# Answer
> 0 votes
Refer to Unity Android Sensor Plugin I made an Android plugin for Unity and successfully printed battery temperature. Due to the privacy of my company, I can't give the code I made but if you are interested in building Android plugin for Unity, I recommend Get temperature of battery on android to begin.

---
Tags: unity
---


# Question
Title: Do all normalized quaternions represent valid rotations?
Basically, I'm getting a bug where the rotations in the animations seem to be skewing the model even though I'm normalizing them. I suspect that the rotations are showing the error, but not causing it, if that makes sense. But that's based on the idea that a normalized quaternion can't skew a model.

# Answer
> 1 votes
Yes. There are two equivalent normalized quaternions for every orientation in 3D space (the unit quaternions form a double cover over the space of orientations), and every unit quaternion can be expressed as an angle-axis rotation.

If you're observing skewing, then it's not from your quaternions themselves, but could be due to non-uniform scales at parent levels of your hierarchy, or a math error somewhere. We'll need to see more of your implementation to advise, though.

Consider asking a question "How do I solve this unwanted skew in my skeletal animation?" instead.

---
Tags: quaternion, skeletal-animation
---


# Question
Title: Will working with a publisher help me prevent my game from being cloned?
I read many articles on "How (or why not without) to make mobile game without publisher". But the question that bothers me is:

"What if I make a game, that really hits the market in the eye and people start playing it BUT some publisher will see my game and make the very similar game in 2 weeks and makes it ever more succesfull?"

Is this the main reason why I should choose to go with the publisher?

**EDIT: My main concern is not about my weeks spent on developing (I love it!). My concern is: Me working WITHOUT publisher (therefore using not so great marketing techniques) can take some time to get my game to peoples hart VS other developer (USING publisher) can clone my game and with publishers help get their cloned game to public much faster. Before people even realizing it is a copycat.**

# Answer
> 28 votes
A publisher would not be able to protect you from someone else creating a more popular clone of your game. Games from large publishers get ripped off just as often as those from small indies. *Maybe* the publisher has enough money in their war chest to fight a legal battle, but considering that such lawsuits are expensive and the success rate is hard to estimate, you can't count on them being willing to invest the money required to defend your game. Especially if it isn't one of the fattest cash cows in the barn.

There are essentially two reasons why you would want to work with a publisher.

* They complement your skillset. Maybe you are a great game developer, but you don't know anything about marketing and how to promote your game? A publisher might help out with that. They might also be able to get you into contact with people who can help you with the game itself.
* You need their money. Publishers are *sometimes* willing to fund a game up-front or pay you a flat fee for your game regardless of its commercial success. So if you are in risk of running out of money or need some guaranteed payout to plan your own financial future, then selling your game to a publisher can help you. That means, if you can convince them that your game is worth it. Nobody is going to throw money at you if they are not convinced that your game will make them a profit.

But there are also reasons why you would not want to work with a publisher:

* Executive meddling. Publishers might want to have some creative influence over your game. They might demand that you change things or force you to meet deadlines. Usually their demands are well-meaning. After all, their primary interest is making sure your game is as profitable as it can be. But maybe your game is a labor of love? You want it to be exactly the game you imagined and haters gonna hate? You don't care if you lose profits if it means you don't compromise your artistic integrity? Then you might prefer to work without a publisher behind your back.
* IP rights. Some publishers will want to own your intellectual property rights, like the copyright to the game and its assets, the trademark or the rights to use the characters and scenario. So if you ever want to create a sequel or spinoff, you might not be able to do that without the permission of the publisher. Or even worse, the publisher might hire someone else to do that, which means you get cut out of the creative process and won't get paid. Read the contracts carefully and make sure you understand all their implications. Ask a lawyer if you need help.
* They want their share of the money your game generates (no exceptions here). If you can cut out the middle-man and sell your game directly (like many independent developers do nowadays) you can make more money per sale for yourself. That means **if** you have the necessary business skills to sell your game without their help. But if you feel that the publisher's contribution won't result in enough additional sales to justify their cut, then there is little reason to work with them.

I am looking forward to playing your game.

---
Tags: game-industry, marketing, publishing
---


title: clock synchronization

text:
# Question
Title: clock synchronization
Is there something I'm not seeing or there is a flow in this algorithm(which everyone is referring to) http://www.mine-control.com/zack/timesync/timesync.html

Assumption 1: When I say a is substracted from b it means "b - a", maybe in the text they actually meant the other way arround? I would guess so. Assumption 2: the synchronization is to get the server clock on the client - If this is the gase shouldn't latency from server to client suffice?

Anyway, he article says: Client sends packet with timestamp t1, Server responds with it's timestamp t2. Client receves this packet at t3. So t3 \> t2 \> t1

RTT = t1 - t3 (gives a negative value, I guess it should be t3 - t1) latency = RTT / 2 (more or less, again it shoul be positive) client server time delta = t2 - t3 (server timestamp - current time) clock delta = t2 - t3 + RTT/2 (again, gives a negative value, abs again?)

Surely this cannot be... if the client time to server time is the same as the client thrn the clock delta is the RTT or 0 if I do abs (t2 -t3) + RTT/2.

if it is latencies are asymetric then the las calculation gives different results depending where I put abs abs(t2 - t3) + RTT/2 abs(t2 - t3) + abs (RTT/2) t2 - t3 + abs(RTT/2)

# Answer
The industry standard network time protocol (NTP) also takes into account the latency of the server processing. This means there are 4 timestamps, one each for send/receive of client/server. when properly calibrated it would look like: `t_cr > t_ss > t_sr > t_cs` and `t_cr - t_ss == t_sr - t_cs`

That is: the travel time of the packet from client to server is equal to the travel time from server to client. And you can offset the client time to make that true.

The offset needed is = `(t_ss + t_sr)/2 - (t_cs + t_cr)/2` adding this to the client time will line them up.

The NTP clients will do some statistical analysis and such to smooth out time changes and filter out outliers.
> 3 votes

---
Tags: networking, server, synchronization, client
---


# Question
Title: How to make a horizontal scrolling menu in Game Maker Studio 1.4?
I know how to place the items you see in the picture, my problem is how do I move them? How do I know if the player is swiping right or left? I made the items with a `ds_list` in a script file and then have an object `obj_MenuCreation` run that script, so if I move the `obj_MenuCreation`, will it move the list with it?

# Answer
Assuming you're using the Device Input functions, finding out if the user is swiping left or right shouldn't be much hard.

In the documentation, about the function `device_mouse_x()`, it says that the returned value *"for mobile devices (...) will only be updated while the screen is being touched"*. You can use this function in a *Step Event* to get the last *x* value of the mouse (the finger on mobile devices).

Let's say we have two variables, `cur_x_new` and `cur_x_prev`, and we updated them in a *Step Event* as follows:

```
// Step event - Update cursor input
cur_x_prev = cur_x_new;
cur_x_new = device_mouse_x(0);

```

We can then define three different cases:

* **Equal values:** the user isn't moving the finger on the screen or, more likely, they aren't even touching the screen at all;
* **New value greater than previous:** the user moved the finger towards right since the last update;
* **New value smaller than previous:** the user is moving the finger towards left.

The swiping "speed" can be calculated as `cur_x_new - cur_x_prev`, and you can also check for this value to be at least greater than a threshold, otherwise you can assume no swipe action is occurring.

**Edit** Once you know whether the user is swiping, you can move the sprites by drawing them at *coordinates + offset*, where *offset* is a clamped value that increases/decreases depending on the swiping direction.
> 1 votes

---
Tags: android, game-maker, touch, menu
---


title: Infinite ball bouncing problem (Unity)

text:
# Question
Title: Infinite ball bouncing problem (Unity)
I am trying to develop a basic Breakout game using this tutorial using Unity 5. But the ball starts to bouncing infinitely very easily. I cannot understand why this happenes.

In my physics knowledge starting an infinite bounce is very hard, and even impossible. To return the ball to same position after bouncing we must send the ball with zero degrees with the vertical axis. To send the ball with zero degrees with vertical axis we must receive the ball with zero degrees with the vertical axis. To receive the ball with zero degrees with the vertical axis we must send the ball with zero degrees, and so on. We can send a ball with zero degrees only in initial ball throw. In all the other cases there must be an angle which is not equal to zero. Am I wrong?

I mean the ball does not change its rotation. Ball moves between two plates which are parallel to each other infinitely (for example between paddle and upper wall)

I added physics material to ball, paddle and the walls. This material has following settings: Dynamic friction: 0 Static friction: 0 Bounceness: 1

Settings of the ball: Mass: 0.5 Drag: 0 Angular Drag: 0 Is Kinematic: true (I changed to false just before firing) Use Gravity: false

Settings of the paddle: Mass: 0.5 Drag: 0 Angular Drag: 0 Is Kinematic: true Use Gravity: false

# Answer
> 1 votes
I think you mean that the trajectory (the direction it is traveling) does not change, such that the ball bounces perfectly up and down between the two same points on the parallel plates. You are correct that this is extremely difficult and nearly impossible in real world conditions, because there are so many factors that can alter the ball's path.

However, you have created two perfectly parallel planes in the Unity physics model, and I assume that you have not added any external forces such as wind. If the ball is launched vertically, why would there be any change to its angle on the first bounce or any subsequent bounces? When Unity's perfect sphere collides with the perfect plane, the ball will bounce vertically in the opposite direction. This will continue indefinitely unless some additional force comes into play.

As Alexandre mentioned in the comments, you could add some variation in the bounces by giving the paddle a curved surface. This adds a game mechanic where bounces are easier to control closer to the center of the paddle.

You could also add friction to the physics materials, as Blindman suggested. Your current implementation has zero friction, so a moving paddle will have no effect on the bounces. If you set a nonzero friction, then players can alter the bounce direction by moving the paddle right when it hits the ball.

However, both of these solutions will still allow indefinite vertical bouncing if the player simply leaves the paddle in its original position. If you want to completely prevent that situation, you could add some randomization to the bounces. You could do this by applying a slight random horizontal force to the ball on each bounce, or by slightly changing the angle of the planes between bounces. These changes would not have to be very large to prevent an indefinite vertical bounce situation.

The rotation of the ball is a separate issue, but adding friction will also cause the rotation to change with each bounce.

# Answer
> 0 votes
I know this has been posted quite some time ago but for the sake of others who may stumble upon this I will try to answer this as I experienced the same problem a few days ago. You can either solve it by \[1\] randomizing the velocity after each collision to ensure that you will always get a slightly different path for your ball, or \[2\] you may change the ball path by adding force to either x or y velocity once it is nearing zero(meaning that the ball is starting to stagnate at the same position). I will show both answers below. I guess it is up to you which one you prefer. Note that that these methods must be implemented on the ball game object script.

1. Random velocity tweak after each collision

```
[SerializeField] float randomFactor = 0.3f;

//ball object collision
private void OnCollisionEnter2D(Collision2D collision){
    RandomVelocityTweak();
}

private void RandomVelocityTweak(){
    //create random velocity tweak from 0 - 0.3f
    Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor), Random.Range(0f, randomFactor));
    //add velocity tweak to velocity
    myRigidBody2D.velocity += velocityTweak;
}

```
2. Adding force to either x or y velocity

```
private void OnCollisionEnter2D(Collision2D collision){
    SuddenXVelcoityTweak();
    //tweak y velocity
    SuddenYVelcoityTweak();
}

//Left and right (x) stagnation of ball: use y velocity tweak to change direction to either up or down
private void SuddenYVelcoityTweak() {
    float min_y_velocity = 1f;
    //if y velocity is lower then min y velocity and y velocity is positive (ball direction: up)
    if ((myRigidBody2D.velocity.y  -min_y_velocity) &&
    (Mathf.Sign(myRigidBody2D.velocity.y) == -1))
    {
        //push ball down
        myRigidBody2D.AddForce(new Vector2(0, -5f));
    }
}

//Up and down (y) stagnation of ball: use x velocity tweak to change direction to either left or right
private void SuddenXVelcoityTweak()
{
    float min_x_velocity = 1f;
    //if x velocity is lower then min x velocity and x velocity is positive (ball direction: right)
    if ((myRigidBody2D.velocity.x  -min_x_velocity) &&
    (Mathf.Sign(myRigidBody2D.velocity.x) == -1))
    {
        //push ball left
        myRigidBody2D.AddForce(new Vector2(-5f, 0));
    }
}

```

Then if you want you may add after how many bounces the ball should change direction

```
int bounceCount = 0;

private void OnCollisionEnter2D(Collision2D collision)
{
    //increment bounce count
    bounceCount++;

    if (bounceCount % 4 == 0) {

        //include your code here

        bounceCount = 0;
    }
}

```

I hope this helped. Have a great day.

---
Tags: physics, unity
---


title: How manage multiple images in Unity?

text:
# Question
Title: How manage multiple images in Unity?
I'm new in Unity and creating a game. So I have a class `PicManager` in which I have to load my images(sprites) from assets into a `List` and then use them in my game. What is the proper way to load multiple images from a folder in Assets?

I know, that I can use `Sprite[] sprites = Resources.LoadAll<Sprite>(texture.name);` But this article of Unity says not to use `Resource` folder.

# Answer
> 2 votes
The reason why the article tells you to not use the Resources folder is exactly because it leads to the anti-pattern you want to create here: Loading multiple images from a folder in Assets before the engine decided that it acutally needs them. So if you insist on doing this, then all that advise is invalid and you can use the method described in the question.

An alternative method which might replicate your architecture in a more Unity-friendly way would be:

* Turn your PicManager into a MonoBehaviour
* Make `Sprite[] sprites` a public variable if it isn't already
* Add a new game object with that behaviour
* Add the sprites you need to the game object through the inspector.

But there is just one scenario I could think of where this would make sense: If you have game objects which frequently change their appearance during the game. In that case you could store all the available appearances in the pic manager. When the appearance of a type of game object does not change, then it would be better to assign the sprite directly to the game object and create a prefab for each type of game object which you then instantiate whenever you need one.

# Answer
> 1 votes
If you must load from assets without using Resources.Load, I'd suggest checking out unity's scriptable objects\[ScriptableObjects\] you save them as assets and can create a list of those objects.

But I also agree with Tom, use the engine. You can always have another script that inherits from monobehavior and implements PicManager if abstraction is what you're going for.

---
Tags: unity, 2d, textures, sprites, assets
---


# Question
Title: Using the Command design pattern for game AI
I'm trying to learn the Command design pattern and apply it to the game I'm working on. First I read about the general implementation, and I feel like I understand it pretty well. Now I want to know how to use it in games. I started reading this book about design patterns in games and in the section about the command pattern the author says:

> We can use this same command pattern as the interface between the AI engine and the actors; the AI code simply emits Command objects.

and

> The decoupling here between the AI that selects commands and the actor code that performs them gives us a lot of flexibility. We can use different AI modules for different actors.

I'm trying to figure out how this pattern would be used for game AI in practice. I assume there would be an `AIEngine` class or something like that with `GenerateCommand()` function. Then the `GameActor` would ask the `AIEngine` for a `Command` whenever it finishes executing the previous one.

What I don't understand is how exactly it would work. In order to generate commands the `AIEngine` needs to keep track of all the `GameActor` objects anyway (or at least of the one it's generating the commands for), so what's the point of using commands? At this point the `AIEngine` could just manage the `GameActor` objects directly.

I've been trying trying to wrap my head around this for quite a while. If someone could write a example implementation of the `AIEngine` interfacing with `GameActor` it would help me a lot. I don't think I'm able to understand it without seeing some code.

# Answer
The key to why you would use the command pattern is in the text you quoted here.

> The decoupling here between the AI that selects commands and the actor code that performs them gives us a lot of flexibility. We can use different AI modules for different actors.

The decoupling is key here. If you have the code for determining which action to perform (what command to execute) completely decoupled from your code for determining what to do given a certain action, then you can freely change one without having to think about the other.

For example: Imagine that you create an `AIEngine` subclass, call it `SimpleAIEngine`, that generates a command for the enemy unit to attack the player whenever that player is close enough to the enemy unit. All `SimpleAIEngine` would do is determine if the unit is close enough to the player and if so generate an `AttackCommand` and if not generate a `DoNothing` or `ContinuePatrolling` command. It might create the command with something like `return AttackCommand(enemy, player);`.

Now imagine you want the player to be able to cast a spell called "Confusion" that causes an enemy unit to attack a random enemy unit. You can use the same `AttackCommand` as before, but just pass it a random enemy unit instead of the player, doing something like `return AttackCommand(enemy, randomEnemyUnit());`.

The way that these commands are generated is completely different, but the behavior of the enemy when they receive the command is the same. Neither your `SimpleAIEngine` nor your Confusion spell logic has to dive into how an enemy attacks another unit, it just generates the command to be handled by the abstraction that does handle said logic. Because you don't call some sort of unit API call, to unit test either of these command generating methods you do not need to dive into the unit to see if it was appropriately told to attack another unit; you need simply check that the appropriate command was generated.
> 3 votes

# Answer
I own a copy of this book and my interpretation of this example of the command pattern is to encapsulate an action (to be executed by an AI actor) and execute it at a later date. In doing this you could create a queue of these actions. An AI actor would then use this queue of actions as its behaviour.

Consider a turn based game in which the objective is to build and conquer. The AI opponent may need to build up some sort of base, gather resources, and eliminate enemies. The AI engine (opponent) would crank out a queue of commands to satisfy each of these requirements. Specialised AI actors would then execute the commands from a given queue when it is their turn.

The AI "engine" only needs to know how to turn objective requirements into commands. A command does not need to know how it was created or who will execute it, it just needs to encapsulate some logic. The AI actors only need to know how to execute commands given to them. By seperating the logic, the same code can also be used for player governed AI actors to carry out a queue of commands created by said player. It also makes unit testing a lot easier.
> 3 votes

# Answer
First off, GREAT book. It's one of my go-to books when I'm looking to revamp one of my patterns and make it tighter. Good call.

As for doling out actions, the nice thing about this is that you can interpret actions on the `GameActor` or `Player` or `Object` at any time (or simply ignore them). This decoupling allows the actor itself to determine which commands are valid for it in a given situation.

Think of it this way. Your `AIEngine` or `AIManager` might have very basic instructions to give, say: patrol, attack, defend, hide. These are assuming certain parameters (can see player, player in range, et cetera). Perhaps some actors don't play by those rules at all times. The `AIEngine` can tell an actor ATTACK but the actor itself, due to it's state can then say NUH-UH and carry on. This allows your AI to have deeper involvement of actor actions.

I need to move my AI to a command pattern, to make changes easier down the road. However, this is precisely why I'm doing so slowly. Right now each actor in my game manages it's own AI from a class - which is ugly and inefficient, but allows that granularity. The decoupling allows one to keep the granularity, but use command patterns for "high level" AI. If the `AIEngine` says it's time to jump, but the actor cannot, the actor can ignore that while letting the engine carry on. It also allows complex ML to be introduced for your AI without overriding other rules you may have in your game.

But, as DMGregory said above, it doesn't mean you have to go this route. My current system of AI uses a state machine, which does work fine. It just also adds a lot of duplication to my code and makes it somewhat less manageable in some situations. If I implement a command pattern and decide that it can't give me QUITE the level of granularity I want or need, I'll end up sticking with the current system and trying to flesh it out better.
> 1 votes

---
Tags: c#, ai, design-patterns
---


title: Automated LAN Matchmaking

text:
# Question
Title: Automated LAN Matchmaking
I'm looking to build an automated LAN matchmaking system for games and wondering if/how it would differ from the online applications (like FaceIt, ESEA) that serve a similar function. Ideally, a user would first select the game they wanted to play (PUBG, LoL, etc) then be paired up with others on the LAN who are playing the same game. Is that possible?

# Answer
> 1 votes
You could do this by having your matchmaking launcher/client use UDP broadcast to advertise their existing on the network. Clients can broadcast information about themselves (such who they are and what their actual LAN address is) while the client is open, and in turn receive those broadcasts from others. This allows each client to build up a view of other clients on the network.

From there you can directly negotiate connections to send more heavyweight information (such as who is playing what).

The main hurdle you'll likely run into is actually interfacing in any clean fashion with the actual games. Your client may be able to tell what the user is playing by monitoring the active process list on the machine (looking for "PUBG.exe" or whatever), but achieving any kind of seamless join from your client program *directly* will be a challenge. Unless a game exposes some kind API for you to query against (which is extremely unusual), you can't tell if somebody playing a game is actually in a lobby or joinable state or even present at the machine.

Building any kind of seamless join from your client program is thus going to involve a lot of per-game hacking and reverse-engineering, and may be impossible for many games.

If all you're trying to do is give users an idea of who is playing what now, and let them handle negotiating the join themselves, this is fairly doable.

---
Tags: game-mechanics, peer-to-peer, matchmaking
---


title: PhaserJS: Detecting intersection

text:
# Question
Title: PhaserJS: Detecting intersection
I'm making a card game to get my legs with phaser. I have an row of overlapping, face down cards. I want to detect when any card is covered by another card.

The deck is shuffled before being placed on the board, so the order is known `card[1]` thru `card[54]`. It goes `card.events.onInputDown.add(tap, this)` on each card during setup to detect interaction, and then calls `tap(this)`:

```
function tap(pointer){
    console.log(pointer.z);
    let zpos = pointer.z
    if (Phaser.Rectangle.intersects(pointer, *abovecard*)) {
        console.log("covered");
    } else {
        pointer.play("front"); // anim to show the card back
    }
}

```

*(`abovecard` is asterisked as a placeholder because I'm not sure what to put there)*

A simple boundary overlap check seems to be the model to use. But when I go `abovecard = card[zpos + 1]`, it doesn't see a card above it. Even when I do in the console `Phaser.Rectangle.intersects(card[37], card[38])`, which are visibly overlapping, it says `false`.

Primary question: What am I missing here?

2ndary question: Is there a better way, than what I've described, to detect if one sprite is overlapping another sprite (whether the other sprite is known or not)?

# Answer
Well, as it goes, as soon as I posted I figured it out.

`Phaser.Rectangle.intersects(pointer, card[zpos + 1]` needs an explicit rectangle. I thought I'd read that it automatically took the rectangle of the referred sprites, but it does not.

The solution is `Phaser.Rectangle.intersects(pointer.getBounds(), card[zpos + 1].getBounds()`
> 1 votes

---
Tags: javascript, phaser
---


title: Removing a pair from array of pairs

text:
# Question
Title: Removing a pair from array of pairs
Im making a Breakout clone game and im stuck with deleting objects after they are hit. There are 3 rows. Each contains 12 blocks.

I'm trying to delete a pair in the array of pairs. The array contains coordinates of an object (texture) displayed, and if that object is hit with a ball I want to delete it and then my ball changes direction.

```
for each(pair<int, int> par in koordinateBlokova) {

    if (provjeraKolizijeBloka(par.first, par.second, rectLoptica) == true) {
        lopticaTrenutniY = -lopticaTrenutniY;

    }
}

```

Array and SDL\_Rects are defined like:

```
pair<int, int> koordinateBlokova[36];
SDL_Rect rectBlock01;
SDL_Rect rectBlock02;
SDL_Rect rectBlock03;

```

Their definition is:

```
for (int j = 0; j < brojBlokovaRed; j++) {

    rectBlock01 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj, sirinaBloka, visinaBloka);
    rectBlock02 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj + visinaBloka + razmakStupaca, sirinaBloka, visinaBloka);
    rectBlock03 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj + 2 * visinaBloka + 2 * razmakStupaca, sirinaBloka, visinaBloka);

    SDL_RenderCopy(renderer, block01, NULL, &rectBlock01);
    SDL_SetRenderTarget(renderer, block01);
    koordinateBlokova[j] = make_pair(rectBlock01.x, rectBlock01.y);

    if ((j + 1) % 3 == 0) { // if its 3rd block, make it a impenetrable (not implemented yet, just drawn)
        SDL_RenderCopy(renderer, blockNeprobojni, NULL, &rectBlock02);
        SDL_SetRenderTarget(renderer, blockNeprobojni);
        koordinateBlokova[j+12] = make_pair(rectBlock02.x, rectBlock02.y);
    }
    else {
        SDL_RenderCopy(renderer, block02, NULL, &rectBlock02);
        SDL_SetRenderTarget(renderer, block02);
        koordinateBlokova[j+12] = make_pair(rectBlock02.x, rectBlock02.y);
    }

    SDL_RenderCopy(renderer, block01, NULL, &rectBlock03);
    SDL_SetRenderTarget(renderer, block01);
    koordinateBlokova[j+24] = make_pair(rectBlock03.x, rectBlock03.y);
}
SDL_SetRenderTarget(renderer, NULL);
SDL_RenderPresent(renderer);

```

To make it easier to understand:

```
brojBlokovaRed = number of blocks in a row
sirinaBloka= block width
visinaBloka= block height
razmakRedova = space between rows
razmakStupaca = space between columns
gornjiOdstoj = space from top of the screen to first row of blocks

```

My question is how to delete that current pair from array?

# Answer
> `pair<int, int> koordinateBlokova[36];`

This is an actual C++ array, which is a fixed-size structure. Elements cannot be added to or removed from such an array. It has 36 items and it will *always* have 36 items.

Instead, you probably want to store your pairs in a `std::vector`, which is C++'s standard library container implementing a *resizable* array. It would look like this:

```
std::vector<pair<int,int>> koordinateBlokova(36);

```

You can then use the member function `erase` to remove elements based on iterators; since vector's iterators are random-access you can erase an element at some arbitrary index `i` using `koordinateBlokova.erase(koordinateBlokova.begin() + i)`.

---

That said, as noted in Garrett Gutierrez's answer, this may not be what you ultimately *want* to do (although it will directly address your question). Erasing from a vector invalidates (most) outstanding iterators referring to the vector and causes all elements above the erased one to be copied down. If you're going to erase many times from a vector at effectively-random interior indices, there are other broader solutions you can explore that won't have that overhead.

Garrett Gutierrez's suggests a linked list. Another option, if the order of your items is irrelevant, is to simply move the "dead" elements to the end of the array, swapping them with the first live element, and either erase them all there using `remove` or simply keeping a "live index" that refers to the last live element in your array. This has the advantage of keeping all your elements contiguous in memory (which you don't get with a linked list, per se) and also avoiding heap allocation/free operations when adding or removing elements.

It's a touch "less obvious" than a linked list, though, so if you do not need those criteria, that's also a viable path.
> 2 votes

# Answer
First of all, in general, you do not want to modify a vector in C++ while iterating through it. Even if you did take the trouble to write your loop such that it permitted this, this would make your collision detection something like a O(n^2) operation, in other words it would be quadratic with respect to the number of elements in the vector, and so it would grow to be prohibitively slow relatively quickly as you added more elements into the array.

What you should do is either consider a linked list structure (list) or do something like mark the elements in the vector for later deletion and then, after you have done all the collision detection, move only the objects not marked for deletion into a new vector that you replace the old vector with. This could be done by making the vector a vector of structs/classes that contain the pair as a member but also a bool for keeping track of if the object is deleted or not.

In the latter case you would have to decide: do you want multiple balls to be able to bounce off the same object in a single frame, or do you want only one to be able to do that, and then for the object to be deleted immediately and no other balls be able to bounce off if it in the same frame? If you are okay with multiple, then just do your collision detection as normal and delete the objects afterward. If you want the object to be deleted "immediately", then make your collision detection conditioned upon neither of the objects being marked for deletion.
> -1 votes

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