title: Town generation algorithms

text:
# Question
Title: Town generation algorithms
In this RPG.SE post a long-lost page with several online generators is mentioned.

I'm particularly curious about the way towns were generated. Take this image for example:

Although a lot of things could be improved graphics-wise, it was *very* good considering the tools available at the time (mid to late 90s):

* The road layout seems fairly organic (even considering all roads are placed in an orthogonal manner).
* Not all roads are necessarily connected, but it *feels right*.
* Buildings are placed in *believable* spots.
* Even trees seem to be placed in *logical spots*.

I think it would be fun to give it a shot and try it myself. Especially since my previous attempts have been too "blocky":

You'll notice that I'm describing many of the qualities with not-quite-measurable adjectives (*seems*, *feels*, *believable*, etc) so I'm having a hard time translating them to instructions and ultimately to an algorithm.

## Are there any tried-and-true algorithms for town generation?

I understand this seems to be too broad, so consider this: If I asked for an algorithm for generating maps of continental land masses, I'd get references to Perlin and other noise algorithms right away; closely followed by Voronoi.

I've seen questions like this one but they seem to have a more concrete idea already in mind (ie: 2x2 houses, fixed number of houses, canal and road placement restrictions).

What I'd like to have is something less constrained. Except maybe for the grid layout, which should be a lot easier for a first attempt than, say, L-system.

# Answer
Introversion Software made a really impressive city generator for their cancelled indefinitely suspended project Subversion:

The algorithm is designed to generate large, modern metropoles. But the same techniques can be used to generate more rural settlements.

It is a top-down algorithm which generates the rough outlines first and then generates more and more details to fit into them (for the opposite bottom-up aproach to procedural generation, check the answer by uliwitness). Here is a video which visualizes the algorithm in progress.

The algorithm seems to work as follows (slightly simplified):

1. **City centers:** Pick some points of the still empty map as main traffic nodes. They should be evenly distributed around the map
2. **Highways:** Connect the main traffic nodes to their neighbors and to the outside world using major roads.
3. **Freeways:** Subdivide the cells generated by the major roads by creating some minor roads.
4. **Streets:** Repeat the subdivision process recursively with smaller and smaller roads until you've reached the desired building block size
5. **Blocks:** Decide the purpose of each building block (residential, retail, corporate, industrial...). Relevant factors are the sizes of the neighboring roads and the distance from the center.
6. **Allotments:** Divide the edges of all building blocks into lots (this means each lot has at least one edge which is connected to a road).
7. **Buildings:** Generate a fitting building for each lot.

Regarding the placement of trees: My first approach would be to integrate those in the building generation algorithm. A building does not need to fill its lot completely. You can fill the free space with appropriate decorative objects.

The problem with the top-down approach is that while it might generate a plausible city, it might not generate a plausible city with *everything you want*. Let's say that every city in your game needs one weapon shop, one armor shop, one potion shop and one inn. The above algorithm picks buildings based on the requirements of the lot, so you might end up with 12 armor shops but not a single inn. I would approach that problem in the building generation phase. Before you start generating buildings randomly, go through your list of must-have buildings and select the most appropriate lot for each of them. Then fill the remaining lots with randomized buildings.

I'm looking forward to exploring the procedurally generated towns in your game.
> 10 votes

# Answer
## Get constraints from real life

Often the answer on how to find the right algorithm starts with looking at how these things happen in real life. Have you looked into that? Off the top of my head, I can think of the following:

* Roads are there to connect buildings and other points of interest
* Buildings are placed along existing roads, if possible
* If there is no road, a building is placed in an empty spot and connected to a nearby road via its own road
* Buildings are placed near other buildings that are of interest to their inhabitants: People move to live near their workplaces, food and clothing stores etc.
* Buildings are placed near resources that are necessary for their intended use. E.g. a sawmill is placed near forests, or even in a forest clearing. people need water and food (plants, animals) to live somewhere.
* Buildings are placed far away from other buildings that are detrimental to their intended use, or that they would be a detriment to. E.g. a dyer's shop smells horrible, so is usually not placed in a residential area. Similarly, taverns and restaurants are loud, so residents don't want to live on top of them, but need customers, so need to be near residential areas.
* Some countries have zoning laws that also influence building placement. Usually these are a more formalized way of anticipating what kinds of buildings may be detrimental to each other, or what resources are unique to the area (like, high-quality soil is for fields, not for building parking lots on).
* Buildings are for inhabitants, and their personal style and preferences are reflected in them. E.g. if a population is poor, they're much more likely to share ground (skyscrapers, apartment buildings), if they're more well off, they may get condominioms, if they're rich, they get a standalone villa. If certain groups do not like other groups, they will be less likely to co-habitate. If there is an affinity between certain groups, they may move into similar areas.

## Apply them to your topography

Once you have these constraints, you can try to build an algorithm around it. E.g. generate your topography and distribute needed resources around the map (maybe keeping an eye on placing small deposits of the most important resources in the starting area, then larger deposits farther away and from each other). This is where your game's needs and mechanics come into play, of course, but you'll likely also add a random element.

Then build businesses (and their residential buildings) near those resources that use them. E.g. a quarry next to a large mountain. Then add infrastructure needed by them. E.g. a trading post with post office and tavern where they can do business and sell their product, a smithy to provide tools etc.

To decide what goes where, split the map into tiles where you calculate a number for each tile how desirable it is for a certain purpose, using a weighting function. Put the buildings in the most desirable tiles for that kind of building. Add rules like "one trading post can handle 50 businesses or 100 homes", which increase the likelihood of adding another trading post if a city reaches a certain size.

Once you have this, you should get some fairly decent maps. If you notice that maps all end up as unnatural shapes, add penalties to your weighting functions for those shapes, like "if my street ends up right next to another street, -100 desirability", or "if my street crosses itself, -100 desirability" etc. You can always add in a random element to allow this for a more quirky feel, or add other mechanics like "if a crossing has more than N buildings connected to its roads, turn it into a roundabout".

You can even use these constraints to give different maps a different feel, like make a certain country have more mountains in its topography, or have a certain culture build more winding roads, and another prefer straight roads etc. All just by modifying one of your weighting functions.

## Simplify

Of course, this approach is too complex for games that aren't trade simulations, but work this out anyway, and see which kinds of buildings make sense for your game, and eliminate the unneeded ones. Then come up with simplified rules like "place cities near a river, a mountain or good soil. 1 building per 100 resources, businesses based on resource type, 10 residential buildings for each full set of food/crafting resource ... or just "1m of river/1sqm of soil can support 10 residential buildings ... whatever makes sense for a game. Still, once you know how much area you have (e.g. no buildings on steep mountain sides), and how many buildings the area can support, just place sets of buildings in that area until it is full (like, 1 business building, 10 residential, 3 infrastructure, or whatever) and connect them with roads.
> 6 votes

---
Tags: procedural-generation
---


# Question
Title: LibGDX Stage and Viewport management for Actors?
So I've done research about how to use Stage, Actor and Viewports etc. To optimize the game for most devices running Android. I'm pretty sure that the viewport is configured or the background image is just being drawn over the screen without actually using the viewport. That is fine though. So I'm basically telling the viewport to draw an image over the whole screen and it seems that that applies to actors also. So I guess the viewport is trying to draw the actor over the whole screen.

**When testing the app on emulators with different screen sizes the actor is not resized (probably because of the viewport setting), but how can I get the actor to resize so that the actor fits in the world? The world will be the whole screen of the device.**

**Do I need to use two viewports where one is for UI (background so far) and another for the game?** If I need to do that wouldn't the UI viewport need to be the screen size and the Game viewport holding the world size would have size constants? If so, then I don't have the whole screen size as the world, but drawing the Game viewport using the screen width and height would probably result in drawing the actor over the whole screen again, right?

And I've seen in some tutorials that they often set a constant unit of the world width and world height. **Wouldn't that fail to fit all devices since they have a specific constant for width and height?**

I want all of my Actors to be resized so that they fit inside the world (screen size).

**UPDATE TO CLARIFY MY QUESTION**

As you see the background is scaled up and down due to being drawn as the width and height of the screen, I guess, but I need the actors to also be scaled up or down. The actors can't remain the same size for all screens.

MyGdxGame

```
public class MyGdxGame extends ApplicationAdapter {

private OrthographicCamera camera;
private Stage stage;
private Viewport viewport;
private Texture textureBackground;

@Override
public void create () {
    camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);

    final float GAME_WORLD_WIDTH = Gdx.graphics.getWidth();
    final float GAME_WORLD_HEIGHT = Gdx.graphics.getHeight();
    viewport = new FitViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, camera);

    stage = new Stage(viewport);
    MyActor actor = new MyActor(new Texture("badlogic.jpg"));
    actor.setPosition(0, 0);
    stage.addActor(actor);
    stage.getViewport().apply();
    Gdx.input.setInputProcessor(stage);

    textureBackground = new Texture("TheWorld.png");
}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
    stage.getCamera().position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.getBatch().setProjectionMatrix(stage.getCamera().combined);
    stage.getCamera().update();

    stage.getBatch().begin();
    stage.getBatch().draw(textureBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    stage.getBatch().end();

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}
}

```

MyActor

```
package com.mygdx.game;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class MyActor extends Actor {

    private Texture texture;
    public MyActor(Texture texture) {
        this.texture = texture;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(texture, getX(), getY());
    }
}

```

Images:

Research links:

Using two viewports for UI and Game

Viewports and World units

LibGDX Viewport Tutorial

# Answer
> 4 votes
I had take your code and change it a little bit.
I hope this will solve your problem otherwise I do not know what exactly your problem is.

I will recommend you to not use `Gdx.graphics.getHeight/getWidth`.
With the camera, you can use your own unit in this example 100 and the `stage.getBatch().setProjectionMatrix(stage.getCamera().combined);` will do the calculation for you. More about the camera and Matrix are on this site: github.com/libgdx/libgdx/wiki/Orthographic-camera

Code:

