# Question
Title: How can I make a menu item that splits animations based on a text file?
I want to split all the animations inside a FBX by using a .txt file which contains start times and names for the animations in this FBX.

I found a script that does exactely that here.

However, this script uses the PostProcessor, and this means that I have little possiblity over when it's called.

Instead, I would like this to happen when I click a certain menu item. To do that, I have added a new menu item to the Unity toolbar like this:

```
public class NewBehaviourScript : MonoBehaviour
{
    [MenuItem("Tools/FBX/Split")]
    private static void SplitFBX()
    {

```

However, as soon as I add the line

```
 ModelImporter modelImporter = assetImporter as ModelImporter;

```

from the other script, the Editor says that

```
 "The name assetImporter isn't available in the current context".

```

Does anybody see why this compiler error occurs?

I have also tried

```
"public class NewBehaviourScript : AssetPostprocessor"

```

but it gave me the error "An object reference is required for the non-static field, method or property "AssetPostprocessor.assetImporter".

This is the entire script:

```
using UnityEngine;
using UnityEditor;
using UnityEditor.VersionControl;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System;

public class NewBehaviourScript : MonoBehaviour
{
    [MenuItem("Tools/FBX/Split")]
    private static void SplitFBX()
    {
        var selected = Selection.activeObject;
        string assetPath = AssetDatabase.GetAssetPath(selected);

        EditorUtility.DisplayDialog("", assetPath, "Ok");

        try
        {
            // Remove 6 chars because dataPath and assetPath both contain "assets" directory
            string fileAnim = Application.dataPath + Path.ChangeExtension(assetPath, ".txt").Substring(6);

            if (!File.Exists(fileAnim))
            {
                return;
            }

            StreamReader file = new StreamReader(fileAnim);

            string sAnimList = file.ReadToEnd();
            file.Close();

            if (EditorUtility.DisplayDialog("FBX Animation Import from file", fileAnim, "Import", "Cancel"))
            {
                System.Collections.ArrayList List = new ArrayList();
                pParseAnimFile(sAnimList, ref List);

                ModelImporter modelImporter = assetImporter as ModelImporter;
                modelImporter.clipAnimations = (ModelImporterClipAnimation[])List.ToArray(typeof(ModelImporterClipAnimation));

                EditorUtility.DisplayDialog("Imported animations", "Number of imported clips: " + modelImporter.clipAnimations.GetLength(0).ToString(), "OK");
            }
        }
        catch (Exception e)
        {
            // EditorUtility.DisplayDialog("Imported animations error: ", e.Message, "OK");
        }
    }

    void pParseAnimFile(string sAnimList, ref System.Collections.ArrayList List)
    {
        Regex regexString = new Regex(" *(?<firstFrame>[0-9]+) *- *(?<lastFrame>[0-9]+) *(?<loop>(loop|noloop| )) *(?<name>[^\r^\n]*[^\r^\n^ ])",
                                      RegexOptions.Compiled | RegexOptions.ExplicitCapture);

        Match match = regexString.Match(sAnimList, 0);
        while (match.Success)
        {
            ModelImporterClipAnimation clip = new ModelImporterClipAnimation();

            if (match.Groups["firstFrame"].Success)
            {
                clip.firstFrame = System.Convert.ToInt32(match.Groups["firstFrame"].Value, 10);
            }
            if (match.Groups["lastFrame"].Success)
            {
                clip.lastFrame = System.Convert.ToInt32(match.Groups["lastFrame"].Value, 10);
            }
            if (match.Groups["loop"].Success)
            {
                clip.loop = match.Groups["loop"].Value == "loop";
            }
            if (match.Groups["name"].Success)
            {
                clip.name = match.Groups["name"].Value;
            }

            List.Add(clip);

            match = regexString.Match(sAnimList, match.Index + match.Length);
        }
    }
}

```

# Answer
I got the solution:

I have re-written the code because some variable names were not easy to understand.

And as DMGregory pointed out, now that the ModelImporter is called from a different location (and not from the PostProcessor), it doesn't know which FBX we're dealing with, so we need to get the ModelImporter from the Asset.

Here is what it looks like:

```
using UnityEngine;
using UnityEditor;
using UnityEditor.VersionControl;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;

public class NewBehaviourScript : AssetPostprocessor
{
    [MenuItem("Tools/FBX/Split")]
    private static void SplitFBX()
    {
        var nSelectedObject = Selection.activeObject;
        string sAssetPath = AssetDatabase.GetAssetPath(nSelectedObject);

        EditorUtility.DisplayDialog("", sAssetPath, "Ok");

        try
        {
            string sPathTextfile = Application.dataPath + Path.ChangeExtension(sAssetPath, ".txt").Substring(6);// Remove 6 chars because dataPath and assetPath both contain "assets" directory

            if (!File.Exists(sPathTextfile))
            {
                return;
            }

            var sLines = new List<string>();

            var lines = File.ReadAllLines(sPathTextfile);
            foreach (string line in lines)
            {
                sLines.Add(line);
            }

            System.Collections.ArrayList nList = new ArrayList();
            pParseAnimFile(sLines, ref nList);

            ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sAssetPath);

            nModelImporter.clipAnimations = (ModelImporterClipAnimation[])nList.ToArray(typeof(ModelImporterClipAnimation));

            EditorUtility.DisplayDialog("Imported animations", "Number of imported clips: " + nModelImporter.clipAnimations.GetLength(0).ToString(), "OK");
        }
        catch (Exception e)
        {
            // EditorUtility.DisplayDialog("Imported animations error: ", e.Message, "OK");
        }
    }

    private static void pParseAnimFile(List<string> sAnimList, ref System.Collections.ArrayList uList)
    {
        // My text file has lines that look like this: animation name, 0, 76
        for (int i = 0; i < sAnimList.Count; i++)
        {
            string s = sAnimList[i];
            List<string> sItems = SplitReturnEmptyListIfInputIsEmptyEx(s, ",");

            string sName = sItems[0].Trim();
            string sFrom = sItems[1].Trim();
            string sTo = sItems[2].Trim();

            ModelImporterClipAnimation nClip = new ModelImporterClipAnimation();
            nClip.firstFrame = float.Parse(sFrom);
            nClip.lastFrame = float.Parse(sTo);
            nClip.loop = false;
            nClip.name = sName;
            uList.Add(nClip);
        }
    }
    public static List<string> SplitReturnEmptyListIfInputIsEmptyEx(string u, string uSplitBy)
    {
        var n = new List<string>();
        if (string.IsNullOrEmpty(u))
        {
        }
        // do nothing, else we get a "" string as the only item in our list
        else
        {
            var sDelimitersAsStringArray = new string[] { uSplitBy };
            var sLines = u.Split(sDelimitersAsStringArray, StringSplitOptions.None);
            foreach (string sLine in sLines)
                n.Add(sLine);
        }

        return n;
    }
}

```
> 0 votes

---
Tags: unity, scripting
---


title: ecs network synchronization

text:
# Question
Title: ecs network synchronization
I'm working on implementing combat into my isometric RPG game which uses an ECS architecture. When synchronizing the actions of the different clients, is it preferable to serialize and synchronize raw components, actions or a mix of both.

For example, an action might be "entity X attacks entity Y", whereas the components approach would need to send stuff more like raw component state (which animation to play, frame, sound, etc). I currently use an action-based approach for movements, and that works very well locally, but implementing combat this way seems more difficult as systems become more complex and components are added down the road, and I want to be as aware as I can about possible friction now.

# Answer
This is a very broad and unspecified question, with a simple answer that is whatever gets results on screen is the correct approach.

To elaborate on that, I'll quote David Aldridge on his excellent talk I Shot You First: Networking the Gameplay of Halo: Reach

> What is gameplay networking?
>
> > Technology to help multiple players sustain the belief that they are playing a fun game together.

This is a relevant statement because if focuses us on the emphatic part of networked gameplay. In other words - it's not about perfectly synchronizing a complex state between networked machines, but maintaining a perception of *synchronicity* and *fun* between multiple players.

If we were to describe the optimal state of a multiplayer game system from a technical perspective it would be a system that replicates state perfectly, which updates at an interactive framerate with no latency across multiple machines. This is a borderline impossible problem to solve.

Like all impossible problems, when it comes to games, the solution is to fake it until it *feels right*. This means that any one specific solution needs to be derived from the gameplay itself and not the technology backing it.

To circle back to your question with some concrete discussion points:

* Sending game events or game actions imply some form of reliable transmission - if such message is not received by a client his simulation state goes out of sync.
* Sending state snapshots of the game world are much more fault tolerant because if you miss one update, you'll get the data on the next update and "catch up".
* The decision on the communication protocol itself is a major deciding factor in how to architect a solution - a browser game might have limited access to unreliable channels, a slower game might be easier to implement using reliable channels. In general on the opposite side of the reliability scale is delivery time - your choice is in the range of slow and reliable to fast without guarantees.

In reality most solutions would either use a reliable only channel for slower paced games, since the implementation overhead is substantially lower - or a mix of reliable and unreliable channels and a mix of state synchronization and event notifications.

For example - player position can be sent every frame as a state snapshot on an unreliable channel since we expect that state to change frequently while chat messages can be sent through a reliable channel since we only expect each unique message to manifest once, and it's not a time sensitive piece of information.

I realize this is a very long winded way of repeating my original answer of "whatever works works" - but I feel the core question was conceptual and not concrete and I hope I've given you some pointers to unpack it a bit more on your own.

One final and more pragmatic note - since you specifically mention ECS - one of the key benefits of ECS to networking is the fact that world state is very easily serializable. I would start by simply throwing the entire world state into a message and render it on the remote machine. This approach will most likely not work at scale but it will get you up and running very quickly - at which point it will float all the issues and allow you to solve and optimize domain specific problems:

* Game state to big? Figure out which data can be inferred and which data must be explicitly sent. Find a way to compress the data for transmission.
* Game feels unresponsive on a client? Look into client-side prediction and reconciliation (assuming you have server authority), Do distributed simulation if you have a PvE game where each player can claim ownership on entities he's interacting with
> 1 votes

