title: Displaying possible movement tiles

text:
# Question
Title: Displaying possible movement tiles
What's the fastest way to highlight all possible movement tiles for a player on a square grid? Players can only move up, down, left, right. Tiles can cost more than one movement, multiple levels are available to move, and players can be larger than one tile. Think of games like Fire Emblem, Front Mission, and XCOM.

My first thought was to recursively search for connecting tiles. This quickly demonstrated many shortcomings when blockers, movement costs, and other features were added into the mix.

My second thought was to use an A\* pathfinding algorithm to check all tiles presumed valid. Presumed valid tiles would come from an algorithm that generates a diamond of tiles from the player's speed (see example here http://jsfiddle.net/truefreestyle/Suww8/9/). Problem is this seems a little slow and expensive. Is there a faster way?

---

Edit: In Lua for Corona SDK, I integrated the following movement generation controller. I've linked to a Gist here because the solution is around 90 lines of code.

https://gist.github.com/ashblue/5546009

# Answer
A\* is for finding the shortest path from vert a to vert b. Its not a good fit for finding all verts x distance from vert a.

A Depth First Search (DFS) should be suitable for your problem and very cheep on both memory and clock cycles. There is another basic search algorithm called the Breadth First Search (BFS) that would run at similar speeds but uses slightly more memory because it stores all possible edges instead of immediately exploring them.

Things such as edges effecting speed can be handled by tracking distance (for example if a tile is 50% speed then its twice the length of other tiles) and only pushing new verts onto the stack if they are closer than the maximum distance. For example a bit of tinkering to the standard DFS algorithm gives you the below where all vertices labeled explored are within range of your character.

Note the below may not look it but its pseudocode. Not guaranteed to compile.

```
procedure Iterative_DFS(startVert) {
    startVert.distance = 0;
    var pop = true;
    HashSet discovered = new HashSet();
    Stack s = new Stack(startVert);
    s.push(startVert)
    while (!s.empty) {
          var t = s.pop();
          pop = true;
          foreach (vert v in t.adjacent) {
              if (!discovered.contains(v)) {
                  v.distance = t.distance + v.travel;
                  if (v.distance < maxDistance) {
                      discovered.add(v);
                      S.push(v);
                      pop = false;
                      break;
                  }
              }
          }
          if (pop) {
              label t as explored
              S.pop()
          }
     }
}

```
> 4 votes

# Answer
## Final Update

* `Unit.MovementPoints = 5`
* `Segment.Distance = 2`
* `First.Segment.Position = (1, 0, 1)`

In the end what worked for me was actually `Dijkstra's/BFS` which searches nothing, there is no end point. You could extend this to create a `Flow Field` if you backtrack each tile but it's not required for this use case. Code represents a general idea and an algorithm, it's from my project, so it won't work out of the box.

```
// PolytopialSegmentsStructure = it's my grid.
// Segment = tile.
// Segment.Id = I set it to be the index in cached array from 0 to n.

// This is my thingy to get cost of a tile, you can ignore this.
[SerializeField] private ExperimentalSegmentCostRelation _experimentalSegmentCostRelation;

public override Segment[] GetNeighbours(Segment segment, int maxCost)
{
    this._experimentalSegmentCostRelation.Initialize(segment.PolytopialSegmentsStructure);

    int capacity = segment.PolytopialSegmentsStructure._RelativeBounds.size.x * segment.PolytopialSegmentsStructure._RelativeBounds.size.y * segment.PolytopialSegmentsStructure._RelativeBounds.size.z;

    Queue<Segment> frontier = new Queue<Segment>(capacity: capacity);

    frontier.Enqueue(item: segment);

    Dictionary<int, float> cost = new Dictionary<int, float>(capacity: capacity)
    {
        [segment.Id] = 0.0f
    };

    while (frontier.Count > 0)
    {
        Segment current = frontier.Dequeue();

        Segment[] neighbours = current.GetNeighbours();

        for (int a = 0; a < neighbours.Length; a++)
        {
            Segment next = neighbours[a];

            float newCost = cost[current.Id] + this._experimentalSegmentCostRelation.GetCost(next) + 1; // + this.Distance(current, neighbours[a]) // + 1 was to replace distance

            if (newCost <= maxCost && (!cost.ContainsKey(next.Id) || newCost < cost[next.Id]))
            {
                cost[next.Id] = newCost;

                frontier.Enqueue(next);
            }
        }
    }

    // This is me getting all of the tiles/segments this way because each key is Id anyway.
    // In your case you might need to store your visited tiles this way `Dictionary<int, Segment>` where `int` would be `Segment.Id`.
    // Or some other way.
    // But in my case I can just get these visited tiles this way.
    Segment[] segments = new Segment[cost.Keys.Count];

    int i = 0;
    foreach (int segmentId in cost.Keys)
    {
        segments[i] = this._gridSegmentsCache[segmentId];

        ++i;
    }

    return segments;
}

```

## More Details (My thoughts and steps I took to discover that algorithm above works.)

For small maps Flow Field algorithm would work in some cases.

I am also looking for the same thing. What I understood is in case we have max steps to take to reach some point that Flood Fill and similar algorithms won't work. The reason - they don't take into account the calculation of number of steps taken to reach the point. So in the end we need the same algorithm that is going to calculate a shortest path to do the job of calculating all possible distances it can reach with this amount of `movement points`.

We could use concept of Flow Field to optimize memory footprint and only save number of moves that need to be taken from one point of map to another. But the issue with this approach is not memory, it's rather we would have to recalculate this field each time some change on a map changes the `movement cost` of a tile. One tile can affect many paths that were calculated before, so it would only be efficient for maps that don't change their `movement cost` of a tile.

What if you don't care about `movement points` to reach some tile? - You can just as well do the `Flood Fill` constrained by `distance` to check if this tile is reachable at all. Or if you don't need to check if it's reachable - then for a grid and hex maps it's easy to just calculate the tiles from simple math like `Clamp((int)(localPos +- radius), 0, maxX);` \- then use this result to iterate through tiles to get the ones you need. (This is rough pseudo-code, just for example.)

But of course, if we take `CIV 5` as an example, imagine tile changing to mountains, enemy unit stepping on a tile, your other unit occupies that other tile, a building, an obstacle, a river, an ocean. If we take into account all of these variables I can assume that `Flow Field` would be a lot slower than using `A*`.

## DFS or BFS?

Using DFS or BFS = not possible for weighted graphs. https://stackoverflow.com/questions/30409493/using-bfs-for-weighted-graphs

So our case like `CIV 5` wouldn't work.

## A\*

If we have a case like `CIV 5` and our `Unit` has `5` movement points and we need to get all of the tiles that we can reach with those `5` movement points - then we need to use pathfinding algorithm that is going to be used to find path to a tile player chooses this `Unit` to go to, otherwise the result of path a `Unit` takes and tiles that `Unit` can reach will be inconsistent.

In code: Select all tiles that are distanced at `Unit`s `movement points` as if each tile cost was `1` or lower possible distance. Run `A*` on each of those to get correct distances and to check if they are reachable.

I keep thinking that there is a more efficient approach, even when using `A*`. I would love to hear any ideas to optimize this to not run `A*` on every possible tile. I think @UnderscoreZero is closer to the most efficient and right approach, it might even be the one. I am just leaving all of the considerations that I have taken till this point.

## Conclusion

I came to a conclusion that we just need to calculate a `Weighted Flow Field` and stop adding neighbours when max number of movement points is reached.

Basically a `Weighted Flow Field` with distance limit and starting from position of a `Unit`.

`(Feel free to correct me if I am wrong, I would be very thankful for finding a better approach or fixing a mistake.)`

### Additional Resources

https://www.youtube.com/watch?v=zr6ObNVgytk

https://www.youtube.com/watch?v=tSe6ZqDKB0Y

https://www.redblobgames.com/pathfinding/a-star/introduction.html

https://www.redblobgames.com/pathfinding/tower-defense/
> 1 votes

# Answer
You can actually do this without A\*. I did this on a hex grid using recursion but the premise is the same.

You start at your characters current position with the set number of moves. then move outward in all directions reducing the number of moves by the amount of moves required to enter that square. Then repeat for each square you entered.

One thing to remember is that when moving to a square already visited, you must check the movement that the character had on that square, if it is higher than your current movement, don't enter the square.

Once you are done, you highlight any square that has 0 or more moves on it.

I did this in sort of a hacky way in that the moves were saved to each point on the map rather than an array but to me it ended up working very well. No A\* required.
> 0 votes

---
Tags: 3d, tiles, movement, path-finding, optimization
---


# Question
Title: OpenGL Vertex Shader "joint matrix * weight" multiplication performance
Trying to implement animation on my engine.
I'm at the first stage, rendering default pose of skinned meshes.
Working as expected but very slow.

With the below calculation, the shader takes **6ms** to run.

```
struct MeshUniform {
    mat4 transform;
    mat4 normalMatrix;
    vec4 baseColorFactor;
    vec4 roughnessMetallicNormal;
    vec4 hasColorMetallicNormalTexture;
    mat4[30] jointMatrices;
};

layout (std430, binding = 4) buffer meshUniformSSBO { MeshUniform[] meshUniforms; };

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 uv;
layout (location = 3) in vec4 tangent;
layout (location = 4) in uvec4 joints;
layout (location = 5) in vec4 weights;
layout (location = 6) in int drawId;

void main() {
   MeshUniform meshUniform = meshUniforms[drawId];
   mat4 model = meshUniform.transform;

   mat4 skinMat =
     meshUniform.jointMatrices[joints[0]] * weights[0] +
     meshUniform.jointMatrices[joints[1]] * weights[1] +
     meshUniform.jointMatrices[joints[2]] * weights[2] +
     meshUniform.jointMatrices[joints[3]] * weights[3];

   vec4 positionVec4 = skinMat * model * vec4(position, 1.0);

   ...
}

```

If I remove skinMat calculation and multiplication, same shader takes **1ms**.

```
// mat4 skinMat =
//  meshUniform.jointMatrices[joints[0]] * weights[0] +
//  meshUniform.jointMatrices[joints[1]] * weights[1] +
//  meshUniform.jointMatrices[joints[2]] * weights[2] +
//  meshUniform.jointMatrices[joints[3]] * weights[3];

// vec4 positionVec4 = skinMat * model * vec4(position, 1.0);

vec4 positionVec4 = model * vec4(position, 1.0);

```
* Scene has 87706 vertices, shown in Blender statistics.
* I'm using glMultiDrawElementsIndirect with single VAO.
* Joint matrices for non-skinned meshes are identity matrix.
* MeshUniform is persistent, coherent ssbo map. Only updated when needed.
* I'm using the same calculation on shadowmaps, so it takes another 6ms.
* Gpu is 1080 Ti.

I tried adding "jointCount" to MeshUniform struct, and doing the joint calculation only if jointCount \> 0. But it still took 6 ms to calculate.