```
public class MyGdxGame extends ApplicationAdapter {
    private OrthographicCamera camera;
    private Stage stage;
    private Viewport viewport;
    private Texture textureBackground;

    private static final int WORLD_WIDTH = 100;
    private static final int WORLD_HEIGHT = 100;

    @Override
    public void create () {
        camera = new OrthographicCamera(WORLD_WIDTH,WORLD_HEIGHT);
        camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);

        viewport = new StretchViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);

        stage = new Stage(viewport);
        MyActor actor = new MyActor(new Texture("badlogic.jpg"));
        actor.setPosition(0, 0);
        stage.addActor(actor);
        stage.getViewport().apply();
        Gdx.input.setInputProcessor(stage);

        textureBackground = new Texture("TheWorld.png");
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height);
        stage.getCamera().viewportWidth = WORLD_WIDTH;
        stage.getCamera().viewportHeight = WORLD_HEIGHT * height / width;
        stage.getCamera().position.set(stage.getCamera().viewportWidth / 2, stage.getCamera().viewportHeight / 2, 0);
        stage.getCamera().update();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.getBatch().setProjectionMatrix(stage.getCamera().combined);
        stage.getCamera().update();

        stage.getBatch().begin();
        stage.getBatch().draw(textureBackground, 0, 0, 100,100);
        stage.getBatch().end();

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
}

public class MyActor extends Actor {

    private Texture texture;
    public MyActor(Texture texture) {
        this.texture = texture;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
//        batch.draw(texture, getX(), getY());
        batch.draw(texture, 50, 50, 20, 20);
    }
}

```

---
Tags: libgdx, screen
---


title: Isolate UI elements from 3D scene

text:
# Question
Title: Isolate UI elements from 3D scene
this might seem like a silly question but I'm raycasting on specific objects (Targets) in a scene and zooming in on them but i also have a few UI elements (buttons, toggles...) on the side of the screen that need to always be visible because they provide certain functionalities (isolate target, switch view...).

The problem is that sometimes when i want to click on a certain UI element I unintentionally send a Raycast that changes my target. Moving the UI elements is not helpful since the objects occupy the whole screen. What other ways do I have to make sure I'm only clicking the UI element? (especially for smaller screens)

# Answer
> 2 votes
You can query EventSystem.Current.IsPointerOverGameObject() to check whether the mouse cursor is over a UI object associated with the EventSystem.

If it is, then you can refrain from firing your raycast, on the assumption that the player is trying to click the button, not select the 3D world behind the button.

---
Tags: unity, raycasting, ui-design
---


# Question
Title: InvalidOperationException in build only, when trying to select object in a dynamically loaded scene using Linq
Here is the relevant code:

```
private void Awake()
{
    StartCoroutine(LoadScenes());
}

private IEnumerator LoadScenes()
{
    this.sceneLoad1 = SceneManager.LoadSceneAsync(Scene1, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 1...");
        yield return null;
    }

    this.sceneLoad2 = SceneManager.LoadSceneAsync(Scene2, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 2...");
        yield return null;
    }
}

private void Start()
{
    SceneManager.GetSceneByName(Scene1)
                .GetRootGameObjects()
                .Where(root => root.GetComponent<God>() != null)
                .Select(root => root.GetComponent<God>())
                .Single()
                .SpreadGospel();
}

```

(`Scene1` and `Scene2` are `const string`s.)

The program works fine when running in the Unity editor. However, when I make a development build, I see the follow error message:

```
    InvalidOperationException: Operation is not valid due to the current state of the object
  at System.Linq.Enumerable.Single[God] (IEnumerable`1 source) [0x00057] in /Users/builduser/buildslave/mono/build/mcs/class/System.Core/System.Linq/Enumerable.cs:1968
  at MySolution.GodInitializer.SpreadGospel () [0x00001] in D:\repos\MySolution\SourceCode\SourceCode\GodInitializer.cs:100
  at MySolution.GodInitializer.Start () [0x00012] in D:\repos\MySolution\SourceCode\SourceCode\GodInitializer.cs:77

```

... which indicates that the scene wasn't fully loaded before I tried to access the `God` singleton.

What changes should I make to fix the problem?

# Answer
Your code in `Start` assumes that `Scene1` has already loaded. But you have no guarantee that's true. Instead you can write something like this:

```
private IEnumerator LoadScenes()
{
    this.sceneLoad1 = SceneManager.LoadSceneAsync(Scene1, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 1...");
        yield return null;
    }

    // NOW it's safe to look for God.
    OnScene1Loaded();

    this.sceneLoad2 = SceneManager.LoadSceneAsync(Scene2, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 2...");
        yield return null;
    }
}

void OnScene1Loaded() {
    // Find God & spread gospel.
}

```

Now you know `OnScene1Loaded` won't get called until Scene1 has finished loading.
> 1 votes

# Answer
Coroutines are not async in any way, they simply run when the object is Updated (similar to just performing the work in `Update`). `Start` is in turn called before the first update. Meaning that the scenes cannot be loaded properly since the coroutines did not finish yet (they did not even start yet).

I am not sure what you do in God initializer and why your code works in the editor, but it seems to me you are assuming some things which are not correct. E.g., the scene could not be fully loaded.

If your code in `Start` depends on some scene being initialized I would simply initialize it sequentially in `Start` (or `Awake`). Even if Coroutines were async or if your coroutine did run right when you "Start" it, your code suggests, that scene loading should be done async - therefore you can't rely on it being done unless you synchronize somehow (check whether the scene was loaded).

For more information about the execution order please refer to the documentation.
> 0 votes

---
Tags: unity, c#, scene, linq
---


title: How Can I Fix Spawning The Tiles?

text:
# Question
Title: How Can I Fix Spawning The Tiles?
I am making a 3D infinite runner game in Unity in C#. When the player has reached the end of the tile it should spawn another tile and then delete the previous tile. When the player reached the end of the first tile it deletes that tile and spawns another(just like it should), but when the player reached the second tile is does nothing. Does someone have a solution?

Thanks

Here is my code: Old:

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

public class Terrain : MonoBehaviour
{
    private List<GameObject> objs = new List<GameObject>();
    public GameObject terrain;
    public GameObject terrain2;
    public GameObject player;
    //private float z = 4130.875f;
    private float safeZone = 260.0f;
    private float tileLength = 260.0f;
    private int animTilesCount = 2;
    private Vector3 position;
    void Start()
    {
        objs.Add(terrain);
        objs.Add(terrain2);
        for (int i = 0; i < animTilesCount; i++)
        {
            spawnTile();
        }
    }
    void Update()
    {
        if ((objs.Count > 1) && (player.transform.position.z - objs[0].transform.position.z > safeZone))
        {
            spawnTile();
            DeleteTile();
        }
    }

    public void spawnTile()
    {
        position = objs[objs.Count - 1].transform.position;
        position.z += tileLength; //21, -13
        position.x += 21;
        position.y += -13;

        GameObject go = Instantiate<GameObject>(
                      terrain,
                      position,
                      terrain.transform.rotation);

        go.transform.SetParent(transform);

        objs.Add(go);
    }

    public void DeleteTile()
    {
        Destroy(objs[0]);
        objs.RemoveAt(0);
    }
}

```

New:

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

public class Terrain : MonoBehaviour
{
    [SerializeField]
    private List<GameObject> objs = new List<GameObject>();
    public GameObject terrainPrefab;
    public GameObject player;
    public GameObject terrain;
    public GameObject terrain2;
    //private float z = 4130.875f;
    private float safeZone = 260.0f;
    private float tileLength = 260.0f;
    private int animTilesCount = 2;
    private Vector3 position;
    void Start()
    {
        objs.Add(terrain);
        objs.Add(terrain2);
        for (int i = 0; i < animTilesCount; i++)
        {
            spawnTile();
        }
    }
    void Update()
    {
        if ((objs.Count > 1) && (player.transform.position.z - objs[0].transform.position.z > safeZone))
        {
            Debug.Log("Hello");
            spawnTile();
            DeleteTile();
        }
    }

    public void spawnTile()
    {
        position = objs[objs.Count - 1].transform.position;
        position.z += tileLength; //21, -13
        position.x += 21;
        position.y += -13;

        GameObject go = Instantiate<GameObject>(
                      terrainPrefab,
                      position,
                      terrainPrefab.transform.rotation);

        go.transform.SetParent(transform);

        objs.Add(go);
    }

    public void DeleteTile()
    {
        Destroy(objs[0]);
        objs.RemoveAt(0);
    }
}