---
Tags: networking, entity-component-system
---


# Question
Title: How to construct a matrix with the following mapping
How would I create a matrix that maps coordinates like so:

Near plane

```
x: [-3,3] -> [-1,1]
y: [-6,2] -> [-1,1]
z: 2 -> -1

```

Far plane

```
x: [-4,4] -> [-1,1]
y: [-4,4] -> [-1,1]
z: 0 -> 1

```

Visual

Result:

My current solution is a transformation in a vertex shader like below, but if it's possible to use a matrix I can keep my shaders as is.

```
vec4 special_projection(vec4 p){
  float ty = 0.25 * p.z;
  float tx = 0.25 * p.x;
  float xz = (tx / 3.0) * (p.z / 2.0);
  float x = tx + xz;
  float y = 0.25 * p.y + ty;
  float z = -0.5 * p.z;
  return vec4(x,y,z,1);
}

```

# Answer
> 0 votes
Let's take an initially unknown matrix, and multiply it by one of the points on your near plane:

$$\begin{bmatrix} a & b & c & d\\ e & f & g & h\\ i & j & k & l\\ m & n & o & p \end{bmatrix} \begin{bmatrix} -3\\\-6\\2\\1 \end{bmatrix} = \begin{bmatrix} -3a - 6b +2c +d\\ -3e -6f +2g + h\\ -3 i - 6 j + 2k + l\\ -3m -6n +2o + p \end{bmatrix}$$

After the perspective divide, that becomes:

$$\frac 1 {-3m -6n +2o + p}\begin{bmatrix} -3a - 6b +2c +d\\ -3e -6f +2g + h\\ -3 i - 6 j + 2k + l \end{bmatrix} = \begin{bmatrix} -1\\\-1\\\-1 \end{bmatrix}$$

Here you have 3 equations in 16 unknowns:

$$\begin{align}-3a - 6b +2c +d &= 3m + 6n -2o - p\\ -3e - 6f +2g +h &= 3m + 6n -2o - p\\ -3i - 6j +2k +l &= 3m + 6n -2o - p\\ \\\-3a - 6b +2c +d - 3m - 6n +2o + p &= 0\\ -3e - 6f +2g +h - 3m - 6n +2o + p &= 0\\ -3i - 6j +2k +l -3m - 6n +2o + p &=0 \end{align} $$

Now repeat this for each of the corners of your near and far planes, and you'll have \\$3 \times 4 \times 2 = 24\\$ equations in 16 unknowns. That's enough to plug this system of linear equations into a solver and come up with values for the 16 variables \\$a\\$ through \\$p\\$, giving you a matrix that satisfies this mapping.

---
Tags: mathematics, transformation, graphics-programming, vertex-shader
---


# Question
Title: How to make a custom 3d view cone that mixes orthographic and perspective cameras
I'm trying to make a camera that displays objects the same height no matter the distance, but still changes width relative to distance. Similar to having an orthographic view vertically and a perspective view horizontally. From what I've gathered the best way to go about this is to create a custom 3d mesh. Is that correct or is there a more efficient way? Thanks!

Edit: Here are some images for visual reference.

This is a white cube against a yellow wall at medium distance.

This is the cube up close.

This is the cube further away.

The cube stays the same height no matter the distance, but its width changes relative to how close the camera is.

I've tried modelling what the view cone would look like for this FOV/perspective based on the form of the perspective and orthographic view cones in unity. As can be seen the height of the view cone is static, but the width increases with distance.

Does anyone know the best way to create this view system in unity?

# Answer
> 1 votes
the vertex shader way would be to divide the x/horizontal axis (screenspace) by the z/depth axis (screenspace) though i don't really know how unity works that much

---
Tags: unity, 3d, camera, mesh
---


title: why isnt this pause menu code working?

text:
# Question
Title: why isnt this pause menu code working?
the code when it works right should pause the game (which means setting the timescale to 0)when you press esc and bring up a pause menu. it does this, but when i press the menu button( which brings me to the main menu) and then press play(brings me to level 1) the level starts off with a timescale of 0 and i have to press esc for the game to start.

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

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;

    public GameObject pauseMenuUI;

    void Start()
    {
        pauseMenuUI.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }
    public void Resume()
    {
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Pause()
    {
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }

    public void LoadMenu()
    {
        SceneManager.LoadScene("main menu");
    }
}
```
</code></pre>

# Answer
just put the timescale set to 1 under the public void load menu.

```
 public void LoadMenu()
{
    SceneManager.LoadScene("main menu");
    Time.timeScale = 1f;
}

```
> 1 votes

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


# Question
Title: Creating a simple countdown timer in unity
Hello's I was looking for a way to do a countdown timer in unity and stumbled across this solution :

```
public float timeRemaining = 10;

private void Update()
{
    if (timeRemaining > 0)
    {
        timeRemaining -= Time.deltaTime;
    }
    else
    {
        WinGame();
    }
}

```

Which at first seemed pretty elegant and easy to use, however, I was thinking about it, and wouldn't this be inconsistent for players with different FPS?

For example, if the player has 60 FPS vs 30 fps it would take longer for the player having 60 FPS to reach 0 on time remaining.

# Answer
By using `deltaTime`, the timer is independant of the amount of FPS.

`deltaTime` is the time *between the current and last frame*, meaning on 60 fps the delta time is smaller than on 30 fps. So for people with 60 fps the timer updates 60 times with a small amount, for 30 fps the timer updates 30 times with a bigger amount (in this case double).

So for both users, the timer depletes in the same amount of time, but the steps per frame are just different in size.
> 5 votes

# Answer
You can also use *Coroutines* and *InvokeReapeating*. The advantage is that you can run many of them in one script and your *Update* function doesn't get cluttered.

**example with *InvokeReapeating***:

```
public int theCount =300;

void Start()
{
    InvokeRepeating("doCoundDown", 1, 1);  //fires the function every second
}

public void doCoundDown()
{
    if (theCount>=0) {
        theCount--;
    }
    else {
        // timer is finished...
        CancelInvoke();
    }
}

```

**example with *Coroutine***:

```
void Start()
{
    StartCoroutine(doCoundDown());  //fires coroutine
}

public IEnumerator doCoundDown()
{
    for (let i = 300; i > 0; i--) {
        yield return new WaitForSeconds(1);
    }

    // timer is finished...
}

```
> 1 votes

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


# Question
Title: Get vertices of a terrain mesh affected by a brush or placement shape
I have the following mesh, it has very simple structure. You can think of it as a terrain from top-down view: each vertex (red and numbered) is a fixed distance away from its four neighbours in the horizontal `xz` plane (e.g 1 unit); only `y` (height) is different.

How could I get the vertices affected by a given overlaid shape?

By "Affected" I mean vertices that are inside or on the border of the shape, and any vertices that share a triangle with them.

Here I've drawn a pink rectangle on my mesh, and circled in green the vertices that should be considered "affected" by that shape.

**I know:**

* The constant distance between vertices
* The center of the mesh as a *Vector3* (mesh is a square)
* The mesh's width/height (any corner could be calculated easily)

**Some context, for what?**

* Flatten terrain on when building a structure, road, etc
* Edit terrain with a brush (circle and other brushes)
* Vertex/texture painting, etc

# Answer
This is actually a problem that GIS software can help you with. The easiest way to solve it is to just use the NetTopologySuite library instead of you implementing the algorithms that it uses. The best way to figure out how to use it is by looking at the tests.

I'm thinking it might look something like this.

```
var fact = new NetTopologySuite.Geometries.GeometryFactory();

var polygonSelect = fact.CreatePolygon(
    new NetTopologySuite.Geometries.Coordinate[] {
        new NetTopologySuite.Geometries.Coordinate(0, 0),
        new NetTopologySuite.Geometries.Coordinate(0, 3),
        new NetTopologySuite.Geometries.Coordinate(3, 3),
        new NetTopologySuite.Geometries.Coordinate(3, 0)
    });

var mpt = fact.CreateMultiPointFromCoords(
    new NetTopologySuite.Geometries.Coordinate[] {
        new NetTopologySuite.Geometries.Coordinate(1, 1),
        new NetTopologySuite.Geometries.Coordinate(2, 2),
    });

var pointCollectionSelected = mpt.Intersection(polygonSelect);

```
> 0 votes

# Answer
This answer assumes simple shapes as per OP's comment, as well as the terrain being broken up into smaller, manageable chunks (you should probably be doing this anyway).

First of all, treat the whole thing as 2D for the purpose of these calculations.

Then implement a common `Shape` or similar class (perhaps better an interface) that has a function that takes some points and returns a list of points the `Shape` contains. The exact struct/class of the points doesn't matter and probably depends on the framework/engine you're using if any.

Circles are straightforward, just check every point in your terrain chunk against the centre of the circle - anything with smaller distance than its radius is inside.

Rectangles are easy if aligned to the coordinate grid - but if you want arbitrary rotation, it is not hard. If you know your rectangle's centre and its rotation, you can rotate the rectangle and the points the opposite way, then use the axis aligned algoritm - any point that has its X coord more than rectangle's origin X and less than rectangle's origin X + width, same for its Y (Z) coord. In your case you are probably using X-Z as the "flat" directions and Y as the "ignored" height, so keep that in mind.

Any other stuff, probably the same, just rotate to axis align and calculate from that.

You'll probably be returning indices anyway, so not really needed to "unrotate" stuff after you're done with it as you're working on a copy of the vertex data anyway.

It might even be simpler to never touch the vertex data at all and use some "fixed" constant grid that you just copy and rotate to axis align, calculate indices and then dispose the copy at the end.

Your function then would look something like this in pseudocode:

```
for (x, y)
    generate point P for index x,y
    rotate by inverse of Shape's rotation if needed
    check if  it's inside the inverse rotated Shape
        add to list of indices if true

