# Question
Title: How I start a over a new game using a ui button logic code?
My Hierarchy have 3 main GameObjects :

1. Game Data where all the gameplay objects are stored as childs of the Game Data GameObject.
2. Main Menu and all objects of the main menu stored as childs under the Main Menu GameObject.
3. Game Manager GameObject that have a script that control the game like pausing the game or go to the main menu.

By default the Game Data is disabled and all the gameplay objects childs disabled too. Then when starting the game with the main menu when clicking the button to start a new game I'm just activating the Game Data object :

This script is attached to the Main Menu :

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

public class MainMenu : MonoBehaviour
{
    public GameObject gameData;

    public void StartNewGame()
    {
        gameData.SetActive(true);
    }

    public void ResumeGame()
    {

    }

    public void QuitGame()
    {
        Application.Quit();
    }
}

```

This is working for first time starting a new game.

And this script is attached to the Game Manager GameObject :

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

public class GameController : MonoBehaviour
{
    public static bool gamepaused = false;

    public GameObject gameData;
    public GameObject mainMenu;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            gamepaused = !gamepaused;

            if (gamepaused)
            {
                Time.timeScale = 0f;
            }
            else
            {
                Time.timeScale = 1f;
            }
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            gameData.SetActive(false);
            mainMenu.SetActive(true);

            Time.timeScale = 0f;
        }
    }
}

```

This script is working. When pressing the P button the game pause/continue. When pressing the ESCAPE key the game also pause but also back to the main menu by switching the gameobjects disable/enable.

Now let's say I pressed the escape key while playing the game and I'm back to the main menu now I want to start a new complete game but clicking the StartNewGame ui button.

The problem is that this time I don't want to just active the Game Data like I did before :

```
gameData.SetActive(true);

```

This time at least in my logic I want to destroy the existing Game Data and instantiate a new Game Data using a prefab I already have of the Game Data. This is my logic but I'm not sure how to do it. Or something like that.

The main goal is to be able to start over a new game each time clicking the StartNewGame ui button.

# Answer
> 1 votes
You could just reload scene (I presume you have one scene in the game that contains all objects and logic?) using `SceneManager.LoadScene(0)`.

This will load the scene with build index '0' (the first scene in the game). You can find additional info about scenes in build here: https://docs.unity3d.com/Manual/BuildSettings.html

After loading scene all scene data will reset to default state.

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


# Question
Title: How can I get the NodePath that points to the property, rotation, of the parent node?
The 2nd arg in `interpolate_property` takes a `NodePath`, but str of a path to a prop seems fine too. So I'd expect this to work:

`var rotation_node_path = "/root/Main/Boid1/InitialRegion/Bird:rotation"`

but I'm getting the error

`ERROR: interpolate_property: Condition ' !prop_valid ' is true. returned: false`

```
func lerp_rotation():
    add_child(tween)

    var rotation_node_path = str(parent.get_path()) + ":rotation"
    var current = Math.smallest_equal_angle(parent.rotation)
    var target = Math.smallest_equal_angle(target_rotation)
    var duration = 1
    print(current, ' ', target, ' ', rotation_node_path)

    tween.interpolate_property(parent, rotation_node_path, current, target, 1, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
    tween.start()

```

# Answer
> 2 votes
It seems that `Tween.interpolate_property` does *not* look at the path before the resource. You should just pass the target node (`parent`) as the first argument, and a pure resource path as the second:

```
tween.interpolate(parent, ":rotation", ...)

```

I believe this stems from an of `set_indexed` in `Object`:

> The trouble with supporting this with set/get\_indexed directly is that they are defined in Object, and not in Node, and Object shouldn't really know about Node. Maybe the method could be overridden in Node, but this could have performance implications.

# Answer
> 0 votes
isolated & minimal project w/ solution: the triangle rotates counter-clockwise forever

Child.gd

```
extends Node2D

onready var parent = $"../"
onready var tween = Tween.new()
onready var target_rotation = parent.rotation

func _ready():
    add_child(tween)
    tween.start()
    tween.connect("tween_completed", self, "_on_tween_tween_completed")
    lerp_rotation()

func lerp_rotation():
    var current = parent.rotation
    target_rotation += -PI / 2
    var duration = 1
    print(current, ' ', target_rotation, ' ')

    tween.interpolate_property(parent, "rotation", current, target_rotation, duration, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)

func _on_tween_tween_completed(object, key):
    lerp_rotation()

```

---
Tags: godot, gdscript
---


# Question
Title: How to change the amount of Fast Linear Gaussian blur in GLSL?
I implemented the GLSL from http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/, but is unclear to me how to reduce or increase the amount of blur. Has it something to do with the iterations? I don't understand how.

# Answer
There are a few ways to control the amount of blur:

1. Change your kernel size.

This is the width of the window you sample from your source texture. The guide you're using samples a 9-pixel window (4 pixels to either side of the center), using 5 texture samples.

By adding more texture samples you can make that window wider, for more blur. Or by sampling a smaller neighborhood around your center you can get less blur.

To maintain the Gaussian property when using a different kernel size, you'll need to adjust the weight you apply to each pixel (called the kernel weights), which your guide already shows you how to calculate.
2. Iterate your blur.

If you want to blur *a lot* more, then just making your kernel wider and wider might start to get prohibitively expensive because you have to do so much texture fetching for every fragment.

Instead you can just blur once with your current kernel size, then blur again with the same (or different) kernel size. That is:

* Original Image --\[horizontal blur\]--\> intermediate
    * intermediate --\[vertical blur\]--\> 1x blurred
    * 1x blurred --\[horizontal blur\]--\> intermediate
    * intermediate --\[vertical blur\]--\> 2x blurred

This gives you the effect of a single Gaussian blur whose radius is the square root of the sum of the squares of the radii of the blurs used as stepping stones.

So repeating your 9-pixel blur (horizontal & vertical) twice would do the same as scaling up your kernel 1.4x (to about 13 pixels) — so it's not as efficient as just widening your kernel as long as you can do so. It's just a way to keep blurring more even if you hit an absolute cap on texture samples (eg. on older/weaker hardware)
3. Down-sample first.

If you need a particularly extreme blur, you can go via a smaller texture as an intermediate.

Your first pass might average blocks of 4 pixels to produce a texture half the width and height of your original. Then repeat with this texture to make one a quarter the width & height of your original.

Now when you run your 9-pixel Gaussian blur using this quarter-sized texture as input, it's like running a 36-pixel blur on your original source texture, at vastly reduced cost.

The downsampling will erase high-frequency information from your texture, but so does a big blur kernel, so in practice the scaling artifacts are not very noticeable in the blurred output.
> 3 votes

---
Tags: shaders, glsl, blur
---


# Question
Title: Unity - Rotating X on camera changes result of ScreenPointToRay completely
I am using `ScreenPointToRay` to draw a Line along my Mouse drag. My code for getting my mouse position looks like so:

```
public static RaycastHit RaycastScreenPoint(Vector2 mousePosition, LayerMask mask, Camera cam)
{
    var ray = cam.ScreenPointToRay(mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, float.PositiveInfinity, mask))
    {
        Debug.DrawRay(hit.point, Vector3.up, Color.red, 2);
        return hit;
    }
    else
    {
        throw new System.Exception("Mouse raycast did not hit anything");
    }
}

```

With my perspective camera at `65, 0, 0`, this works great. However, if I change the rotation of my camera to `90, 0, 0`, the line is drawn outside the camera view, why is this?

I want this line to be drawn the same no matter the camera rotation.

My code for drawing line:

```
private void Update()
{
    if (Input.GetMouseButtonDown(1))
    {
        lr.positionCount = 2;
        startPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(0, startPos);
    }

    else if (Input.GetMouseButton(1))
    {
        endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(1, endPos);
    }

    else if (Input.GetMouseButtonUp(1))
    {
        endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(1, endPos);
    }
}

```

This image is with the camera rotation at `64, 0, 0`. As you can see, the Line is drawn inside the camera view as intended, and follows my mouse:

This image is with the camera rotation at `90, 0, 0`. I am dragging my mouse in the middle of the game view, and yet for some reason, the line is ending up outside the camera:

# Answer
Ah, I think I know what the problem is. At least, this is the only thing I was able to reproduce. What happens is that you are drawing your line on top of or **inside of** the object you are hitting with your raycast. Meaning that when rendering it has to choose which it has to put on top (the line or the plane). And at the rotations of 0, 90, 180, etc. it chooses to draw the plane on top of the line.

To fix this, you could give the line a small offset to make sure the line is in front of the plane, for example, change your raycast method to something like this:

```
public static Vector3 RaycastScreenPoint(Vector2 mousePosition, LayerMask mask, Camera cam)
{
    var ray = cam.ScreenPointToRay(mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, float.PositiveInfinity, mask))
    {
        Debug.DrawRay(hit.point, Vector3.up, Color.red, 2);
        return hit.point - ray.direction * 0.01f;
    }
    else
    {
        throw new System.Exception("Mouse raycast did not hit anything");
    }
}

```

Or give the line a material that uses a shader that always draws on top of the material used by the plane.
> 1 votes

# Answer
I can't comment because of reputation... but troien is right. Not sure why you downvoted them. Your plane and line are taking up the exact same area in the world. Depending on camera angle and position it will either draw the line first or the plane first. When the plane is drawn first you will not see your line due to depth checks. This is often called z-fighting when it causes flickering with moving cameras or objects.

You can also manipulate when the line drawing is queued in rendering but just moving the line to be in front of the plane like troien did is a better idea. If you use a transparent material for the plane it might reorder the draw queue to avoid this problem as well but thats more like wishfull thinking than a solution.
> 0 votes

---
Tags: unity
---


# Question
Title: How to scale player as they travel between 2 points
I'm doing a VR Project where the player walks down a hallway.

The player starts with a size of 10 and is supposed to scale down to a size of 0.5 (well the GameObject in which all the player stuff is inside is supposed to do the scaling). The script below is on the GameObject which has all the player things like the camera, hands and so on are inside it.

I'm not very good at coding so I'm pretty much failing on managing to write this script. this is how far I have gotten:

```
public class ScalePlayer : MonoBehaviour
{
    public GameObject minDistance;
    public GameObject maxDistance;

    public Vector3 maxScale;
    public Vector3 minScale;

    Vector3 posStart;
    Vector3 posEnd;
    Vector3 curDistance;
    Vector3 distance;

    void Start()
    {
        posStart = minDistance.transform.position;
        posEnd = maxDistance.transform.position;

        maxScale = transform.localScale;
    }

    void Update()
    {
        distance = posStart - posEnd;

        curDistance = transform.position - posEnd;

        transform.localScale = Vector3.Lerp(maxScale, minScale, curDistance);
    }
}

```