```

# Answer
You're trying to use the first tile in the map as your source for spawning new tiles.

```
GameObject go = Instantiate<GameObject>(terrain, ...

```

But the first tile in the map is also the first one you destroy when the player gets far enough.

```
Destroy(objs[0]);

```

Once it's destroyed, you no longer have a source tile to use for spawning new copies. So no future tiles can spawn.

So, you have two different jobs here. Separate them.

* **Source for spawning tiles:** prefab

Take one of your tile objects and drag it into your Project folder. This creates what's called a Prefab asset. It's an archetype of the object that exists outside your scene, and you can use it as the source object to copy from when you want to `Instantiate` new copies.

Prefabs are also useful for batch-updating many similar objects across multiple scenes: update the prefab, and its spawned copies will inherit the changes.

Add a `public GameObject terrainPrefab;` variable to your script, and assign your prefab object from the Project folder into it.

Change your spawning line to use this prefab: `Instantiate<GameObject>(terrainPrefab, ...`
* **Tiles currently in your map:** objs list

Add a `[SerializeField]` attribute above your `private List<GameObject> objs = new List<GameObject>();` line. This will make it show up in the Inspector, so you can add your initial level tiles to it directly.

Now you can delete your `terrain` and `terrain2` variables and the calls to `Add()` them on start. They're already part of the list because you put them there.

Now you're never using a scene object / list member as a spawning source, and you can't accidentally delete your source tile.
> 0 votes

# Answer
I can see at least one other problem with your code. When spawning a new tile, you set its rotation by accessing `terrain.transform` after destroying it. This would cause a null reference exception and fail to spawn the tile.

Are there any errors being printed to the console?
> 0 votes

---
Tags: unity, 3d, game-design, game-mechanics, platformer
---


# Question
Title: How to destroy an object, and then instantiate it again later?
I'm creating an enemy spawner in Unity (2D). At long last, I have something that is quite close to working, but the problem is that I want it to destroy all instances of the enemy when the player can no longer see the spawn area.

That is, the player happens upon the spawn area to find several enemies, but if they move so that the camera can no longer see the spawn area, I want those enemies to be deleted and then a different set of the same enemies to be instantiated when the player (camera) happens upon the spawn area again. But when I attempt this initial delete, the script component no longer has an object to instantiate when the player returns.

Here's a snippet of what I have:

```
    if (!notOnScreen && spawned == false)
    {
        int numberOfEnemies = Random.Range(1, enemyMax);

        for (int i = 1; i <= numberOfEnemies; i++)
        {

            spawnX = Random.Range(minX + 1, maxX - 1);
            spawnY = Random.Range(minY + 1, maxY - 1);

            Vector3 spawnpoint = new Vector3 (spawnX, spawnY, 0);

            if (enemies.Length == 1) {
                typeOfEnemy = 0;
            }
            else if (enemies.Length > 1) {
                typeOfEnemy = Random.Range(0, enemies.Length);
            }
            else {
                typeOfEnemy = -1;
            }

            Instantiate(enemies[typeOfEnemy], spawnpoint, Quaternion.identity);
        }

        spawned = true;
    }

    if (notOnScreen) {
        spawned = false;

        currentEnemies = GameObject.FindGameObjectsWithTag("Enemy");
        for (int i = 0; i <= currentEnemies.Length; i++) {
            Destroy(currentEnemies[i]);
        }
    }

}

```

}

I'm sure there's a way to preserve an instance of the enemy so that they can be instantiated again later, but I'm not sure how (sorry--very new to this). I thought about cheating and having one enemy remain at a different z coordinate behind the map (as this is a 2D game), but that doesn't seem like an appropriate solution. Any thoughts or advice?

# Answer
> 0 votes
I agree with Pascal Lohscheidt that for a case like this, where you're repeatedly spawning & despawning many enemies, recycling them may be a better option.

But, for the general problem of saving an out-of-scene object that you want to be able to spawn on demand, you can use Prefabs.

Take one of the object you want to spawn multiple times, and drag it into your Project folder. This creates a Prefab asset, that exists independent of any scene. Now your spawning scripts can reference the prefab as the source to copy newly-instantiated objects from, instead of relying on an object that's already in the scene.

One often-overlooked trick for Prefabs is that they can be referred to by the type of any component they contain. So if you ultimately want to access an `Enemy` component on your newly-spawned critter, you can declare its prefab variable as `public Enemy enemyPrefab;` and instantiate it as `Enemy myEnemy = Instantiate<Enemy>(enemyPrefab, ...)` to get a reference to the newly created enemy's `Enemy` component without `GetComponent` or `as`. This still spawns a copy of the whole Prefab, not just a free-floating `Enemy` component. ;)

# Answer
> 2 votes
If I understand you right, you want to reposition the enemies at a random position anytime you look at them again. A really Simple way would be to have an array (maybe a list) of enemy objects and method which replaces them and every time the player camera leaves the spawn area you simply disable the objects and replace them and any time your camera enters the area you simply enable them. That would be solution if you really want the same set. Code example:

```
GameObject[] enemies = FindGameObjectsWithTag(...);

if(camLeaves)
{
   foreach(GameObject enemy in enemies) //place them into another
                                           position
   {
      enemy.transform.position = new Vector(RandomX, 0, RandomY);
      enemy.SetActive(false);
   }
}

if(camEnters)
{
   foreach(GameObject enemy in enemies)
   {
       enemy.SetActive(true);
   }
}

```

Anyway this way you won´t lose your references. But that are always the same enemies. And also if an enemy dies you won´t have any reference to him anymore. Maybe it´s worth using a list and removing the instance once it dies. Or you ask anytime you change the positions or enable & disable the objects for new reference with the method FindObjectsWithTag(). If you have questions or when I understood something wrong. Feel free to comment below & ask :)

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


# Question
Title: Huge level size after build APK in Unity
I made maps used bunch of small objects which are mostly scenary, like part of road, buildings, obstacles. They are all lightmap static, batching static, occludee static.

However after build APK, "levels" takes most spaces:

```
Uncompressed usage by category:
Textures      23.4 mb    5.3%
Meshes        24.9 mb    5.6%
Animations    4.5 mb     1.0%
Sounds        1.9 mb     0.4%
Shaders       1.8 mb     0.4%
Other Assets  4.8 mb     1.1%
Levels        287.1 mb   65.0%
Scripts       2.1 mb     0.5%
Included DLLs 3.9 mb     0.9%
File headers  389.1 kb   0.1%
Complete size 442.0 mb   100.0%

```

As you can see, it's 287.1mb, it's too big. Actual APK size is almost 100mb. Funny thing is that in my game, I don't use lightmap. I have 9 different maps, all of them don't have light map, only has baked navigation mesh and occlusion data.

I don't think that occlusion data and navigation mesh takes that much, because I can see that occlusion data is less than 1MB even in the biggest map.

Does it matter that using lots of small objects to create level without lightmapping takes much spaces?

Also I combined those scenary objects together with MeshBaker, which is Unity Asset that combine meshes and materials/textures. After build, there's a little size reduction only in "Levels" part, however overall game performance getting worse and total apk size is not changed.

So, why I have those huge "levels" size, and how do I reduce it? Is there something that I missed?

And which situtation is proper to combine multiple meshes into single? In stats result, average batches are 40 in my game. Should I combine those bunch of small objects as big single object?

# Answer
This problem was coming from huge static batching. I didn't noticed but the assets that I used for making maps were have too much geometry. When you set "Batching Static" in object, Unity combine them as single mesh for fast rendering. However this process will clone all geometry to result, so high geometry eventually drastically increases level size, and that's why I had this issue.

After retopology, total build size reduced. Not just size reduction, I have significant performace boost too.
> 1 votes

---
Tags: unity, android, mobile, batching
---


# Question
Title: From screen space to world space for a 2D game
I'm making a 2D game and I want the user to be able to position an object in the world using mouse input. After a while I found an answer to 'OpenGL Math - Projecting Screen space to World space coords' on Stack Overflow but even after working on it for multiple hours I couldn't get the right depth (z) value; after clicking the x and y coordinates of the square are correct for this z value, but as you can see the z value is way to big in this case and hence the size is too; It should be as big as all the other squares:  (I clicked where the circle is).

My current handler is:

```
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods)
{
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
    {
        double x, y;
        int width, height;
        glfwGetCursorPos(window, &x, &y);
        glfwGetWindowSize(window, &width, &height);

        vec4 pos1(
            static_cast<float>(x / (width / 2.f)) - 1,
            1 - static_cast<float>(y / (height / 2.f)), 0 /*☃*/, 1);

        pos1 = MVPinv * pos1;
        pos1.w = 1 / pos1.w;
        pos1.x *= pos1.w;
        pos1.y *= pos1.w;
        pos1.z *= pos1.w;

        std::cout << pos1.x << " / " << pos1.y << " / " << pos1.z << " // " << pos1.w << std::endl;

        objects[0]->position = vec3(pos1);
    }
}

```

Here `MVPinv` is the inverse of the model-view-projection matrix (don't mind the model matrix, it is the identity matrix and if I understand this correctly I can probably get rid of it in this place). I'm using modern OpenGL/GLEW, GLFW and GLM. Tweaking the z value indicated by  can give me the correct result, but only for a certain view-projection matrix.

All objects I draw currently have a z value of 0. My question is thus: what is the best way to get the right xy coordinates if I want z to be 0?

Note: I'm very new to all these concepts of view-projection matrices, the w value, OpenGL and game development in general.

Edit: This is how the matrix is generated (more or less copied from a tutorial):

```
const mat4 Projection = perspective(radians(45.f), 4.0f / 3.0f, 0.1f, 100.0f);
const mat4 View = lookAt(
    vec3(0, 0, 10),
    vec3(0, 0, 0),
    vec3(0, 1, 0)
);
const mat4 Model = mat4(1.0f);

MVP = Projection * View * Model;
MVPinv = inverse(MVP);

```

---

My updated code after reading the answer:

```
vec2 vecTranslate;

float factScale;
vec2 vecScale;

mat4 matTranslation, matScaling, matTransform;

void updateTranslate()
{
    matTranslation = translate(mat4(1), vec3(vecTranslate, 0));
}

void updateScale(const int viewWidth, const int viewHeight)
{
    vecScale = vec2(factScale, factScale / viewHeight * viewWidth);
    matScaling = scale(mat4(1), vec3(vecScale, 1));
    matTransform = matTranslation * matScaling;
}

void updateViewport(const int width, const int height)
{
    glViewport(0, 0, width, height);
    updateScale(width, height);
}

void mouse_button_callback(GLFWwindow *window, const int button, const int action, const int mods)
{
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
    {
        double x, y;
        int width, height;
        glfwGetCursorPos(window, &x, &y);
        glfwGetWindowSize(window, &width, &height);

        const vec2 view(x / (width / 2.f) - 1,
                        1 - y / (height / 2.f));

        objects[0]->position = vec3((view - vecTranslate) / vecScale, 0);

        /* Or:
        const vec4 view(x / (width / 2.f) - 1,
                        1 - y / (height / 2.f), 0, 1);
        const auto pos = inverse(matTransform) * view;
        objects[0]->position = {pos.x / pos.w, pos.y / pos.w, 0};
        */
    }
}

void window_size_callback(GLFWwindow *window, const int width, const int height)
{
    updateViewport(width, height);
}

```

# Answer
> 0 votes
You don't even need to use *Look At* and projection matrices if you are in 2D. They are good for 3D, but needless complexity for 2D. Your camera view can be simply the multiplication of a rotation matrix, scaling matrix and translation matrix. If your camera doesn't rotate, you can remove the rotation matrix out of it. Then your view matrix can be:

```
mat4 translation_matrix;
mat4 scaling_matrix;
mat4 view_matrix;

translation_matrix = mat4_translation(view_x, view_y, 0.0);
scaling_matrix  mat4_scaling(1.0 / view_width, 1.0 / view_height, 1.0);

view_matrix = translation_matrix * scaling_matrix;