```

Once you have found the vertices that the `Shape` contains, you can also add any vertices that share a triangle with it by simply checking for each vertex as this is pretty fixed for such a grid.
> 0 votes

---
Tags: c#, geometry
---


# Question
Title: Orthogonal Camera Clip/Hide part of 3D model
How to prevent the `Camera` from `Clipping/Hiding` part of the 3D Model/Object?

I tried playing around with `Near`/`Far` properties , but it doesn't change the result.

EDIT: it happens when the `Camera` follow the player : https://youtu.be/ewi-TzI3204

I'm moving the `CameraRig` which the `Camera` is child of it:

```
void MainCamera::_process(float delta)
{
    auto pos = hero->get_translation();
    pos.y = 0;
    camera_rig->set_translation(pos);
}

```

# Answer
> 0 votes
well, silly me , I didn't see the `Camera` port of view is going through the floor, which was the reason it was clipping:

moving the `Camera` up , fixed the issue :

# Answer
> 2 votes
Move the `Camera` away.

*I'm not suggesting to move the `CameraRig`, as the `CameraRig` is moved by code. Instead change the (local) transform of the `Camera`. Which is relative to its its parent (i.e. the `CameraRig`).*

Even though the `Camera` is using an orthogonal projection. It still has a position in the world, and things behind the `Camera` get clipped. *Remember that the near plane is always in front of the `Camera`.*

Thus, pull the `Camera` away. Position it distant enough that everything that should be visible is visible.

That, of course, is no way around objects getting close to the `Camera` anyway. You can try setting objects materials with "Distance Fade" to handle that.

---
Tags: camera, godot, clipping
---


title: Godot distance between 3d and 2d nodes

text:
# Question
Title: Godot distance between 3d and 2d nodes
Godot has the `distance_to` methods for `Vector3` and `Vector2` but what would be the best way to get the distance from a 3d node to a 2d node? For example, I'm looking to see how far away the 3d kinematic body is from a 2d text label.

Currently, I'm trying something like:

```
var player_global_origin = player.global_transform.origin
var player_vec2 = Vector2(player_global_origin.z, player_global_origin.x)

var distance_to_label = player_vec2.distance_to(label.get_global_transform().origin)

```

Which seems to work ok when just moving forwards and backwards but it feels like it's easy to break.

# Answer
> 1 votes
If you want the position of a 3D object *on screen*, you can do the following:

```
var position_2d = get_viewport().get_camera().unproject_position(position_3d)

```

That is, we use the camera projection to get the 3D position into screen coordinates with `Camera.unproject_position` which takes a `Vector3` and returns `Vector2`. *Why is that unproject and not project? Don't know.*

However, we need a `Camera` to do that. Luckily `Viewport.get_camera` returns the current 3D `Camera`. *Why is there not a 2D counterpart? Don't know.*

And of course, to use `get_camera` we need a `Viewport`. We can get the `Viewport` the node belongs to with `Node.get_viewport`.

---

Of course, once you have the 2D position on the screen, you can use `distance_to` to find the distance to any `Control` on the screen, or whatever you need.

You can also use this to have a control follow a 3D object. This example is from the official documentation:

```
control.visible = not get_viewport().get_camera().is_position_behind(global_transform.origin)
control.rect_position = get_viewport().get_camera().unproject_position(global_transform.origin)

```

---
Tags: 2d, 3d, godot
---


# Question
Title: How can I make a more engaging research/progression system?
I am making a game similar to RimWorld and I am having trouble designing a good research/progression system.

In RimWorld, the player has a research tree and all technology to research is visible from the beginning. More advanced research is locked until you research simpler things first, like so:

However, a player may only research one technology at a time and does so by having a colonist sit at a research table and mindlessly wait while the technology is being researched, which seems pretty dull.

On a map that is quite limited and further exploration isn't possible (think 500x500 tiles), I want to make a progression/research system that unlocks new items (weapons, tools) and structures (furniture, production devices, turrets, etc...), that can then be crafted or built, and that is:

* **active** (not having to select research and wait for it to complete over a while)
* **interactive and meaningful** (brings the player into the research, making it somewhat interactive)
* **consistent and progressive** (a player should know at least vaguely what they are progressing towards, but maybe not all game content should be revealed to them)
* **rewarding** (research shouldn't be a chore, and every time a new technology is discovered/researched, it should be something to look forward to)

Some ideas I had (and why they're **not good enough**):

* recipes/blueprints could have a chance to be dropped while mining (the initial mountains that generate would eventually run out, so **this isn't sustainable**)
* killing creatures that drop clues/technology (the game has to have a limited amount of creatures, which probably **isn't enough to match the required amount of technology that needs to be dropped**)
* random events happen, such as a plane crash, which results in a blueprint/recipe being left on the floor (this is a cool and exciting way to do it, but **it's unpredictable and inconsistent**)

**Additional related questions:**

1. If the research tree were similar to the one in this question (example from Rimworld), as in, be very linear, would randomly obtained blueprints always unlock a recipe that's CURRENTLY available (one the player can see), or should it have a chance to unlock a recipe down the line which has unfulfilled requirements? (one that is locked and the player has no idea what it could be?
2. Is a linear approach to research/progression good, or are there ways of making it less predictable and more dynamic?

How can I design a research/progression system that meets the goals described above, while avoiding the problems posed by my ideas so far?

# Answer
> 5 votes
## Not boring

> ##### Not having to select research and wait for it to complete over a period of time

Well, science actually *does* take time when it comes to Research & Development in real life. Therefore, the player expects time shall pass between the beginning of a research and its final results, be it a couple of minutes or a whole day. At the same time, research isn't a linear process but it involves several steps: data gathering & analysis, experiments, testing... It usually depends on the field of study, e.g. robotics, biology, military. As a game designer, you can **translate** these aspects into opportunities to involve the player in the action; this leads to the next point,

## Interactive and meaningful

> ##### How to bring the player into the research, making it somewhat interactive

Research, regardless of the scope (e.g. academic, industrial), needs **resources**: time, money, people. But also machinery, energy, materials, specimens, equipment... All these can become the first mean of interaction between players and your research system. Players can:

* **Provide resources for a research job:** by providing the bare minimum (for example: 1 scientist, 1 computer, and 1 additional item), the research can start and will take a given amount of time.
* **Add more resources to a job:** the player can increase the number of resources for a given job, e.g. putting more scientists to work or increasing/upgrading the current machinery in use. An upper bound is needed: an infinite workforce doesn't get the job done at a glance. Also, such resources aren't necessarily available to the player yet: if a research job is about a newly discovered mineral, more samples of such mineral are needed, and the player needs to go and harvest more.
* **Parallel tasks:** a research job may consist of different tasks that can be performed independently before joining everything and move to the next step (like collecting data before analysing it or testing a scenario multiple times). If this applies, you may let multiple groups research the same technology (not different ones, as you stated) so that the player gets multiple chances (alternate "drop system") to make major discoveries and unlock that technology level.

I'm thinking about how OS threads work: a single-thread task can be improved by converting the program into a multi-threaded application (although that's not always possible, depending on the task). Different threads could need the same resources, then race conditions may arise and are to be dealt with.

## Consistent and progressive

> ##### A player should probably know at least vaguely what they're progressing towards, but maybe not all game content should be revealed to them

An individual technology's description should be fine to give the player a good idea of what they are going to get when unlocking that technology. You could include both a description ("*Microelectronics - Develop fine-tuned devices and controllers to create advanced utility items.*") and a practical summary ("*UNLOCKS: Jump packs, Brain wiring, Compact weaponry... REQUIRES: 1 scientist, 3 silicon, 10 energy.*") the player can read to get information at a glance. Additionally, the research tree can be explored only up to a certain depth level, for example, the next available technologies only, or their 1st-level subsequent items too.

On the other hand, **implications** of owning a given technology may be explicitly hidden to the player. They may not know how to combine two technologies works until they randomly find a blueprint/recipe of some sort; **BUT** they could also figure out themself, in which case the game provides the blueprints automatically for ease of access. If they manage to discover tech combos by themselves rather than waiting for blueprint drops (which are a useful way of preventing players to be stuck nonetheless) they will feel smart and clever and believe they are making progress. They will feel rewarded.

## Rewarding

> ##### Research shouldn't be a chore, and every time a new technology is discovered/researched, it should be something to look forward to

Completing researches is something to look forward to if it is **needed**. Any technology knowledge must have a purpose, i.e. a direct (and useful) application in your game. Why jump packs? There are high-altitude areas not directly accessible. Ground-penetrating scanner? Because stuff may be buried deep down the terrain. Gunlink? Improves efficiency on the battlefield. Every technology in your research tree shouldn't be there only to unlock more: the player may decide to explore a different branch of technologies, therefore everything available until that moment should work without making them think something is missing. If every technology can be applied in the game rather than being just a barrier towards something better, then players will exploit it until curiosity kicks in. Of course, the player will research certain fields in order to progress throughout the game, but objectives shouldn't be the only reason to do so.

---

**Edit**

Unlocking advanced blueprints may draw the player's attention and push them to explore and discover more about such items. But it may also become a distraction from the current and spoil the experience you designed because players aren't paying attention to the current game and are just focusing on upgrading that particular technology.

As you stated in the comments, you don't want players to just play around and randomly discover tech combos by themselves. Then, you could bind tech availability and blueprint ownership to prevent game-breaking experiences or "gold rushes" in one's subsequent games. In this case, no advanced blueprints shall be dropped at all, unless there's a valid reason to do so (an alien technology yet to be unveiled, for example). But, you shall be generous with other blueprints, as the player expects to progress faster in a certain field when their research is over.

A linear approach is neither good nor bad: *it depends on your game*. Complex systems aren't necessarily better, and simple ones can be good enough to get the job done. Remember that simple rules can create complex behaviours like in-game AI or procedural generation. Even if your player owns a handful of tech, the possibilities may be countless and even unpredictable: what if Jump packs and Gunlink make units too powerful? You shall also test and balance these scenarios.

# Answer
> 2 votes
I don't have novel ideas for you. I'll suggest some ideas lifted from other games, combined and adapted.

---

You could have the player discover recipes/blueprints via experimentation. You would have machines that let you transform or combine resources, and if you guess the right combination, you discover a recipe/blueprint. Thus, the recipes/blueprints you have access to are limited to the resources and machines you have access to. *I'm thinking Minecraft.*

Furthermore, you can make the experimentation - or the use of the machines in general - a mini-game, so you don't only need to guess the resources to use, you also need to win the mini-game. *I'm thinking Spiritfarer. But don't let that limit the mini-game ideas.*

---

Alright, so you are going to need resources. If the limited terrain is main issue (you say terrain and creatures run out), there would be some technology that allows the player to "detect" (the game can generate them on demand) previously unavailable resources, and they will be available on already existing terrain. *I'm thinking Civilization.*

---

There are other ways to make a game with limited terrain an open system. Going with the idea of events, they could range from the arrival of people (e.g. merchant) or wildlife (addressing the the limited creatures) giving you access some resources, to a meteor strike that destroy some of the terrain but also has some rare minerals. *I'm thinking of some Minecraft mods.*

These are things that may happen multiple times. And what resources they offer can be tailored to what the player has access to. In fact, you might have a background system that makes some events more likely or less frequent depending on the situation of the player, which would help in keeping the game interesting (not too boring, not too frustrating). *I'm thinking SimCity disasters.*

And sure, you might get recipes/blueprints by events too. You control multiple units, right? Perhaps an event is that a unit has an idea, and now you need to find the resources for that unit to make it, and if you manage you get a new recipe/blueprint. *I'm thinking Dwarf Fortress strange mood.*

---

There might be some argument for mini-games without the resources by the way. I'm not sure of the setting of the game, but you could have some decoding themed puzzles (*Fallout hacking comes to mind*) that you could just keep trying (or not). For example, you might buy some arcane book, or unearth an ancient tablet, or intercept some ciphered communication (which would be an event with the prerequisite of you having some machine for radio communication, I guess), and that triggers a mini-game, that if you win, gives you a new recipe/blueprint. *I'm thinking Civilization (plus mini-games).*

---
Tags: game-design, progression
---


# Question
Title: Equipped weapon does not appear in JSON data
I'm trying to make an RPG style game with equipment using `ScriptableObject`, but whenever I equip the item, it does not register in my JSON data.

Here is the script I use:

```
for (int i = 0; i < weaponItemSOs.Length; i++)
{
    if (weaponItemSOs[i].isEquiped == true)
    {
        selectedweapon = i;
    }
    else if (weaponItemSOs[i].isEquiped == false)
    {
        selectedweapon = -1;
    }
}
if(selectedweapon >= 0)
{
    power = 25 + weaponItemSOs[selectedweapon].attackBonus;
    distance = weaponItemSOs[selectedweapon].Shootdistance;
    ammo = weaponItemSOs[selectedweapon].ammo;
    currentammo = weaponItemSOs[selectedweapon].ammo;
}
else
{
    power = 25;
    distance = 20;
    ammo = 10;
    currentammo = 10;
}
PlayerGameManager.Power = power;
ShootEnemy.distanceOfRay = distance;
PlayerGameManager.Ammo = ammo;
PlayerGameManager.CurrentAmmo = currentammo;
JSONSaveSystem.SavePlayer();