In my logic I have an invisible object for the start point and one at the end to save where the player is supposed to be big and where they should be small.

I don't know though how or where to put my scaling values (10 -\> 0.5) and the script itself is throwing errors (probabaly because I really am not sure how to get the current position of my player compared to the start and end of the hallway).

But what I hope for, is that when the player walks down the Hallway and gets closer to my invisble end point, they smoothly shrink down to the size of 0.5 on their way there, and when they decide to go back, they scale up gradually on the way to the start to 10 again when they reach the beginning.

Working with Unity 2019 and C#.

Halfway solved my problem but I am Stuck with VRTK4. But thank you for the Edit DMGregory.

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

public class ScalePlayer : MonoBehaviour
{
    public GameObject minDistance;
    public GameObject maxDistance;

    float StartScale = 10;
    float EndScale = 0.5f;

    Vector3 posStart;
    Vector3 posEnd;
    float curDistance;
    float dist;

    public Transform movingPlayer;

    // Start is called before the first frame update
    void Start()
    {

        posStart = minDistance.transform.position;
        posEnd = maxDistance.transform.position;

    }

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

        dist = posStart.x - posEnd.x;
        curDistance = movingPlayer.position.x - posEnd.x;
        float shrinkProgress = Mathf.Clamp(curDistance, 0, dist) / dist;
        float scale = EndScale + ((StartScale - EndScale) * shrinkProgress);
        transform.localScale = Vector3.one * scale;
        //movingPlayer.transform.position = preScalePos;
        //Vector3.Lerp(Vector3.one * StartScale,Vector3.one * EndScale, curDistance);
        //Vector3 preScalePos = movingPlayer.transform.position;
        //transform.position = child.transform.position;

    }
}

```

Was my first time posting anything anywhere, so sorry for not getting it 100% right the first time with how things are supposed to look.

If anyone has tried something like this with VRTK and has any idea how to scale the player, I would appreciate the help.

# Answer
> 0 votes
One solution could be to scale it over the remaining distance since you start at 10 then running back and forth would auto scale back up also. You would have to adjust to your needs.

```
using UnityEngine;

```

public class ScalePlayer : MonoBehaviour {

```
public GameObject maxDistance;
public Transform movingPlayer;

void Update()
{
    //moving transform example to show movement remove this if you have a move already.
    transform.Translate(Vector3.forward * 2 * Time.deltaTime);
    //distance is the remaining distance before Moveplayers position and the end position.
    var dist = Vector3.Distance(movingPlayer.transform.position, maxDistance.transform.position);
    //set the scale to be the remaining distance
    transform.localScale = new Vector3(dist,dist,dist);
}

```

---
Tags: unity, c#, scale, virtual-reality
---


# Question
Title: How can I move my player on exact x and y coordinates, like on a grid?
I'd like to implement movement exactly like it is done in this game. (You can see it in action on YouTube.)

I need my Player to always stay in the center of X and Y similar to grid movement, but with free movement/line like. Only move on x and y lines. And I need smooth changes at intersections.

```
 var x = Input.getAxis("Horizontal");
 var y = -Input.getAxis("Vertical");
 var deltaPos = Vector2.zero;

 if (Mathf.Abs(inputY) > Mathf.Abs(inputX)) {
     deltaPos.Y = speed * inputY * Time.deltaTime;
 }
 else {
     deltaPos.X = speed * inputX * Time.deltaTime;
 }

 transform.position += deltaPos;

```

# Answer
Disabling the diagonal movement could be a good enough option. The example looks like they did that along with adding box colliders notice that the characters can be overlapped under the blocks at some points in the video. This may be enough to get you going on the right path.

```
void Update()
{
    TranslateNonDiagnalMovement(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void TranslateNonDiagnalMovement(float x, float y)
{
    x = y > .1f | y < -.1f ? 0 : x;
    y = x > .1f | x < -.1f ? 0 : y;

    transform.Translate(x * 3, y * 3, 0);
}

```
> 1 votes

---
Tags: unity, 2d, movement
---


# Question
Title: Rotate an object on itself, from one random Quaternion to another
I have a situation: I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector: vector A, and vectorB:

My question is: How to I rotate over time my object, from A to B ? The vector A is important: I don't want to simply rotate the forward of the object from current forward to B.

I know I can use the function vector3 C = Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A & B.

but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do: gameObject.transform.forward = C;

I want something like: gameObject.transform.rotation = SomeQuaternion(C, initial rotation A). or something.

Thank you for help !

PS: I don't want to parent / unparent gameObject or something like that, i want the math answer, using Quaternion.

# Answer
---

## New Answer

Since you have two vectors to begin with, *instead of two quaternions*, Find the quaternion representing the rotation from one vector to another.

Then you can take a copy of the current rotation quaternion, and multiply it with the quaternion you got from the vectors, which gives you the final rotation quaternion. You can then lerp from your copy of the current rotation quaternion to the final rotation quaternion you computed.

---

## Old Answer

You had the right keyword: lerp.

To be more precise, Quaternion.Lerp.

Example from docs.unity3d.com:

```

using UnityEngine;

public class Example : MonoBehaviour
{
    // Interpolates rotation between the rotations
    // of from and to.
    // (Choose from and to not to be the same as
    // the object you attach this script to)

    Transform from;
    Transform to;
    float speed = 0.1f;
    void Update()
    {
        transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);
    }
}

```
> 1 votes

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


# Question
Title: Confused why draw code is clearing, pico-8 api demo
In the API demo when they do the example of how to draw a colour pallette at the top of the screen: I notice the commands don't work when used inside the draw function. When used inside of draw they showup for a second and disappear. removing the cls() allows them to stay, but I need cls included. What do i need to be doing to get the pallette to stay while using the following within the draw function?

```
function _draw()
       cls()
       rectfill(1,1,7,7,5)
       for i=0,10 do
          print(i,x,2,i)
          x = x + 6
       end
end

```

# Answer
I can't find the API demo you were looking at to get that code. But here's how to fix the code you wrote so that it does what *I think* you want it to.

First, make sure you set the variable X somewhere before the `FOR` loop.

Second, there are 16 colors ( zero through fifteen ) so the `FOR` loop should start at 0 and end at 15.

Third, each number/letter is 3 pixels wide so adding 6 to X works for numbers 0 - 9 but double digits begin to overlap so increasing it to `X=X+8` works well.

Fourth, the rectangle is there, I assume, to make the zero color (black) visible. But it can be better positioned around the zero by changing the x-axis variables of the `RECTFILL`.

CODE:

```
function _draw()
  cls()
  rectfill(0,1,4,7,5)
  x=1
  for i=0,15 do
    print(i,x,2,i)
    x = x + 8
  end
end

```

RUN:
> 1 votes

---
Tags: pico-8
---


# Question
Title: Calculate Discrete Fourier Transform by using c#
There is a definition of Discrete Fourier Transform:

>

I want to calculate amplitude and phase of a transformed sequence.

>

I tried :

```
 public ArrayList phase = new ArrayList();
 public ArrayList amp = new ArrayList();
 public float phi = 0;

 void Start ()
 {
      DFT();
      foreach (var ampList in amp)
      {
        Debug.Log(ampList);
      }
 }

 void DFT()
 {
  //Given sequence of Numbers

  float[]  X = {1,2,3};
  float[]  Y = {2,3,5};
  float  N = X.Length;
  float re = 0;
  float im = 0;

  for (int k = 0; k < N; k++)
  {
      //The discrete Fourier transform, lists of Re & Im instead of a+ib
      for (int n = 0; n < N; n++)
       {
           float phi =  (Mathf.PI * k *n)/N;
           re += X[n] * Mathf.Cos(phi) - Y[n] * Mathf.Sin(phi);
           im -= Y[n] * Mathf.Cos(phi) - X[n] * Mathf.Sin(phi);
       }

      re = re/N;
      im = im/N;
      var  ampp = Mathf.Sqrt(re*re + im*im);
      var  phasse  = Mathf.Atan2(re,im);

      phase.Add(phasse);
      amp.Add(ampp);
  }
}

```

but answer is Not correct, I use Wolfram Mathematica to check the answer :

>

# Answer
> 1 votes
There are a number of minor issues that are getting in your way. The following corrections are assuming you are using the definition you provided by Wikipedia:

1. The `re` and `im` variables should be inside the `for` loop for variable `k`, so that they get reset for every element of the output sequence
2. `phi` is missing a factor of `2`
3. The signs of some of the `sin` and `cos` terms are reversed
4. There is no need to divide `re` and `im` by `N`

The final code should look something more like this:

```
float[] X = {1, 2, 3};
float[] Y = {2, 3, 5};
float N = X.Length;

for (int k = 0; k < N; k++)
{
    float re = 0;
    float im = 0;

    //The discrete Fourier transform, lists of Re & Im instead of a+ib
    for (int n = 0; n < N; n++)
    {
        float phi = (2 * Mathf.PI * k * n) / N;
        re += X[n] * Mathf.Cos(phi) + Y[n] * Mathf.Sin(phi);
        im += Y[n] * Mathf.Cos(phi) - X[n] * Mathf.Sin(phi);
    }

    var ampp = Mathf.Sqrt(re * re + im * im);
    var phasse = Mathf.Atan2(re, im);

    phase.Add(phasse);
    amp.Add(ampp);
}

```

Also, Wolfram Mathematica's `Fourier` function uses a different convention by default than the one you are using. See the section on `FourierParameters` in the documentation of the `Fourier` function. It looks like the definition found in Wikipedia is using the "signal processing" convention, and so you would need to try this in Wolfram Mathematica instead.

```
Fourier[{1 + 2 * I, 2 + 3 * I, 3 + 5 * I}, FourierParameters -> {1, -1}]

```

Unfortunately I do not currently have access to Wolfram Mathematica for testing, and Wolfram Alpha does not seem to support this syntax according to this stack exchange, so I will leave that part up to you :-)

As a final note, while it is definitely good to implement the Discrete Fourier Transform yourself as a learning exercise, I would recommend searching for a library which implements this for use in an actual application. Especially if you are going to be processing a lot of data, then a "Fast Fourier Transform" implementation in a good library is likely to be faster, better tested, and more accurate than anything you could make yourself in a reasonable amount of time.

Hope this helps, and best of luck!

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


# Question
Title: how to display current time as a static value in lua/pico8
Pico8 has a function time() that when called displays the current time from start of program.
i.e. print(time(),0,0,14) --prints time at (0,0) with colour 14

However the function doesn't stop and keeps drawing the time each frame. I'm trying to figure out how I would draw the time without it increasing/changing. So If I printed this 5 seconds from the start of the program I'd want it to display 5, but not change from that 5 value.

https://pico-8.fandom.com/wiki/Time I don't know how to store a static value of this time as a variable. Although according to the wiki, assigning var=time() will cause time at 0 to be stored.

Another way of phrasing this is...how would I display the time of 10 seconds when the following print is triggered? So after 10 seconds "time's up" is displayed. How would I display the current time 10, as well, as a static? Maybe I don't know what the time is when the event is triggered, so how can I count using time()?

```
function _init()
  last = time()
end

function _update()
  -- (empty update to use game loop)
end

function _draw()
  cls()
  if (time() - last) > 10 then
    print("time's up!", 44, 60, 7)
  end
end

```

# Answer
> 1 votes
You are doing it correctly by setting `time()` at a certain point as your own static variable.

Things you should know:

* `time()` can be abbreviated to `t()`
* `time()` is recorded as a float (a decimal) of seconds to ten-thousandths of a second.

To print what time your timer went off, first re-set your `LAST` variable to be the current time within your timer `IF` statement.

Then outside and after your timer `IF` statement, print the `LAST` variable.

```
function _init()
  last = time()
end

function _update()
  -- (empty update to use game loop)
end

function _draw()
  cls()
  if (time() - last) > 10 then
    print("time's up!", 44, 60, 7)
    last=time()
  end
  print(last, 44, 70)
end

```

If you don't want to print the time as a decimal and instead show only the seconds, then you can use the function `flr()` to round down like this:

```
  print(flr(last), 44, 70)

```

> NOTICE: The only problem with this code, is that `"TIME'S UP!"` will only flash on the screen because I reset `last` to the current time. So the timer resets and flashes every 10 seconds and updates the static time variable.

# Answer
> 0 votes
I'm not sure what exactly are you trying to achieve, but maybe something like this?

```
local start
local limit = 10
local finish

function _init()
  start = time()
end

function _draw()
  cls()
  local now = time()
  local delta = now - start
  if delta >= limit then
    -- time's up
    print("time's up!", 44, 60, 7)
    -- saving timestamp
    if finish == nil then
      finish = now
    end
  else
    -- still ticking
    print(delta, 44, 60, 7)
  end
end

```

---
Tags: lua, pico-8
---


# Question
Title: Can I add non-trees to terrain.terrainData.treeInstances on Unity 3D?
I need to create a brush in which there will be stones, poles, bushes and other elements of the environment. I bought a Prefab Brush. Whether it is possible to add the objects that I draw on the Prefab Brush scene to terrainData.treeInstances, as regular trees add?

Is it possible to use a not prefab tree as an object for the TreeInstance class?

# Answer
You can technically add any game object to the tree brush in the terrain object how ever the objects might not be rendered as you like since they will follow the billboard rules of trees.
> 0 votes

---
Tags: unity, c#, tree, prefabs
---


# Question
Title: How to figure out that I'm onto ice tile?
It might be very silly question but serfing for two hours still can't find an answer.

I'm trying to replicate battle city.

I've made level with TileMap. But can't figure out how to know that my tank is onto ice tile to slow him up?

# Answer
> 0 votes
I've never used the TileMap myself but reading the docs I can tell you this.

First of all you need a TileMapCollider Component, then you need to make a script and add it to the tilemap game object. The script should use `OnCollisionEnter2D(Collision2D collision)`

then feed `collision.gameObject.transform.position` to `tilemap.WorldToCell()` and use the result of that to get the specific tile you are on with `tileMap.GetTile()` that returns a TileBase class that has a tile name that you can use to determine if it is ice or not. Like I sad I've never used the TileMap so there might be a way better way of doing it. :)

# Answer
> 0 votes
Well I figured out how to do it!:)

It was easier than I thought.

Tiles have TileCollider2D it inherits all the stuff from Collider 2D. So You can turn on a trigger. And in the player's script write down event Monobehavior methods OnEnterTrigger2D OnExitTrigger2D. Where I change speed if I'm onto the ice tile:) Thanks for an answer though!:)

---
Tags: unity, 2d, tilemap
---


# Question
Title: Unity3D playing sound when Player collides with an object with a specific tag
I using Unity 2019.2.14f1 to create a simple 3D game.

In that game, I want to play a sound anytime my Player collides with a gameObject with a specific tag.

The MainCamera has an Audio Listener and I am using Cinemachine Free Look, that is following my avatar, inside the ThridPersonController (I am using the one that comes on Standard Assets \- but I have hidden Ethan and added my own character/avatar).

The gameObject with the tag that I want to destroy have an Audio Source:

---

In order to make the sound playing on the collision, I started by creating an empty gameObject to serve as the AudioManager, and added a new component (C# script) to it:

```
using UnityEngine.Audio;
using System;
using UnityEngine;

public class AudioManager : MonoBehaviour
{

    public Sound[] sounds;

    // Start is called before the first frame update
    void Awake()
    {
        foreach (Sound s in sounds)
        {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;

            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
        }
    }

    // Update is called once per frame
    public void Play (string name)
    {
        Sound s = Array.Find(sounds, sound => sound.name == name);
        s.source.Play();
    }
}

```

And created the script Sound.cs:

```
using UnityEngine.Audio;
using UnityEngine;

[System.Serializable]
public class Sound
{
    public string name;

    public AudioClip clip;

    [Range(0f, 1f)]
    public float volume;
    [Range(.1f, 3f)]
    public float pitch;

    [HideInInspector]
    public AudioSource source;
}

```

After that, in the Unity UI, I went to the Inspector in the gameObject AudioManager, and added a new element in the script that I named: CatchingPresent.

On the Third Person Character script, in order to destroy a gameObject (with a specific tag) when colliding with it, I have added the following:

```
void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.CompareTag("Present"))
            {
                Destroy(other.gameObject);
                count = count - 1;
                SetCountText();

            }
        }