```

Knowing where the player is clicking, in world coordinates, is a matter of adding `view_x/y` with `cursor_x/y`. No need to work with matrices here.

> All objects I draw currently have a z value of 0. My question is thus: what is the best way to get the right xy coordinates if I want z to be 0?

The whole `Z` problem seems to me caused by the use of the projection/look at matrices.

---
Tags: 2d, mathematics, transformation, projection-matrix
---


# Question
Title: Vibration/Rumble with PS4 Pad and LPDIRECTINPUTDEVICE8
I actually try to make my PS4 Pad rumble. I get the pad capabilities with

```
DIDEVCAPS capabilities;
capabilities.dwSize = sizeof(DIDEVCAPS);
ps4pad->GetCapabilities(&capabilities);

```

the next step is to check if the flag `DIDC_FORCEFEEDBACK` is ok

But `capabilities.dwFlags & DIDC_FORCEFEEDBACK` always return false.

As my pad is a ps4, I know it support feedback.

Have you an idea why it's return false, what I missed?

# Answer
Windows lacks DirectInput support for DS4 gamepads. In general there's no standard way to do haptics for HID gamepads, and the DS4 isn't even really a standard HID gamepad.

To get this working in Chrome I had to send the vibration commands as raw HID packets:

https://cs.chromium.org/chromium/src/device/gamepad/dualshock4\_controller\_base.cc?l=45

https://cs.chromium.org/chromium/src/device/gamepad/dualshock4\_controller\_win.cc?l=38

You can also use third-party drivers like DS4Windows to make your DS4 behave like an XInput device.
> 2 votes

---
Tags: input, windows, gamepad, playstation4, directinput
---


# Question
Title: (Unity) Serializing Data with Custom Object Stored by Reference
I have a custom class that I serialize/deserialize to/from file(s), and is not guaranteed to be identical each time the game runs (in this example, a language pack. it's possible to fix a typo manually). As a result, I do not use UnityEngine.Object on it, and deserialize it each load. However, some classes that implement UnityEngine.Object (Monobehavior), have references to it. these references must persist (so that the language stays the same each load)
As per the Unity Scripting page, https://docs.unity3d.com/Manual/script-Serialization.html, this can cause undesired behavior: *"If you store a reference to an instance of a custom class in several different fields, they become separate objects when serialized. Then, when Unity deserializes the fields, they contain different distinct objects with identical data."*

Naturally, I'd prefer this not be the case. again from Unity documentation linked above: *When you need to serialize a complex object graph with references, do not let Unity automatically serialize the objects. Instead, use ISerializationCallbackReceiver \[interface\] to serialize them manually*.

I know how to implement the interface. How do I preserve the reference? (Disclaimer: not an expert in serialization, so if it's a simple fix, I'm sorry. Unity documentation doesn't provide an example for references).

# Answer
I'd be tempted to create a ScriptableObject-derived class that serves as a "file handle" to this separately-serialized file. All your scripts that need to reference this file will reference the ScriptableObject, so references are preserved correctly (and you keep the conveniences of Unity's inspector for populating them), and the ScriptableObject can be responsible for tracking the deserialization state of this file (and possibly loading it on demand)

For example:

```
public abstract class ExternalResource<T> : ScriptableObject {

    [SerializeField]
    protected string filePath;

    T reference;

    public T GetResource() {
        if(reference == null)
            reference = Load();
        return reference;
    }

    protected abstract T Load();
}

[CreateAssetMenu(menuname = "External Resource/Bytes", filename = "new bytes.asset")]
public class ExternalBytes : ExternalResource<byte[]> {

    protected override byte[] Load() {
        return System.IO.File.ReadAllBytes(filePath);
    }
}

public class MyComponentRequiringExternalData : MonoBehaviour {

    public ExternalBytes dataSource;
}

```
> 0 votes

---
Tags: unity, serialization
---


title: moving ball on spawn

text:
# Question
Title: moving ball on spawn
I'm working on some special pick ups on an arkanoid-like game. Currently, I have one that should spawn several balls all in a row, right after the original ball hits the paddle. All the additional balls should spawn just above the paddle and then they are passed the vector from the original ball, in which case they should follow that vector, essentially causing a line of balls all traveling in the same direction. The problem I am having is the ball's spawn just above the paddle, but they are spawning in place. Gravity pulls them down, and when they hit the paddle, that seems to be when the vector becomes active and the ball takes off like it should have when it spawned. I'm not sure what I am doing wrong here to keep it from just taking off like that as soon as it spawns. Can anyone see anything here that could be causing this behavior?

This is the code for spawning a ball and setting the vector.

```
  Instantiate(newBall, new Vector3(paddle.transform.position.x, (paddle.transform.position.y + 1), 0), Quaternion.identity);
    newBall.GetComponent<Ball>().hasStarted = true;
    GameManager.pickUpManager.allBalls.Add(newBall.GetComponent<Ball>());
    newBall.GetComponent<Rigidbody2D>().AddForce(mainBallVector, ForceMode2D.Impulse);      //use the original ball's vector3 to follow it directly

```

Here is where mainBallVector gets set, it is a vector3:

```
  mainBallVector = mainBall.GetComponent<Rigidbody2D>().velocity;

```

# Answer
> 1 votes
Don't forget to capture the instance of the ball you've just spawned (returned by the Instantiate method) - otherwise your subsequent lines accessing `newBall` are acting on the prefab you spawned it from, not the new instance.

eg.

```
// At the top of your script:
public Ball ballPrefab;

// ... in your spawning method:

var ball = Instantiate<Ball>(
            ballPrefab,
            (Vector2)paddle.transform.position + Vector2.up,
            Quaternion.identity);

 ball.hasStarted = true;
 GameManager.pickUpManager.allBalls.Add(ball);

 ball.GetComponent<Rigidbody2D>().velocity = mainBallVelocity;

```

You'll note I changed the last line, because your code had a mismatch between the way you read the vector from the main ball (as velocity), and the way you applied it to the new ball (as an impulse).

If we call 1.0 worldspace units a meter, then velocity has units of meters per second, and impulse has units of Newton seconds (or kg m/s)

So for objects with a mass other than one, these two numbers won't agree. If you just want to overwrite the new ball's velocity to exactly match the main ball's, assigning it directly is probably the simplest & clearest way.

Or if you want to continue using `AddForce`, don't forget to scale up your velocity by the ball's mass to convert it to a desired change in momentum for use as an impulse.

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


# Question
Title: How to add mesh collider which updates with water wave vertex offset?
I have written a shader (in the new LWRP shader graph) which simulates an ocean with vertices which offset to create a moving "waves" effect.

I believe that in order to have objects "float" on my moving waves, I shall need to create a mesh collider which is a trigger (please correct me if I'm wrong) which updates with the moving vertices of the mesh as per direction from the shader.

How is such an effect possible? Am I taking the correct approach here? Please advise :)

Many thanks in advance!!

(the original model for the water is a plane which has been subdivided multiple times to provide suitable resolution for the vertices to be offset)

# Answer
I would not recommend using a meshCollider for this. They're one of the more expensive types of collider to process, and every time you move the vertices the physics engine will need to recalculate all its acceleration structures that try to make looking up the right colliding triangles faster. You'll likely burn a ton of CPU this way.

One method I've seen used is to attach "floaters" to objects that are meant to float in the water. These behave like a virtual flotation device, exerting forces on the object according to their degree of immersion in the water.

Each physics update, each floater samples the water height at its position (eg. by evaluating the same wave function you use in the shader). If the floater is fully above the water, it exerts no force on its parent body. If the floater is partially or fully immersed (you can analytically model the floaters as spheres with a particular radius, for example), it calculates the total buoyancy force according to how much of it is underwater, and applies it as an upward force on the parent body, applied at its point of attachment.

These floaters can also compute & apply viscosity drag forces or lateral currents in a similar way. If you compute the local (low frequency) gradient vector of the waves, you can tilt the axis on which you apply these forces to push outward from larger sea swells.

With these, a floating object will not collide with the water like a solid floor, but ride within it on a fluid cushion spring. By adding more floaters distributed around your object, you can simulate more complex buffeting by waves (as eg. the starboard bow floaters take the wave first, causing the ship to lurch from the uneven forces on it)

Similarly for effects spawned at the water's surface - I wouldn't count on collision tests and raycasts to place them. Instead, sample your wave height function at the x/z coordinates of the effect and snap it to that height.
> 2 votes

---
Tags: unity, collision-detection, physics, unity-shader-graph, water
---


# Question
Title: Correctly transforming normals for G-Buffer in Deferred Rendering
I have a deferred rendering system: first there is the G buffer generation, then there is the lighting or shading calculation on that gbuffer data.

However there seems to be an issue with various rendering algorithms and I can’t determine why that is. I think it’s because my normal’s Gbuffer texture or other G buffer texture does not have the proper format or space in terms of world space, tangent space etc.

The algorithms that rely on normal information such as normal oriented ambient occlusion and parallax occlusion mapping don’t work they just look wrong And not what they’re supposed to be by a long shot.

In the G buffer generation stage, my vertex shader simply passes along world space vertex positions and world space normals to the Gbuffer's fragment shader. I do this by multiplying the world matrix or model matrix by the normal and by the position. In the fragment shader I then write these out as is to the G buffer.

Is this correct? Should I be passing along the Raw position & normals to the fragment shader and then multiplying the matrices in the fragment shader instead?

Edit 1:

Ok, So using the "normalMatrix" didn't change anything. Here is a screen shot of my ambient-occlusion pass demonstrating the issue. There is a screen space split that basically inverts the colors. and some other oddities.

The SSAO Shader is As Follows.

```
void main()
{

vec3 WorldPosition = texture(GPositionsTexture, In_TexCoords).xyz;
vec3 WorldNormal = normalize(UnScaleNormal( texture( GNormalsTexture, In_TexCoords ).xyz ));

vec3 Random = texture(KernalNoiseTexture, In_TexCoords * KernelNoiseScale).xyz;
vec3 Tangent = normalize(Random - WorldNormal * dot(Random, WorldNormal));
vec3 BiTangent = cross(WorldNormal, Tangent);
mat3 TBN = mat3(Tangent, BiTangent, WorldNormal);

float Occlusion = 0.0;
for (int i = 0; i < KERNEL_SIZE; ++i)
{
    // get sample position:
    vec3 Sample = TBN * Kernel[i];
    Sample = Sample * Radius + WorldPosition;

    // project sample position:
    vec4 Offset = vec4(Sample, 1.0);
    Offset = CamData.Projection * CamData.View * Offset;
    Offset.xy /= Offset.w;
    Offset.xy = Offset.xy * 0.5 + 0.5;

    // get sample depth:
    float SampleDepth = texture(GPositionsTexture, Offset.xy).z;

    // range check & accumulate:
    float RangeCheck= abs(WorldPosition.z - SampleDepth) < Radius ? 1.0 : 0.0;
    Occlusion += (SampleDepth <= Sample.z ? 1.0 : 0.0) * RangeCheck;
}

Occlusion = 1 - (Occlusion / KERNEL_SIZE);

Out_Diffuse = pow(Occlusion, Power);
}