Is this to be expected and what can I do to improve?

---

## **Edit with DMGregory's suggestions:**

I tried,

* Multiplying joint matrices by position vector, then summing the results.
* Pre-multiplying model with joint matrices on cpu.

It looks like this now;

```
vec4 positionVec4 = vec4(position, 1.0);

vec4 sum =
  meshUniform.jointMatrices[joints[0]] * weights[0] * positionVec4 +
  meshUniform.jointMatrices[joints[1]] * weights[1] * positionVec4 +
  meshUniform.jointMatrices[joints[2]] * weights[2] * positionVec4 +
  meshUniform.jointMatrices[joints[3]] * weights[3] * positionVec4;

positionVec4 = sum;

```

It's still taking 5-6ms to run.

---

Someone in lwjgl forums posted a question similar to mine in 2012.
http://forum.lwjgl.org/index.php?topic=4519.0

In his last message he said;

> using a constant as the array index while accessing boneMatrixes brings performance up

Sure enough if I exclude *joints* array lookup from above code like this;

```
vec4 positionVec4 = vec4(position, 1.0);

vec4 sum =
  meshUniform.jointMatrices[0] * weights[0] * positionVec4 +
  meshUniform.jointMatrices[1] * weights[1] * positionVec4 +
  meshUniform.jointMatrices[2] * weights[2] * positionVec4 +
  meshUniform.jointMatrices[3] * weights[3] * positionVec4;

positionVec4 = sum;

```

it renders in 1ms. But of course resulting image is not correct.

Maybe it will give some ideas to more experienced people on OpenGL.

# Answer
Thanks to Khronos forum user mhagain, he suggested to try different storage options.

I tried an SSBO that only holds the jointMatrices data and it worked!

```
layout (location = 4) in ivec4 joints;
layout (location = 5) in vec4 weights;
layout (location = 6) in int drawId;

struct JM {
    mat4[30] jointMatrices;
}; layout (std430, binding = 7) buffer jmSSBO { JM[] jm; };

void main() {
  ...
    vec4 positionVec4 = vec4(position, 1.0);
    vec4 sum =
      jm[drawId].jointMatrices[joints.x] * positionVec4 * weights.x +
      jm[drawId].jointMatrices[joints.y] * positionVec4 * weights.y +
      jm[drawId].jointMatrices[joints.z] * positionVec4 * weights.z +
      jm[drawId].jointMatrices[joints.w] * positionVec4 * weights.w;

  ...
}

```

With this, render time is under 1ms.
> 1 votes

---
Tags: opengl, shaders, animation, vertex, skinning
---


title: How to save / load a scene in unity?

text:
# Question
Title: How to save / load a scene in unity?
I have 60+ levels in the game, that is, 60+ scenes. Let's say a player has passed to level 10 and leaves the game, then when he returns to the game , he will have to appear first on the MAIN MENU stage and then click CONTINUE and appear on stage 10. The game is on android, I tried it through PlayerPrefs, but it doesn't work for me( I just need to save the player on the current stage and then load it on the same stage where it was last time.

# Answer
There are a few way you can persist data between sessions. To simply name a few you can use playerprefs **or** a simple file format like xml or json **or** custom binary files.

As a very simple example, at certain stages in your game (e.g. when a user finishes a level) you can save in a file a number associated with that level (lets say as in your case, 10). If he closes the game and relaunches it, you can load that 10 from the file in the main menu and further see what you want to do with it. (you might want to look into `SceneManager.LoadScene(sceneANumber);`)

Brackeys had a very nice video explaining those methods step by step if interested: https://www.youtube.com/watch?v=XOjd\_qU2Ido

The last resort would be to use a package such as Easy Save 3 that provides everything needed for a save/load system, including file encryption, however it's not free.
> 0 votes

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


# Question
Title: How do I make my obstacles (separate prefabs) appear randomly in the world?
I am using Unity in C# to code a game similar to Google's Dinosaur Run where random obstacles are spawned in the player's path which they need to jump to dodge. I have 6 different prefabs (with animations) for my obstacles which use Polygon Colliders to detect collisions. How can I use an array to randomly select one of these obstacle prefabs to spawn them at various distances apart?

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

public class ObstacleController : MonoBehaviour
{
    [SerializeField]
    private Sprite[] sprites;

    public int Type { get; set; }

    private SpriteRenderer spriteRenderer;

    private PolygonCollider2D polygonCollider2D;

    public void Initialise()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        polygonCollider2D = GetComponent<PolygonCollider2D>();

        int type = Random.Range(0, sprites.Length);

        Type = type;
        spriteRenderer.sprite = sprites[type];

    }
}

```

Above is the code I have so far which only allows me to have sprites as obstacles whereas I want to use prefabs with set dimensions and animation properties.

# Answer
> 0 votes
use this,

```
[Serializefield] GameObject [] prefabs;
int type = Random.Range (0, sprites.Length);
float spwanRangeX = 10f; // desired value
Vector3 spwanPos = new Vector3 (Random.Range(spwanRangeX,-spawnRangeX),0,0);

Instantiate (prefabs[type], spawnPos , prefabs[type].transform.rotation);

```

---
Tags: unity, c#, 2d
---


title: how to create spin the wheel godot

text:
# Question
Title: how to create spin the wheel godot
I want to create a 2d board game that involve a spinning wheel that has 1 - 6 numbers that pick in random then it will animate in the wheel. how can i code the physics of a spinning wheel while generating an random number 1 - 6??

# Answer
Since you want a physics simulation, in 2D, in Godot, for a wheel spinning...

We will make the wheel as a `RigidBody2D`. It will have a a `Sprite` child for visual representation.

A couple options for fixing it in place come to mind:

* You can set its `gravity_scale` to `0`, so it does not fall. *In theory something else could knock it off.*
* You can use a `PinJoint2D` to fix it an `StaticBody2D`. *Make sure the `PinJoint2D` has `Node A` and `Node B` connected to the `StaticBody2D` and `RigidBody2D`.*

I'll also suggest to have a `Node2D` to contain the whole arrangement (that way you can position the parent `Node2D` instead of moving its children nodes). It is also convenient to put our code there, in particular if we want to save this as a scene and instance it somewhere else.

*`CollisionShape`s are NOT strictly necessary in this case, but you may add them too.*

---

For the rotation the simplest solution is to give it a random `angular_velocity`.

I'll be writing the code for the parent `Node2D`. For example:

```
func spin() -> void:
    $RigidBody2D.angular_velocity = rand_range(500.0, 10000.0)

```

And it will slow down and stop according to its `angular_damp`.

---

We also need to know when it stopped. For that we can add a custom signal:

```
signal stopped_spinning

```

And check the angular velocity in `_physics_process` to know when it stopped.

By the way, we cannot rely on the angular velocity hitting 0. Instead we will consider it stopped when it is close to zero.

I will take advantage of `set_physics_process` to enable when spinning, and disable it is when done:

```
extends Node2D

signal stopped_spinning

func _ready() -> void:
    set_physics_process(false)

func spin() -> void:
    $RigidBody2D.angular_velocity = rand_range(500.0, 10000.0)
    set_physics_process(true)

func _physics_process(_delta: float) -> void:
    if abs($RigidBody2D.angular_velocity) < 0.02:
        $RigidBody2D.angular_velocity = 0.0
        emit_signal("stopped_spinning")
        set_physics_process(false)

```

*In my test, the angular velocity gets down to `0.010584`. So I picked `0.02` as threshold. If that gives you problems, experiment with the value.*

*Even though I only put positive angular velocities, I decided to use `abs` so the code can handle a negative value.*

---

You can then create a button, and make it call `spin` when pressed. You can also handle the custom `"stopped_spinning"` signal to get the result. For that, you may use `$RigidBody2D.rotation_degrees` and some arithmetic, for example:

```
func get_value() -> int:
    var offset_degrees = 90
    var options = 6
    var option_degrees = 360 / options
    return int(fposmod($RigidBody2D.rotation_degrees + offset_degrees, 360) / option_degrees) + 1

```

The `fposmod` will give you a value between 0 and the second parameter (360 in this case).

*I added `offset_degrees` to account for the fact that I don't know at what angle the first option is. Also, I added 1 at the end because it would give you values in the range \[0, options), but you probably want a value on the range \[1, options\]. Tweak that as needed.*
> 0 votes

---
Tags: godot
---


# Question
Title: How can I scale multiple objects at the same time with coroutine?
```
public IEnumerator ScaleOverSeconds(List<GameObject> objectsToScale, Vector3 scaleTo, float seconds)
    {
        if (objectsToScale != null)
        {
            for (int i = 0; i < objectsToScale.Count; i++)
            {
                float elapsedTime = 0;
                Vector3 startingScale = objectsToScale[i].transform.localScale;
                while (elapsedTime < seconds)
                {
                    if (objectsToScale == null)
                    {
                        yield return null;
                    }
                    else
                    {
                        objectsToScale[i].transform.localScale = Vector3.Lerp(startingScale, scaleTo, (elapsedTime / seconds));
                        elapsedTime += Time.deltaTime;
                        yield return new WaitForEndOfFrame();
                    }
                }

                objectsToScale[i].transform.localScale = scaleTo;
            }

            waitForScaleOver = true;
        }
    }