```

It is working properly as that specific object is disappearing on collision. Now, in order to play the sound "CatchingPresent" anytime the Player collides with the object with the tag, in this case, `Present`, I have tried adding the following to the `if` in the `OnCollisionEnter`:

* `FindObjectOfType<AudioManager>().Play("CatchingPresent");`

But I get the error:

> The type or namespace name 'AudioManager' could not be found (are you missing a using directive or an assembly reference?)

* `AudioManager.instance.Play("CatchingPresent");`

But I get the error:

> The name 'AudioManager' does not exist in the current context

As all the compiler errors need to be fixed before entering the Playmode, any guidance on how to make the sound playing after a collision between the player and the gameObject with the tag `Present` is appreciated.

# Answer
> 0 votes
Reformulated the approach that I was following and solved the problem by simply adding an Audio Source to the ThirdPersonController (with the AudioClip that I wanted to call) and added `GetComponent<AudioSource>().Play();` to the if statement as it follows:

```
void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.CompareTag("Present"))
            {
                Destroy(other.gameObject);
                count = count - 1;
                SetCountText();
                GetComponent<AudioSource>().Play();
            }
        }

```

# Answer
> 0 votes
My guess is that since the Standard assets for the character are in their own namespace it cant find your AudioManager code. Add the AudioManager to a namespace and then #include it in the character class.

---
Tags: unity, c#, collision-detection, audio
---


title: Improve the algorithm A *?

text:
# Question
Title: Improve the algorithm A *?
Hello, I have a question about algorithm A * !

S : Start.

D : Destination.

W : Wall.

My hero goes from S and the destination is D, W is the walls, my hero can't go in there. If I use the algorithm A \*, the hero will go from Cell (3,3) then to Cell (2,2) and finally to Cell (1,1).

It would be very logical if my hero is only a point. But my hero is about the same size of a Cell. So if my hero goes from Cell (2,2) to Cell (1,1), he will be hit by two walls. Each cell is 32 * 32 in size, my hero moves pixels by pixel, so he can collide with the edge of a cell. I have a collision test function, and thus the hero cannot move on.

Can someone help me, thank everyone !

# Answer
> 0 votes
This is not a problem with the A\* algorithm. It's a problem with the data you've given it as input.

At some point in the algorithm, A\* asks your map to enumerate the neighbouring nodes reachable from the node it's currently examining.

At this point, if the node (1, 1) is not supposed to be reachable from the current node (2, 2), it's the responsibility of your map / neighbour iteration to not offer (1, 1) as an option for the algorithm to consider. If you give it that as an option, you're saying "paths that pass from that node to this node are valid".

So for example, if your neighbour-enumerating function looks like this, visiting all 8 neighbours of a node, including diagonals:

```
IEnumerator<Node> GetNeighbours(Node source) {
    for(int x = -1; x <= 1; x++) {
        for(int y = -1; y <= 1; y++) {
            if(x== 0 && y == 0)
                continue;
            if(!map.IsInBounds(source.x + x, source.y + y)
                continue;

            var node = map.GetNode(source.x + x, source.y + y);
             yield return node;
        }
    }
}

```

...then you likely want to restrict it to visit only the four orthogonal neighbours instead:

```
IEnumerator<Node> GetNeighbours(Node source) {
    if(map.IsInBounds(source.x - 1, source.y);
        yield return map.GetNode(source.x - 1, source.y);

    if(map.IsInBounds(source.x, source.y - 1);
        yield return map.GetNode(source.x, source.y - 1);

    if(map.IsInBounds(source.x + 1, source.y);
        yield return map.GetNode(source.x + 1, source.y);

    if(map.IsInBounds(source.x, source.y + 1);
        yield return map.GetNode(source.x, source.y + 1);
}

```

---
Tags: path-finding
---


title: Downsides to automatic UV unwrapping

text:
# Question
Title: Downsides to automatic UV unwrapping
I have seen several software packages that offer auto UV unwrapping as an option.

My question is why would you ever manually UV unwrap if there is an automated tool to do so? Are there any significant downsides to using an automatically generated UV map?

# Answer
> 1 votes
Like any automated tool, it's a matter of control, and whether you like the decisions the algorithm makes on your behalf.

Occasionally, you have very particular needs for a UV unwrap that the algorithm might not be optimized to serve.

For instance, I once had to set up a flowing lava river for a Wii game. We achieved the fluid flow effect by scrolling the textures along the mesh, which meant that I needed to ensure that "downstream" always aligned with "positive v" in the UV space. This involved contorting the winding river in very strange ways within the UV texture space, and going well outside the normal 0...1 bounds (since the lava textures tiled) - stuff that an automatic unwrapper wouldn't think to do out of the box, and it might be difficult or impossible to instruct it to do so. We also had to apply small aesthetic touch-ups here and there to hide stretching in inconspicuous parts of the mesh, or speed up & slow down flow based on the level art, which necessitated going in by hand.

More common cases where this might arise could be when you're hand-painting textures for your models in a conventional 2D texture map, rather than a 3D painting program or procedural material generation system. In a situation like that, it's helpful if the model's UVs are laid out in a way that's intuitive to the texture artist - similar parts grouped together, oriented in a sensible way - again stuff that an automated unwrapper might not know about or prioritize in the quest for efficient packing and uniform texel density.

Like any hypothetical, it's hard to give a concrete answer about when you should or should not use an automatic unwrap. It's easier to work on concrete examples case-by-case. If for your current task, the unwraps you're getting from the automated tools seem to be serving your needs, great! If it ain't broke, don't fix it. If you run into a case where you're not getting what you want from the automated tools - for any idiosyncratic reason that might arise in your particular project - then it will be clear that you need a different strategy.

So, don't go trying to solve that problem until / unless it actually becomes a problem for your work. ;)

---
Tags: 3d, blender, 3dsmax, uv-mapping, maya
---


# Question
Title: Unity URP - Batching GPU instanced objects with same material/mesh not working
I have 100 units (exact same prefab) on screen. The material is a URP Lit using a texture with GPU instancing enabled. Why is it not batching? Am I missing something?

I also noticed it requires 3-4 batches per model, why is this?

See screenshots for stats and info.

# Answer
> 1 votes
From docs.unity3d.com/Manual/GPUInstancing.html

> SkinnedMeshRenderer is not supported

---
Tags: unity
---


# Question
Title: Why can't I read .ttf file when running Android configuration?
When running or debugging my game on Android device, I get this error in the logcat:

> com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/fonts/myFont.ttf (Internal)

Which is created by this code line:

```
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);

```

where `fontFile` is defined like this:

```
FileHandle fontFile = Gdx.files.internal("data/fonts/myFont.ttf");

```

This doesn't happen when I run the desktop configuration.

I know that for desktop configuration you have to define the working directory of your project, but I don't see such option in android configuration and it also makes no sense, so I don't think it's a "working directory"-related problem.

Obviously, the file is in the correct path.

Also note that everything worked fine in my previous project. I created this new project by creating a new blank prj using libgdx-setup and then copying all the classes and packages from the older project. So maybe it's a problem related to some Gradle file?

# Answer
> 1 votes
If your test desktop filesystem is running on Windows NTFS and the Android device filesystem is on Android native, the difference is in the filesystem drivers.

The Windows filesystem drivers are not case sensitive but Android uses Linux which is case sensitive.

Make sure your capitalization is correct on the file.

Additionally I noticed you were using an absolute path with no environmental variable. This is dynamic to your current working directory on Android. Hence if the app is run from a different directory it will look in a different place for the file. This could cause problems between various system revisions. Always give absolute paths in Android. This means starting with either an environmental variable or the root directory (i.e. "/") For the sake of being able to move the app to an SD card it is better to use the environmental variables.

Additionally, you shouldn't be using the dynamic data directory for your font. You should be bundling it into your app's package.

# Answer
> 0 votes
I believe for android you need to have an assets folder with all of the assets loaded into it, this assets folder would be in the android project rather than the core project. Desktop, HTML, etc all use core project assets so they would work fine, but android needs its own assets folder. do you have one for it?

# Answer
> 0 votes
The Options are:

1) Try TTF upper case instead of ttf in all of your code - in case your original file has TTF suffix, because android is case sensitive.

2) In build.gradle file under your android module make sure that:

```
assets.srcDirs = ['assets']

```

And not:

```
assets.srcDirs = ['assetManager']

```

In another words make sure its your android assets folder. this one worked for me. then clean build project, and uninstall old app from android device.

# Answer
> -1 votes
Try copying the font files directly into the assets folder.

# Answer
> -1 votes
Just do one thing you can change the method which your following now. you can use the "hiero" tool for the font creation . Just download "hiero" jar file from the following link

https://libgdx.badlogicgames.com/tools.html

by using hiero you will be able to access almost all the fonts . after creating the fonts save it on your android project files "asset" folder and add the folowing code.

```
     private BitmapFont font;
     font = new BitmapFont(Gdx.files.internal("myNewFontCreatedByHiero.fnt"));

```

just try this method. it will work.

# Answer
> -1 votes
Make sure the files are inside /android/assets.

---
Tags: libgdx, loading, fonts, file, ttf
---


# Question
Title: toString() - method doesnt' choose right Array Index
My topic is a adventure game. The heroes have Superpowers, but if I want to print the superpowers from a superhero, it prints just the last index of my array, which I set it before.

My code: \`

```
public void createdTeam() {
    Superhero krieger = new Superhero("Thylraz");
    Superpower[] kriegerPowers = { new Superpower("Schwertwirbel\n", " Thylraz wirbelt mit seinem Schwert."),
            new Superpower("Schildschlag\n", " Thylraz schlägt den Zombie mit dem Schwert."),
            new Superpower("Durchschlag\n", " Thylraz macht einen Durchschlag!") };
    krieger.setSuperpowers(kriegerPowers);
    krieger.setHeroRole("Krieger");
    team.add(0, krieger);
    Superhero archer = new Superhero("Artemis");
    Superpower[] archerPowers = {
            new Superpower("gezielter Schuss", " Artemis versucht einen gezielten Schuss zu treffen."),
            new Superpower("Pfeilregen", " Artemis lässt Pfeile über den Zombie regnen!"),
            new Superpower("Falkenschlag", " Artemis ruft nach ihrer Falke!") };
    archer.setSuperpowers(archerPowers);
    archer.setHeroRole("Bogenschützin");
    team.add(1, archer);
    Superhero berserk = new Superhero("Adukan");
    Superpower[] berserkPowers = {
            new Superpower(" Elektroschlag", " Adukan lädt seine Äxte mit Elektrizität auf und schlägt zu!"),
            new Superpower(" Blutrausch",
                    " Adukan geriet in Blutrausch! Er haut auf sein Gegner mit voller Aggro!"),
            new Superpower(" Blutiger Schlag", " Adukan versucht einen tödlichen Schlag zu treffen!") };
    berserk.setSuperpowers(berserkPowers);
    berserk.setHeroRole("Berserker");
    team.add(2, berserk);
}

```

and my print method:

```
public void printOneSuperhero() {
    System.out.println("\nVon welchem Superhelden möchtest du die Daten sehen?\n");
    int index = selectSuperhero();
    System.out.println("=====================================================================================");
    System.out.println("Heldenname\tHeldenrolle\tHP-Max\tHP\tEXP\tKampfbereit\tlebendig\tFähigkeiten");
    System.out.println("=====================================================================================");
    System.out.println(team.get(index).toString());
    startMenu();
}

public class Superpower {
private String id = UUID.randomUUID().toString();
private static String superpowerName;
private static String actionDescription;

public Superpower(String superpowerName, String actionDescription) {
    this.superpowerName = superpowerName;
    this.actionDescription = actionDescription;
}
public String toString() {
         return "Skill: " + superpowerName + "\n" + "Beschreibung: " + actionDescription + "\n";

}

```

}

Edit:

```
public int selectSuperhero() {
int index = 0;
for (int i = 0; i < team.size();) {
    System.out.println("Position: " + (i++) + "" + team.get(index).print());
    index++;
}
index = scan.nextInt();
return index;

```

}

# Answer
Change

```
private static String superpowerName;
private static String actionDescription;

```

to

```
private String superpowerName;
private String actionDescription;

```

(Remove the `static` keyword.)

The `static` keyword means "the same instance of the variable for *all* of the instances of this class". Thus if you change the value for one instance, it will change it for every objects of that class.
> 1 votes

---
Tags: java
---


# Question
Title: Unity3D in WebGL the Player doesn't have animations
I using Unity 2019.2.14f1 to create a simple 3D game.

I want to build the project for WebGL, but, even though the player has animations on Unity, in the web the Player doesn't have animations even though it jumps and moves around \[as you can see here\].

For the Player, I am using the ThridPersonController from on Standard Assets \- but I have hidden Ethan and added my own character/avatar.

And this is the inspector of the avatar:

What am I missing here?

# Answer
When WebGL is not behaving the same as Unity player, something is conflicting.

In this case, as we can see from the images there are **2 animators** (one in each image) controlling for the **same purpose**.

The problem was solved by disabling the second animator (the one related with Santa - the avatar, that is inside the ThirdPersonController).
> 0 votes

---
Tags: unity, 3d, webgl, build-process
---


title: How to store information into the tile?

text:
# Question
Title: How to store information into the tile?
I have made a map via TilePallete tool.

Now I want to store information in certain tile. How I can do this?

ForEx:

I'm hittin a certain tile and I need it to have info about health remaining. For first hit I change a tile. For second I set it to null.

# Answer
> 2 votes
Unity have that tool in their 2d-extras Github repository. The tool is called GridInformation. It's basically a dictionary that can hold Integer, String, Float, Double, UnityObject or Color values and uses Vector3Int(i.e. cell position) as a key.

# Answer
> 2 votes
One approach could be to do that with scriptable tiles.

In order to do that, you need to create a new C# class which inherits from `TileBase`. You can now implement any functionality you need in this class, like having a `health` property. A useful method to override is the method `bool GetTileData(Vector3Int location, ITilemap tilemap, ref TileData tileData)`. If you want to change the appearance of the tile based on something, then you can do that by changing the `tileData` structure passed to the class, specifically the field `sprite` which you could set depending on the current health.

Unfortunately it is not that straight-forward to create a tile asset which uses that script. You have to do that through an editor script which calls `AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<YourScriptableTileClass>(), path);`. This official example shows how that can look (starts at `#if UNITY_EDITOR`).

But now you have another problem: Detecting that the tile is hit. How to do that depends on what "hitting a tile" actually means in the context of your game, but I assume that it would somehow involve having a game object with a Trigger Collider and an attached script which implements OnTriggerEnter and carries a reference to the tile it is supposed to change.

# Answer
> 1 votes
What you could do, which is think is the best solution for tiles & information is to have a dictionary containing a class thats connected to the tile index. This will behave like a lookup table in the "general terms".

some psudo code.

```
int key = TilePositionY * TileMapWidth + TilePositionX;
if( TileLookupDictionary.ContainsKey( key ) == true )
{
   MyTileDataClass = TileLookupDictionary[key];
}

```

---
Tags: unity, tilemap, tiles
---


# Question
Title: Why aren't game mods allowed to talk to the outside?
Sorry if the title is a bit obscure, I didn't know what to call this. I recently got into mod making and thought of a mod which is able to control Spotify through in-game commands, using Spotify's API to do so. However, most of the games I found which support mods (WoW through addons and Skyrim and Fallout 4 through Creation Kit) don't allow you to perform requests or even communicate with external applications. I wanted to ask why game developers perform this practice, specifically what problems can arise if the user is permitted to perform requests through the internet or communicate to external applications?

# Answer
> 3 votes
Apart from cheating:

**Security issues!**

Most of the times, mods are installed without thorough review regarding trustworthiness of the creator (who can be anyone, as opposed to a studio), so it would not be a surprise if people were to use this vector to get malicious code executed on the victims computer. Now if the code then can not under any circumstance communicate with the outside world, there is nothing to be gained from such an attack (without further, far more complicated exploits).

This comes on top of that many games with a patching functionality are executed with admin privileges, meaning that such an attack would immediately have heightened permissions.

**Tl;dr:** is would be a far too easy and exploitable security vulnerability.

---
Tags: software-engineering, modding
---


# Question
Title: Why when loading back the player position and rotation it's loading the player in a different position and rotation?
State class :

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

[Serializable]
public class SaveState
{
    public float posX;
    public float posY;
    public float posZ;

    public float rotX;
    public float rotY;
    public float rotZ;
    public float rotW;

    public float scaX;
    public float scaY;
    public float scaZ;

    public DateTime LastSaveTime { set; get; }
}

```

Manager script :

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;

public class SaveManager : MonoBehaviour
{
    public static void Save(SaveState player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/player.bin";
        FileStream stream = new FileStream(path, FileMode.Create);

        SaveState data = new SaveState();

        formatter.Serialize(stream, data);
        stream.Close();
    }

    public static SaveState Load()
    {
        string path = Application.persistentDataPath + "/player.bin";
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            SaveState data = formatter.Deserialize(stream) as SaveState;
            stream.Close();

            return data;
        }
        else
        {
            Debug.LogError("Save file not found in " + path);
            return null;
        }
    }
}

```

Test script :

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

public class SaveTest : MonoBehaviour
{
    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.T))
        {
            var player = GameObject.Find("Player");
            SaveState saveState = new SaveState();
            saveState.posX = player.transform.position.x;
            saveState.posY = player.transform.position.y;
            saveState.posZ = player.transform.position.z;

            saveState.rotX = player.transform.rotation.x;
            saveState.rotY = player.transform.rotation.y;
            saveState.rotZ = player.transform.rotation.z;
            saveState.rotW = player.transform.rotation.w;

            saveState.scaX = player.transform.localScale.x;
            saveState.scaY = player.transform.localScale.y;
            saveState.scaZ = player.transform.localScale.z;

            //Save data from PlayerInfo to a file named players
            SaveManager.Save(saveState);
        }

        if(Input.GetKeyDown(KeyCode.L))
        {
            //Display loaded Data
            var player = GameObject.Find("Player");
            player.transform.position = new Vector3(SaveManager.Load().posX, SaveManager.Load().posY, SaveManager.Load().posZ);
            player.transform.rotation = new Quaternion(SaveManager.Load().rotX, SaveManager.Load().rotY, SaveManager.Load().rotZ, SaveManager.Load().rotW);
            player.transform.localScale = new Vector3(SaveManager.Load().scaX, SaveManager.Load().scaY, SaveManager.Load().scaZ);
        }
    }
}

```

I can see the created saved file player.bin 1 KB size.

This is a screenshot when I press the T button to save : On the left bottom game window. And the inspector player info position and rotation when saving.

I press the T button once to save while the player is in coroutine. When the game start the player is not moving but rotating using coroutine. Not sure if the coroutine if saving while the player is rotating make the problem.

This is a screenshot when pressing the L button and the inspector of the player position and rotation :

Not same position and rotation when loading.

# Answer
> 1 votes
```
public static void Save(SaveState player) {
    BinaryFormatter formatter = new BinaryFormatter();
    string path = Application.persistentDataPath + "/player.bin";
    FileStream stream = new FileStream(path, FileMode.Create);
    SaveState data = new SaveState();
    formatter.Serialize(stream, data);
    stream.Close();
}

```

This code ignores the save data passed in as the argument `player`. Instead it creates a new, default/empty save called `data`, and saves this to your file. So naturally when you read it, you get default values.

Unrelated, your load function is repeatedly opening the file, reading its contents, closing the file, then using just one of the values it read and throwing out the rest. Then it opens the file again, reads all its contents, uses the next value, and throws out the rest again...

Just read the file once into a variable, and re-use that variable to populate the various parameters you need.

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


title: Timing in holding LWJGL keyboard event

text:
# Question
Title: Timing in holding LWJGL keyboard event
I'm using LWJGL to develop a 3D game.

I'm having trouble with my keyboard handler. My aim is to implement the function which is holding `Space` then release it to trigger an increasing of the velocity and height of the main character within an interval of time (the longer you hold, the more powerful the bounce).

The point is, I want to increase the acceleration in `Keyboard.isRepeatEvent()` but, in this condition, the interval between 2 frames is nearly 0, so I can't increase the acceleration. It seems like this event is calculated in 1 frame so now I couldn't think out a new method. This my code:

```
Keyboard.enableRepeatEvents(true);

    while(Keyboard.next())
    {
        if(Keyboard.getEventKey() == Keyboard.KEY_SPACE)
            if(Keyboard.getEventKeyState())
            {
                if(Keyboard.isRepeatEvent())
                {
                    while(test <= 200)
                    {
                         test += getDelta() / 1000;
                         System.out.println("test Value ---- " + test);
                    }
                }
                // Key held down
                else {

                }
                // Key pressed
            }
            else
                System.out.println("test ------------------- " + test);
        // Key released
    }

```

`getDelta()` gets the interval between 2 frames.

# Answer
> 1 votes
Why not get the system time upon the 1st detection of the event, then get the system time when the event is no longer detected (*i.e. "button up"*)? This interval could then be used to calculate the acceleration.

Ergo (using your code):

((**Disclaimer: I don't program in java so please forgive any syntax issues. I'm aiming for java-esque psuedocode.**))

```
Keyboard.enableRepeatEvents(true);
long timeI; //timestamp when button is hit
long timeF; //timestamp when button is released
long deltaT; //time period between timeF and timeI
while(Keyboard.next())
{
    if(Keyboard.getEventKey() == Keyboard.KEY_SPACE)
        if(Keyboard.getEventKeyState())
        {
            //setTimeI if it hasn't been set yet.
            if (timeI == 0)
            {
                timeI = System.currentTimeMillis();
            }
            if(Keyboard.isRepeatEvent())
            {
                while(test <= 200)
                {
                     test += getDelta() / 1000;
                     System.out.println("test Value ---- " + test);
                }
            }
            // Key held down
            else {

            }
            // Key pressed
        }
        else
        {
            //setTimeF if timeI hasn't been set
            //and if the button is not pressed (ergo released)
            if(timeI > 0)
            {
                timeF = System.currentTimeMillis();
                deltaT = timeF - timeI;
                timeI = 0; //reset initial time
            }
            System.out.println("test ------------------- " + test);
    // Key released
}

```

# Answer
> 0 votes
You should not use a while loop to fetch keyboard events, instead, find a way to fetch keyboard events with a lower, less variable complexity.

However, to answser your question:

```
//fetch your key events
...
//setup
final double maxSpaceHoldTimeInSeconds = 2.;
final Vector3 maxVelocity = ..; //max velocity after keyboard is released.

//apply your space-bar logic

//if the keyboard is PRESSED
if ( Keyboard.getEventKey() == Keyboard.KEY_SPACE && Keyboard.getAction() ==         Keyboard.ACTION_PRESSED ) {
    spaceBarTimer = 0.;
}

//if the keyboard is not yet RELEASED
else if ( Keyboard.getEventKey() == Keyboard.KEY_SPACE && Keyboard.getAction() != Keyboard.ACTION_RELEASED ) {
    if ( spaceBarTimer > maxSpaceHoldTimeInSeconds ) {
        //some logic to stop the player from holding their spacebar for too long.
        return;
    }

    spaceBarTimer += getDelta();
    //the delta counts the time between frames as you have already stated.
    //what this means is if your gameloop is setup for a 60fps game loop
    //then your delta == 1/60
}

//if the keyboard is RELEASED
else if ( Keyboard.getEventKey() == Keyboard.KEY_SPACE && Keyboard.getAction() == Keyboard.ACTION_RELEASED ) {
    player.addVelocity(maxVelocity.multiplyWithDouble( maxSpaceHoldTimeInSeconds / spaceBarTimer ));
}

```

Of course, this will increase velocity in a linear fashion, if you want your player to experience an exponential increase of velocity when holding their keyboard for longer, then you need to modify the player.addVelocity() line, something like this maybe.

```
player.addVelocity(maxVelocity.multiplyWithDouble( maxSpaceHoldTimeInSeconds / Math.min(maxSpaceHoldTimeInSeconds, spaceBarTimer * spaceBarTimer) ));

```

---
Tags: lwjgl, keyboard, timing
---


title: Multiple If Operations at Once

text:
# Question
Title: Multiple If Operations at Once
In my game, I want to have it so that if a chess piece tries to move farther away than a certain distance it won't work. To do this, I need it to have an if statement that works between two numbers, but I can only seem to do above or below a number, not between. Is there a way to do this, or am I going to have to use to if statements?

# Answer
> 0 votes
You can do it direct using the function `point_distance()` or create a variable and give it the value of that distance.

**Code:**

---
Tags: game-maker-dnd
---


title: Python path finding

text:
# Question
Title: Python path finding
Im making a dungeon crawler in python, and I want to make it so that a certain enemy (only 1) will chase you through the dungeon

the map is stored like this: \[ \['0','0', '0'\], \['0','0', '0'\] \]

in which the cord's for the enemy (and the player) is placed like this: \[x, y\]

how may I do this?

# Answer
It is unclear what you want to achieve.
I would want to know more about whether this is CUI/GUI, how the player and the crawler are going to behave, what happens when they *do* meet, what the zeroes stand for (empty spaces?), how the map is being updated, is it 2-D or 3-D, what libraries are you using etc.

I can only assume you are looking for a logic to implement a path finding algorithm in 2-D space, that is, how should the "dungeon crawler" chase you.

With so little information, my answer will be vague as well.
How *I* would do it is to have a 2-D map of the "dungeon", like so:

```
[                             # assuming 5x5 grid
    [ 0  , 0, 0, 0  , 0 ],    # 'P' is where the player is
    [ 'P', 0, 0, 0  , 0 ],    # 'C' is where the crawler is
    [ 0  , 0, 0, 0  , 0 ],    # Now, call function "updateCrawler"
    [ 0  , 0, 0, 0  , 0 ],    # to chase the player,
    [ 0  , 0, 0, 'C', 0 ],    # Call "updatePlayer" to react to the crawler
]

```

This is assuming that the player and the crawler are the only ones in this dungeon.

I would save the positions of both of these to avoid calculating them every time.
And I would have 2 functions to update both things. For a player, like so:

```
def updatePlayer(map, player_position):
    # Get the input (Keyboard? Screen? Mouse?)
    map[<player y>][<player x>] = 0

    if input == <go left>:
        # move player left, update player position

    if input == <go right>:
        # move player right, update player position

    if input == <go up>:
        # move player up, update player position

    if input == <go down>:
        # move player down, update player position
    map[<player y>][<player x>] = 'P'

```

As for the crawler, a (very) simple way would look something like this:

```
def updateCrawler(map, crawler_position):
    map[<crawler y>][<crawler x>] = 0

    if <player is above crawler>:
        # move crawler up, update crawler position

    if <player is left of crawler>:
        # move crawler left, update crawler position

    if <player is right of crawler>:
        # move crawler right, update crawler position

    if <player is below crawler>:
        # move crawler down, update crawler position
    map[<crawler y>][<crawler x>] = 'C'

```

Again, this depends very much on what else is in the world. Are there walls? Are there other creatures for crawler to avoid? And so on.

Hopefully, this is a starting place. I would also update my answer as and when the question is improved.
> 0 votes

---
Tags: path-finding, python
---


# Question
Title: How do I detect input from the left or right arrow-keys in C#?
I'm using the line of code `if (Input.GetKey("left"))`, but it obviously didn't register the input of the arrow key. How can I detect arrow keys like this?

My code is as follows:

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce = 2750f;
    public float sidewaysForce = 150f;

    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
        else
        {
            if (Input.GetKey("left")
            {
                rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
            }
        }

        if (Input.GetKey("d"))
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
        else
        {
            if (Input.GetKey("right"))
            {
                rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
            }
        }

        if (rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

```

# Answer
The `left` is the correct name of the Left arrow key according to the documentation. But as advised in the comments, it's advised to use the axes of the Input manager so that the user will be able to customize the input keys, or use the overload of `GetKey` taking `KeyCode` as argument for a more robust solution if you want to "manually" check for the individual keys.

It's often advised to handle input in the `Update` function (but not necessary depending on your Physics configuration)

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour
{
    // This is a reference to the Rigidbody compenent called "rb"
    public Rigidbody rb;

    // This creates variables for the movement
    public float forwardForce = 2750f;
    public float sidewaysForce = 150f;
    private Vector3 force;

    void Update()
    {
        force.Set(0, 0, 0);

        if (rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
        else
        {
            force.z = forwardForce;
            if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
                force.x = sidewaysForce;
            else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
                force.x = -sidewaysForce;

            force *= Time.fixedDeltaTime;
        }
    }

    // We marked this as "fixed"update because we are using it to mess with Physics
    // In this case Unity likes FixedUpdate a lot better than Update
    void FixedUpdate()
    {
        rb.AddForce(0, 0, force.z);
        rb.AddForce(force.x, 0, 0, ForceMode.VelocityChange);
    }
}

```
> 0 votes

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


# Question
Title: Dynamically added gameobject didn't show on canvas
I have a canvas with a `Scroll View` in it.

When I manually add a prefab under the `Content`, it showed up nicely.

But when I add it through the following code, nothing showed up!

```
GameObject RaceGO = (GameObject)Instantiate(Resources.Load("Race"));
RaceGO.transform.SetParent(Content);

```

Could somebody please tell me why!?

Much appreciated!

PS. I had checked that the gameobject IS in the content! I just can't see it!

# Answer
> 2 votes
Based on your comments, it sounds like the problem was calling `SetParent` without the second argment.

`RaceGo.SetParent(Content)` is equivalent to `RaceGo.SetParent(Content, true)`, saying you want `worldPositonStays` to be true. That is, it's asking Unity to adjust the object's local transformation after parenting to keep the object in the same place in the world that it was before parenting.

So your prefab was probably spawned somewhere like the world origin - which might be a long way from your UI canvas - and parenting it with `worldPositionStays` set to true will try to keep it there after re-parenting, meaning it's likely well outside the screen in UI space.

By explicitly making this argument false, `RaceGo.SetParent(Content, false)`, you're telling Unity not to try to keep the object where it is. So it keeps its local transformation, just relative to the new parent now. This likely keeps it much closer to where you actually want it. You can inspect its transform properties to see if you still need to nudge it into place after parenting.

---
Tags: unity, initialization
---


# Question
Title: D3D11 Instancing - Help with sending instance data using two vertex buffers. First, for position and color and Second, for per-instance Matrix Data
So here is the premise:

I have 2 vertex buffers buffers whose data and corresponding definition is as follows:

Vertex 1: This one contains the per instance data

```
// Somewhere defined in the header
std::vector<XMMATRIX> instancedMeshTransformMatrixArray;

...// Following code is in a function called loading data

// We will compute and setup the buffer with the information of the indexed mesh here
static float angle = 0.0f;
//angle += 90.0f * deltaTime;
XMVECTOR rotationAxis = XMVectorSet(0, 1, 1, 0);

g_WorldMatrix = XMMatrixIdentity();
XMMATRIX scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
XMMATRIX rotate = XMMatrixRotationAxis(rotationAxis, XMConvertToRadians(angle));
XMMATRIX translate = XMMatrixTranslation(0.8, 0.0f, 0.0f);
g_WorldMatrix *= translate  * rotate * scale;

// We will also fill/process the matrix buffer here that will be used to index into to rendered indexed mesh
instancedMeshTransformMatrixArray.push_back(g_WorldMatrix);

// create and initialize the instanced data buffer
D3D11_BUFFER_DESC vertexInstancedBufferDesc = {};
vertexInstancedBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexInstancedBufferDesc.ByteWidth = sizeof(XMMATRIX) * instancedMeshTransformMatrixArray.size();
vertexInstancedBufferDesc.CPUAccessFlags = 0;
vertexInstancedBufferDesc.Usage = D3D11_USAGE_DEFAULT;

D3D11_SUBRESOURCE_DATA resourceData = {};
//ZeroMemory(&resourceData, sizeof(D3D11_SUBRESOURCE_DATA));

resourceData.pSysMem = &instancedMeshTransformMatrixArray[0];

HRESULT hr = g_d3dDevice->CreateBuffer(&vertexInstancedBufferDesc, &resourceData, &g_d3dIndexedVertexBuffer);
if (FAILED(hr))
{
    return false;
}

```

Vertex 2: This contains the per model data

```
// Somewhere in the header
// Vertex data for a colored cube.
struct VertexPosColor
{
    XMFLOAT3 Position;
    XMFLOAT3 Color;
};

VertexPosColor g_Vertices[8] =
{
    { XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) }, // 0
    { XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, // 1
    { XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) }, // 2
    { XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, // 3
    { XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, // 4
    { XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) }, // 5
    { XMFLOAT3(0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) }, // 6
    { XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) }  // 7
};

...//Following code is in a function called loading data
   //It is followed by the loading of data for Vertex 1

// Create and initialize the vertex buffer.
D3D11_BUFFER_DESC vertexBufferDesc = {};
//ZeroMemory(&vertexBufferDesc, sizeof(D3D11_BUFFER_DESC));

vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.ByteWidth = sizeof(VertexPosColor) * _countof(g_Vertices);
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;

resourceData.pSysMem = g_Vertices;

hr = g_d3dDevice->CreateBuffer(&vertexBufferDesc, &resourceData, &g_d3dVertexBuffer);
if (FAILED(hr))
    {
    return false;
}

```

I also load data for the index buffer and constant buffer. I have tested it with the VS Graphics debugger and the data seems to have loaded correctly. However, I can provide how I do that as well if needed.

Following is how is create the Input Desc for the 2 buffers:

```
// Create the input layout for the vertex shader.
D3D11_INPUT_ELEMENT_DESC vertexLayoutDesc[] = {
// Per vertex data
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPosColor,Position), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPosColor,Color), D3D11_INPUT_PER_VERTEX_DATA, 0 },

// Instanced Data
{ "INSTANCED_MATS", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1},
{ "INSTANCED_MATS", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1},
{ "INSTANCED_MATS", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D11_INPUT_PER_INSTANCE_DATA, 1},
{ "INSTANCED_MATS", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 64, D3D11_INPUT_PER_INSTANCE_DATA, 1}

};