```

# Answer
> 0 votes
So, Using the "NormalMatrix" actually did solve many of my issues with other algorithms that use them such as Parallax Occlusion Mapping.

However, there still remains an issue with my Ambient Occlusion algorithm so i'm going to create a different question specific to that. Thanks :)

# Answer
> 1 votes
In the case of a deferred system, your pipeline is as follows:

1. Compute projection matrix
2. Compute view matrix
3. Compute world to screen ( `mat4 pm = projection * view` )
4. Clear Geometry/Depth buffers.
5. Then, for each scene object, compute their world space transforms, and normal matrices. Tangent space (TBN) matrices can be computed in the first pass shader. The normal matrix is the inverse transpose of the world space transform(not object space to view space, as you would in a simpler forward rendering pipeline).
6. Activate your Geometry buffer, and draw as normal.

This next part is very important:

7. Compute the screen space position as normal (`vec4 s = pm * world * vertex`), in the vertex shader, along with your per vertex TBN (tangent space) matrix, this is obviously used for normal/parallax mapping. Your Bi/Co tangents should be computed when you load your meshes, for a faster, more efficient pipeline.

The data that gets written to each buffer is in *world space*, at *screen space* position for each buffer target.

Buffer0 is world space positions, buffer1 is world space normals. The rest are colour, and emissive properties, depending on your lighting model (let's take a simple example). Buffer2 rgb values are diffuse colour, and the alpha value is reflectity (or clamped specular value). Buffer3 is glow/emissive. Any additional buffer textures are for whatever else you may need.

8. Then you bind the GBuffer textures for sampling, and activate your swap buffer(composed of two buffer textures) and shaders.

Lighting calculations are performed in world space, by sampling all the information they need from the buffers.

9. Then, if you want to perform, additional post processing(HDR/AA etc), you swap and clear your swap buffers for each post process.
10. When you are done, finally, render a full screen quad, with the last written buffer as it's texture, directly to the back buffer.

This is the simple version, bereft of specific technical details, but I think that should answer any general questions you may have, and give you what you need to google anything else that pops up.

---
Tags: opengl, c++, glsl, deferred-rendering, normals
---


# Question
Title: How to select two different instances in Unity C#
I have 2 Balls, 2 Nodes, and 1 Hand. I can pick up a ball, send it to a Node, grab it, put it on another Node, but I can't grab any other balls.

The problem is that the Ball is defined publicly in The Node Manager. The Node Manager is a script given to The Hand and Each Node, because these are the places The Ball needs to go. While each Holding Place can easily declare itself, there is only one spot for a Ball. I can't add two Balls. I could make a `Ball1` and a `Ball2`, but that's not very scalable.

What I'd like to do is find a way to get the name of the Ball being looked at and use that to power the Ball Selection instead of using a public declaration.

What I want to do is something like a Raycast, but I feel like I'm already using a Raycast by using Pointer Enter and Pointer Exit. When you look at the Balls, they use the Pointers to activate certain scripts like changing the colors of the Balls, and actually triggering the code to grab things. If I can do all that with the Event Triggers, I should be able to specify a Ball. But I can't find out how to do that.

Part of me thinks the code for grabbing the Ball with your Hand actually needs to be on the Balls themselves, and not the Hand, but as much as I try, I can't seem to figure it out. I am officially giving in and asking for help.

I'm working off of this tutorial. I sent the author a message and he said that he's Working On It and would get back to me, but it's been like two weeks. It seems like it should be a really easy fix, but then again, the whole thing is spaghetti code, so who knows.

# Answer
Oh gosh... I would not recommend following this tutorial series. Apart from the brittle architecture that doesn't scale to multiple balls as you've discovered, I'm seeing errors in their transform code and asset setup already. Their naming conventions are certainly cute, but not as instructive as you'd want to use in production code that needs to make sense to your whole team months later.

I'd recommend starting from scratch. Since I don't currently have a VR development environment configured, I can't give you fully tested code to build from, but I can give a sketch of how we could architect this to scale better:

* **IGazeSelectable** interface: defines a contract for anything we want to select with our gaze. It says all these interactions must expose:

+ `bool IsSelectionAvailable()` predicate: so we know to ignore stuff that's not currently selectable.
    + `void OnSelectionComplete()` action: a behaviour to fire after our gaze has lingered long enough to complete the selection.
* **Pickup** component: represents an object that can be picked up. Holds a reference to the Holder that's currently holding it, if any. Implements IGazeSelectable:

+ `IsSelectionAvailable()`: check if the Inventory is not currently full.
    + `OnSelectionComplete()`: tell the Inventory to pick up this object. (Removing it from its current Holder, if any)
* **Holder** component: represents a place where a pickup can be stored. Stores a reference to the Pickup it's currently holding, if any. Implements IGazeSelectable:

+ `IsSelectionAvailable()`: check if the holder is currently empty AND the Inventory has something that can be placed here.
    + `OnSelectionComplete()`: tell the Inventory to place its object in this holder.
    + also: `void Store(Pickup pickup)`: takes the provided Pickup and handles transforming/parenting it as necessary to sit in the right place for this Holder.
* **Inventory** component: a singleton that represents what the (local/VR) player is carrying. Has its own Holder (the hand) to store a carried pickup object. Other scripts can interact with it via...

+ `bool CanPickUpObject(Pickup pickup)`: check if we have room in our hand to hold the item.
    + `bool CanPlaceObject(Holder holder)`: check if we have an object that we can place into the given holder (you can build on this to make certain holders only accept certain objects, like locks & keys)
    + `void Pickup(Pickup pickup)`: take the given pickup object and store it in our hand, and remove it from any previous Holder that held it.
    + `void PlaceIn(Holder holder)`: place a carried object in the given holder, removing it from our hand/Inventory.

Using this setup, we can later choose to expand our Inventory to a stack of objects, a set (from which we automatically select the best fit for a given interaction), or a menu the player can cycle through, without affecting any of the other scripts that communicate with the Inventory.
* **Gaze Selection** component: handles checking when the gaze has entered a new object or left an old one (this script can implement some hysteresis so you have a little wiggle room and your selection doesn't flicker).

The Gaze Selection component uses `GetComponent<IGazeSelectable>` to find any gaze-interactive scripts on the objects being looked at, and if `IsSelectionAvailable()` it can display the selection timer, firing the gazed-upon object's `OnSelectionComplete()` action when the timer finishes.

Now we have no concept of "The Ball" anywhere in the code. Each holder (including the Inventory's hand) knows what it's holding, the Gaze Selection component knows what it's looking at, and Pickup objects know when they're eligible for pickup.
> 2 votes

---
Tags: unity, c#, raycasting, picking
---


# Question
Title: Upgrade to Unity 2018.2.2f1 resulting in missing file errors from Visual Studio
After being prompted by Unity to upgrade and doing so, Visual Studio is now giving me a long list of errors in the project about missing files.

```
Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\FastAction.cs' could not be found.  Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active
Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\MaterialReferenceManager.cs' could not be found.    Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active
Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\PackageResourceImporterWindow.cs' could not be found.   Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active

```

There are 45 of these, and they're all in the project Unity.TextMeshPro. I've looked for these files and they don't see to be anywhere on my PC. Should I try reinstalling Unity or starting a new project again? Has anyone else run into this?

# Answer
It turns out I did have all 45 files, but they were nowhere near the project folder VS was trying to find them in. They were in

```
C:\Users\(me)\AppData\Local\Unity\cache\packages\packages.unity.com\com.unity.textmeshpro@1.2.4\Scripts\Runtime.

```

I copied them over and everything seems fine now. I expect Unity to handle this kind of stuff on its own when I run the installer.
> 4 votes

---
Tags: unity, visual-studio
---


# Question
Title: Solutions for maintaining importers and exporters when chaning file formats
After having a very short discussion with Delix on youtube (see link below) on custom data storage formats, I started thinking. What are some useful ways of maintaining importers / exporters when you change your file format during the development of your game?

The most obvious solution would be to write different functions for file formats like `exporterV1(), importerV1(), exporterV2(), importerV2()`, etc. Then call the correct function based on some sort of header in your file. Like using the first byte(s) to store the version of the file format. However, this seems incredibly inefficient. Especially since you'll have to writer converter functions to translate between the file formats. I.e. `v1tov2converter()`.

Usually when writing this kind of thing, a voice in the back of my head screams "there must be a better way of doing this", but I'm drawing a blank so far.

Naughty Dog seems to use scheme for describing both the data and how it should be read. However, my knowledge of scheme is non-existent so I have no clue how that would work. This would however, solve my problem, as the data would describe itself see reference.

What are, in your opinion, some of the clever ways you know of, to solve this issue?

As a response to a question in comments asked by @DMGregory: I'm mostly talking about changes during development of the game(engine). Changing file formats in production seems like a can of worms I would not like to open. Especially if your dealing with importer / exporters of safe game data.

# Answer
> Naughty Dog seems to use scheme for describing both the data and how it should be read. However, my knowledge of scheme is non-existent so I have no clue how that would work. This would however, solve my problem, as the data would describe itself see reference.

Not something I would recommend if you are a solo developer or a small group of developers. This requires a dedicated team only for such task.

> What are some useful ways of maintaining importers / exporters when you change your file format during the development of your game?

Get rid as fast as you can of older/legacy versions.

**Exporting**

Don't export to older/legacy formats, only export to the most recent format.

**Importing**

* Option 1. do as you mentioned, having a function `importV1()`, `importV2()`, etc.
* Option 2. similar, but instead of having these functions all inside your main application (game or editor), make a separate command-line tool that converts to the most recent format, then the main application can only load the most recent version.

Don't turn you format into the new PSD.
> 6 votes

# Answer
Never remove data from your saved data, only add. Let .NET's serializers take care of the rest. (That's my advice if you have access to .NET, as with Unity). This comes from experience with handling this exact problem both professionally, and in my home projects.
> 2 votes

---
Tags: architecture, software-engineering, file-format, asset-management
---


title: how to represent a nested menu system?

text:
# Question
Title: how to represent a nested menu system?
I'm wondering what would be a clever way of making a layered menu system, in terms of what data structures to use.

An example of what I mean: A unit has the ability to construct buildings, and to cast some spells. The selection of buildings and spells are accessed either through pressing a hotkey or clicking an icon in the user interface. What is the best way to achieve this in the code?

I'm thinking something like:

Menu base state: options are A and B. If the players clicks A: change state and display the suboptions of A, and so on. But how is this achieved in the actual code? Perhaps a `dict()` containing functions:

```
options = {
           'A' : self.change_state ('a', self.current_state),
           'B' : self.change_state ('b', self.current_state)
          }