```

Now when I start the coroutine it's scaling one objectsToScale when it finish than it's moving to the next one and scale it and so on. I want to scale them all at the same time in this coroutine.

The full script :

In short : I want to be able to scale multiple objects at the same time automatic or using the R key.

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

public class GenerateWalls : MonoBehaviour
{
    public GameObject gameObjectToRaise;
    public float wallsAmount;
    public float gap;
    public float duration;
    public Vector3 raiseAmount;
    public bool go = false;
    public Color[] colors = new Color[4];
    public bool randomColors = false;
    public bool autoGenerate = false;
    public bool waitForScaleOver = false;

    private GameObject wall;
    private List<GameObject> walls = new List<GameObject>();

    private void Start()
    {
        Init();

        ColorWalls();

        // The z Axis must be minimum 1 or any value above 0 could be also 0.1f
        // but it's better to keep it minimum as 1 by default.
        if (raiseAmount.z < 1)
        {
            raiseAmount.z = 1f;
        }

        if (go)
        {
            CoroutineManager();
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            autoGenerate = false;
            CoroutineManager();
        }

        if(autoGenerate)
        {
            CoroutineManager();
        }
    }

    private void Init()
    {
        walls = new List<GameObject>();

        for (int i = 0; i < wallsAmount; i++)
        {
            wall = Instantiate(gameObjectToRaise);
            wall.transform.position = new Vector3(i + i * gap, 0, i + i * gap);
            wall.name = "Walls";

            walls.Add(wall);
        }
    }

    private void CoroutineManager()
    {
        if (waitForScaleOver)
        {
            for (int i = 0; i < walls.Count; i++)
            {
                if (raiseAmount.z < 1)
                {
                    raiseAmount.z = 1f;
                }

                Destroy(walls[i]);
            }

            Init();
            ColorWalls();

            StartCoroutine(ScaleOverSeconds(walls, new Vector3(raiseAmount.x, raiseAmount.y,
                raiseAmount.z), duration));

            waitForScaleOver = false;

        }
    }

    public IEnumerator ScaleOverSeconds(List<GameObject> objectsToScale, Vector3 scaleTo, float seconds)
    {
        // Do you really need to handle this case?
        // You probably want to just not start the coroutine at all
        // if you have nothing to scale.
        if (objectsToScale == null) yield return null;

        Vector3[] startingScale = new Vector3[objectsToScale.Count];

        for (int i = 0; i < objectsToScale.Count; i++)
        {

            // Similar here - shouldn't you just remove null objects first?
            if (objectsToScale[i] == null) continue;

            startingScale[i] = objectsToScale[i].transform.localScale;
        }

        for (float t = 0; t < 1f; t += Time.deltaTime / seconds)
        {
            for (int i = 0; i < objectsToScale.Count; i++)
            {
                {
                    if (objectsToScale[i] == null) continue;

                    objectsToScale[i].transform.localScale = Vector3.Lerp(
                              startingScale[i],
                              scaleTo,
                              t
                    );
                }
                yield return null;
            }

            foreach (var obj in objectsToScale)
                obj.transform.localScale = scaleTo;

            waitForScaleOver = true;
        }
    }

    private void ColorWalls()
    {
        var childrenWalls = GameObject.FindGameObjectsWithTag("Wall");

        for (int i = 0; i < childrenWalls.Length; i++)
        {
            if (randomColors)
            {
                childrenWalls[i].transform.GetChild(0).GetComponent<Renderer>().material.color
                    = GetRandomColour32();
            }
            else
            {
                childrenWalls[i].transform.GetChild(0).GetComponent<Renderer>().material.color = colors[i];
            }
        }
    }

    private Color32 GetRandomColour32()
    {
        //using Color32
        return new Color32(
          (byte)UnityEngine.Random.Range(0, 255), //Red
          (byte)UnityEngine.Random.Range(0, 255), //Green
          (byte)UnityEngine.Random.Range(0, 255), //Blue
          255 //Alpha (transparency)
        );
    }
}

```

# Answer
Just reverse the order of the loops, obviously. Loop over time first, then over objects in each moment/frame - instead of looping over objects and then over time for each object.

You may want to work your way through some beginner programming tutorials if you're having difficulty with the basics like this.

```
public IEnumerator ScaleOverSeconds
      (List<GameObject> objectsToScale, Vector3 scaleTo, float seconds)
{
    // Do you really need to handle this case?
    // You probably want to just not start the coroutine at all
    // if you have nothing to scale.
    if (objectsToScale == null) return;

    Vector3[] startingScale = new Vector3[objectsToScale.Count];

    for (int i = 0; i < objectsToScale.Count; i++)
    {

        // Similar here - shouldn't you just remove null objects first?
        if (objectsToScale[i] == null) continue;

        startingScale[i] = objectsToScale[i].transform.localScale;
    }

    for (float t = 0; t < 1f; t += Time.deltaTime/seconds)
    {
        for (int i = 0; i < objectsToScale.Count; i++) {
        {
            if (objectsToScale[i] == null) continue;

            objectsToScale[i].transform.localScale = Vector3.Lerp(
                      startingScale[i],
                      scaleTo,
                      t
            );
        }
        yield return null;
   }

   foreach (var obj in objectsToScale)
       obj.transform.localScale = scaleTo;

   waitForScaleOver = true;
}

```
> 1 votes

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


title: How to implement a simple Scrollbar

text:
# Question
Title: How to implement a simple Scrollbar
I'm making a simple UI system for a small game and i'm having some difficulty to implement a *Scrollbar*.

At the moment i'm having two major problems that i need some help to solve:

**.** Calculating the **"Value"** property of the *Scrollbar* when the current position of the *Thumb* on the *Track* is changed.

**.** Calculating the **"Minimum"** and **"Maximum"** properties to limit the position of the *Thumb* on the *Track*.

Below is part of the code that i currently have. Please, look at the commented blocks.

```
public int Minimum  { get; set; }
public int Maximum  { get; set; }

public int Value    { get; set; }

public void Update()
{
    // Calculate the Scrollbar Thumb height:
    var viewable_ratio = ViewportHeight / ContentHeight;
    var scrollbar_area = ViewportHeight - ( ArrowHeight * 2 );

    this.ThumbHeight = scrollbar_area * viewable_ratio;

    // Calculate the Scrollbar Thumb step:
    var track_space = ContentHeight  - ViewportHeight;
    var thumb_space = ViewportHeight - ThumbHeight;

    this.ThumbStep = track_space / thumb_space;

    // TODO: Calculate the "Minimum" and "Maximum" values.
    this.Minimum = ???
    this.Maximum = ???

    Point mouse = Input.MousePosition();

    if(Thumb.Rectangle.Contains(mouse) && Input.MouseDown(0))
    {
        int x = Thumb.Position.x;
        int y = ( mouse.y - Thumb.Position.y );

        Thumb.Position = new Point(x, y);

        if(Thumb.Position.y < Minimum) Thumb.Position.y = Minimum;
        if(Thumb.Position.y > Maximum) Thumb.Position.y = Maximum;

        // TODO: Set the "Value" property to the correct value when the Thumb is moved.
        this.Value = ???
        this.Content.Position.y = this.Value;
    }
}

```

The **"Value"** property is used to scroll the **Content** and represent his position in the *Scrollbar*.

The **"Minimum"** and **"Maximum"** properties are used to not let the *Thumb* move outside of the *Track*.

Could someone please provide a direct answer with the math to calculate the scrollbar *Value*, *Minimum* and *Maximum* properties?

**Thanks in advance!**

# Answer
I'm going to give values to `Minimum`, `Maximum` and `Value` from the way you want to use them.

We start with this code, where you use `Minimum` and `Maximum`:

```
if(Thumb.Position.y < Minimum) Thumb.Position.y = Minimum;
if(Thumb.Position.y > Maximum) Thumb.Position.y = Maximum;

```

It appears that `Minimum` and `Maximum` should be actual positions on screen. In that case your `Minimum` is going to be `ArrowHeight`, and your `Maximum` is going to be `ViewportHeight - ArrowHeight - this.ThumbHeight`.

---

As per `Value`, you want to use it like this:

```
this.Content.Position.y = this.Value;

```

We need to transform `Thumb.Position` to a get the value that `this.Content.Position.y` should have… What do we know?

* When `Thumb.Position.y` is `Minimum`, `this.Content.Position.y` should be `0`.
* When `Thumb.Position.y` is `Maximum`, `this.Content.Position.y` should be `ViewportHeight - ContentHeight` a.k.a `-track_space`.
* It is a linear transformation. I.e. `this.Content.Position.y = Thumb.Position.y * factor + offset`.

*I'm assuming that the positive y goes downwards, and thus when you scroll down, you need give a negative position to the content so it moves upwards.*

Thus, we have two unknowns: `factor` and `offset`. And two linear equations:

```
Minimum * factor + offset = 0

Maximum * factor + offset = -track_space

```

Solve the system. *If my assumptions are wrong, you should still be able to come up with an equation system to solve.*

I'm feeling substitution:

```
Minimum * factor + offset = 0

=>

offset = -Minimum * factor

=>

Maximum * factor + -Minimum * factor = -track_space

=>

factor * (Maximum - Minimum) = -track_space

=>

factor = -track_space / (Maximum - Minimum)

=>

factor = track_space / (Minimum - Maximum)

```

And thus:

```
var factor = track_space / (Minimum - Maximum);
var offset = -Minimum * factor;
this.Value = Thumb.Position.y * factor + offset;
this.Content.Position.y = this.Value;

```

---

By the way, if I understand correctly, you are checking if the user is clicking on the `Thumb`:

```
if(Thumb.Rectangle.Contains(mouse) && Input.MouseDown(0))
{
   ...
}

```

And moving it:

```
int x = Thumb.Position.x;
int y = ( mouse.y - Thumb.Position.y );

Thumb.Position = new Point(x, y);

```

Which means that just clicking on the `Thumb` will make it move.

However, I believe that if the user is just clicking there you should do nothing! Instead you need to handle drag. And change `Thumb.Position` according to that drag.
> 1 votes

---
Tags: c#, mathematics, user-interface
---


title: Displaying text on a 3D plane

text:
# Question
Title: Displaying text on a 3D plane
I am busy with a pet project where I am trying to create a Collectible Card Game in 3D.

These cards have Hp and Damage etc. but I cannot find a way to neatly display these values. I tried to use a TextMesh, but all the text just blends into each other if the cards happen to overlap (eg. when the cards are in the hand).

Currently, I am using a plane for each value, and then changing the Material used on that plane, to match the value (eg. a '3' Material if the Damage is 3). It works, but I can't help to think that there *has* to be a better way.

Is there a way to dynamically display values on a plane so that it looks like the value is a part of the card itself, without changing the materials every time a change occurs? Or suggest anything else that would suit my needs?

If I am taking a horrible approach, you're welcome to nudge me in a better direction.

Thanks in advance

# Answer
> 1 votes
Cards in a collectible card game usually have a standardized layout with several images and text labels. That means they are pretty much a UI widget. So you can create each card as a separate UI canvas with the "World Space" rendering mode.

A world space canvas basically behaves like a sprite. You control its position, size and rotation in 3d space using its transform. You can control the draw order of multiple canvases in your scene by:

* Sorting Layer
* Order In Layer
* Distance from camera

(by that priority)

# Answer
> 0 votes
I don't know if this will less costly, but using the Profiler you can find out yourself. You could attach a UICanvas on your card object. On this Canvas, place Text Components in the correct positions.

# Answer
> 0 votes
TextMesh is the way to go with what you are looking for, as you are displaying these cards in a plane. This component wouldn't be a valid choice with non flat surfaces.

Add an empty gameobject to your card as a child and then add TextMesh as a component -\> Add Component / Mesh / TextMesh. Put the text you need and, after that, you have to adjust the text to where you want it, do it moving the position of the gameObject. Notice that if the father objects aren't with a 1-1-1 Scale, the text will be deformed, if thats the case you'll need to change your object organization and move the text by script instead using it as a child.

If you rotate the card, you'll notice that the text overlaps above every mesh in the scene, even your own card. To avoid this you need to use a custom shader for the "TextMesh" that will make it render like any other object in the scene.

This is the shader:

```
Shader "Text/TextNonOverlap Shader" {
    Properties {
        _MainTex ("Font Texture", 2D) = "white" {}
        _Color ("Text Color", Color) = (1,1,1,1)
    }

    SubShader {
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
        Lighting Off Cull Off ZWrite Off Fog { Mode Off }
        Blend SrcAlpha OneMinusSrcAlpha
        Pass {
            Color [_Color]
            SetTexture [_MainTex] {
                combine primary, texture * primary
            }
        }
    }
}

```

To use the shader, you need a font in your project, anyone will work. Create a material and put this shader on it, then pick the font you chose and assign it's "Font Texture" in the same field "Font Texture" of the material, this is important.

Then, in the gameobject with the TextMesh, change the font to the one you selected, the same as the one you put it's Font Texture on the material or it won't work. Select in the component MeshRenderer "Materials -\> Element 0" and put the material you just created on it, now you have a text that won't overlap, to change it's color just change the color of the material.

It's not complicated but it's easy to mesh up, so be careful.

P.S: Yeah, the text can go outside the card but, as you can see, even hearthstone used a similar approach

---
Tags: unity, 3d, text, card-game
---


# Question
Title: How can I include vertex color information in .OBJ files?
The .obj files I export are missing data for vertex colors. Is there a way to include color information in the .obj file? If not, what are the alternatives?

# Answer
Blender can export PLY files (.ply), which are text-based, very easy to parse, and include vertices colors. The hard way is to change the OBJ exporter code so that it includes the vertices colors (thus breaking obj compatibility).
> 11 votes

# Answer
There does exist a flavour of Wavefront's \*.obj that facilitates Vertex Coloring.. I know of two applications that can export these namely "MeshLab" (free) and "MeshMixer" (also free from Autodesk).. The vertex colours is actually found just after each vertex definition as shown below..

(Piece of \*.obj)

```
####
#
# OBJ File Generated by Meshlab
#
####
# Object VERTEXPAINT_004_OBJ.obj
#
# Vertices: 284
# Faces: 281
#
####
mtllib ./VERTEXPAINT_004_OBJ.obj.mtl

vn 0.029683 0.730087 -0.682709
v 1220.094482 -572.500000 177.713943 0.984314 0.764706 1.000000

# "3 vals for Vert and 3 vals for Col"

vn 0.000000 0.858139 -0.513418
v 1291.571533 -609.439636 -28.628490 0.921569 0.219608 1.000000
vn 0.303129 0.896367 -0.323480

```

Try using meshlab to generate "Vertex Based Ambient Occlusion", then open it with "MeshMixer"..

This should clarify your issue.. I think Vertex colouring is coming back with the advent of shaders.. Its funny how vertex colouring seems to be neglected when image maps were discovered.. Now we should see the the return of "Vertex Colouring"! Let me know if this was usefull!
> 21 votes

# Answer
Wavefront OBJ supports *materials*, which color *groups* of meshes the same color.

Material statements look like this:

```
newmtl redMtl
Kd 1.00 0.00 0.00
Ks 0.50 0.50 0.50
Ns 18.00

```

So, Kd is the diffuse component, Ks specular.

These would be specified inside a .mtl file that accompanies the .obj file. Inside the .obj file are statements like

```
usemtl redMtl
f 1/5/1 30/39/2 20/29/3
f 20/29/4 30/39/5 31/41/6
f 35/48/7 26/35/8 2/6/9

```

This means the faces specified there are to use the redMtl material. When you're parsing the obj file, this translates down to per-vertex color.

If there are lots of different colors, you will have a lot of different materials, but you can do it.

Here's a video of how to assign a particular group of faces a different material. You can assign a different material to each face in a mesh if you wish.
> 8 votes

# Answer
I know this is an old question, but what about specifying vertex texture coords (`vt`) for each unique color and then referencing those in the face (`f`) statements? OBJ allows for 1-3 dimensional texture coords. They'll obviously be incorrect when interpreted in the usual way (unless you have a texture of RGB space), but your program could interpret them as vertex colors.
> 0 votes

---
Tags: graphics, blender, file-format, color, obj
---


# Question
Title: How To Deselect (Unfocus) All gameObjects in a Unity Scene View?
When I'm done with moving and rotating gameObjects in a Unity scene, I want to deselect everything to not accidentally change it. How?

In some applications ESC key does the trick, in others 'D' (deselect) comes to rescue. But I don't know any remedy in Unity. My workaround is that I click somewhere in the Project View (I don't like this approach because it brings up the inspector for that asset).

# Answer
> 2 votes
You could click on a blank area in the scene view, or in the hierarchy, or if you really really want a keyboard shortcut you could add a custom editor script: (Untested)

```
using UnityEngine;
using UnityEditor;

static class DeselectEverything() {
  [MenuItem("Edit/Select None _d")]
  //alternatively MenuItem("Edit/Select None _ESC")] although it may be _ESCAPE
  static void DoSelectNothing() {
    Selection.objects = new Object[0];
  }
}

```

You can take look at the Unity documentation to see more about how to use MenuItem, specifically how to organize the item within the Edit menu and how to give it a different keyboard shortcut.

# Answer
> 2 votes
The hotkey to deselect all GameObjects in a Unity Scene is

`Shift + D`

Also you could use the action from the menu `Edit` then choose `Deselect All`.

Unity 2020.3.16f1

---
Tags: unity, level-design
---


# Question
Title: Game Mode: call StartPlay when second map is loaded
I've just started to learn Unreal Engine 4.26.2 and C++.

I have two maps: one used only to show the main menu, and another one to play the game (Pong clone).

On my GameMode, which inherits from Game Mode Base, I have implemented method Start Play. My problem is that method must be called when the player enters into the game (when the second map is shown), but that method is called when the game start.

Is there any method to call when the second map is loaded? I have thought to call a custom Game Mode method from second map level blueprint.

# Answer
If you're using two maps then you can use the Open Level node which allows you to call a new level by name.

In your maps and modes, choose your menu level for the game start map.
> 1 votes

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


# Question
Title: How to pass PNG image data directly to SDL?
Well passing just external PNG to SDL is very easy with the SDL\_image library. I have a class that does just that. The code looks like the following:

```
SDL_Surface* Texture::LoadImg(const char *filename) {
    SDL_Surface* Image = IMG_Load(filename);
    if (Image == NULL ) {
        printf("Unable to load picture%s\n",SDL_GetError());
        return NULL;
    }
    return Image;
}

```

Later on I can just call it with

```
//some code
SDL_Texture* Texture = SDL_CreateTextureFromSurface(Renderer,LoadImg(filename));
//some code

```

But I don't have just a PNG file. I have a binary file that consist of many PNG files inside. Basically I combine binary(PNG) files into one larger file. Later on I just open that binary file and load pictures into memory from one single file. So now I have an array of vectors or pointers or any other types (depending how you read the binary file). Now I need to pass this from memory into SDL or SDL\_image to load it as texture. How would I pass already loaded PNG (binary) data into SDL to use as an `SDL_Texture`?