```

# Answer
Whenever your equipped weapon is not the last one in the array, the one immediately after it sets `selectedweapon = -1` at the end. What you want to do is scan through the array *until* you find the equipped weapon, then *stop* searching.

Replace your for loop with something like this:

```
selectedweapon = -1;
for (int i = 0; i < weaponItemSOs.Length; i++)
{
    if (weaponItemSOs[i].isEquiped)
    {
        selectedweapon = i;
        break;
    }
}

```

Or as a one-liner:

```
selectedWeapon = System.Array.FindIndex(weaponItemSOs, weapon => weapon.isEquipped);

```
> 1 votes

---
Tags: unity, c#, json, scriptable-object
---


# Question
Title: add force to object that has 2 different rigid bodies
I need add force to object that has 2 different rigid bodies and someone said that the best way of this is using fixed joint. The case is this ; I have player object and it has a pusher object that while playing if I raise my finger, pusher object will move forward and backward so that push to enemies. The player object is like on the attacted photo below.

So I added Fixed Joint to movingPusher. But the problem is this; When I want to add force to movingPusher, for break force = 50, it breaks the joint and so movingPusher move forward. So far so good, but I need this joint right after this push mechanic. So in here, someone suggest to point its connected body to null. ok well said. But even if I point it to null before I add force to movingPusher, the movingPusher object doesnt not affected by AddForce and not moving forward. So I couldnt figure out how to use fixed joint. If you could give some suggestions/ideas, I really will be appreciated:))

Here this is the code part also;

```
private void MovePlayer(Rigidbody PlayerRigid)
    {
        if (Input.GetMouseButtonDown(0))
        {
            firstTouchPos = Input.mousePosition;
            _gameStarted = true;
        }

        if (Input.GetMouseButton(0))
        {
            //MovingPusherTransform.position = StablePusherTransform.position;
            MovingPusherTransform.rotation = StablePusherTransform.rotation;

            if(fixedJoint.connectedBody == null)
            {
                fixedJoint.connectedBody = PlayerRigid;
            }

            _pushing = false;
            deltaTouchPos = Input.mousePosition - firstTouchPos;
            direction = new Vector3(deltaTouchPos.x, 0f, deltaTouchPos.y);
            PlayerRigid.velocity = direction.normalized * Speed;

            if (PlayerRigid.velocity != Vector3.zero)
            {
                PlayerRigid.rotation = Quaternion.LookRotation(PlayerRigid.velocity);
            }
        }

        else
        {
            if (_gameStarted)
            {
                PlayerRigid.velocity = Vector3.zero;
                fixedJoint.connectedBody = null;
                StartCoroutine("Push", 0.8f);
            }
        }
    }

    private IEnumerator Push(float duration)
    {
        if (!_pushing)
        {
            Debug.Log("forward!");
            PusherRigid.AddForce(StablePusherTransform.forward * PusherSpeed);
            PusherRigid.velocity = transform.TransformDirection(0, 0, 5);
            yield return (new WaitForSeconds(duration));
            _returning = true;
            _pushing = true;
        }

        else if (_returning)
        {
            Debug.Log("backward!");
            MovingPusherTransform.position = Vector3.MoveTowards(MovingPusherTransform.position, StablePusherTransform.position, 0.1f);
            yield return (new WaitForSeconds(duration));
            _returning = false;
        }

        else
        {
            //MovingPusherTransform.position = StablePusherTransform.position;
            fixedJoint.connectedBody = PlayerRigid;
            yield break;
        }
    }

```

**Edit for extra explanation:** I try to code clone of "Push'em all" mobile game. I want my movingPusher object to follow the main object, "Player", while I am moving the Player object ( in if(Input.GetMouseButton(0)) statement ) . And when I raise my finger, I want to add force on movingPusher so that enemies will be pushed.

# Answer
EDITED

In Unity you have 2 ways of moving objects - either 'manually' move it little by little, or let Unity physics move it for you - add rigidbody, and give rigidbody force or velocity. Both methods are 'legal'.

To push things you will need rigidbody (but you still can move it little by little).

**This should work:**

* Use separate rigidbody for pusher, make it a child, but give it big mass, also give big mass to player object as compared to pushed objects, then go to pusher rigidbody panel\>constraints and mark FreezeRotation for all axes (alternatively checking the box isKinematic also works in my case). Here is gif of working pusher:

Here I used move little by little method:

```
public IEnumerator doThePush()
{
    for (int i = 0; i < 58; i++)
    {
        transform.Translate(Vector3.forward * 2.2f * Time.deltaTime);
        yield return null;   //wait one frame
    }
    StartCoroutine(doGoback());
}

```

This works because pusher object already is moving according to parent, and *on top of that* I add its own movement.

In your code you are using move-by-velocities method, that is OK, however you set new velocity with this line:

```
PusherRigid.velocity = transform.TransformDirection(0, 0, 5);

```

basically you are saying "ignore any previous forces, ignore its parent velocity, just take this new velocity". So your previous line where you added the force is meaningless. You can avoid this by ***adding*** new velocity to existing one, not *setting* it. (For example just adding force, or combine your new velocity with existin one, *then* setting it). Or just use move-little-by-little method.
> 1 votes

---
Tags: unity, game-mechanics, rigidbody, joints
---


# Question
Title: How to create the slow random movement effect you see in shmup enemy idles?
I’ve noticed in a lot 2D shmups, after enemies accelerate onto screen and arrive at their arrival point, **they don’t simply sit static at their arrival position, but rather begin to gently move in place in what appear to be slow random movements in their immediate neighborhood**.

For example, airborne bosses in Cave shmups have this kind of slow seemingly random movement.

This movement helps to give them life, as if they were really floating in space and subject to the capriciousness of their thrusters.

This principle is discussed briefly here.

**My question is what are some effective ways to implement this kind of movement?**

I think that a lot of shmups use steering behavior methods to get their enemies to arrive on screen and move from point to point (especially for the types of enemies that need to appear and remain on screen, as opposed to popcorn that follow parameterized bezier curve splines). For example, I imagine an enemy spawns just off screen and does normal `SeekWithArrival()` behavior to their destination point on screen. (Though sometimes it looks like ships overshoot their destination point and get pulled back a bit—also curious how to implement this kind of thing!)

If this is true, and this technique is used for arrival, maybe you can also use some kind of `Wander()` steering behavior to achieve the small random movements in the enemy’s neighborhood to achieve this effect? **Does anybody have tips or techniques here?**

## Examples

1. DoDonPachi \- notice how the boss and the pods on the left and right moves at their locations
2. Cho Ren Sha 68K \- notice how when this enemy arrives at a point, he moves gently in place before moving to a new point on screen

# Answer
> 1 votes
One way to do this is with a noise function.

```
wobblePhase += deltaTime * wobbleFrequency;

wobbledPoint.x = destinationPoint.x + wobbleAmplitude * Noise(wobblePhase);
wobbledPoint.y = destinationPoint.y + wobbleAmplitude * Noise(wobblePhase + DECORRELATION);