def on_key_event(self, key):
     options[key]

def change_state(self, key, state):
     if state == state_1:
          if key == 'a':
              ...

```

And so on, this seems really tedious and if possible I want to avoid `if / else` loops and just define everything in the simplest, and shortest manner.

I'm interested in how you would do this, or if you've already made a similar system, how you solved it in your own code.

# Answer
> 4 votes
Try using a common class/interface for each of your "states", this is a fairly common approach to state machines (and avoids the long chain of if/else).

You *could* use just a dictionary of functions, but more often than not you'll likely find you want some form of initialisation functions too, or notification of completion - so may as well go with a "classic"

Generally a state implementation will have at minimum `enter(), exit() and update()` methods, and the state machine will just contain a stack of states which it updates.

It can also be handy (as you mention) to have a dictionary lookup for them, otherwise you need to keep references or instantiate new states in order to switch. For a menu system I'd **highly** recommend having a dictionary of some sort as it becomes a lot easier to dynamically switch between menus in a data-driven fashion. (eg. switching to a menu based on metadata in the button rather than pre-coding everything)

Depending on your needs, you can either:

* build your menu on top of these vanilla states (and have things like input checks happen in each respective `update()` method)
* extend the types of "events" states can receive so that your central application can call states with things like `userSelected(), mouseClicked()` or similar.

I've whipped up a (very) simple example in Python here, but I'm not a Python programmer, so apologies if it burns your eyes.

The main purpose of this code is to demonstrate that the state machine itself can be a state, allowing you to nest them for complex behaviour (or just more flexible menus)

```
""" A simple base state for the state machine
"""
class BaseState:
    parent = None
    name = "state"
    isDone = False
    def __init__(self, name):
        self.name = name or self.name

    def enter(self):
        pass
    def update(self):
        pass
    def exit(self):
        pass

""" A simple State Machine
    Note that it is a sub-class of BaseState, this allows
    for nested complex states.

"""
class StateMachine(BaseState):
    def __init__(self, name):
        BaseState.__init__(self, name)
        self.stateDict = {}
        self.reset()

    def update(self):
        """ Update states
            note that it's sometimes beneficial to have an extra
            method on your state objects to allow them to forcibly
            seize control in certain scenarios, this simple model
            doesn't include such things
        """

        # no processing an empty stack often this will be used
        # to exit the menu or application (for example)
        if len(self.stateStack) <= 0:
            # here we're manually exiting the last state (if any)
            # since we are ensuring predictable behaviour by delaying
            # calls to enter() and exit() ie. not exiting a state
            # when it's done, but instead once we're ready for it to be
            self.exitState(self.lastState)
            self.isDone = True
            return

        currentState = self.stateStack[-1]

        if self.lastState != currentState:
            """ We've switched states, notify everyone involved """
            self.switchState( currentState )

        if currentState != None:
            currentState.update()
            if currentState.isDone:
                self.popState()

    def reset(self):
        """ Reset the state machine, but leave its dictionary intact """
        self.stateStack = []
        self.lastState = None
        self.isDone = False

    def switchState(self, newState):
        """ Handles exiting and entering states appropriately """
        self.exitState( self.lastState )
        self.enterState( newState )
        self.lastState = newState

    def enterState(self, stateObj):
        """ Helper function to safely enter the specified state object """
        if stateObj != None:
            stateObj.enter()

    def exitState(self, stateObj):
        """ Helper function to safely exit the specified state object """
        if stateObj != None:
            stateObj.exit()

    def addState(self, state):
        """ Add a state to the dictionary for later
            ! Doesn't push or enter !
        """
        state.parent = self
        self.stateDict[state.name] = state

    def pushState(self, stateName):
        """ Push a state onto the stack by name """
        if not self.stateDict.has_key(stateName):
            print "here you whinge that state:%s doesn't exist.." % stateName
            return
        newState = self.stateDict[stateName]
        self.stateStack.append(newState)

        return newState

    def popState(self):
        currentState = self.stateStack.pop()

""" A little example state for demonstration
"""

class TestState(BaseState):
    def __init__(self, name):
        BaseState.__init__(self, name)

    def enter(self):
        print "entered " + self.name

    def update(self):
        print "updated " + self.name

        # just bail out of this state for testing
        self.isDone = True

    def exit(self):
        print "exiting " + self.name

if __name__ == '__main__':
    """ Test out the state machine """

    machine = StateMachine("Master Control Program")

    ## Ultra simple
    machine.addState( TestState("State-A") )
    machine.addState( TestState("State-B") )

    ## set up a simple stack
    machine.pushState("State-A")
    machine.pushState("State-B")

    ## test it out
    print("Running simple state machine...\n")
    while not machine.isDone:
        machine.update()

    ## Nested test
    machine.reset()

    nestedMachine = StateMachine("Nested-A")
    nestedMachine.addState( TestState("Sub-State-A") )
    nestedMachine.addState( TestState("Sub-State-B") )
    nestedMachine.addState( TestState("Sub-State-C") )

    ## Set up a simple nested stack
    nestedMachine.pushState("Sub-State-A");
    nestedMachine.pushState("Sub-State-B");
    nestedMachine.pushState("Sub-State-C");

    machine.addState( nestedMachine )

    ## set up another simple stack
    machine.pushState("State-A")
    machine.pushState("Nested-A")
    machine.pushState("State-B")

    print("Running simple nested state machine...\n")
    while not machine.isDone:
        machine.update()

```

# Answer
> 0 votes
Clearly this is five years late, but I created a menu system in Python that isn't necessarily tied to state machines or games. However, it does require that you separately define the submenus and/or leaf procedures that menu options lead to. My approach takes advantage of the fact that functions in Python are first-class objects (and can therefore be stored in dictionaries, as you noted).

Here's the code:

```
# A Menu consists of one or more sub-Menu objects that a user can choose
# to run or subroutines that the user can call.
class Menu:

    # Constructor
    def __init__(self):
        self.options = {}
        self.setPrompt("Please choose an option:")
        self.setErrorText("Error! Please enter a valid option.")

    # Adds an option to this Menu. An option consists of a number,
    # name, and the actual object it corresponds to (submenu or procedure).
    # The last value in each key-value pair denotes whether the given option
    # should trigger an exit from the current Menu after it is called.
    def addOption(self, optionNumber, optionName, option, TriggersExit):
        self.options[optionNumber] = [optionName, option, TriggersExit]

    # Sets this Menu's error text
    def setErrorText(self, errorText):
        self.errorText = errorText

    # Sets this Menu's prompt
    def setPrompt(self, prompt):
        self.prompt = prompt

    # Returns the number of options in this Menu
    def size(self):
        return len(self.options)

    # Displays this Menu's error text
    def displayError(self):
        print("\n{}\n".format(self.errorText))

    # Prints the Menu in its entirety
    def display(self):
        print(self.prompt)
        for i in range(1, self.size()+1):
            print("{} - {}".format( i, self.options[i][0] ))
        print()

    # Runs this Menu
    def run(self):
        userInput = ""
        self.display()
        while True:
            userInput = input("Your selection: ")
            try:
                userInput = int(userInput)
                if userInput <= 0 or userInput > self.size():
                    self.displayError()
                else:
                    # If the menu option is a function, call it
                    if callable(self.options[userInput][1]):
                        self.options[userInput][1]()
                        # And if it's an option that triggers a return/exit, then return after it's called
                        if self.options[userInput][2]:
                            return
                        # Otherwise, redisplay the menu options
                        else:
                            self.display()
                    # But if the menu option is a submenu, run it
                    else:
                        self.options[userInput][1].run()
                        # And display the calling menu's options again upon return from the submenu
                        self.display()
            except ValueError:
                self.displayError()

def Exit():
    print("\n\tThanks for using my program!\n")

def Return():
    return

def Option1():
    values = input("\n\tEnter some values: ")
    print("\n\tYou entered these values:", end=" ")
    for i in range(0, len(values)):
        print(values[i], end=" ")
    print()

def MyLife():
    print("\n\tLife's hard.\n")

def GettingHelp():
    print("\n\tRecursion jokes suck\n")

def main():

    mainMenu = Menu()
    mainMenu.setPrompt("\nSelect an option:")

    menu1 = Menu()
    menu1.setPrompt("\nSelect an option:")
    menu1.addOption(1, "Option1", Option1, False)
    menu1.addOption(2, "Return", Return, True)

    menu2 = Menu()
    menu2.setPrompt("\nWhat would you like help with?")
    menu2.addOption(1, "My life", MyLife, False)
    menu2.addOption(2, "Getting help", GettingHelp, False)
    menu2.addOption(3, "Return", Return, True)

    mainMenu.addOption(1, "Enter new values", menu1, False)
    mainMenu.addOption(2, "Help", menu2, False)
    mainMenu.addOption(3, "Exit", Exit, True)
    mainMenu.run()

main()