hr = g_d3dDevice->CreateInputLayout(vertexLayoutDesc, _countof(vertexLayoutDesc), vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_d3dInputLayout);
if (FAILED(hr)) {
    return false;
}

```

Finally in another function called Draw I attach the data to the IA and call DrawInstanced as follows. :

```
...
const UINT vertexStride = sizeof(VertexPosColor);
const UINT offset = 0;

const UINT instancedVetexStride = sizeof(XMMATRIX);

g_d3dDeviceContext->IASetVertexBuffers(0, 1, &g_d3dVertexBuffer, &vertexStride, &offset);
g_d3dDeviceContext->IASetVertexBuffers(1, 1, &g_d3dIndexedVertexBuffer, &instancedVetexStride, &offset);
g_d3dDeviceContext->IASetInputLayout(g_d3dInputLayout);
...

// Draw the cube
g_d3dDeviceContext->DrawIndexed(std::size(g_Indicies), 0, 0);
//g_d3dDeviceContext->DrawIndexedInstanced(std::size(g_Indicies), 1, 0, 0, 0);

```

The following is my vertex shader as is:

```
//VERTEX SHADER

cbuffer PerApplication : register(b0)
{
    matrix projectionMatrix;
}

cbuffer PerFrame : register(b1)
{
    matrix viewMatrix;
}