```

You keep `destinationPoint` consistent, but have your unit seek toward `wobbledPoint`, which continues moving each frame as you advance its phase.

Here `wobblePhase` is a measure of time, tracking how far along this object is in the wobbling pattern. You can initialize it to a random value for each unit, so that two units are unlikely to sync-up and wobble in exactly the same way, even if they spawned/arrived at the same time.

`wobbleFrequency` controls how quickly the point wobbles back and forth / how frequently it changes direction - higher values are more jittery, lower values are more gradual. `wobbleAmplitude` controls how far the object can stray from its `destinationPoint` \- larger values allow it to drift further away.

Now for the noise function itself. You can use something like 1-dimensional Perlin Noise or Simplex Noise here. Or for something quick & dirty, you can add together a few periodic functions at different frequencies/amplitudes to get a slightly less regular waveform:

```
float SimpleTrigNoise(float t) {
    return 0.5*Sin(0.7*t) + 0.3*Sin(1.3*t) + 0.2*Sin(1.7*t);
}

```

The `DECORRELATION` constant is just an offset you apply so that the value you get for y isn't the same as the x - they're separated in time. If you choose a large offset (that isn't close to a multiple of the period of your noise function), then that should nicely decorrelate the two values so they have no apparent relationship to each other.

---
Tags: movement, ai, path-finding, steering-behaviors, behavior
---


# Question
Title: Calculating new Velocities of split Physics Body
Given a Physics body with all his properties i want to break the body into two or multiple parts that keep the original velocities.

for linear velocity this should be original velocity + centrifugal force based on original center of mass to new center of mass. however with angular velocity this gets more tricky. i could sample multiple linear velocity points as mentioned above and then try to resolve the angular velocity from that but that seems like the brute force way.

# Answer
I intended this as a comment, but got too long.

In real world angular velocity 'kinda does not exist' as such. Spinning is linear speed which is constantly changing. Lets take scenario of ball spinning around point in space and attached to that point by the rope. If you cut the rope, ball will travel in straight path! In spinning disk scenario all parts of disk want to travel in straight path but tension force pushes them toward the axis, resulting in 'spinning'. But if the disk is shattered - all pieces should travel in straight line, with no angular speed.

But... they don't. Depending of size and shape of broken piece - it will have some angular speed. This happens because those points traveling closer to axis have slower speed, points traveling further from axis - higher, this result in tension between them forcing part to spin. *The higher difference in speeds between different points on broken piece - the bigger the angular speed*.

In the image part 1 will have small angular speed. Part 2 - much bigger. 3 - will have big angular speed.

Slo Mo guys have YouTube video of spinning shattering disk - you will see that broken parts are traveling in straight line, and angular speeds depend of size/shape of broken chunk..

**how to calculate angular/linear speeds of broken chunks in Unity..** This approximation could work - just before breaking take angular velocity of object, take two points of (will-be) broken chunk - nearest to axis (let's call it *n*) and furthest one *f*. Find out their speeds (*Vector3*). Now find the difference between *n* and *f* speed vectors and according to this difference give this chunk angular velocity. Also 'draw' tangent vector from the middle of chunk - this will be the movement direction of it.
> 1 votes

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


# Question
Title: Why does my spawner spawn multiple times at start-up, only in build?
I'm making a small game similar to *Super Hexagon*. I've recently asked a question about making the game harder as the player progresses by increasing the obstacles' spawn rate. I was able to implement this feature with the help of an answer. The game works fine in the game view and the spawn rate is low at first and increases slowly which is exactly what I want. But the problem starts where I create a build. Unlike the game view, the spawn rate is high as soon as the game starts but after a few seconds it changes back to what it was in the game view. I changed the values on the Animation Curve multiple times and found out that this difference only occurs with my current values. In fact, if I change the values to something that starts high at the beginning, the game view and the build behave similarly but using values like these and even smaller, creates this issue.

Spawner script:

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

public class Spawner : MonoBehaviour
{
    // the spawn rate is 1 in the inspector and it doesn't change by the curve.
    public float spawnRate = 1f;

    public GameObject hexagonPrefab;

    private float nextTimeToSpawn = 0f;
    public AnimationCurve spawnOverTime;
    public LifeTime life;

     void FixedUpdate()
    {
        float spawn = spawnRate * spawnOverTime.Evaluate(life.TimeAlive);
        if (Time.time >= nextTimeToSpawn)
        {
            Instantiate(hexagonPrefab, Vector3.zero, Quaternion.identity);
            nextTimeToSpawn = Time.time + spawn / spawnRate;
        }

    }
}

```

The game when it starts in the game view.

The game when the build starts.

This is the spawner's Animation Curve.
First point from left: time = 11, value = 1
Second point: time = 164.2441 , value = 0.3

# Answer
> 0 votes
I updated the code and now it works perfectly fine.

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

public class Spawner : MonoBehaviour
{
    public float spawnRate = 1f;

    public GameObject hexagonPrefab;

    private float nextTimeToSpawn = 0f;
    public AnimationCurve spawnOverTime;
    public LifeTime life;
    void Start()
    {
        nextTimeToSpawn = Time.time;
    }

     void FixedUpdate()
    {
        float spawn = spawnRate * spawnOverTime.Evaluate(life.TimeAlive);
        if (Time.time >= nextTimeToSpawn)
        {
            Instantiate(hexagonPrefab, Vector3.zero, Quaternion.identity);
            nextTimeToSpawn = Time.time + spawn / spawnRate;
        }

    }
}