```

Note that it does take some code to set up the menu hierarchy at first. But after you set everything up, all you have to do is invoke `run` on the `mainMenu` and let it do its thing.

---
Tags: python, optimization, menu
---


# Question
Title: Keeping instantiated grid in the centre of the screen?
everyone, I'm making a mobile game and I need help. In the game, I instantiate a grid of dots as seen in the first attached file below. My problem is the grid is not in the centre of the screen I could just position my main camera so the grid is in the centre the only problem with this approach being that the grid changes in size depending on your level as shown in attachment 2

here's my spawn code

```
  for (int x = 0; x < gridX; x++)
         {
          for (int y = 0; y < gridY; y++)
             {
                 SpawnDelay = Random.Range(0.2f, 0.5f);
                 yield return new WaitForSeconds(SpawnDelay);
                 Instantiate(Dot, transform.position, transform.rotation);

                 NumberOfdots++;
        transform.position = new Vector2(transform.position.x + distanceBetween, transform.position.y);
                 if (y % MutpleNum == ByMutpleNum)
                 {
                     transform.position = new Vector2(GridoffsetX/2, transform.position.y + GridoffsetY);
                 }
             }

         }

```

Is there anyway I can have the grid centre regardless of its size

Thanks,

David

# Answer
> 1 votes
1. Determine the width, height, and the coordinates of the corner of the rectangle in which you want the dots to appear. How to do this depends on how large you want the border to be and on the settings and position of your camera.
2. Divide width by the horizontal number of dots. This is your x-increment.
3. Divide height by the vertical number of dots. This is your y-increment.
4. Determine the instancing position by multiplying the increment with the loop-counter and then add the start position and half the width (to get it neatly centered).

Here is an example script. The script uses the orthorgaphic size of the main camera as the desired size of the rectangle, which is half the vertical screen size:

```
public class GridCreator : MonoBehaviour {

    public GameObject dotPrefab;
    public int numRows;
    public int numColumns;

    // Use this for initialization
    void Start () {

        Camera camera = Camera.main;

        // determine the size of the whole rectangle
        float rectWidth = camera.orthographicSize;
        float rectHeight = camera.orthographicSize;
        float rectX = camera.transform.position.x - rectWidth / 2.0f;
        float rectY = camera.transform.position.y - rectHeight / 2.0f;

        // fill the rectangle with dots
        float xDistance = rectWidth / numColumns;
        float yDistance = rectHeight / numRows;

        for (int x = 0; x < numColumns; x++) {
            for (int y = 0; y < numRows; y++) {

                Vector2 position = new Vector2( x * xDistance + rectX + xDistance / 2.0f,
                                                y * yDistance + rectY + yDistance / 2.0f);

                Instantiate(dotPrefab, position, Quaternion.identity);
            }
        }
    }
}

```

You could optimize this code slightly by avoiding the `+ xDistance / 2.0f` part in the position calculation by add that offset to rectX instead, but in my opinion this makes the code harder to follow. And considering that this isn't performance-sensitive code, I would rather go for the clearer solution.

I'm looking forward to playing your game.

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


# Question
Title: What is the difference between a sprite sheet and a texture atlas?
I wondering what the difference is between a sprite sheet and a texture atlas?

Aren't both the same? In a sprite sheet you have some Sprites and in a texture atlas you also have some sprites, so what's the difference?

# Answer
A sprites-sheet (often refers to a large image that) is supposed to contain the **animation frames** of a specific *2d* character or projectile in a game. You can almost think of it as the *model* of a 2d-character. It stores all the various animations created for a specific character.

A texture-atlas (is often taken to mean a large 2d image that) contains many **textures**. You can think of these as 2d images "painted" over 3d objects or otherwise applied to them as part of a shader to explain to the renderer (the part that converts 3d data into a 2d image) how they reflect light (normal map) or if there are any grooves, bumps or cracks on their surface (bump map) or possibly something else altogether like opacity and what not. This term (texture atlas) will often be used in a `3d` game environment. Any 3d object (e.g a weapon, a garbage can) or character can have a texture applied to it. Especially 3d levels may require multiple different textures for various walls and elements in the 3d scenery. All these textures can be contained accessibly and effectively in a single large image composed of many squares (subregions) devoted to a specific model.

Also, it may be important to note a texture atlas often contains character skins (character textures) and that the actual animation is (stating the obvious) not stored as 2d imagery as the animation in such cases is generally based on deformation of the mesh with tools like bones.
> 25 votes

# Answer
Technically seen it's the same: It's a big image that contains smaller images (sprites).

The 3d vs 2d does not make a difference here since almost all 2d game engines use 3d hardware for rendering....
> 11 votes

# Answer
A sprite sheet and texture atlas are nearly the same. They are both bitmap image files (jpg, png, etc.) that contain multiple smaller images, usually in a grid, that are indexed and displayed using software / game engine that locates the individual images by their coordinates. They also both serve to simplify resource management and lower draw calls by only requiring the management and loading of a single file.

This sheet/atlas has both frame by frame animations of the character (typically used in a "sprite sheet") as well as images that will be tiled as a texture for the walls (a.k.a. a "texture atlas"):

The difference, it seems, is how they are typically implemented. As other answers state, a sprite sheet is often used in 2d games for animations or buttons, while the images in a texture atlas are used as textures for mesh objects.

While the context and what is displayed on the images matters, so does the way that the program manages and manipulates the images. An image file used as a sprite sheet in a game engine could play the individual images one after another to create an animation. But you could equally use the same image file as a texture atlas in the same engine as tiles on a mesh to create a wall of bricks.

This means there are more specific distinctions depending on how your software manages these two types of uses. In Unity for example, it is not so easy to convert an image applied to a GameObject from a sprite sheet to a Texture2D that can then be applied to a different GameObject as a texture. Which is how I arrived on this page via Google and decided to add this answer. :-)
> 6 votes

# Answer
I would say that texture atlas is the most general term: you can build a sprite sheet out of a texture atlas, but usually not the other way around.

The key distinctive assumption is the way texture coordinates are mapped to geometry: sprite sheets assume rectangular sub-regions, whereas texture atlases can be mapped to any geometrical surface.

If all geometrical surfaces mapped from the texture atlas happen to be 2D quads, you have a sprite sheet. If you change the mapping over time, or on a frame-by-frame basis, you can simulate 2D character animation.
> 0 votes

---
Tags: spritesheet, texture-atlas
---


# Question
Title: Fixed timestep on the server without hogging CPU?
It sounds backwards, but it's the situation I'm currently trying to solve on my dedicated server.

Everything I've read about fixed timestep assumed it was on a client, where you're already running in a loop as fast as you can to render the game, and you are just inserting the fixed timestep updates within that.

Problem is, on the server, that's the *only* thing being done in the loop, aside from checking for network activity. So my server ends up using 100% CPU, looping needlessly while waiting for the next fixed timestep.

The only way I know to fix this is by adding a sleep to the loop, but I know how inaccurate that delay can be, which would throw off the accuracy of the timesteps.

Is there a better way to keep it from burning CPU? Or is sleep what most dedicated servers are doing anyway?

# Answer
> 3 votes
Sleeping is a valid solution and it's easy to implement. Pick a sleep duration that will use less CPU but still give you acceptable simulation accuracy.

An alternative solution is to use an event loop on your server. An event loop would only wake up the main thread when it's needed, for example at a regular interval, or when a network message arrives.

There are many event loop libraries available in various programming languages. libuv and Boost.Asio are popular alternatives if you use C/C++. If you use one of these libraries, you probably want to have a look at their timer implementations. A timer can run a callback at a regular interval, perfect for your fixed steps. The code below shows you how to create and run a timer using libuv (read more at http://docs.libuv.org/en/v1.x/guide/utilities.html#timers):

```
#include <stdio.h>
#include <uv.h>

uv_loop_t *loop;
uv_timer_t timer_req;

void callback(uv_timer_t *handle) {
    fprintf(stderr, "Running callback!\n");
}

int main() {
    loop = uv_default_loop();

    uv_timer_init(loop, &timer_req);

    // Start the timer after 0ms and run callback at a 30ms interval
    uv_timer_start(&timer_req, callback, 0, 30);

    return uv_run(loop, UV_RUN_DEFAULT);
}

```

---
Tags: client-server, server, fixed-timestep
---


title: How to distort 2d perlin noise?

text:
# Question
Title: How to distort 2d perlin noise?
I am using Unity's 2D `Mathf.PerlinNoise(x, y)` function and I would like to make it distorted. What I mean is described with this picture I made:

How can I do that? What transformations should I apply to `Mathf.PerlinNoise(x, y)` to achieve this effect?

# Answer
It sounds like you want an effect called Domain Warping.

This is when you layer your noise using function composition:

* First you sample some noise based on your input position
* Then you add the results to your input position to get a shifted position
* Then you sample some noise *at that shifted position* to produce your final output

It's called domain warping because you're distorting the space of inputs to your noise function (the function's domain)

On the left is basic Perlin noise, and on the right the same noise with a small amount of domain warping applied (with topographic contours to help show the effect)

In Unity C# code it might look a bit like this:

```
public float DistortedNoise(float x, float y, float distortionStrength) {
    // Take two samples from our distortion function
    // (Shifted in space by > 1 so they don't correlate with each other)
    float xDistortion = distortionStrength * Distort(x + 2.3f, y + 2.9f);
    float yDistortion = distortionStrength * Distort(x - 3.1f, y - 4.3f);

    return Mathf.PerlinNoise(x + xDistortion, y + yDistortion);
}

float Distort(float x, float y) {
    // Optionally, you can scale your internal noise frequency
    // or layer several octaves of noise to control the wiggly shapes.
    float wiggleDensity = 4.7f;
    return Mathf.PerlinNoise(x * wiggleDensity, y * wiggleDensity);
}

```
> 3 votes

---
Tags: unity, perlin-noise
---


# Question
Title: Unity Shader Graph, set blackboard properties from code
I have a Shader Graph shader with a blackboard property that I want to change from within my code. The property is called `Highlight` here are the things I have tried:

```
Color myColor = new Color(1f,0,0,1f);
material.Color = myColor;                       // throws error (as I expected)
material.SetVector("Highlight", myColor);       // Name in blackboard window
material.SetVector("HighlightColour", myColor); // Name in material property
material.SetVector("Color_8C3A526", myColor);   // Name in the shader inspector