cbuffer PerObject : register(b2)
{
    matrix worldMatrix;
}

struct AppData
{
    float3 position : POSITION;
    float3 color: COLOR;
    matrix instancedMatrix : INSTANCED_MATS;
};

struct VertexShaderOutput
{
    float4 color : COLOR;
    float4 position : SV_POSITION;
};

VertexShaderOutput SimpleVertexShader(AppData IN, uint instanceID : SV_InstanceID)
{
    VertexShaderOutput OUT;
    uint p = instanceID;
    matrix mvp = mul(projectionMatrix, mul(viewMatrix, IN.instancedMatrix));// worldMatrix));
    float4 pos = float4(IN.position, 1.0f);
    OUT.position = mul(mvp, pos);
    OUT.color = float4(IN.color, 1.0f);

    return OUT;
}

```

I am not sure if I am setting the offsets incorrectly or if I am incorrectly attaching the slots for the VB's to the IA. Or is it something to do with my input description for the BV's.

But I get the following D3D11 Warning, which to me is vague as I do not know what offset of 80 it is talking of.

```
D3D11 WARNING: ID3D11DeviceContext::DrawIndexed: Input vertex slot 1 has stride 64 which is less than the minimum stride logically expected from the current Input Layout (80 bytes). This is OK, as hardware is perfectly capable of reading overlapping data. However the developer probably did not intend to make use of this behavior.  [ EXECUTION WARNING #355: DEVICE_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL]
D3D11 WARNING: ID3D11DeviceContext::DrawIndexed: Vertex Buffer at the input vertex slot 1 is not big enough for what the Draw*() call expects to traverse. This is OK, as reading off the end of the Buffer is defined to return 0. However the developer probably did not intend to make use of this behavior.  [ EXECUTION WARNING #356: DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL]

```

I have been stuck here for hours. Any help, hints is greatly appreciated!!

# Answer
INSTANCED\_MATS", 3, DXGI\_FORMAT\_R32G32B32A32\_FLOAT starts at 48. Not 64.

Your offset is wrong.
> 0 votes

---
Tags: directx11, instancing, vertex-buffer
---


title: Querying game objects in real-time

text:
# Question
Title: Querying game objects in real-time
I'm thinking about working on a game where I need to find all the objects matching certain properties.

For instances I might need to look up all the objects...

* Producing gold.
* Whose level is 5 or higher.
* Within 10 meter from a point.
* Currently fighting.
* That have anything to do with metal (e.g. producing, consuming, made of, wearing, standing on etc).

And so on and so forth. I would also like to be able to add new objects with new properties without having to change everything else.

Ideally I would need to run multiple queries per frame (hundreds or thousands per second). I'll probably rely on some properties way more than others, but this kind of usage pattern is likely to change over time.

---

Is there any data structure, design pattern, method or idea to help me implement an efficient real-time query system?

I've been thinking about assigning to each object a dynamic set of tags with properties, then recursively partition the space storing in each partition a mapping from those tags to the objects. It might work, but I'd like to hear about existing solutions before wasting efforts.

# Answer
> 1 votes
It all depends on the query types, but broadly speaking...

**If world is very large,** as in an MMO, use a database, whether SQL or noSQL style is up to you, but it is a lot simpler to read (with your own eyes) the output of noSQL DBs which serve JSON output natively (GraphQL, MongoDB). Database tech is designed by specialists to cope admirably with *large* quantities of data, i.e. in the hundreds of thousands to millions of entries per table.

Even though the database may get millions of results very quickly once it receives that query, *latency* to send query and retrieve results can impact performance due to interprocess communication overhead. So you'd ideally queries out as soon as possible, at end of last frame.

A database's fixed interface can make it easier for secondary systems to operate against, e.g. level editors, without being broken by breaking changes to your game's core. On a secure remote server, it can also keep things safe from player's prying eyes / fingers.

Persistence these days can be achieved with something as simple as `LocalStorage` in Unity or HTML5, so this is not a reason in itself to use a DB.

**Ordinarily in games**, we'd split entities up into some kind of **spatial bucketing system**. For example, if we have a 2D grid, then we'd sort entities each frame into grid cell buckets, and then when checking entities against each other, we'd only compare against entities in the same cell or one of its eight neighbours. Dimensions of each cell (typically the same across 2 or 3 dimensions) depend on the maximum distance across wish you which to compare entities in your queries.

To create the grid (I assume C# as you have not specified):

```
const int X = 0;
const int Y = 0;
const int CELLWIDTH = 32;
var grid = new GridCell[,] //x, y or y, x

for (int y = 0; y < grid.GetLength(X); y++)
    for (int x = 0; x < grid.GetLength(Y); x++)
        grid[x, y] = new GridCell(cellWidth, etc);
        //GridCell has an empty array of entities created in its constructor.
        //Instead of GridCell here, can even just use a 1D array of entity indices.

```

Sort entities into these, at end of each frame or start of next frame like

```
//clear each GridCell's .entities first! left to the reader

//fresh sort into grid cells
foreach (Entity entity in world.entities)
{
    int xGrid = entity.pos.x / CELLWIDTH;
    int yGrid = entity.pos.y / CELLWIDTH;
    grid[xGrid, yGrid].entities.push(entity);
}

```

You now have all your entities sorted spatially, and can use as

```
GridCell cell = grid[entity.pos.x, entity.pos.y];
//...now you can consider all other entities in this cell

//or even use some simple arithmetic on x and y to get all GridCell neighbours, too...
GridCell[] cells = grid.getCellNeighbourhoodAround(entity.pos); //this cell + all 8 neighbours

```

**Use LINQ**

If you are using C#, LINQ can do this very efficiently both in terms of code brevity and performance:

```
var results = from entity in gridCell.entities
              where (entity.pos - other.pos).magnitude < 10 //distance check
              select entity.Key; //returns a list of IDs

```

Rather than using `gridCell.entities`, you could query across all entities in a neighbourhood of 3x3 cells for instance, by assembling each `.entities` into a single, larger array to be queried, or you could query the whole world using the complete (non-bucketised) `world.entities`.

**Conclusion**

In games, a database usually won't *replace* the core data structures. It typically acts *in addition* to those, and only where required. This is out of necessity, for performance reasons.

# Answer
> 0 votes
Your solution sounds a lot like indexing, and in truth I'd go the same route as well. Just remember that this will eat up quite a lot of RAM if you your world's really big. Try dynamically calculating your indexes, maybe using a quad tree. i.e. you only index the tagged elements in a certain region around the player, this way you will be able to reduce how much RAM your world chews up.

Below I've made a working example of this in JS, though I have not added any way to only query entities close to the player, but I'm guessing you can create your own little algorithm. Maybe even check each step if the entity is close to the player and if so, then add the `close-to-player` tag.

```
// Used to create entities that we can index and query later on
function Entity(type, tags) {
  this.type = type;
  // Add the type to the tags
  tags.push(type);
  this.tags = tags;

  // The Query system that this entity belongs to (we set this later
  this.qs = {};
}

//
function Query(entities) {
  this.entities = entities;
  // This is where we link the entities to the corresponding tag
  this.init();
}

Query.prototype.init = function() {
  // Keep a reference to 'this' object
  var that = this;

  // Initialize the tags object
  this.tags = {};

  this.entities.forEach(function(entity) {
    // First set the entities' qs property to this query system
    entity.qs = that;

    // Now loop through the entity list and link the entities to the corresponding tag
    entity.tags.forEach(function(tag) {
      // If the tag doesn't exist then create it
      if (!that.tags[tag]) {
        that.tags[tag] = [];
      }

      // Add the entity to
      that.tags[tag].push(entity);
    });
  });
};

// Allows you to query based on tags
Query.prototype.get = function(tag) {
  return this.tags[tag];
};

// Entities in a MOBA
var entities = [
  // By the way, I think it would be better to use objects for tags instead of using strings, or maybe even using an object/map instead of a list for the tags param.
  // This will allow you to have a 'tags' param like so `{ lvl: 7, 'prd-gold': true, 'has-gold': true }`
  // You can then run more complex queries using '<=' or '>=' (e.g. query..
  // Anyways moving on...
  new Entity('player', ['lvl7', 'prd-gold', 'has-gold', 'prd-health', 'has-sword', 'armed']),
  new Entity('minion', ['lvl4', 'has-gold', 'prd-health', 'fighting', 'has-club', 'armed']),
  new Entity('monster', ['lvl3', 'has-gold', 'prd-health', 'idle'])
];

var qs = new Query(entities);
window.qs = qs;
console.log('Query System:', qs);
console.log("Query.get player:", qs.get('player'));
console.log("Query.get prd-gold:", qs.get('prd-gold'));
console.log("Query.get has-gold:", qs.get('has-gold'));
```

Check your browser's console for result.

---
Tags: architecture, design-patterns, data-structure, gameobject, objects
---


# Question
Title: Unintended window opening when pressing Unity's "Submit" button
I've been working on a top down 2D game for a while now, and yesterday I found a strange bug that I just can't explain to myself whatsoever. I have a loot window for looting enemies, as well as a character panel to equip gear/see stats. I realized that after I open and close a loot window, if I press the space button (used for attacking, not for opening any windows) while holding A/LeftArrow or W/UpArrow it opens the character panel. Once this happens, I can press space to open/close the character panel.

Went to the character panels OpenClose() function (all it does is set the canvas group alpha to 0 and block raycast to false and vice versa) which is being called unintentionally, put a debug.log inside to verify if it really was being called, and yes, it is. I look up all references to see where I used it, but I only use it in a single place in the project that is behind an if-statement looking for they keycode C (NOT space). I added a debug.log for the Input.inputstring to see if somehow a magic C button press is ending up in that function, but no. If I press C to open the window, the debug log pops up, if I press space, the inputstring appears to be empty, so the if statement to get to the only place in the code referencing that function cannot be met. Removed the space button from my Player entirely, the behaviour still persists.

Added another debug.log with stackTrace.GetFrame(1).GetMethod().Name to show who is actually running this function, but it turns out that if I run it and press C, it says it's being opened by the update function in the UIManager (as expected). If I run it the strange, unintended way, it says it is being run by the EventSystems Invoke function. Coupled with the fact that the behaviour persists despite the space button being removed from the player, I realized that it's Unity's built in "Submit" button being pressed.

Strange behaviour:

* It appears to call the submit function on the OpenClose button for the character panel, but only under the circumstance that I closed a loot window and haven't clicked the mouse anywhere yet afterwards. If I deactivate the button that holds the character panels OpenClose function, the behaviour stops. The button shouldn't be pressed though, because it is on a canvas group with alpha 0/block raycast=false, just like all the other buttons with the identical function that work fine. The loot window has no idea about the character panel either, and all the windows are properly wired to their own OpenClose function.
* Upon further inspection, the window only starts showing up if, after closing a loot window, i press A/LeftArrow+Space or W/UpArrow+Space. This is getting more and more confusing for me.

So basically my issue is; how do I figure out why this function is being called? It feels as if closing the loot window somehow "caches" the OpenClose button for the character panel onto the submit button, but only until I click elsewhere on the screen. Did you guys have any experience with a similar situation? Could you share some pointers on how to debug this? What is the "submit" button usually used for, and what would make it only work in combination with the left/top directional buttons? I've spent about 4 hours on this now and don't know how to get any further.

# Answer
> 0 votes
First, I would recommend looking at the debug view of the EventSystem GameObject in the inspector window. Looks like this:

I’m guessing that your button is still the selected GameObject (the very first row in the debug window) even though it’s invisible, so input events are still being sent to it, including the standard “spacebar presses buttons” UI event (configurable in several places). Just like the OS UI system, clicking an interactive element selects it, causing it to be the active, or focused, control. When you click away, or navigate using other methods (eg. pressing tab, arrow keys, etc.) then a different element or no element will become selected.

If you don’t want to allow the keyboard to be used to allow UI focus navigation, you can turn off focus navigation on a per-object basis by selecting the GameObject, finding the Navigation dropdown, and choose “None”. Then that object will never become selected, so pressing spacebar will not click the button. It will still be interactive though, so clicking will still work.

If you do still want to allow focus navigation via keyboard, then you need to actually remove focus from the GameObject. This can be done by disabling the GameObject, or by calling

```
UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(null);

```

Once you no longer want the keyboard to activate the UI

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


# Question
Title: Is anyone else having problems launching UE4 4.23.1 on OS X 10.12?
So I recently switched machines from Windows to OS X (I still have the Windows machine but it's not available to me sometimes so I wanted to keep going while it's processing some other stuff). UE4 installs fine on my machine but I never actually get it to initialise the engine. Even if I start directly from the .uproject file it doesn't do anything.

Has anyone else had a similar experience and how did you solve the problem?

PS. I verified the 4.23.1 Version already so that's all good.

**Edit:** I went to the engine directory and set all flags to 777. So permission is no longer an issue. Problem persists though.

# Answer
> 0 votes
So the problem was solved by upgrading. For those who read this: If you're using the Wise Audio Engine (like I do) or any other third party application that you need for your Audio Workflow in UE4, please never upgrade to the latest OSX version straight away. In my case, upping the OSX to 10.13 did the job.

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


# Question
Title: How to make progress bar in EditorWindow with Threading in Unity?
I need to make a progress bar in EditorWindow. To do this, I perform the function of calculations in threads: Thread thread = new Thread (\_worker.Work); thread.Start (); The class itself emitting calculations looks like this for me (Worker.cs):

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;
public class Worker
{
    private bool _cancelled = false;
    public void Cancel() {
        _cancelled = true;
    }
    public void Work() {
        for (int i = 0;i<=100;i++) {
            if(_cancelled)
                break;

            Thread.Sleep(50);
            Debug.Log("i="+i);
            ProcessChanged(i);
        }
        WorkCompleted(_cancelled);
    }
    public event Action<int> ProcessChanged;
    public event Action<bool> WorkCompleted;
}

```

The PlacementObjects: EditorWindow (PlacementObjects.cs) class looks like this:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using System.IO;
using System.Linq;
using System;
using System.Text.RegularExpressions;
using UnityEditor.IMGUI.Controls;
using UnityEngine.Profiling;
using Newtonsoft.Json;
using System.Threading;

public class PlacementObjects : EditorWindow
{
    private Worker _worker;
    bool pressedbool = false;
    float scaleSlider = 0;
    float scaleMinSlider = 0;
    float scaleMaxSlider = 100;
    [MenuItem("Window/PlacementObjects")]
    static void Init()
    {
        _windowPlacementObj = (PlacementObjects)EditorWindow.GetWindow(typeof(PlacementObjects));
        _windowPlacementObj.titleContent = new GUIContent("Работа с объектами и terrain");
    }
    ...
    void OnGUI()
    {
      DrawFooter();
    }
void DrawFooter()
{

    GUILayout.BeginArea(FooterSection);
        GUILayout.BeginVertical();

            if (!pressedbool)
            {
                GUILayout.Label("Выберите json");
                GUILayout.BeginHorizontal();
                    stringTextFieldURLjsonfile = GUILayout.TextField(stringTextFieldURLjsonfile);
                    if (GUILayout.Button("Обзор...", GUILayout.Width(100)))
                    {
                        stringTextFieldURLjsonfile = EditorUtility.OpenFilePanel("Выбрать json", "", "json");
                    }
                GUILayout.EndHorizontal();
                if (GUILayout.Button("Старт"))
                {
                    _worker = new Worker();
                    _worker.ProcessChanged += worker_ProcessChanged;
                    _worker.WorkCompleted += _worker_WorkCompleted;
                    pressedbool = true;
                    // ProcessJSONPlaceONmap();
                    Thread thread = new Thread(_worker.Work);
                    thread.Start();
                }
            } else {
                if (GUILayout.Button("Стоп"))
                {
                    pressedbool = false;
                }
                scaleSlider = EditorGUI.IntSlider(new Rect(3, 20, position.width - 6, 15), scaleSlider+"%", Mathf.RoundToInt(scaleSlider), scaleMinSlider, scaleMaxSlider);
                EditorGUI.ProgressBar(new Rect(3, 45, position.width - 6, 20), scaleSlider / scaleMaxSlider, scaleSlider+"%");
                Repaint();
            }

        GUILayout.EndVertical();
    GUILayout.EndArea();
}
private void _worker_WorkCompleted(bool cancelled)
{
    Action action = () =>
    {
        string messeg = cancelled ? "Процесс отменён" : "Процесс завершён!";
        Debug.Log("messeg=" + messeg);
        pressedbool = true;
    };

    // if (InvokeRequired)
    //     Invoke(action);
    // else
    //     action();
}
private void worker_ProcessChanged(int progress)
{
    Action action = () => {scaleSlider=progress;};
    // if (InvokeRequired)
    //     Invoke(action);
    // else
    //     action();
    action();
}
}

```

This code does not update the progress bar.

Found an example of Asynchronous tasks / methods But here it is not clear how to call StartCoroutine (LoadingRoutine ()) from EditorWindow.

# Answer
I got this code:

PlacementObjects

```
namespace marijnz.EditorCoroutines
{
    public class PlacementObjects : EditorWindow
    {
      ...
    private Worker _worker;
    public static bool pressedbool = false;
    private Thread _thread;
    private UnityEngine.Object _locker;
    public static int _progress;

        void DrawFooter()
        {
            GUILayout.BeginArea(FooterSection);
            GUILayout.BeginVertical();
            if (!pressedbool)
            {
                GUILayout.Label("Выберите json");
                GUILayout.BeginHorizontal();
                stringTextFieldURLjsonfile = GUILayout.TextField(stringTextFieldURLjsonfile);
                if (GUILayout.Button("Обзор...", GUILayout.Width(100)))
                {
                    stringTextFieldURLjsonfile = EditorUtility.OpenFilePanel("Выбрать json", "", "json");
                }
                GUILayout.EndHorizontal();
                if (GUILayout.Button("Старт"))
                {

                    pressedbool = true;
                    _worker = new Worker();
                    _worker.ProcessChanged += worker_ProcessChanged;
                    _worker.WorkCompleted += worker_WorkCompleted;
                    Worker._cancelled = false;
                    _thread = new Thread(_worker.Work);
                    _locker = new UnityEngine.Object();
                    _progress = 0;
                    _thread.Start();

                    // if (count_list_index >= 0)
                    // {
                    //     if (myList[count_list_index].geometry_type == 0)
                    //     {
                    //         ProcessJSONPlaceONmapTextures();
                    //     }
                    //     else if (myList[count_list_index].geometry_type == 1)
                    //     {
                    //         ProcessJSONPlaceONmap();
                    //     }
                    // }

                }

            }
            else
            {
                if (GUILayout.Button("Стоп"))
                {
                    pressedbool = false;
                    Worker.Cancel();
                }
                EditorGUI.ProgressBar(new Rect(3, 45, FooterSection.width - 6, 20), _progress / 100.0f, "progress: " + _progress + "%");
            }
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }
        // IEnumerator LoadingRoutine()
        // {
        //     while (_thread.IsAlive)
        //     {
        //         lock (_locker)
        //         {
        //             _progress = EditorGUILayout.IntSlider(Rect(3, 3, position.width - 6, 15), "progress:", _progress, 0, 100);
        //         }
        //         yield return null;
        //     }
        // }
        public static void worker_WorkCompleted(bool cancelled)
        {
            Action action = () =>
            {
                string messeg = cancelled ? "Процесс отменён" : "Процесс завершён!";
                Debug.Log("messeg=" + messeg);
                pressedbool = false;
            };
            action();
            // if (InvokeRequired)
            //     Invoke(action);
            // else
            //     action();
        }
        public static void worker_ProcessChanged(int progress)
        {
            Action action = () => { _progress = progress; };
            // if (InvokeRequired)
            //     Invoke(action);
            // else
            //     action();
            action();
        }
        void OnInspectorUpdate()
        {
            Repaint();
        }
        ...
    }
}

```

Worker

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;
public class Worker
{
    public static bool _cancelled = false;
    public static void Cancel()
    {
        _cancelled = true;
    }
    public void Work()
    {
        for (int i = 0; i <= 100; i++)
        {
            if (_cancelled)
                break;

            Thread.Sleep(50);
            Debug.Log("i=" + i);
            marijnz.EditorCoroutines.PlacementObjects.worker_ProcessChanged(i);
        }
        marijnz.EditorCoroutines.PlacementObjects.worker_WorkCompleted(_cancelled);
    }
    public event Action<int> ProcessChanged;
    public event Action<bool> WorkCompleted;
}

```
> 0 votes

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