# Answer
> 6 votes
SDL uses a type called `SDL_RWops` for this purpose. This is essentially a wrapper around a stream. When you call a function like `IMG_Load(filename)` it is just a small wrapper around `IMG_Load_RW(ops)` which constructs the `ops` using `SDL_RWFromFile`. You can create an `SDL_RWops` yourself (it's just a struct with some function pointers) if you have a custom stream type.

There's also a helper function `SDL_RWFromMem` which creates an `SDL_RWops` for manipulating bytes in memory like they are a file, which is probably what you're looking for in conjunction with `IMG_Load_RW`.

# Answer
> 0 votes
MNG might be worth looking into which basically specifies a single file containing multiple images with PNG like compression. And there are a couple of libraries for assigning the MNG components to SDL textures.

---
Tags: c++, c, image, sdl2, png
---


# Question
Title: Unity - How to create a game-save with a preview image?
I want my game-save to be shown with a preview image. This is often seen in City Builder games: The game-save usually has a name, a date and often also provides a preview of the build city (just a screenshot of what was seen on the screen when the user pressed Save).

For my game, I provide 16 game-save slots, and they all get saved in "one big" JSON file. For testing purposes, I currently take a screenshot, convert it to a Texture2D and assign it to the game-save slot in my UI.

**What would be a good way to store the preview-screenshots so that it is available the next time the game is started?**

The most obvious way would be to convert the screenshot to a png file, and save it together with the one big JSON file. But that would mean that the game-saves are no longer all just in one JSON file, but instead also rely on a separate file that holds the preview image, and that for each different game-save. (Downside: 1. Player can see the actuall png files in the save folder 2. with 16 save games, we now don't have only one save file, but 17 (16 screenshots, 1 JSON file))

Since I would like to have the save file to consist of only one file, I was considering to not save the screenshot at all, and just take new screenshots every time the game starts (based on the information stored in the JSON file). Since I am working on a small game, with only one scene, this would be easily possible. But this does not seem like an elegant solution. (Upside: Only one save file needs to be stored: the JSON file)

I found this reply to a question about complex save systems, which hints into the direction of storing a screenshot with the binary formatter. Would it be possible to save a collection of Texture2D in one file, using the binary formatter? If yes, where can I read more about that and, would it be possible to save the Texture collection together with the JSON file, to have only one save file in the end (or alternatively 2 files: 1 JSON + 1 File that holds all 16 previews)?

# Answer
> 4 votes
Since you're working with JSON format already, you could simply include the preview image as a Base64 blob that can be decoded on the fly when reading the savegame list.

Assuming you have access to a **Texture2D** representing your savegame preview (let's call it `previewImage`), you can do the following:

```
public string EncodePreview(Texture2D previewImage) {
    byte[] previewBytes = previewImage.EncodeToJPG();
    string previewBase64 = Convert.ToBase64String(previewBytes);
    return previewBase64;
}

```

This way, you can save the image as a string in the same JSON file where you keep the savegame data. When it's time to show up the save slots, you can convert the image back as follows:

```
public Texture2D DecodePreview(string previewBase64) {
    byte[] previewBytes = Convert.FromBase64String(previewBase64);

    Texture2D previewImage = new Texture2D(0, 0);
    if (ImageConversion.LoadImage(previewImage, previewBytes))
        return previewImage;
    else
        return null;
}

```

---
Tags: unity, c#, savegame, json
---


title: how does unity handle image scaling

text:
# Question
Title: how does unity handle image scaling
Unlike in android SDKs, in almost all tutorials I've seen, creating UI elements like menus in unity starts with laying out a default background image onto a canvas object.

I don't really get the fact that different resolution image are not kept in the folder as we do in android(mdpi, xdpi etc.). Is this expected for unity? I mean, the same app can be viewed in a 4K wide screen right? Wouldn't the image appear blurred? How is that handled for apps created by unity? No tutorial I've viewed so far seems to really care for that. Please give me some idea on how this is handled or supposed to be handled in unity 3D.

# Answer
It depends what you are making. If it is reasonable to change image resolution based on mobile, you may have to handle that yourself in your game. Unity is a general solution which does not necessarily specialize in UI, though it does have UI abilities.
> 1 votes

---
Tags: unity, unity-ui
---


title: How to access GameObject inside Action

text:
# Question
Title: How to access GameObject inside Action
I'm stuck inside an Action :

```
socket.On("login", data => {
            Debug.Log("1");
            Debug.Log("2?");
            Debug.Log(gameObject);
            Debug.Log("1^^");
        });

```

All I get is **1** and **2?** on console. After calling the gameObject it freezes. Although other functions work, as they should. But if I just remove that gameObject, it works fine.

I've called gameObject from many different places, they simply log GameObject.

And the method it's referring to, its definition looks something like this :

```
    public Emitter On(string eventString, Action<object> fn) {
      ListenerImpl listenerImpl = new ListenerImpl(fn);
      return this.On(eventString, (IListener) listenerImpl);
    }

```

And this is type of System.Action.

***Now my question is how can I access gameObject inside Action.***

The socket.io library I'm using : https://github.com/Rocher0724/socket.io-unity

And logging outside the closure, it just logs. But when logging inside the library, I get :

```
UnityEngine.Debug:Log(Object)
<>c__DisplayClass3_0:<ActivePalyerCountStomp>b__0(Object) (at Assets/Scripts/Home.cs:26)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.ListenerImpl:Call(Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/ListenerImpl.cs:26)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.Emitter:Emit(String, Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/Emitter.cs:17)
Socket.Quobject.SocketIoClientDotNet.Client.QSocket:OnEvent(Packet) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/QSocket.cs:207)
Socket.Quobject.SocketIoClientDotNet.Client.QSocket:OnPacket(Packet) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/QSocket.cs:178)
Socket.Quobject.SocketIoClientDotNet.Client.QSocket:<SubEvents>b__21_0(Object) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/QSocket.cs:59)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.ListenerImpl:Call(Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/ListenerImpl.cs:26)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.Emitter:Emit(String, Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/Emitter.cs:17)
Socket.Quobject.SocketIoClientDotNet.Client.Manager:OnDecoded(Packet) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/Manager.cs:233)
Socket.Quobject.SocketIoClientDotNet.Client.Manager:<OnOpen>b__50_1(Object) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/Manager.cs:217)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.ListenerImpl:Call(Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/ListenerImpl.cs:26)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.Emitter:Emit(String, Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/Emitter.cs:17)
Socket.Quobject.SocketIoClientDotNet.Parser.Decoder:Add(String) (at Assets/Socket/Quobject/SocketIoClientDotNet/Parser/Parser.cs:120)
Socket.Quobject.SocketIoClientDotNet.Client.Manager:OnData(String) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/Manager.cs:225)
Socket.Quobject.SocketIoClientDotNet.Client.Manager:<OnOpen>b__50_0(Object) (at Assets/Socket/Quobject/SocketIoClientDotNet/Client/Manager.cs:209)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.ListenerImpl:Call(Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/ListenerImpl.cs:26)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.Emitter:Emit(String, Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/Emitter.cs:17)
Socket.Quobject.EngineIoClientDotNet.Client.Socket:OnPacket(Packet) (at Assets/Socket/Quobject/EngineIoClientDotNet/Client/Socket.cs:236)
Socket.Quobject.EngineIoClientDotNet.Client.EventPacketListener:Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.IListener.Call(Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/Client/Socket.cs:490)
Socket.Quobject.EngineIoClientDotNet.ComponentEmitter.Emitter:Emit(String, Object[]) (at Assets/Socket/Quobject/EngineIoClientDotNet/ComponentEmitter/Emitter.cs:17)
Socket.Quobject.EngineIoClientDotNet.Client.Transport:OnPacket(Packet) (at Assets/Socket/Quobject/EngineIoClientDotNet/Client/Transport.cs:115)
Socket.Quobject.EngineIoClientDotNet.Client.Transport:OnData(String) (at Assets/Socket/Quobject/EngineIoClientDotNet/Client/Transport.cs:105)
Socket.Quobject.EngineIoClientDotNet.Client.Transports.WebSocket:ws_MessageReceived(Object, MessageReceivedEventArgs) (at Assets/Socket/Quobject/EngineIoClientDotNet/Client/Transports/WebSocket.cs:64)
Socket.WebSocket4Net.Default.WebSocket:FireMessageReceived(String) (at Assets/Socket/WebSocket4Net/Default/WebSocket.cs:295)
Socket.WebSocket4Net.Command.Text:ExecuteCommand(WebSocket, WebSocketCommandInfo) (at Assets/Socket/WebSocket4Net/Command/Text.cs:5)
Socket.WebSocket4Net.Default.WebSocket:ExecuteCommand(WebSocketCommandInfo) (at Assets/Socket/WebSocket4Net/Default/WebSocket.cs:389)
Socket.WebSocket4Net.Default.WebSocket:OnDataReceived(Byte[], Int32, Int32) (at Assets/Socket/WebSocket4Net/Default/WebSocket.cs:399)
Socket.WebSocket4Net.Default.WebSocket:client_DataReceived(Object, DataEventArgs) (at Assets/Socket/WebSocket4Net/Default/WebSocket.cs:201)
Socket.WebSocket4Net.SuperSocket.ClientEngine.ClientSession:OnDataReceived(Byte[], Int32, Int32) (at Assets/Socket/WebSocket4Net/SuperSocket.ClientEngine/ClientSession.cs:114)
Socket.WebSocket4Net.SuperSocket.ClientEngine.AsyncTcpSession:ProcessReceive(SocketAsyncEventArgs) (at Assets/Socket/WebSocket4Net/SuperSocket.ClientEngine/AsyncTcpSession.cs:62)
Socket.WebSocket4Net.SuperSocket.ClientEngine.AsyncTcpSession:SocketEventArgsCompleted(Object, SocketAsyncEventArgs) (at Assets/Socket/WebSocket4Net/SuperSocket.ClientEngine/AsyncTcpSession.cs:25)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()

```

And this `socket.on` is being called from `Start()` directly. No additional context.

Main purpose of this is to get some component of that gameobject :

```
        string playerRoute = Defaults.baseApi + "/player/count";
        JsonRestClient restClient = GetComponent<JsonRestClient>();
        restClient.Get<BaseDto>(playerRoute, "onSuccess", "onError");

```

# Answer
I have been using this solution to this problem. Create a script with this code and attach it to a Game Object:

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

public class ExecuteOnMainThread : MonoBehaviour {

    public static readonly ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();

    void Update()
    {
        if(!RunOnMainThread.IsEmpty)
        {
           while(RunOnMainThread.TryDequeue(out var action))
           {
             action?.Invoke();
           }
        }
    }
}

```

Then when you need to call something on the main thread and access the Unity API from any other function in your application:

```
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {

    // Code here will be called in the main thread...

});

```

Solution from: https://stackoverflow.com/a/53818416/10305444
> 0 votes

---
Tags: unity, callbacks
---


title: Singleton issue

text:
# Question
Title: Singleton issue
I have two scenes, The first one called "Boot" contains and ObjectPoller class that instantiates all GameObject in the game and disable them. I made it a singleton with "don't destroyOnLoad" attribute. In the the second scene called GamePlay, There is a LevelManager that get acces to the ObjectPooler of the first scene by a function called GetPooledObject. When I boot the game by the first scene (Boot) in the Unity editor, everything works fine. But when I boot the game by the second scene, Unity editor freezes completely. I can't even shut it down. I'm do ctrl + Alt+delete to stop Unity. Is there any logic to prevent this behaviour?

```
 // in the ObjectPooler file

private PoolInfo GetPoolByType(PoolObjectType type)
{
    for (int i = 0; i < allPoolObjectList.Count; i++)
    {
        if (type == allPoolObjectList[i].type)
            return allPoolObjectList[i];
    }
    return null;
}

// In the LevelManager
private void Spawn(BlocType _type)
{
    if (ObjectPooler.Instance != null)
    {
        Bloc b = ObjectPooler.Instance.GetPooledBloc(_type);
        if (b)
        {
            // logic
        }
    }
}

```

# Answer
While I can't be certain, you have most likely a loop error in your `//logic` bloc. But why does it work when you load the `boot` scene first? You have a second mistake. `if (b)` is always true as long as `b` is extended from `MonoBehaviour`.

```
public class Test : MonoBehaviour {

    private class NullTestClass : MonoBehaviour {

    }

    private NullTestClass demo = null;

    void Start()
    {
        if (demo)
            Debug.Log("It is null");
        else
            Debug.Log("This gets printed");
    }
}

```

This piece of code prints `This gets printed` even though demo has no value. MonoBehaviour has the line `This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).`

Use the longer null comparison instead.

```
if (demo == null)
   Debug.Log("This gets printed now");

```
> 3 votes

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


# Question
Title: In Unity, how do you manually set an interactable to an interactor (XR Grab Interactable to XR Socket Interactor)
I'm trying to figure out how to manually attach an XR Grab Interactable to a XR Socket Interactor but using `XRBaseInteractor.selectTarget` has the `protected` modifier.

How can you do this via C# in Unity?

# Answer
You can use the XR Interaction Manager to help with this!

Both `XRSocketInteractor.StartManualInteraction();` and `XRInteractionManager.ForceSelect();` are now confirmed working in the **XR Interaction Toolkit 1.0.0-pre.5**

Example script for testing:

```
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class XRSocketConnector : MonoBehaviour
{
    public XRSocketInteractor socket;
    public XRBaseInteractable interactable;
    public XRInteractionManager interactionManager;

    void Start()
    {
        // Both of these work in 1.0.0-pre.5
        socket.StartManualInteraction(interactable);
        // interactionManager.ForceSelect(socket, interactable);
    }
}

```
> 0 votes

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


# Question
Title: How can we access private variables of a c# script from bolt visual script graph directly?
As public variables are accessible from the bolt script and not private variables, is there a way to access them or we have to set the `set`s and `get`s as well?

# Answer
> 2 votes
You shouldn't. Variables get declared as `private` because they are not supposed to be changed from anywhere except from inside the class itself.

But if you really, really need to do this (again, you shouldn't), you could write a custom Bolt node implemented by a C# class derived from `Unit` with a method which accesses and changes a private variable on another object and then put *that* into your bolt graph. You can violate the privacy of a variable via the C# reflection API. Some examples for how to perform this forbidden operation can be found in the answers to this stackoverflow question. But again, **this is not a good idea**. When a variable is private and has no public getters or setters, then the author of that class likely had a reason for that.

---
Tags: unity, c#, bolt-visual-scripting
---


title: AI driver for racing games

text:
# Question
Title: AI driver for racing games
I'm very curious about AI drivers in a racing game, so I tried to build one :). I've built a 3D closed racing course and a car with Unreal engine and all the physics, and I try to develop an algorithm that drives the car.

I saw several posts in the past, like this one Driver AI in racing game but I still don't understand how to control the throttle, steering, and breaks to actually do it.

What I have tried so far is to create some waypoints in the course and use a PID controller to control the throttle and steering that goes to the next waypoint every time. The results were not so good... Depends on the car speed and curves, the steering PID controller has overshoots and/or slow response. After some testing, I think that the PID controller cannot fit for driving a car...

I want the car to drive like an AI driver in a good racing game. Without collision with the walls (closed course) and drive as well as possible.

What is the best method for optimizing the path and what is the best way to control the car (throttle, breaks, steering) to follow that path?

# Answer
> 2 votes
To get more optimized results, you may want to train a Reinforcement Learning model on your racing game mechanics.

Alternatively, to optimize the route for straight lines, you could use a navmesh. This would make the speed and turn rate computation more difficult.

To start with

1. Generate a spline (or a 3d line path) of the track's center.
2. Based on the spline: compute the rate at which the car needs to turn at each point on the track. The turning angle can be compute the dot products of two consecutive directional vectors on the path spline.
3. Gather information about friction, road-tilt and game world gravity to compute the top speed at which this specific vehicle can turn at that rate. You can do this by a binary search on the physics engine with with the specifics of the track and the car, or alternatively if the physics engine is a black box, you can do this with experimentation, storing the results programmaticaly.
4. Now work your way backwards, taking into account the time it takes to decelerate to determine the top speed in previous portions of the road.
5. If the car has to move at a slower rate than the optimal speed, the turning rate should be calibrated accordingly.
6. To get better results: understand how much leeway the car has to take the turn at increased speeds.
7. Adjust the optimal speed a bit according to the leeway.

Yes, one method that could work he is to record the expected driving behavior and then play it back according to the progress on the track.

---
Tags: game-design, ai, racing
---


# Question
Title: Text Only Dungeon Crawler game. Hardcoding Maps vs Generating Map Data externally?
I am trying to make a text-only dungeon crawler game.

The general structure for the game is in place (ie. a 'Level' is a 16x16 grid of 'Rooms').

```
#pragma once
#include <string>

class RoomData
{
    bool isRoom;
    std::string title;
    std::string description;
    int items;
    int exits;
};

```

I can move around the map with my Player class. After a 'Move' is made, the console prints the title and description from the Room.

But so far, I have to hardcode the level design in my C++ code.

Armed with my current knowledge only, I am having to externally draw my map in art software and manually write notes for each cell (0,0 ; 0,1 ; etc) and then when I create my `std::vector<Room>` I manually fill it with all the necessary data. Even for 16x16 map size this takes a very long time and mistakes are hard to spot (if I miss a cell in the middle for example).

I want to use my RoomData class (above) and then I want to make my Level class take input from a Text File and automatically populate my vector with the rooms in order.

Please can someone help me find ways to do this, I honestly have been trying this forever over many projects but I always end up hardcoding.

# Answer
> 2 votes
I would recommend to use a standard markup format like XML, YAML or JSON for your files. There are plenty of C++ libraries available for each of them which make converting between text files and C++ objects a breeze.

You can use a text editor to edit those files. Most more advanced text editors have syntax highlighting rules for each of these which should catch the most egregious typos.

But when you intend to invest quite a lot of time into creating content for your game, then it might make sense to develop an own level editor as a separate UI application. Whether or not that's worth it depends on how much time it would cost you to develop it, which depends on how much you already know about UI development. And of course on how much time it would save you during the creation of all the content. This is a cost/benefit calculation you have to do by yourself, because I know neither your skillset nor the scope of your game.

---
Tags: c++, level-design, levels, serialization
---


# Question
Title: Switching out the mesh of a game object at runtime
I am trying to switch out the mesh of a game object. I have this script:

```
public GameObject rockPile;
MeshFilter rockMesh;
private string[] rockMeshes = new string[] {"rocks-0", "rocks-25", "rocks-50"};
private int rockIndex = 0;

void Start()
{
   rockMesh = rockPile.GetComponent<MeshFilter>();
}

void Update()
{
    if (Input.GetMouseButtonDown(0)) { // click

        rockMesh.sharedMesh = Resources.Load<Mesh>(rockMeshes[rockIndex]); // <-- not working

        if (rockIndex == rockMeshes.Length - 1) {
            rockIndex = 0;
        } else {
            rockIndex++;
        }
    }
}

```

However the mesh isn't changing when I click on the object. The meshes for the rocks are part of imported .fbx files. If I search Assets for the strings I'm using in the `rockMeshes` array, they are there, but they are not the names of the imported fbx files. I'm not sure the right way to reference the meshes or store them.

File structure:

```
Assets/
├─ 3d/
│  ├─ rockMesh0.fbx  <-- rocks-0 mesh in this file
│  ├─ rockMesh25.fbx  <-- rocks-25 mesh in this file
│  ├─ rockMesh50.fbx  <-- rocks-50 mesh in this file

```

# Answer
I used @Philipp's suggestion and made a public meshes array, assigned those in Unity, and was able to set the mesh using the `sharedMesh` property:

```
public GameObject rockPile;
public MeshFilter[] meshes;
MeshFilter rockMesh;
private int rockIndex = 0;

void Start()
{
    rockMesh = rockPile.GetComponent<MeshFilter>();
}

void Update()
{
    if (Input.GetMouseButtonDown(0)) { // click

        rockMesh.sharedMesh = meshes[rockIndex].sharedMesh

        if (rockIndex == meshes.Length - 1) {
            rockIndex = 0;
        } else {
            rockIndex++;
        }
    }
}

```
> 1 votes

---
Tags: unity, 3d-meshes
---


# Question
Title: How to rotate an image around its center point in a JavaScript canvas?
I have this function to get the rotation angle from my sprite and a target:

```
getAngle( spr:Sprite, x:number, y:number ):number
{
    let vx:number = x - ( spr.getX() + spr.w / 2 );
    let vy:number = y - ( spr.getY() + spr.h / 2 );
    let angle = Math.atan2( vy, vx ) * (180 / Math.PI);
    return angle;
}

```

Basically this is:

```
target.x - sprite.centerX;

target.y - sprite.centerY;

```

Then i use **atan2** and multiply by radians. The way I use that angle is:

```
ctx.translate( this.getX() + centerX, this.getY() + centerY );
ctx.rotate( this.angle );
ctx.scale( this.xScale, this.yScale );
ctx.translate( - ( this.getX() + centerX ), -( this.getY() + centerY ) );

```

However, the above is not working. I have been investigating this and it seems to be okay, but it still does not work for me. Any ideas?

# Answer
after i posted the question i was looking a little deeper, the code seems to work fine, however works if the canvas element has a position of `x:0 & y:0`, so if is in a different place like mine which is centered and has margings/paddings then the coordinates of the canvas are different. to fix this i had to correct `mouseMove.clientX` & `mouseMove.clientY` values not passing them directly:

```
mouseMove(event:MouseEvent)
    {
        let boundingRect = canvas.getBoundingClientRect();
        let eX = event.clientX - boundingRect.left;
        let eY = event.clientY - boundingRect.top;
        this.arrowShooter.angle =getAngle(this.arrowShooter, eX, eY);
    }

```

so substracting **left** and top **from** *canvas.getBoundingClientRect()* to **event.clientX/Y** fixed mouse canvas coordinates.
> 1 votes

---
Tags: javascript, html5, html-canvas, typescript
---


# Question
Title: How to draw splatter (one color) on 2D grid to cover approximate number of pixels? (looking for algorithm/math answers)
Imagine a 2D grid, where water stain increasing because of water drops. But not in plain circular way but more like noisy-splatter way. Or like corruption way. I want to create effect that will increase existing splatter (if drop of water drops into position where splatter exists) or will create new (if drop of water drops into position where pixel is clear).

And it would be nice if I would be available to create approximate percentage coverage.

What algorithms should I use for this? What formulas?

I tried to sketch example:

# Answer
A simple way to do this is to loop over the pixels in your image (or process them in parallel with a shader). For each pixel, measure its distance to the center of each splat, and subtract the radius of the splat. This gives you a signed distance field (SDF): negative values are inside the splat, positive values are outside. Take the minimum of this SDF over all splats, and colour the pixels with negative values black and positive values white. (You can also use intermediate greys for values close to zero for a smooth antialiased effect)

Out of the box, that just gives you simple circular splats. But we can make them look more blobby and organic by adding a little noise. For each pixel you can generate a noise value using something like Perlin noise, or sampling from a texture with some random fuzzy shapes. Add a multiple of that noise value to your SDF value to bias it slightly - making some pixels that are strictly outside the radius count as inside, and some pixels that are strictly inside the radius count as outside. This breaks up the simple circular border and makes it look a little more naturalistic. Using different noise functions/textures and different multipliers can help you art direct the particular shape of the border.

Here's an example of this as a Unity shader that will draw up to four splats in one pass:

```
Shader "Unlit/Splats"
{
    Properties
    {
        _SplatPos1("Splat Positions A/B", Vector) = (1, 2, 10, 10)
        _SplatPos2("Splat Positions C/D", Vector) = (5, 7, 20, 5)
        _Intensity("Splat Intensity A/B/C/D", Vector) = (10, 5, 1, 0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        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 _SplatPos1;
            float4 _SplatPos2;

            float4 _Intensity;

            // Perlin noise implementation by Inigo Quilez,
            // via https://iquilezles.org/www/articles/gradientnoise/gradientnoise.htm
            float2 hash(float2 p) {
                const float2 k = float2(0.3183099f, 0.3678794f);
                p = p * k + k.yx;
                return -1.0f + 2.0f * frac(16.0f * k * frac(p.x * p.y * (p.x + p.y)));
            }

            float3 noised(float2 p) {
                float2 corner = floor(p);
                float2 t = p - corner;

                float2 u = t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f);
                float2 du = 30.0f * t * t * (t * (t - 2.0f) + 1.0f);

                float2 ga = hash(corner + float2(0, 0));
                float2 gb = hash(corner + float2(1, 0));
                float2 gc = hash(corner + float2(0, 1));
                float2 gd = hash(corner + float2(1, 1));

                float va = dot(ga, t - float2(0, 0));
                float vb = dot(gb, t - float2(1, 0));
                float vc = dot(gc, t - float2(0, 1));
                float vd = dot(gd, t - float2(1, 1));

                return float3(va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * (va - vb - vc + vd),
                    ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd) +
                    du * (u.yx * (va - vb - vc + vd) + float2(vb, vc) - va));
            }

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

            float splat(float noise, float2 offset, float intensity) {
                return intensity - length(offset) + noise * saturate(intensity/2.0f) * 1.5f;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                const float scale = 30.0f;

                float2 p = i.uv * scale;
                float noise = noised(p).x + noised(p).x;

                float intensity = max(
                    max(
                        splat(noise, i.uv * scale - _SplatPos1.xy, _Intensity.x),
                        splat(noise, i.uv * scale - _SplatPos1.zw, _Intensity.y)
                    ),
                    max(
                        splat(noise, i.uv * scale - _SplatPos2.xy, _Intensity.z),
                        splat(noise, i.uv * scale - _SplatPos2.zw, _Intensity.w)
                    )
                );

                float speed = fwidth(intensity);

                float distance = intensity / speed;

                return smoothstep(0, 1, 1.0f - (distance + 0.5f));
            }
            ENDCG
        }
    }
}

```
> 1 votes

---
Tags: mathematics, textures, algorithm
---


title: Dynamic textureIds in glsl

text:
# Question
Title: Dynamic textureIds in glsl
I have a bunch of texture IDs that each correspond to an image, I would like an `integer` to be passed in as an attribute, and then just get a `uniform sampler2D <integer>` You cannot do this in glsl, since `sampler2D` has to be a uniform, so I took the approach of just activating a uniform based on a provided integer. Is there a way to directly get a `sampler2D` based on a `textureId` without if statements?

Code

```
precision mediump float;

uniform sampler2D bedrock;
uniform sampler2D dirt;
uniform sampler2D grass;
uniform sampler2D gravel;
uniform sampler2D sand;
uniform sampler2D snow;
uniform sampler2D stone;

varying float vTextureId;
varying vec2 vUv;
varying float vBrightness;

int bedrockId = 0;
int stoneId = 1;
int dirtId = 2;
int sandId = 4;
int grassId = 5;
int gravelId = 6;
int snowId = 7;

void main() {
  int textureId = int(vTextureId);
  vec4 texel;

  if (textureId == bedrockId) {
    texel = texture2D(bedrock, vUv);
  } else if (textureId == stoneId) {
    texel = texture2D(stone, vUv);
  } else if (textureId == dirtId) {
    texel = texture2D(dirt, vUv);
  } else if (textureId == sandId) {
    texel = texture2D(sand, vUv);
  } else if (textureId == grassId) {
    texel = texture2D(grass, vUv);
  } else if (textureId == gravelId) {
    texel = texture2D(gravel, vUv);
  } else if (textureId == snowId) {
    texel = texture2D(snow, vUv);
  };

  gl_FragColor = vec4(texel.xyz * vBrightness, 1);
}

```

# Answer
We bind the sampler2D array to a list of textureIds, then we access them using a for loop in the shader (we cant use variables since glsl doesn't accept variable indices)

```
const textureIds = [];

function bindTexture(image, textureId) {
  const texture = gl.createTexture();
  gl.activeTexture(gl.TEXTURE0 + textureId);
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  gl.generateMipmap(gl.TEXTURE_2D);
};

for (let i = 0; i < numberOfTextures; i++) {
  const textureName = textures[i];
  const image = document.querySelector(`.${textureName}`);

  bindTexture(image, i);
  textureIds.push(i);
};

const program = createProgram(`
  precision highp float;

  uniform mat4 matrix;

  attribute vec3 position;
  attribute float textureId;
  attribute vec2 uv;
  attribute vec3 normal;

  varying float vTextureId;
  varying vec2 vUv;
  varying float vBrightness;

  void main() {
    gl_Position = matrix * vec4(position, 1);

    vec3 lightDirection = vec3(0, 1, 0);
    vTextureId = textureId;
    vUv = uv;
    vBrightness = max(0.0, dot(normal, lightDirection));
  }
  `, `
  precision highp float;

  uniform sampler2D samplerArray[4];

  varying float vTextureId;
  varying vec2 vUv;
  varying float vBrightness;

  void main() {
    int textureId = int(vTextureId);
    vec4 texel;

    for (int i = 0; i < 4; i++) {
      if (i == textureId) {
        texel = texture2D(samplerArray[i], vUv);
        break;
      }
    }

    gl_FragColor = vec4(texel.xyz * vBrightness, 1);
  }
`);

const samplerArrayLocation = gl.getUniformLocation(program, "samplerArray");

gl.uniform1iv(samplerArrayLocation, textureIds);

```
> 0 votes

---
Tags: textures, glsl
---


title: Monogame - SpriteFont build error

text:
# Question
Title: Monogame - SpriteFont build error
I am quite new to Monogame. When I try importing a .spritefont file using the Monogame Pipeline GUI Tool and then build it, it gives me an error: "System.DllNotFoundException: Unable to load DLL 'freetype6.dll'". I tried to go into the "C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools" directory, and I found out that the dll is there. I am really confused why is this happening.

I am using VS Community 2017 and Monogame 3.0

# Answer
> 0 votes
You can try these 2 methods:

1.
2. Try re-compiling freetype6 yourself if method 1 doesn't work.

---
Tags: monogame, spritefont
---


# Question
Title: How can I remove unnecessary vertices from wall edges?
I've got a pretty simple tile based 2d top-down map with an array of walls. In order to figure where to cast light and shadows, I've generated an array of vertex coordinates along the walls like so:

The blue points I'd like to keep while removing the green points. How can I check if a point should be kept or removed?

# Answer
> 0 votes
Instead of guiding a wall-following algorithm along the wall tiles, which is a method that probably would have worked, I decided to solve this problem by finding the line segments that make up the edge of the walls instead.

Here is the code I ended up writing!

For reference, "colmap" refers to the array of walls. colmap\[y\]\[x\] returns the tile value. My tiles are 8x8 pixels, which is why some vectors are being multiplied by 8.

```
// find wall vertices

// first, get the edges of walls in lines
let lines = [];
let overlaps = function(l) {
  for (let i in lines) {
    let line = lines[i];

    if (
      line.a.x == l.a.x &&
      line.a.y == l.a.y &&
      line.b.x == l.b.x &&
      line.b.y == l.b.y
    ) {
      return true
    }
  }
  return false
};
let lineAngle = function(cx, cy, ex, ey) {
  var dy = ey - cy;
  var dx = ex - cx;
  var theta = Math.atan2(dy, dx);
  theta *= 180 / Math.PI;
  return theta;
};
for (let y=0; y<this.colmap.length; y++) {
  for (let x=0; x<this.colmap[y].length; x++) {
    if (this.colmap[y][x] != "wall") continue;

    let tx = x*8;
    let ty = y*8;

    let line;

    // 4 lines for each wall tile
    // top
    if (y > 0 && this.colmap[y-1][x] != "wall") {
      line = {
        a: { x: tx, y: ty },
        b: { x: tx+8, y: ty },
        angle: lineAngle(tx, ty, tx+8, ty)
      };
      if (!overlaps(line)) lines.push(line);
    }
    // right
    if (x+1 < this.colmap[y].length && this.colmap[y][x+1] != "wall") {
      line = {
        a: { x: tx+8, y: ty },
        b: { x: tx+8, y: ty+8 },
        angle: lineAngle(tx+8, ty, tx+8, ty+8)
      };
      if (!overlaps(line)) lines.push(line);
    }
    // bottom
    if (
      x+1 < this.colmap[y].length &&
      y+1 < this.colmap.length &&
      this.colmap[y+1][x] != "wall"
    ) {
      line = {
        a: { x: tx, y: ty+8 },
        b: { x: tx+8, y: ty+8 },
        angle: lineAngle(tx, ty+8, tx+8, ty+8)
      };
      if (!overlaps(line)) lines.push(line);
    }
    // left
    if (x > 0 && this.colmap[y][x-1] != "wall") {
      line = {
        a: { x: tx, y: ty },
        b: { x: tx, y: ty+8 },
        angle: lineAngle(tx, ty, tx, ty+8)
      };
      if (!overlaps(line)) lines.push(line);
    }
  }
}

// second, consolidate lines that connect and have the same angle
for (let i=lines.length-1; i>0; i--) {
  let l = lines[i];
  for (let x in lines) {
    let n = lines[x];

    if (
      l.a.x == n.b.x &&
      l.a.y == n.b.y &&
      l.angle == n.angle
    ) {
      n.b = { x: l.b.x, y: l.b.y };
      lines.splice(i, 1);
    }
  }
}

// lastly, generate vertices from the lines!
let verts = [];
overlaps = function(v) {
  for (let i in verts) {
    let n = verts[i];
    if (v.x == n.x && v.y == n.y) {
      return true
    }
    return false
  }
};
for (let i in lines) {
  let l = lines[i];
  let v = { x: l.a.x, y: l.a.y };
  if (!overlaps(v)) verts.push(v);
  v = { x: l.b.x, y: l.b.y };
  if (!overlaps(v)) verts.push(v);
}

this.vertices = verts;

```

---
Tags: algorithm, geometry, computational-geometry, vertex-arrays
---


# Question
Title: Creating 2d array in gamemaker from code
According to GameMaker2 arrays documentation, GML has 2d arrays. At the same time I could not find any references how can I create 2d array from code. I tried doing

```
board = array_create(global.MAX_HEIGHT);
for(var i = 0; i < global.MAX_HEIGHT; i++){
    board[i] = array_create(global.MAX_WIDTH);
}

```

but that seems to have created a 1d array of 1d arrays, meaning I cannot access them using `board[x, y]` (if I try it doesn't assign values properly) , or even `board[x][y]` (compilation error). Is there a way to dynamically create 2d array? Or to access this array more elegantly, instead of having to use

```
inside_array = board[i];
inside_array[j] = value;

```

# Answer
> 1 votes
The answer is- don't initialize the array, just access it. It will dynamically create 2d array. So to initialize 2d array to `0`s, do

```
for(var i = 0; i < global.MAX_HEIGHT; i++){
  for(var j = 0; j < global.MAX_WIDTH; j ++){
    board[i, j] = 0;
  }
}

```

# Answer
> 0 votes
The documentation says you "access multi-dimension arrays with extra sets of brackets". If you got a compiler error, you must have done something else wrong.

2d arrays are documented to be accessed like so:

```
array2d[i][j]=1;

```

# Answer
> -1 votes
I prefer to use **repeat** instead of **for**, but you can enjoy the logic.

Basically you will use one loop inside another.

**Code:**

```
repeat(global.MAX_HEIGHT){
    i+=1;
    repeat(global.MAX_WIDTH){
        j+=1;
        board[i,j]=0;
    }
    j=0;
}

i=0;
j=0;

```

Then remember to reset the value of **i** and **j**.

---
Tags: game-maker
---


# Question
Title: How do I add multiplayer in to my unity game?
I made a 2d game for phones where screen is divided in two parts. I have made game for local multiplayer. Upper half player1 and lower half player2. What do I need to do to make that upper half multiplayer so you can play with your friends or random people of internet. What is the way to go about it?

# Answer
> -1 votes
#### Getting your game working and networked

If you're not very familiar with coding or network concepts, I would use a package like PUN and just follow one of their introductory tutorials.

#### Learning about networking

If you're interested in networking itself, then I would familiarize myself with the basics of how internet functions, and some of its common protocols: here's a tutorial. After that, I would learn about game specific architectures, how do different genres handle multiplayer? How do FPSs, RTSs, MMOs or Collectible Card Games strategies differ and why? I would implement some simple networked games with lowerish-level APIs (probably System.Net.Socket in .NET if you want cross platform).

---
Tags: unity
---


title: Find Largest Room in 2d World

text:
# Question
Title: Find Largest Room in 2d World
I'm currently working on a generated(Perlin Noise) 2D Cave System with Unity.
The Caves currently look like this:

What I want to do is spawn the Player (and other stuff) in the big Part of the Cave and not the small ones, so I wanted to have some sort of List of all the Tile(positions) of the Big Room.

I thought about a Pathfinding algorithm for finding like the two furthest away points and determine the distance, but I had no clue how to find those starting points.

The final function should look like this:

```
List<Vector2> GetLargestRoom(int[,] map) // where int[x,y] is either 0 or 1 for solid/ not solid

```

# Answer
> 3 votes
To start with, we need to break down what is meant by room or cave. With respect to the 2D array in the problem description, a room is a collection of elements that are 'connected'. For any given starting point, we can identify all the elements of a connected region using a flood fill algorithm.

The flood fill algorithm presented below works as follows:

* tag the starting point
* place a starting point in the work queue
* while the work queue isn't empty
    + remove an element from the queue
    + get the neighbors of the current element
    + for each valid neighbor (meaning it's not a wall & hasn't already been tagged)
        - tag it (the neighbor) & add it to the queue

When the work queue is empty, all of the elements that are reachable from the starting point will have been visited and tagged. Because the problem description requests a list of all the element locations, whenever an element is tagged, it will also be added to a list.

Flood fill alone isn't quite enough to solve the problem though. We still need a way to find the starting point of the largest room. Since we don't necessarily know where the largest room is, we'll need to iterate over the 2D array and look for it. If we encounter an element isn't open or has already been tagged, we can skip over it. If we encounter an open element that hasn't previously been identified as belonging to a region, we flood fill starting at that location.

There are a couple of options regarding what to do each time the flood fill finishes with a region:

* Compare the most recently found region against the largest know region & only keep track of the largest.
* Keep track of all the regions and then find the largest.

The second option requires a bit more memory, but also provides some extra benefits that might be useful when dealing with procedurally generated caves. Also, after seeing the solution for the second, it's pretty trivial to trim it back down it the first option. Since the second option provides more flexibility and isn't significantly more complex, it's the solution we will examine.

Here's the code:

```
using System.Collections;
using System.Collections.Generic;
using System.Numerics;

namespace LargestRoomProject
{
    public class CaveGridManager
    {
        public int[,] regionID;
        public List<List<Vector2>> regionCoords;

        // helper class for dealing with a map
        // assumes 0 == wall & 1 == open
        public CaveGridManager(int[,] data)
        {
            regionID = new int[data.GetLength(0), data.GetLength(1)];
            for(int x=0; x<regionID.GetLength(0); x++)
            {
                for(int y=0; y<regionID.GetLength(1); y++)
                {
                    regionID[x,y] = -1;
                }
            }
            regionCoords = new List<List<Vector2>>();

            for(int x=0; x<data.GetLength(0); x++)
            {
                for(int y=0; y<data.GetLength(1); y++)
                {
                    if(data[x,y] == 1 && regionID[x,y] == -1)
                    {
                        regionCoords.Add(FillNewRegion(data, x, y));
                    }
                }
            }
        }

        // start a new region at the x,y coords, fill it with the next available regionID and
        // return a list of the x,y coords of that regions
        private List<Vector2> FillNewRegion(int[,] data, int x, int y)
        {
            int ID = regionCoords.Count;
            List<Vector2> coords = new List<Vector2>();
            regionID[x, y] = ID;
            Queue queue = new Queue();
            coords.Add(new Vector2(x, y));
            queue.Enqueue(new Vector2(x, y));
            while (queue.Count > 0)
            {
                Vector2 curr = (Vector2)queue.Dequeue();
                foreach (Vector2 neighbor in (ValidNeighbors(curr)))
                {
                    if (data[(int)neighbor.X, (int)neighbor.Y] == 1 && regionID[(int)neighbor.X, (int)neighbor.Y] == -1)
                    {
                        regionID[(int)neighbor.X, (int)neighbor.Y] = ID;
                        coords.Add(neighbor);
                        queue.Enqueue(neighbor);
                    }
                }
            }
            return coords;
        }

        // returns a list of the valid cardinal direction neighbors for the given location on the grid
        private List<Vector2> ValidNeighbors(Vector2 v)
        {
            List<Vector2> neighbors = new List<Vector2>();
            if (v.X - 1 > 0)
            {
                neighbors.Add(new Vector2(v.X - 1, v.Y));
            }
            if (v.Y - 1 > 0)
            {
                neighbors.Add(new Vector2(v.X, v.Y - 1));
            }
            if (v.X + 1 < regionID.GetLength(0))
            {
                neighbors.Add(new Vector2(v.X + 1, v.Y));
            }
            if (v.Y + 1 < regionID.GetLength(1))
            {
                neighbors.Add(new Vector2(v.X, v.Y + 1));
            }
            return neighbors;
        }

        // convenience method to get the coords of the largest room on the map
        // assumes 0 == wall & 1 == open
        public static List<Vector2> GetLargestRoom(int[,] data)
        {
            CaveGridManager mgr = new CaveGridManager(data);
            List<Vector2> largest = new List<Vector2>();
            foreach (List<Vector2> list in mgr.regionCoords)
            {
                if (list.Count > largest.Count)
                {
                    largest = list;
                }
            }
            return largest;
        }
    }
}

```

The class above can be used a couple of different ways. The simplest to pass a rectangular `int[,]` to the static method & get back a list of coords as described in the original problem statement:

```
List<Vector2> coordList = CaveGridManager.GetLargestRoom(map);

```

For any given `x,y` location on the map, we can immediately see which room (if any) it belongs to by checking `regionID[x,y]`. Assuming there's a room there (that is to say `regionID[x,y] >= 0`) we can then immediately get all of the coords for that room by checking `regionCoords[n]` (where `n` is the ID of the room. If desired, these features can help us use the class in other ways. For instance, we could find rooms that are below a certain threshold & fill them. Or include some methods for connecting separate rooms with tunnels.

The flood fill algorithm used here is the four-way stack/queue based non-recursive implementation. It has the advantage of being relatively easy to understand and it has been optimized to check elements before committing them to the queue. It's likely to be fine for most cases, but if profiling the application reveals a problematic bottle in the flood fill code, there are some known optimizations that may help. For instance, it could be optimized further to take advantage of span filling.

---
Tags: unity, 2d, procedural-generation, path-finding, perlin-noise
---


# Question
Title: How to make instantiated gameObject to be child of other object
I have a game object that I want to instantiate. There is no problem at all with the `Instantiate()` method. But the problem is, whenever I instantiate the object I want it to be a child of another object (like in the hierarchy). For example, a keyboard object is a child of a notebook object in the hierarchy.

Whenever I instantiate the keyboard, I want it to be a child of the notebook object.

How to do this?

# Answer
As mentioned by user Zibelas, you can use the `Instantiate(Object original, Transform parent)` function to instantiate an object. This will immediately set `parent` as its parent after its creation, thus it will become a child of the `parent` Transform. Usage:

```
GameObject newObject = Instantiate(originalPrefab, newParent);

```

This is equivalent to doing this:

```
GameObject newObject = Instantiate(originalPrefab);
newObject.transform.SetParent(newParent);

```
> 1 votes

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


# Question
Title: Can't create Render Target with CreateDxgiSurfaceRenderTarget
I'm trying to create ID2D1RenderTarget to be used for writing text with DirectWrite. I tried two methods but can't get it working, both yield "The parameter is incorrect" error code.

In the first one I created Texture2D with CreateTexture2D and got IDXGISurface with ID3D11Texture2D\_QueryInterface. In the second one i got surface directly from back buffer with IDXGISwapChain2\_GetBuffer but that doesn't work either.

I think the problem is in the surface but i just don't understand this stuff deeply enough to debug it correctly. Here is my code for the second method:

Getting the surface (i tried with IDXGISurface2 too):

```
IDXGISurface * BackBuffer = 0;

HR = IDXGISwapChain2_GetBuffer(Renderer.SwapChain2,
                               0,
                               &IID_IDXGISurface,
                               (void**)&BackBuffer);

AssertHR(HR && BackBuffer);

D2DMake(BackBuffer ,&Renderer.DWriteRenderTarget);

```

And the code for creating RenderTarget:

```
extern "C" void
D2DMake(IDXGISurface * DxgiSurface,
        ID2D1RenderTarget ** DWriteRenderTarget)
{
    ID2D1Factory2 * D2DFactory2 = 0;

    HRESULT HR = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED ,&D2DFactory2);
    AssertHR(HR);

    D2D1_RENDER_TARGET_PROPERTIES Props =
        D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,
                                     D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
                                     0,
                                     0);

    Assert(DxgiSurface && D2DFactory2);

    HR = D2DFactory2->CreateDxgiSurfaceRenderTarget(DxgiSurface,
                                                    Props,
                                                    DWriteRenderTarget);

    AssertHR(HR);  // Here is where it fails
    ...

```

And the way i create SwapAndChain

```
DXGI_SWAP_CHAIN_DESC1 SwapChainDesc =
        {
            .Format      = DXGI_FORMAT_B8G8R8A8_UNORM,
            .SampleDesc  = {1, 0},
            .BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
            .BufferCount = 2,
            .SwapEffect  = DXGI_SWAP_EFFECT_FLIP_DISCARD,
            .Scaling     = DXGI_SCALING_NONE,
            .AlphaMode   = DXGI_ALPHA_MODE_IGNORE,
            .Flags       = 0,
        };

        IDXGISwapChain1 *SwapChain1 = 0;
        HR = IDXGIFactory2_CreateSwapChainForHwnd(DxgiFactory2,
                                                  (IUnknown*)Renderer.Device2,
                                                  Window,
                                                  &SwapChainDesc,
                                                  0,
                                                  0,
                                                  &SwapChain1);

        AssertHR(HR);

        HR = IDXGISwapChain2_QueryInterface(SwapChain1,
                                            &IID_IDXGISwapChain2,
                                            (void **)&Renderer.SwapChain2);

        AssertHR(HR);

```

# Answer
> 2 votes
I got to the bottom of this by enabling debug layer, both on d3d11 side and d2d side. Creating ID2D1Factory with debug options set on D2D1\_DEBUG\_LEVEL\_INFORMATION revealed that I didn't enable D3D11\_CREATE\_DEVICE\_BGRA\_SUPPORT flag when creating ID3D11Device.

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