```

None of these work.

Here's the shader set up:

# Answer
In Unity 2018.2, they've added an editable Reference Name for properties in shader graphs, letting you replace these unfriendly generated names like `Color_8C3A5256` with semantically meaningful names.

> You can now edit the Reference name for a property, making it far easier to reference your shader properties from script. To do so, select the property and type a new name next to Reference. If you want to reset to the default name, right-click Reference, and select, Reset reference.
>
> In the expanded Property window, you can now also toggle the Exposed checkbox.
> 2 votes

# Answer
To set the colour in the Shader use:

```
Color myColor = new Color(1f,0,0,1f);
material.SetColor("Color_8C3A526", myColor);

```

Although the blackboard parameter color is "Highlight", it has a unique codename that you can find by opening the inspector and selecting (but not opening) your shader graph. The shader in the question looks like this:

The Highlight colour appears under Properties and has the unique key of `Color_8C3A526`. If you change the name of Highlight in the shader graph tool then the unique key will remain the same.

Thank you to @DMGregory, who got me most of the way there.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Why do I get a blank material in Unreal Engine 4?
When I'm adding a material to a box in UE4, the material loses its textures.

I want to add this material

To this

After I'm trying to drag & drop the material into the scene above (like in UDK) the material loses its textures and does not apply:

When opening the material in Material-builder, the same thing happens: the material loses its textures and I've got these two errors on "Stats":

> \[SM5\] (Node TextureSampleParameter2D) Param2d\> Requires Texutre2D
>
> \[SM5\] (Node TextureSample) TextureSample\> Missing input texture

I've searched and found a thread where they say I need to save the material again to get things right. When I click the save button, I have this error:

> The current material has compilation errors, so it will not render correctly in feature level SM5.

*NOTE: Using DepthFade node + Lerp and changing the blend to translucent didn't resolved my issue.*

Any idea?

# Answer
Make sure your textures exists on the correct path. If you delete or move a texture the materials may throw errors.
> 2 votes

# Answer
Your texture samples in material have no textures inside him. Try to link textures to the material again.
> 2 votes

# Answer
If you want to add the material to an Actor, just select it in the editor, select the StaticMeshComponent of any other Mesh and then you can select a material in the Properties Panel, just type it into the search box. If the Actor is a StaticMesh itself, you can select the Material in the Properties Panel directly.
> 2 votes

# Answer
I guess you have a folder with a bunch of materials that you downloaded and not a complete project.

The thing is that you cannot use them just by copy-pasting them directly into your project.

Do the following to be able to use them:

1. Copy the whole folder and paste it on the directory where your **VaultCache** is located. ( `Program Files x86 > Epic Games > Launcher > VaultCache`).
2. After that, open your Epic Games Launcher and go to **Unreal Engine \> Library**.
3. If you look at the bottom there's a Vault tab. And under that should be the Asset Folder you just pasted in your VaultCache.
4. Press **"Add to Project"** and select the project you want to use it on.

There's a chance that you'll have to select an earlier version than the one you're using.
> 1 votes

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


title: Find hexes on a hex grid given an angle

text:
# Question
Title: Find hexes on a hex grid given an angle
I'm trying to find an elegant solution to calculating the x, y values of hexes that are crossed or intersected by a line or ray at a given angle from a given hex position on a hex grid. I do not want to use linear interpolation with an end point. I want a function that can calculate values to an arbitrary length with just the the angle. Pretend someone is standing at hex 4, 4 and shoots a bullet at angle 30. Which hexes will it cross? In the case of angle 30 where the angle is exactly between two hexes, default to the clockwise hex. I think there must be an elegant solution and at a certain point the number of "straight" moves vs. shifts "right" or "left" must form a repeating pattern. Furthermore, for a given angle, it will only shift right or left at some repeating interval, but never both. How do you calculate this? My grid uses x, y, (z) coordinates with "pointy top" hexes.

The function I'm trying to write would look like this: getXYOffsets(angle):Array of int;

The return value being a list of x, y offsets used to calculate the next hex's xy indefinitely (like I said, the offset pattern will repeat at some point). For example, angle 0 will return an array of \[1, 0\] because a line shot that direction will move in the x direction infinitely and I just loop over that 2 value array to find my next x, y coordinates indefinitely. For second example, angle 30 will return an array of \[0, 1, 1, 0\] because I would draw my line from 0, 0 -\> 0, 1 -\> 1, 1 -\> 1, 2 -\> 2, 2... indefinitely. Obviously, less roundable angles will give longer returns arrays because you might have straight stretches that last a long time before finally "shifting". That's ok. I'll limit that after I get a solution to this math problem.

I just know this calculation is possible but my math is too weak to solve it. Any help would be SO appreciated!

# Answer
I think I've found the best solution I am mathematically capable of to my problem and which uses a type of method signature I want (one that takes an angle as input and draws a draw to a given length. This code isn't pretty and I would welcome suggestions on how to make it more elegant.

```
public static function getHexLine(x:int, y:int, angle:Number, steps:int=5):Vector.<int> {
        if (angle < 0) {
            angle += 360;
        }
        //"quad" is a terrible variable name. There are 6 "quadrants":
        //rb, cb, lb, lt, ct, rt (0, 1, 2, 3, 4, 5)
        //(r = "right", c = "center", l = "left", b = "bottom", t = "top")
        var quad:int = Math.floor(angle / 60);
        //We caculate offsets within an arc for 60 >= angle > 0.
        //Use "quad" to then calculate the resultant position with the right formula.
        angle %= 60;
        var points:Vector.<int> = new <int>[x, y];
        for (var i:int = 1; i <= steps; i++) {
            var angleIncrAmt:Number = 60 / i;
            var angleIncrCount:int = Math.round(angle / angleIncrAmt);
            var roundAngle:Number = angleIncrCount * angleIncrAmt;
            if (quad == 0) {
                points.push(
                    x + i - angleIncrCount,
                    y + angleIncrCount
                );
            } else if (quad == 1) {
                points.push(
                    x - angleIncrCount,
                    y + i
                );
            } else if (quad == 2) {
                points.push(
                    x - i,
                    y + i - angleIncrCount
                );
            } else if (quad == 3) {
                //like q 0 but with signs reversed.
                points.push(
                    x - i + angleIncrCount,
                    y - angleIncrCount
                );
            } else if (quad == 4) {
                //like q 1 but with signs reversed.
                points.push(
                    x + angleIncrCount,
                    y - i
                );
            } else if (quad == 5) {
                //like q 2 but with signs reversed.
                points.push(
                    x + i,
                    y - i + angleIncrCount
                );
            }
        }
        return points;
    }

```

Note that for javascript and ActionScript I would replace the if statement in the loop with a function call and assign that function before entering the loop. There's no reason to continually check "quad" once the loop begins that way. I haven't done that here in case anyone is using a language that doesn't treat functions as objects or allow lambdas (like Java pre-1.8 etc.).
> 0 votes

# Answer
Given a starting point x,y, do something like this:

1. For each adjacent cell (six of them), find the projection of the adjacent cell's center onto the direction ray.
2. Pick smallest one (distance to the ray) - aka the closest one. That is the next cell you'll select. Be sure you're moving in the desired direction, and not 180\* from it (backwards), which can be determined by checking the sign of the dot product of your direction ray with a vector from the start position to the candidate cell. You already calculated this in (1), so don't redo it.
3. Advance x,y to the projected point on the ray that you calculated for the cell selected in (2) and calculated in (1).
4. if (still\_inside\_hex\_grid) goto 1. (Please don't use GOTO, or you may be publicly mocked.)

This is a modified DDA algorithm, which may help you with the Googling.
> 0 votes

---
Tags: vector, angles, intersection, hexagonal-grid, path
---


title: 2D and 3D Tablet Games Definition

text:
# Question
Title: 2D and 3D Tablet Games Definition
I would like some clarifications how to distinguish between a 2D and 3D mobile game, as mobile devices do not really have 3D screens.

i) Do 3D iOS or android games really exist or are they 2D tablet/mobile games with 3D rendering of assets (textures, shadows) to denote the 3D look and feel?

ii) If a tablet game connotes depth with multi-layers and perspective, is it described as a 3D tablet game?

(iii) if there is a combination of 2D assets and 3D assets (both rendered in Photoshop), are they still called a 2D tablet game, if SpriteKit was used to build the game? Thank you

# Answer
> 3 votes
We're pretty loose with our definitions of 2D & 3D in games, meaning a mix of two things:

1. Are the graphics (mostly) rendered as 2D sprites, or 3D polygon meshes (or voxels or raymarched fields or other 3D representations...)?

Note that it's possible to "fake" 3D worlds with 2D techniques (like billboarded sprites, parallaxing, Mode 7, isometric perspective...), and it's arguable whether this is fundamentally less "real 3D" than the rasterization algorithms we use to render 3D polygon meshes. (After all, the math all works out about the same! We're just usually using a few special cases rather than full generality)

Sometimes games in this category will be called "2.5D" which is a term we use *even less* precisely to mean something that has some aspects of 2D and some aspects of 3D.
2. Is the gameplay three-dimensional, or in a 2D plane?

If the player has 3 axes of freedom (eg. a flight sim, or an action game where your character can run north/south & east/west as well as climb/jump/fall), then we can usefully call the gameplay 3 dimensional.

On the flipside, even if a game uses 3D rendering techniques, if the player's navigation space has only two degrees of freedom (eg. left/right + climb/jump/fall in a side-scroller, or north/south + east/west in a top-down game), we might usefully describe that game's play as "2D"

So there's no hard rule for what games get to "count" as 3D or 2D, it's mostly a matter of what it is about the game we want to emphasize as important when we're talking about it.

If we want to emphasize that the game is played on a stereoscopic screen where the player can literally see the depth rather than just infer it from perspective & motion cues (like a VR or mixed reality headset, a 3DS or 3DTV), it's usually best to use the word "stereoscopic" (or VR/MR/XR as appropriate) to avoid further overloading our 2D/3D terminology. ;)

---
Tags: 2d, 3d, mobile, terminology
---