```

---
Tags: unity, c#, timer, spawning
---


# Question
Title: What is the design rationale behind hard content that's limited to only a couple attempts per week?
There is currently a lot of discussion in the World of Warcraft playerbase about a recently added feature: Horrific Visions. Visions are personal areas you can enter alone or with a handful of players and have 5 objectives with increasing difficulty plus additional difficulty options. The details aren't that important, but the core is that these Visions require careful planning of resources and time if you want to progress the harder difficulties, both during the visions themselves and in how you earn the right to complete a Vision. In return for completing these Visions, you can earn increasingly better gear based on difficulty (though repeated gear rewards decline in quality) as well as upgrades for an item you need against the final bosses of the raid that came in the same patch.

Now, usually in games that have really hard content you're supposed to defeat, there is no limit in how many attempts you can do, or the limit is sufficiently high that it makes no real difference. However, this isn't the case in Visions. Visions require you to buy an item to make an attempt, and this item is so costly that even if you log in every day and do all the content that rewards the items you need to buy this item, you can at most earn 4 copies of the item per week. There is also incentive to save these tokens for later weeks because later upgrades require you to complete increasingly more runs, which you can speed up by not using additional tokens in weeks where you don't need them.

This is what many people see as the biggest problem with these Visions. They're hard content, but you have only a couple attempts per week and you need to make them count. So there isn't really a safe way to practise them so you can learn how they work and what the best way to do them is. If you mess up and you don't do enough to earn the upgrade token mentioned above, it's a huge potential loss and you fall behind other players who did manage to complete them.

I'm trying to understand possible design rationale behind this. I don't usually come across this design element in games, and I can't even remember another game with similar design, especially for such a core feature of the content update. in other hard game content, Soulsborne games don't really restrict you in attempts, and Roguelikes actually are built around immediately starting anew when you fail, again without real limitations. AFAIK neither genre really limits you in how often you can try them. And it has been years since Blizzard last put a hard limit on how many attempts you were allowed for the hardest content, especially such a low amount.

What can be potential design rationale behind putting hard content behind a restrictive attempt limit?

# Answer
In addition to the excellent existing answers, there are a couple of other ways this type mechanic can boost retention.

One is by helping to **keep a cohort of players on par with one another**.

When attempts/rewards are limited only by your play time, then players with a lot of time to invest in the game can very quickly race ahead, and players with more limited time tend to lag behind.

Your more casual players (who vastly outnumber those who play most intensely) can feel left in the dust, like they'll never be able to catch up, and this can demotivate them into dropping out of the game. For games with multiplayer, social features, leaderboard competition, or cooperative raids, this can make it harder to find peers to play/share/compete with.

With a limited rate of progress, it becomes easier to keep a friend or peer group playing together at approximately the same level - with all the social stickiness benefits that come with that. Even outside of direct synchronous interaction between players in the game itself, sharing on player forums, Discord, Twitter, Twitch streams, etc. with other players who are in a similar bracket as you helps players feel like part of a community striving together, rather than "the slow one" who can't keep up or so peerlessly far ahead of the masses that you have nothing left to strive for.

This can also **disincentivize sinking "too much" time into the game** in a short interval, reducing the temptation of a game's compulsion loop to lure players into unhealthy play patterns, or burning themselves out.

There are also retention benefits due to **player behaviour and psychology**:

* If I can do an activity anytime I want, I might be inclined to put it off to tomorrow, or the next day, or next week... until I forget about it and lapse out of the game

+ But if I have only a finite number of opportunities per week, each time I put it off, I've lost out on one of my chances. Human psychological bias of **loss aversion** kicks in, making this missed opportunity feel more dire, more urgent.
* Logging in regularly to make use of all my opportunities helps develop a **habit** that I'll tend to persist. If I can just grind the content until I succeed in a shorter real-time interval, I don't have a chance to develop this regular habit that keeps me coming back.
> 41 votes

# Answer
It improves player retention.

When you expect the player to take a lot of attempts to overcome a challenge, and you only give them a limited number of attempts per real-world timespan, then players will take a long real-world timespan to complete this bit of content.

When you have a game with a monthly subscription model, or which you monetize by regular mandatory expansions, then you want to retain players as long as possible. So any features which require your players to return to the game again and again over long time periods make your game more profitable.
> 18 votes

# Answer
Another aspect that hasn't been mentioned yet is basically a variation on "security through obscurity". In this case, it's difficulty through obscurity. The content is hard *because* you can't practice it. If you could grind it as much as you wanted, you'd have more chances to learn the mechanics and figure out how everything works. Because it's limited, you have fewer chances to study how it works. Sure, you could watch videos of other players doing the content on the internet, but they're going to run into the same problems. If the means of completing the content are difficult to learn and detect, they're going to be difficult for *everyone*, and it will take much longer for the player community as a whole to develop effective strategies.

This is also why these types of battles tend to be heavily *mechanics-driven*, rather than just increasing the difficulty by cranking up the numbers (more hitpoints, higher damage, stronger resistances, etc.) Basically, if you know how to beat one tough boss with a given set of attacks, you can figure out how to beat a tougher one with the same set of attacks - the only difference being it will take longer. If a boss fight is fundamentally different from all other boss fights in some way, using unique attacks and tactics not seen before in previous content, it adds difficulty of a different type, where you have to learn how the mechanics work rather than just "how to do more damage/healing in less time". These are exactly the kinds of things that are harder to learn if your opportunities to even make an attempt at them are time and/or resource limited. (The example seems to be both in this case.)
> 13 votes

# Answer
Basically, unlike in most parts of many games where the goal is at least partly to teach you how to understand the game mechanics, the primary goal of limited tries is to cause emotional reactions.

Roguelikes actually often have some kind of daily or weekly leaderboard challenge, where there's a special dungeon and you only get one attempt to beat it for the day. Losing in XCOM Ironman mode can wipe out days of progress.

Not being allowed to retry seriously ups the suspense when even minor setbacks happen. It's more emotionally gripping, with higher stakes. I assume you're supposed to practice by playing less intense but equally difficult parts of the game elsewhere. Perhaps with a few unexpected wrenches thrown into the Vision mission, like how in a heist movie the plan goes off without a hitch, until the pace ramps up even more and everything is thrown into chaos.

From a team perspective, having limited playthroughs makes it more like planning a heist. You try to establish what everyone will be doing during the mission, because when it actually happens the team doesn't have time to coordinate. Sometimes people have difficulty getting together the same group of friends for 20 hours of playtime a week, so having high-intensity group events the players can schedule around helps them make the most of more limited overlaps in schedule.
> 9 votes

# Answer
Another reason not yet listed is to increase communication. With limited attempts, what you do *outside* of the attempts gains value. Sharing info online, talking with guildmates, watching runs on youtube--none of those are single-person tasks. (Even youtube requires a youtuber, unless you're only watching your own replays).

In other words, time-gating it, in theory, doesn't necessarily decrease the amount of time you spent working on that content. It just shifts the balance from grind/practice to prep and communication.

It's about building community.
> 6 votes

# Answer
> Now, usually in games that have really hard content you're supposed to defeat, there is no limit in how many attempts you can do, or the limit is sufficiently high that it makes no real difference.

Usually, games have no interest in how long you play the game. They're interested in you buying the game, and that's where the developer and publisher's interest in you as a customer ends.

There is some interest in ensuring you like the game as that will lead to future sales (you buying next games or you recommending the game), but **time played is not a concern**.

Unless... your customers are paying you for the time spend playing the game. Now, you as a developer/publisher have a clear interest in ensuring that players keep playing your game for as long as possible. Anything you can do to extend that time is in your financial interest.

Imagine if every you get a playing card when you click a button, and I've really interested you in collecting all 52 cards. If you can spam click that button, you would get the deck in a minute's time, and you would only be buying one month of game time before you complete the deck.

But suppose I make it so you can only click the button once a week. Now, it will at least take you a full year to complete, and thus you will buy at least 12 months worth of game time to complete the deck.

Of course, there is a balance to be struck. If I make it so you can click the button once a year, you will simply stop playing the game as it's no longer fun. **But as long as I can extend the play time in greater proportions than I remove the fun, then it'll be financially rewarding for me.**

Your question contains a few examples of exactly how/why game time is being maximized:

> * you can earn increasingly better gear based on difficulty ...
> * ... (though repeated gear rewards decline in quality) ...
> * ... as well as upgrades for for an item you need against the final bosses of the raid that came in the same patch

Every step takes time, totaling a lot of time. If you want to defeat the final boss of a raid (which *of course* you want if you do the raid), then you must invest a long time.

> even if you log in every day and do all the content that rewards the items you need to buy this item, you can at most earn 4 copies of the item per week.

If the item were easily available, people would be able to do it often enough to reach their end goal too quickly

> There is also incentive to save these tokens for later weeks

Because putting things off means that you plan to keep playing the game in the future. If you somehow stop playing, you will have "lost" the special thing you spent effort saving up for.

> So there isn't really a safe way to practise them so you can learn how they work and what the best way to do them is.

If there was, you wouldn't need to retry it as often, and thus it would take you less weeks to successfully complete one.

> In other hard game content, Soulsborne games don't really restrict you in attempts, and Roguelikes actually are built around immediately starting anew when you fail, again without real limitations

These games do not increase profit margins for the developers/publishers when you start a new game.

However, think of games with microtransactions. Virtually every game with addictive or highly enjoyable gameplay will somehow lock your attempts behind some sort of currency that you can get freely in limited amounts or can pay real money for to unlock immediately.

WoW doesn't do microtransaction currency in the same way (at least not for providing access to its gameplay), but instead uses a time lock, which in turn makes you buy more game time, which is a similar way of getting players to "pay to play" the game. It's the same scheme in a slightly different form.
> 2 votes

# Answer
I think the existing answers are great! I'll also add a few things, and boil it down to a few points. :-)

**Retention**

* Making players do the same task over an extended period of time without burning out the player. @DMGregory exaplained this perfectly.
* Artificially extends the task length from hours to many weeks, which in turn adds a lot more variety to the game - by forcing the player to try other things while waiting for the content to be available again.
* Players are more likely to socialize and group up with their friends to complete the content.
* If MMO players could grind it by allocating more hours to it, there would be players grinding for many days with no sleep to get it. This would create a rift between players who have more time to play the game, and those who are more casual with time constrains.
* It gives players something to do between expansions.

**Economy**

* A major currency / resource / time sink - as you said, players are required to collect many things to participate in the content.
* Optimized/controlled reward distribution & reduced market inflation. Its just another way of controlling the influx of items available from the event into the game's economy.

**Content Obscurity**

* Makes it harder to progress to the end and much tougher to learn/master due to long intervals between attempts.
* If it takes more time to claim the rewards, whatever the player gets from the action becomes more valuable to the player.
* High obscurity of the rewards among the community increases the demand for those items. Achievers who like to show off their accomplishments will have a lot more encouragement to grind for it, even if it takes them years.
> 1 votes

# Answer
A lot of the other points I wanted to make were already made better in other answers (like monetization rationales), but two items weren't mentioned that much:

1. Producing scarcity in the interest of an in-game economy. If any of the rewards from these boss fights are tradeable, restricting the amount of units per time that can enter the market per player turns them into rarer items that people will then grind lesser items for to buy, or the like.
2. Helping balance the onrush of players, and spread out players more evenly so there are fewer "low traffic" times. This is more a thing with bigger MMOs, but by forcing players into a 24 hour rhythm, instead of all of them grinding for this one item all weekend and nobody playing the game during the week, you encourage players to also play during the week if they can, which in turn ensures the minority of people unable to play on weekends will have some players to play with. It also means that people will not grind for a single thing all weekend, possibly redirecting them to re-playing older content, thus providing warm bodies for new players to play with.
> 0 votes

---
Tags: game-design, difficulty
---


# Question
Title: Is there a way to create animation from array of 2d sprites in runtime that works in build in Unity
I have an array of sprites that is created at runtime and I would like to create animation from it, so the specific animation would also exist at runtime only it would act as preview animation.

I tried something like this:

```
public void CreateAnimation()
{
    Sprite[] sprites = createSprite();

    AnimationClip animClip = new AnimationClip();

    AnimationClipSettings newSettings = new AnimationClipSettings();
    newSettings.loopTime = true;
    AnimationUtility.SetAnimationClipSettings(animClip, newSettings);

    EditorCurveBinding spriteBinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_sprite");

    float interval = 1 / 4f;
    ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[sprites.Length + 1];

    for (int i = 0; i < spriteKeyFrames.Length; i++)
    {
        if(i == spriteKeyFrames.Length - 1)
        {
            spriteKeyFrames[i].time = i * interval;
            spriteKeyFrames[i].value = sprites[0];
        }
        else
        {
            spriteKeyFrames[i].time = i * interval;
            spriteKeyFrames[i].value = sprites[i];
        }
    }

    AnimationUtility.SetObjectReferenceCurve(animClip, spriteBinding, spriteKeyFrames);

    AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController();
    animatorOverrideController.runtimeAnimatorController = animC.runtimeAnimatorController;
    animatorOverrideController["TestAnim"] = animClip;
    animC.runtimeAnimatorController = animatorOverrideController;

}

```

Inspired by this video and this post.

I managed to create animation clip but I can't play the animation and even if I did what I understand by other comments and posts this method would not work in build because it uses the `UnityEditor` namespace.

So now I am not sure if there is any way of creating this kind of animation at runtime that also works in build.

# Answer
why not just use coroutine:

```
IEnumerator doAnimation()
{
    for (int i = 0; i < spritearray.Length; i++)
    {
        yield return new WaitForSeconds(0.03F);
        myImage.sprite = spritearray[i];
    }

}

```
> 0 votes

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


# Question
Title: Why do RPGs require you to "use" items instead of unlocking them on drop?
Many RPGs have you collecting items (like books, or cosmetics) as inventory items, which you then have to "use" to actually unlock their benefits (say a higher knowledge stat, or being able to use the cosmetic on your character), forcing you to stop periodically in game and using all those items to clear up inventory space.

This is often the case even for items that can't be traded or sold, and for items that have a standard description (you would miss no lore by having the game immediately unlock the cosmetic). Is there a game design reason behind this? Things I could think of:

1. Artificially extending play time to prevent players from being done too early.
2. Allowing the player to not unlock an item to keep their list of available "free of junk cosmetics" they wouldn't use anyway.
3. Making it more like a simulation of real life, where you also have to unwrap purchases or read books to learn
4. Allow items to drop in combat without triggering the "reward animations", which can then be postponed to when the item is used.
5. Cause additional artificial scarcity in the inventory system.
6. It's just been done like that in Ultima or whatever, and devs mindlessly copied the design.
7. Engine limitations.

None of these seem really convincing. #1 is a very dissatisfying way to extend playtime, and #3 doesn't really simulate much. #2 would work but is also done for things that aren't listed but just result in a form of XP.

#4 would work, but many of these still present level up dialogs during combat instead of making them an item, and many also don't show any rewarding animations when using these items.

#5 There are so many better ways for causing scarcity in inventories to prevent people from gaining resources too quick or not focusing on certain gear and switching at will instead.

#6 So many things have been re-thought in games, and this seems like extra effort for most engines when a less cumbersome mechanism also exists for other items.

#7 Since most MMORPG engines have to implement transaction guarantees for the systems you already have for currencies and XP, I don't see how modeling a book as an item would be any improvement over using.

**Does anyone have a reference to an industry source that explained why things like this are done?**

# Answer
I'd say many of the reasons you cite might be in play in any particular game. Remember that a reason doesn't have to be compelling to you to have made sense to the designer or programmer at the time. Game developers disagree about the best mechanic for a particular application all the time.

But I think a major factor that you haven't listed so far is **player attention**.

When a player is in combat or dungeon-delving mode, their attention focuses narrowly on the task at hand. To an outside observer, it can look like they're deliberately ignoring information on the screen or being conveyed to them by sound if it's not specifically related to what they're trying to do this moment. This can lead to much pulling of hair by designers watching playtests, trying to figure out why players aren't getting any benefit from their carefully-crafted tutorials or mission guidance.

This is due to a phenomenon called **inattentional blindness**. You might have seen it in the form of this counting challenge \- they like to show this video in driver's ed. When a person is focused on a task, any information they're not actively looking for can actually vanish from their perception entirely - it's like it wasn't even there.

So if you're trying to tell the player they just picked up a green feather cosmetic while they're furiously clicking attack and watching their healing spell's recharge timer... they might not register that information at all.

And **a reward the player isn't aware of fails to make them feel rewarded** \- you've just wasted one of your finite cosmetic items and the artists' time needed to craft it, for zero impact on this player's perception of that moment in play.

This can happen even outside of active combat. Say I've just finished defeating the enemies in the room and I'm running around cleaning up the loot. I'm looking for healing potions to make sure I'm in good shape for the next fight, or crafting materials for that next upgrade I'm thinking about. I'm high on adrenaline and eager to rush back to town to finish the quest and claim my reward. In that situation too, I might often neglect or only half-register a loot item I wasn't specifically looking for.

This is even worse for items that give an active benefit, like a new skill. If I don't notice when it unlocks, then I'm liable to not realize I have the skill and fail to use it for a long time, getting no benefit from the careful design, coding, animation, and effects work that went into crafting that skill.

But when the player is in the menus managing their inventory, **you know the inventory items have their full attention**. I'll look at each one, register that it's new/unused, and process/participate in the act of using/unlocking it - so I experience that sense of reward, or at least notice that I got something.

We could try to signal these things louder in the midst of play the way we do with level up effects - but just think how flashy the level up effects need to be to get the player's attention when they're in the middle of a fight. Now imagine every bit of skill or cosmetic loot setting off a firework show on that scale. It gets noisy and distracting. It's worth doing for level ups in many games because your level is SO central to everything your character does. You never say, "Oh, I don't care about level 5" the way you might say "Oh, I don't care about that green feather cosmetic". Leveling up is always a salient piece of information that could impact the outcome of the very battle you're fighting, so it's worth treating differently here.
> 5 votes

# Answer
I know skyrim allows you to use spell tomes/skill books to level up your skill by one or unlock a new spell, but you can get one of these books multiple times so you can use it your first time, but why use it again, so you can sell it. Or you might just sell it in the first place if your build doesn't require this school of magic that this new spell tome you found gives you a spell from. It just kinda allows the player more freedom I suppose.
> 1 votes

---
Tags: game-design, game-mechanics, inventory
---


# Question
Title: Why won't Unity drop objects to the origin position?
It seems that my objects drop to the middle of the scene, not a global position of `(0, 0, 0)`.

Why is Unity behaving like this?

# Answer
> 2 votes
When you drag an object into your scene, Unity attempts to place it exactly where you drop it. This can be an unreliable way to position objects, especially if you are working in 3D space. When you create a game object by selecting from a menu in the hierarchy, there is a clear attempt to position the game object at an origin position of `Vector3(0, 0, 0)`; even in this case, the results can be unreliable.

It is *always* important to double check the position of your game object, upon creation. You can do this in two ways. You can directly reset the position values to 0, or if you have no rotation and a default scale, you can simply reset the transform all together. You can do this by clicking on the cog to the top right corner, and selecting *"Reset"*. You can also select *"Reset Position"* from this menu, if more convenient.

In no time at all, this practice becomes pretty standard. It might be annoying, at first, but you will get use to it.

# Answer
> 2 votes
In new versions of Unity, they finally added an option to enable this behaviour (initial empty object position at (0, 0, 0)).

In the Unity Editor:

* open the Preferences window `(Edit -> Preferences)`
* Go to the `Scene View` tab
* locate the `General` section
* click on `Create Objects at Origin` and voilà.

If you don't have this option because you're working with an old version, you can still download the plug-in I published.

# Answer
> -1 votes
Unity doesn't do this, because it's not just an interface for you to drop your objects into. It's also a visual level design tool and your camera is important in that regard.

You probably wouldn't want all your objects to be dropped into (0, 0, 0) in a universe where you need them to be somewhere like (1253, 324, -2432) because that would mean you'd either have to look towards origin and move them by hand or enter some arbitrary coordinates to set their position so that you can do adjustments.

---
Tags: unity, ide
---


# Question
Title: make Shader Graph material flow aligned to the mesh UVs (like a river)
i need to add a flow effect to my river so that the water can flow along the path described by the mesh i created. Using ShaderGraph shader i added a `time node` multiplied with a `screen position` and hooked into a `Tiling and Offset node` but the water keep moving in a global direction only.

Please note that i'm using `Instant River` tool to create the river mesh https://unitylist.com/p/loq/Instant-River

I noticed in its script he's using some methods to rotate and align the UVs, so it should work with any material, but i don't know how to align my shader.

I'm wondering if it's possible to achieve the result with Shader Graph or not. Any idea?

# Answer
I managed to solve the problem myself using a `Normal Unpack` node before the Tiling and Offset one. This gives an orientation along the UVs. I post the solution here for anyone facing the same issue.
> 1 votes

---
Tags: unity, unity-shader-graph
---


title: why isnt this playing a sound?

text:
# Question
Title: why isnt this playing a sound?
This code is supposed to play a sound when I press 'E' but it's not working. also keep in mind I'm new to unity and coding in general so don't be to harsh if I made a really dumb mistake.

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

public class flashlightonoffsound : MonoBehaviour
{

    public AudioSource flashlightsound;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            flashlightsound.Play();
        }
        else
        {
            flashlightsound.Stop();
        }

    }
}

```

# Answer
> 1 votes
Delete this:

```
flashlightsound.Stop();

```

Also make sure you have AudioListener somewhere (usually attached to camera). And make sure AudioSource component is added to the gameobject AND you have access to to it:

```
void Start()
{
    flashlightsound = transform.GetComponent<AudioSource>();
}

```

And make sure your audioClip is attached to audio source and everything will work!

Also make sure your audioListener (usually in camera) is not too far from from AudioSource!

---
Tags: unity, sound
---


# Question
Title: How should I make and use a method for changing the camera(transform) position and angle at run time from any script/s?
The script is attached to a Camera. A bit messed but it's working.

For changing the camera height at run time I'm using a variable name cameraHeight at this line number 88:

```
Vector3 negDistance = new Vector3(0.0f, cameraHeight, -distanceFromTarget);

```

The original line was :

```
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distanceFromTarget);

```

but if instead, I want to create a public method something like :

```
public void ChangeCameraAngle()
{

}

```

What should I do inside this method and then how to use it for things like changing the camera(transform) height or angle in run time?

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

public class CameraController : MonoBehaviour
{
    public Transform targetToRotateAround;

    public bool saveDuringPlay = false;

    public float distanceFromTarget = 5.0f;
    private float oldDistanceFromTarget;

    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;
    private float oldxSpeed, oldySpeed;

    public float yMinLimit = -20f;
    public float yMaxLimit = 80f;
    private float oldyMinLimit, oldyMaxLimit;

    public float distanceMin = .5f;
    public float distanceMax = 15f;
    private float oldDistanceMin, oldDistanceMax;

    public float cameraHeight;
    private float oldCameraHeight;

    public bool makeTransition = false;

    private Rigidbody rigidbody;
    private float x = 0.0f;
    private float y = 0.0f;

    // Use this for initialization
    void Start()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody != null)
        {
            rigidbody.freezeRotation = true;
        }

        LoadSettings();
    }

    private void Update()
    {
        if (saveDuringPlay)
        {
            SaveDuringPlay();

            oldDistanceFromTarget = distanceFromTarget;
            oldxSpeed = xSpeed;
            oldySpeed = ySpeed;
            oldyMinLimit = yMinLimit;
            oldyMaxLimit = yMaxLimit;
            oldDistanceMin = distanceMin;
            oldDistanceMax = distanceMax;
            oldCameraHeight = cameraHeight;
        }
    }

    void LateUpdate()
    {
        if (targetToRotateAround)
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distanceFromTarget * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

            distanceFromTarget = Mathf.Clamp(distanceFromTarget - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);

            RaycastHit hit;
            if (Physics.Linecast(targetToRotateAround.position, transform.position, out hit))
            {
                distanceFromTarget -= hit.distance;
            }
            Vector3 negDistance = new Vector3(0.0f, cameraHeight, -distanceFromTarget);
            Vector3 position = rotation * negDistance + targetToRotateAround.position;

            transform.rotation = rotation;
            transform.position = position;
        }
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }

    public void SaveDuringPlay()
    {
        PlayerPrefs.SetFloat("DistanceFromTarget", distanceFromTarget);
        PlayerPrefs.SetFloat("xSpeed", xSpeed);
        PlayerPrefs.SetFloat("ySpeed", ySpeed);
        PlayerPrefs.SetFloat("yMinLimit", yMinLimit);
        PlayerPrefs.SetFloat("yMaxLimit", yMaxLimit);
        PlayerPrefs.SetFloat("DistanceMin", distanceMin);
        PlayerPrefs.SetFloat("DistanceMax", distanceMax);
        PlayerPrefs.SetFloat("CameraHeight", cameraHeight);
        PlayerPrefs.SetInt("MakeTransition", boolToInt(makeTransition));
    }

    public void LoadSettings()
    {
        distanceFromTarget = PlayerPrefs.GetFloat("DistanceFromTarget");
        oldDistanceFromTarget = distanceFromTarget;

        xSpeed = PlayerPrefs.GetFloat("xSpeed");
        oldxSpeed = xSpeed;
        ySpeed = PlayerPrefs.GetFloat("ySpeed");
        oldySpeed = xSpeed;

        yMinLimit = PlayerPrefs.GetFloat("yMinLimit");
        oldyMinLimit = yMinLimit;
        yMaxLimit = PlayerPrefs.GetFloat("yMaxLimit");
        oldyMaxLimit = yMaxLimit;

        distanceMin = PlayerPrefs.GetFloat("DistanceMin");
        oldDistanceMin = distanceMin;
        distanceMax = PlayerPrefs.GetFloat("DistanceMax");
        oldDistanceMax = distanceMax;

        cameraHeight = PlayerPrefs.GetFloat("CameraHeight");
        oldCameraHeight = cameraHeight;

        makeTransition = intToBool(PlayerPrefs.GetInt("MakeTransition", 0));
    }

    int boolToInt(bool val)
    {
        if (val)
            return 1;
        else
            return 0;
    }

    bool intToBool(int val)
    {
        if (val != 0)
            return true;
        else
            return false;
    }
}

```

# Answer
To lift any object up or down you can simply add *Vector3.up* to your position:

```
transform.position = transform.position + Vector3.up*myDistance;   //if myDistance is negative it will go down
// or even more simpler:
transform.Translate(Vector3.up*myDistance); // does exactly the same job

```

(*In general: to move object to some direction just find that direction vector and add to your position. In this case direction vector is Vector3.up*).

To rotate object around by some angle you can simply use Rotate:

```
transform.Rotate(Vector3.up,myAngle);

```

This will instantly lift/rotate object to desired height/angle.
> 1 votes

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


title: Unity Texture2DArray is too noisy

text:
# Question
Title: Unity Texture2DArray is too noisy
I've generated a `Texture2DArray` from array of Texture2Ds and for some reason, when my shader is using `Texture Array` the output colors are noisy, almost as if noise filter was applied on them. Compare,

Just `Texture2D`:

And when using `Texture2DArray`:

I generate array using this code:

```
        Texture2D sample = materials[0].albedo;
        materialArray = new Texture2DArray(sample.width, sample.height,
        materials.Count * 4, TextureFormat.RGBA32, false);

        for (int i = 0; i < materials.Count; i += 4)
        {
            T_Material material = materials[i];

            materialArray.SetPixels(material.albedo.GetPixels(), i);
            materialArray.SetPixels(material.normal.GetPixels(), i + 1);
            materialArray.SetPixels(material.occulusion.GetPixels(), i + 2);
            materialArray.SetPixels(material.rougness.GetPixels(), i + 3);

        }
        materialArray.Apply(true);
        AssetDatabase.CreateAsset(materialArray, "Assets/_Generated/" + "terrainTextures.asset");
        AssetDatabase.SaveAssets();

```

Initial Texture2Ds are in `RGBA 32bit` format:

Generated `Texture2DArray` (4 Textures, `albedo`, `normal`, `AO`, `roughness`, But I am only using albedo in shader for now):

My shader is simple, it extracts color data from `Texture2DArray` using index and applies it to PBR's albedo input.

And yes, I tried without my special blending effects, just inserting `RGBA4` output to Albedo input of PBR both from `Texture2DArray` sampler and directly from `Texture2D` sampler.

Results were the same, `Texture2DArray` is noisy!

Thanks for any help!

# Answer
> 3 votes
```
materialArray = new Texture2DArray(sample.width, sample.height,
    materials.Count * 4, TextureFormat.RGBA32, false);

```

That `false` says "Do not generate mipmaps for this texture array".

Without mipmaps, you get spatial aliasing - the noise you're observing.

Pass `true` to generate mipmaps. Then when sampling that texture for a distant surface, the GPU will automatically select a smaller mipmap, which is pre-filtered to smooth out that noise.

---
Tags: unity, c#, shaders, textures
---


# Question
Title: Efficient algorithm to aggregate a heightmap to a lower resolution
I have a raw 2D height map which consists of cells of the following structure:

```
type Cell =
{ Coordinate: GeoCoordinate //contains Latitude and Longitude of the coordinate
  Elevation: int16
}

```

I generate this height map from real world data.

Now I want to aggregate the height map to a lower resolution, say from a cell grid length of 300 meters to 10 kilometers. That is, creating an average of the elevations. Of course, I can apply a brute force algorithm to do so, e.g. beginning from the center cell grid and aggregate it to a "bigger cell grid", memorizing which grids have been considered, and so forth. But maybe this is not the best way of doing that. Are there more efficient ways (algorithms) for aggregating such a height map?

# Answer
Mipmapping is the way to do this. The algorithm already exists in hardware and it is extremely fast since GPUs are massively parallel devices.

All you need to do is set up a 3D context in something like MonoGame, LibGDX, or Unity, and have the GPU do the work for you. So you don't need to write any algorithms.
> 12 votes

---
Tags: algorithm, heightmap
---


# Question
Title: what is the fastest way to choose new positions for chunks
I'm having trouble speeding up where I initialise positions for reused / pooled chunks. I found that where I calculate the positions of neighbor chunks, it's even slower than the algorithm I was using, which was just to find all of the positions in a sphere and subtract all of the active chunk positions from it then use the leftover positions for the new chunks. I'm wondering what is the go-to algorithm to do this quickly? I'm dealing with thousands of chunks. Just needs to be faster as it's currently terribly slow.

I have 3d chunks in a vector that contains each position in the world (i.e. not relative to the player position) and these have to be made relative to the player position then, multiplied by chunk size (right now 24) to get the player/camera-relative render position.

# Answer
> 1 votes
> find all of the positions in a sphere

That'll be as slow as treacle, since it involves 3 square root operations for every single check. I have no idea what your sphere radius is, but for a sphere of radius 10 chunks, that is 4188 chunks to be checked every single time you move. That is a *lot of square roots* = pretty costly!

> use the neighbors of the chunks to do it i tried it and its even slower than the algorithm I was using

If they're topological neighbours, i.e. if every Chunk is linked by pointers or references to its neighbour Chunks, it very likely will also be slow as treacle with thousands of chunks in memory at once. The jumps could be large and you will wait potentially up to hundreds of cycles for any Chunks that are not in L1 cache, to be returned from main memory. Major pipeline stall!

> I'm just wondering what is the go to algorithm

**Approach 1: Cheap distance checks**

Generally, we wouldn't use sphere checks to do this. Even a cylinder check (oriented up-down) is going to be a lot cheaper than a sphere check, since it involves only 1 square root distance check, instead of the 3 you're using for sphere distance checking. With a cylinder check you are checking within a circle around that player along the horizon plane, and then doing a simple up / down axis distance check which is cheap.

In fact, any distance check that is not an axis-aligned bounding box check is unwise. AABB checks generally look like this:

`if (p >= min && p < max) then chunk is in range for this axis`

However, if you must use something more like a circle or a cylinder, I suggest using the Manhattan Distance:

`distance = dx + dy`

for 3D that would obviously be

`distance = dx + dy + dz`

Manhattan distances create angular forms but are cheap to calculate, since addition is a very fast operation on any CPU.

**Approach 2: No distance checks - dynamic chunk regeneration**

So here what we do is we don't pull anything back from main memory or disk. Instead we regenerate every chunk from scratch. Every chunk has it's own unique ID based on a combination of:

* the chunk's unique x, y, z position in the world
* (optionally) some unique world seed value

This ID is basically a chunk-seed, and it used to regenerate the chunk as you cross certain world row / column boundaries.

Of course, this data can be placed into reusable chunks that you have allocated once off at runtime - as you are already doing.

So all you are doing here is:

* grab player position `p`
* get your maximum viewing distance and divide it by half, in each axis = `h`
* start from `p - h`, and run to `p + h`, in each axis, generating the chunks
* render each chunk you have just generated.

**EDIT: After comments**

You are checking every chunk against every other chunk at startup - this is logically incorrect and very slow - we call this `O(n^2)` ("big-o n-squared").

You need to do something along these lines...

```
//Get position of chunk player is in:
xChunkPlayer = xWorldPlayer / 24;
yChunkPlayer = yWorldPlayer / 24;
zChunkPlayer = zWorldPlayer / 24;

//Get player chunk - you will do any checks (if required) only against this.
Chunk playerChunk = ... //some means of retrieval

//Let's say the width of your cube of interest is 20, so half that is 10.
//Use this number to get the other chunks' positions by running through
//the cubic space centred around the player's current chunk.

for (int zChunk = zChunkPlayer - 10; zChunk < zChunkPlayer + 10; zChunkPlayer++)
    for (int yChunk = yChunkPlayer - 10; yChunk < yChunkPlayer + 10; zChunkPlayer++)
         for (int xChunk = xChunkPlayer - 10; xChunk < xChunkPlayer + 10; xChunkPlayer++)
         {
             //TODO get the chunk using xChunk, yChunk, zChunk or derivatives thereof which are local to the player
             //TODO do what you need with the chunk, e.g. change or render it or test it against player chunk
         }

```

# Answer
> 0 votes
ok my answer was to just make a 3d array of chunks it is way faster now because an access to the chunks is O(1) pretty much its still a bit buggy though right now but ill figure that out

---
Tags: algorithm, voxels
---