# Question
Title: Methods for generating unevenly distributed item stats?
Conceptually, generating item stats is the same as placing balls into buckets. An even distribution of 50 balls into 5 buckets looks like this: \[10,10,10,10,10\] whereas an uneven distribution might look like this: \[37,0,12,0,1\]. I want a very uneven distribution but not so uneven that 1 bucket has all the balls. Here are some properties that I desire:

* Numbers are very unevenly distributed
* Small numbers (e.g. 0-10, 10-100) appear more often than 0
* Very large numbers (e.g. those exceeding 50% of total balls) appear frequently (e.g. \>20% of the time)

One method I've thought of is this: for each ball, roll a die, if the result is below a threshold then add the ball to the previous bucket, otherwise randomly choose a new bucket. Python code as follows:

```
from random import randint

stats = [0] * 25
threshold = 9985

cur_bucket = randint(0,len(stats)-1)
for i in range(10000):
    c = randint(0,9999)
    if c > threshold:
        cur_bucket = randint(0,len(stats)-1)
    else:
        stats[cur_bucket] += 1

print(stats)

```

Example result: `[0, 1693, 0, 0, 0, 0, 231, 0, 122, 0, 258, 0, 0, 1422, 0, 0, 2406, 526, 0, 0, 2759, 148, 0, 419, 0]`

As you can see there are a lot of 0s and no numbers between 0 and 100, but quite a few numbers in the 1000-3000 range.

Another way is to choose a bucket for each ball where the probability of choosing a bucket is proportional to the number of balls already in the bucket. Python code as follows:

```
from random import randint

stats = [1]*25
cumsums = stats[:]
def recalc():
    global cumsums
    global tot
    tot = 0
    for i,v in enumerate(stats):
        tot += v
        cumsums[i] = tot

for i in range(10000):
    recalc()
    n = randint(0,tot)
    for j in range(len(cumsums)):
        if cumsums[j] > n:
            stats[j] += 1
            break

print(stats)

```

Example result: `[766, 426, 241, 517, 345, 491, 350, 495, 1073, 8, 127, 740, 2, 91, 883, 208, 1041, 208, 49, 287, 22, 50, 16, 269, 1316]`

This method (suggested by a friend) generates a much nicer distribution, notice how there are both small numbers (1, 2, 3, etc) as well as large. You can see all numbers from 0-10, 10-100, 100-1000 and higher up.

But with this method it's also very rare to see numbers above 3000 (I only saw it once in over 30 runs of this program so it does happen but doesn't appear often). Whereas with my previous method, it was quite common to see numbers above 4000.

What other methods are there for generating uneven distributions of numbers for items? Or, how can my existing methods be improved?

# Answer
I recommend weights randomizing with custom weight values.

Given that `10000` is a large number for `25`, the random result will be somewhat close to its mathematical expectation, which means that the result will be a bit fixed.

```
import random

stats = [0] * 25
index_list = [x for x in range(25)]
weights = [x for x in range(25)]
for i in random.choices(index_list, weights=weights, k=10000):
    stats[i]+=1
print(stats)

```

Result: `[0, 35, 90, 105, 146, 160, 197, 214, 270, 301, 307, 339, 405, 471, 444, 527, 529, 546, 612, 642, 679, 692, 683, 794, 812]`

Based on this, we can change the generative expression of the weights, like:

```
weights = [(x/10)**15+500 for x in range(25)]

```

Or you can specify the weight value as required, like:

```
weights =[0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.06, 0.09, 0.16, 0.32, 0.69, 1.49, 3.16, 6.52, 13.05, 25.76, 48.00]

```

Result: `[5, 5, 3, 5, 6, 4, 4, 6, 2, 5, 4, 4, 0, 2, 8, 8, 18, 36, 50, 141, 294, 700, 1318, 2527, 4845]`

Finally, use `random.shuffle` to shuffle the order of the list:

```
random.shuffle(stats)

```

Result: `[4, 8, 18, 141, 6, 4, 36, 2, 6, 4845, 4, 3, 4, 5, 8, 2, 5, 50, 700, 1318, 5, 294, 0, 2527, 5]`
> 4 votes

# Answer
I may be misinterpreting what you want, but heres what I'd do:

1. Randomly sort the order of the "buckets"
2. Loop through the list of buckets
3. For each bucket get a % of the total remaining "balls"
4. Subtract that amount from the remaining balls and put the amount in the bucket
5. Move to next bucket and repeat
6. In last bucket put all the remaining balls

This way you can set the distribution of the balls via %. If you use a fixed %, then the amount of balls will follow a curve because even though each bucket gets the same percent of balls out of the total, the total decreases after each bucket.

Using a random % within a range makes the curve no longer uniform and even more wild outputs.

Since the order of the buckets is randomized, some buckets will be put into the higher end of the curve and others into the low end meaning some will randomly have more balls than the others.

Edit: Using your 50 balls and 5 buckets example. I will say the % is fixed at 50%.

The random order of buckets is 42153

The number of balls in the first will be 50% of 50 or 25, leaving 25. The number of balls in the second will be 50% of 25, or 12.5, leaving 12.5. In the end the ball amount is 25, 12.5, 6.25, 3.125, 3.125. Now you can match up ball count #1 with bucket in spot #1 so for each bucket:

Bucket 4 has 25, bucket 2 has 12.5, bucket 1 has 6.25, bucket 5 has 3.125, bucket 3 has 3.125. Pretty random distribution.

Using a random % in between 50% and 60% each time:

4 has 58% of 50, 29 balls leaving 21 2 has 51% of 21, 10.71 balls leaving 10.29 1 has 55% of 10.25, 5.66 balls leaving 4.63 5 has 53% of 4.63, 2.45 leaving 2.18 3 has 2.18

The key is really to just randomize the order of the buckets and then iterate through each one removing balls from the pool as you go and dumping the rest into the last one (or you could start over the iteration again)

When you reorder 1-5 back into the correct numerical order it looks like this when graphed:
> 0 votes

---
Tags: mathematics, procedural-generation, random, statistics, probability
---


# Question
Title: How to Color.Lerp between multiple colors?
I have found it rather difficult to find a solution to this in the Unity documents.

`Color.Lerp(Color a, Color b, float t)` is a function that gradually changes a color according to a step t, giving it the final value of the Color b.

How do I Lerp between multiple colors one after another?

# Answer
Let **\_colors** be an array of colors let **LENGHT** be the number of colors in the array let **t** be the 0..1 float value

```
float scaledTime = t * (float) (LENGHT - 1);
Color oldColor = _colors[(int) scaledTime];
Color newColor = _colors[(int) (scaledTime + 1f)];
float newT = scaledTime - Mathf.Round(scaledTime);

```

finally you can use Lerp

```
Color.Lerp(oldColor, newColor, newT)

```
> 16 votes

# Answer
One approach that can be taken with multiple color transitions is to leverage a Gradient.

By exposing a public variable of this type a developer an use the Inspector to launch the Gradient Editor to design a gradient containing any number of colors. This editor allows you to use a the unity color pickers, fine tune placement of the color/alpha keys and save/load gradients.

Once designed the `Gradient.Evaluate()` method will accept a float in the range 0-1 to return the appropriate color.

```
using UnityEngine;

public class GradientTest : MonoBehaviour
{
    public Gradient myGradient;
    public float strobeDuration = 2f;

    public void Update() {
        float t = Mathf.PingPong(Time.time / strobeDuration, 1f);
        Camera.main.backgroundColor = myGradient.Evaluate(t);
    }
}

```

Unfortunately the API for programmatically building a Gradient is not as elegant .
> 16 votes

# Answer
```
public float every;   //The public variable "every" refers to "Lerp the color every X"
float colorstep;
Color[] colors = new Color[4]; //Insert how many colors you want to lerp between here, hard coded to 4
int i;
Color lerpedColor = Color.red;  //This should optimally be the color you are going to begin with

void Start () {

    //In here, set the array colors you are going to use, optimally, repeat the first color in the end to keep transitions smooth

    colors [0] = Color.red;
    colors [1] = Color.yellow;
    colors [2] = Color.cyan;
    colors [3] = Color.red;

}

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

    if (colorstep < every) { //As long as the step is less than "every"
        lerpedColor = Color.Lerp (colors[i], colors[i+1], colorstep);
        this.GetComponent<Camera> ().backgroundColor = lerpedColor;
        colorstep +=0.025f;  //The lower this is, the smoother the transition, set it yourself
    } else { //Once the step equals the time we want to wait for the color, increment to lerp to the next color

        colorstep = 0;

        if (i < (colors.Length - 2)){ //Keep incrementing until i + 1 equals the Lengh
        i++;
        }
        else { //and then reset to zero
            i=0;
        }
    }
}

```

So this is the code I ended up using to lerp between three colors of mine, I hope I will be of use to anyone who decides to look for this.
> 1 votes

# Answer
Ok, as we know lerping between 2 values is easy however it seems lerping between more than 2 is... well easy but usually means a heap of branches and/or mucking around.

I had the need to pass in a time value 0.0f to 1.0f and getting back an interpolated float4 color that went from white -\> yellow -\> orange -\> red -\> brown -\> gray -\> black. Basically the 0.0 to 1.0 was the percentage of an explosion duration and the color is used to tint it.

Originally I had a heap of branches and broke it up into 6 conditional lerps. However the code is in a particle system so rather not be adding heaps of branches per particle.

My solution, a small bit of code and a lookup table. The table could be static or filled on the fly.

The code below uses the DX XMVector type but the logic will work just as well for other similar classes.

```
#include <cmath>

// sample data array of colors

const XMVector arr_col_temp[] = {
XMFLOAT4(1, 0.8f, 0.8f, 1), // white
XMFLOAT4(1, 1, 145.0f / 255.0f, 1), // yellow
XMFLOAT4(1, 0.8f, 0, 1), // orange
XMFLOAT4(1, 0, 0, 1), // red
XMFLOAT4(99 / 255.0f, 37 / 255.0f, 19 / 255.0f, 1), // brown
XMFLOAT4(42 / 255.0f, 42 / 255.0f, 42 / 255.0f, 1), // gray
XMFLOAT4(0.2f, 0, 0, 1), // black

XMFLOAT4(0.2f, 0, 0, 1) // black ... last one needs to be duplicated
};

inline XMVector ColorTemp(float t) // t must be 0.0 to 1.0
{
    float i_int;
    float i_frac = modf(t * (ARRAYSIZE(arr_col_temp) - 2), &i_int);
    int i1 = i_int;

    return XMVectorLerp(arr_col_temp[i1], arr_col_temp[i1+1], i_frac);
}

```

This will do a "linear" lerp between the values however if you want a curved fit then just adjust the passed in value.

For example.

```
XMVector c = ColorTemp(sqrtf(t));

```
> 1 votes

# Answer
I feel like there may be a better solution. The only reason I would see to lerp from color to color is if you were wanting to continuously change the hue... http://en.wikipedia.org/wiki/Hue

Here's how to convert HSV to RGB: http://en.wikipedia.org/wiki/HSL\_and\_HSV#From\_HSV

With this you can use HSV colors, simply change the hue, then convert to RGB. Besides, with Color.Lerp, you have the problem of inconsistency. If you lerp from orange to yellow, then to green, you'll find that the color starts to go to yellow very quickly then starts to slow as it nears yellow, then speeds up again once it passes yellow and goes to green. So it will slow color changing at every point that you're lerping to. I think changing the hue would be much more effective - and in the long run, will give a better effect. :)
> 0 votes

# Answer
How about you write your own version, which leverages `Color.Lerp()`?

A very simple version that takes 3 colors, and puts the second one right in the middle could look like this:

```
Color Lerp3(Color a, Color b, Color c, float t)
{
    if (t < 0.5f) // 0.0 to 0.5 goes to a -> b
        return Color.Lerp(a, b, t / 0.5f);
    else // 0.5 to 1.0 goes to b -> c
        return Color.Lerp(b, c, (t - 0.5f) / 0.5f);
}

```
> 0 votes

# Answer
Since you didn't say what you wanted to change color to, I'll give a vague example with a color created on the method.

The point is to have a collection of the colors, and a duration in total (like on the example I'll provide) or a duration between each one (that's up to you).

I personally do not interpolate things on **Update** that I know I won't be constantly interpolating (Camera being an exception), so I use coroutines to handle that.

On this example I divide the duration given on inspector by the colors quantity, and then I Lerp the actual iterator color to the next iterator color, and the duration will be of the duration previously spliced. Here is the sample:

```
public class ColorLerping : MonoBehaviour
{
    public Color sampleColor; /// Just for debugging purposes.
    public float lerpDuration;
    public Color[] colors;

    void Awake()
    {
        StartCoroutine(LerpColors());
    }

    private IEnumerator LerpColors()
    {
        if(colors.Length > 0)
        {
            /// Split the time between the color quantities.
            float dividedDuration = lerpDuration / colors.Lenght;

            for(int i = 0; i < colors.Length - 1; i++)
            {
                float t = 0.0f;

                while(t < (1.0f + Mathf.Epsilon))
                {
                    sampleColor = Color.Lerp(colors[i], colors[i + 1], t);
                    t += Time.deltaTime / dividedDuration;
                    yield return null;
                }

                // Since it is posible that t does not reach 1.0, force it at the end.
                sampleColor = Color.Lerp(colors[i], colors[i + 1], 1.0f);
            }

        }
        else yield return null; /// Do nothing if there are no colors.
    }
}

```

Hope it helps.
> 0 votes

# Answer
I have written these as glsl shader functions, since this is what I needed, but the same thing could be written in other languages, and extended to handle arrays of 'n' length setting 'fromIndex' like this:

```
int fromIndex           = (int)(unitValue * (arrayLength - 1.000001));

```

But shaders require array dimensions to be explicit, so I didnt write it like that.

```
inline fixed4 Lerp3Colors(fixed4 colors[3], half value)
{
    float unitValue         = saturate(value);

    int fromIndex           = (int)(unitValue * 1.999999);     // Will be either 0 or 1
    fixed4 fromColor        = colors[fromIndex];

    int toIndex             = fromIndex + 1;
    fixed4 toColor          = colors[toIndex];

    float deltaAmount       = frac(unitValue * 2);

    return lerp(fromColor, toColor, deltaAmount);
}

inline fixed4 Lerp4Colors(fixed4 colors[4], half value)
{
    float unitValue         = saturate(value);

    int fromIndex           = (int)(unitValue * 2.999999);     // Will be either 0 or 1 or 2
    fixed4 fromColor        = colors[fromIndex];

    int toIndex             = fromIndex + 1;
    fixed4 toColor          = colors[toIndex];

    float deltaAmount       = frac(unitValue * 3);

    return lerp(fromColor, toColor, deltaAmount);
}

```
> 0 votes

---
Tags: c#, unity, color, lerp
---


title: 3D audio performance cost in Unity

text:
# Question
Title: 3D audio performance cost in Unity
I can't find any information about Unity's performance difference between 3D and 2D audio.

If I'm targeting low-performance mobile devices, should I avoid using 3D audio?

How expensive (performance overhead) is 3D audio compared to 2D?

# Answer
I have optimised and shipped 6 mobile games in Unity and have never had to do any audio optimisations. (Except changing music tracks to be streaming instead of decompress on load, and tweaking audio import settings for load time/memory improvements)

I can almost guarantee that your performance problems will be elsewhere, and worrying about something like audio with no indications that it's going to be a performance issue is likely going to distract your attention from other things that are more likely to be performance issues, eg scripts, garbage collection, draw calls, shaders, etc.

However, I would consider if positional audio is even a good idea for a mobile game. Many players may mute sound entirely. Does knowing where a sound comes from actually help the game, or does it just make the audio harder to distinguish?

I would say that using 2D vs 3D audio will make basically no difference, it's unlikely Unity would have some kind of check to skip some processing if an audio source is only 2D, as the savings would be extremely miniscule. (A distance check to calculate volume falloff is very simple and easily optimizable and cache-able, so it's likely highly optimised by Unity/Fmod anyway)
> 3 votes

# Answer
Audio optimisation techniques involve practices that are often shared among different engines. Many concepts and terms are standard in the audio domain, such as listeners, files, clips, and sources.

Unity's audio profiler is your to-go tool when searching for performance bottlenecks and issues you can't see (well, *hear*) when playing. It shows you how many **audio sources** are in your scene, different **CPU consumption** percentages per task, **memory usage**. These depend on the audio settings for your project, which you define according to what devices you're targeting.

Simple 3D audio is just audio where panning and volume depend on the direction and distance from the listener respectively. Unity does this automatically, letting you define additional parameters on a per-Audio Source basis:

* **Panning:** you can control the Spatial Blend parameter to prevent left-only or right-only audio in certain cases. The performance cost is negligible.
* **Attenuation:** you can define an *attenuation function* (or *roll-off curve*, which computes an audio source's volume depending on its distance from the listener. The performance cost depends on the function you set.

A logarithmic roll-off curve behaves differently from a linear roll-off curve: the former is more realistic, but the latter is less expensive to compute (especially if you have many sounds playing at once). All these computations are done by the CPU. While low-end devices are okay with rendering some 3D audio, *overloading* them with unnecessary instructions is definitely not what you want.

---

You can use 3D audio on low-end devices, as long as there isn't too much work for the processor. You can:

* Use linear fall-off curves for 3D audio.
* Limit the number of real voices (i.e. total count of audio clips actually played at the same time) in the Project Settings.

And use the Audio Profiler to check for possible bottlenecks in your audio performance. 3D audio works fine if there aren't too many audio files to stream/store in memory.
> 2 votes

---
Tags: unity, audio
---


title: How to store animation data on the GPU?

text:
# Question
Title: How to store animation data on the GPU?
I want to store my animations on the GPU via buffers (instead of using a single constant buffer which contains the **current** skeleton frame only), so the vertex shaders of the skeletal meshes can read it and transform the vertices accordingly. However, I am not entirely sure how exactly to store the keyframes.

My skeleton is currently stored as a single array that consists of local matrices. The same goes for the keyframes: An animation is simply a list of matrices. The count of the matrices is the count of joints. How am I supposed to store that in a 2D texture?

# Answer
> 1 votes
You can store a matrix in 4 float4 textures. However, since these are transform matrices, you don't need the bottom row, so you can suffice with 3x float4 textures. (And reconstruct the 4th row in the shader, which is simply (0, 0, 0, 1))

Since you need one data set per bone, you could use a 2D texture where each row represents one bone. (But you'll need to make sure you sample in the center of each row to avoid interpolating data from other bones. Alternatively, you could use a Texture2DArray which won't have the chance of accidentally interpolating other bones.

You can optimize this further however. Do you actually need animated scale in your animations? If not, you can condense your data to something like a position, and a float3 for rotation that stores pitch/yaw/roll or similar. This means only 2 texture reads. Taking it a step further, it's possible to condense a quaternion into a single uint with minimal precision loss. That way, you could store the entire animation in a float4 texture, storing the rotation as a uint32 quaternion in the alpha channel, and manually unpacking.

The downside of the last approach however, is that you won't be able to linearly interpolate in the shader. You'll have to do 2 fetches, unpack the rotation, and manually interpolate. (However you could use a Gather instruction to speed this up)

Alternatively, you could consider not using a texture, and simply fetching from a buffer or structured buffer, which you can pack/index/unpack however you like. One benefit to this is you're not limited to simple linear interpolation. Animations are often authored as bezier curves with input and output tangents, for choosing between ease-in/ease-out, linear, constant, or other forms of interpolation. Storing the keyframes as position, intangent, and outtangent would allow you to do this, making your gpu animations as high quality as a CPU implementation.

---
Tags: animation, graphics, skeletal-animation
---


# Question
Title: How to prevent the player from completely blocking the enemy paths in a tower defence game like Fieldrunners?
I am new to Unity and want to create a tower defence game like Fieldrunners.

I need help to create the grid placement area for the towers so that there is always a path for enemies to travel. I mean the game shouldn't let the player to completely block the path of enemies by placing towers in that grid area.

# Answer
If I understand correctly, you're asking how to check that units are able to make it from the start to finish. The normal method would be to run a pathfinding algorithm and see whether it finds a path or flood-fills the arena.

However, for the special case that your start/finish are at the top/bottom of the arena, with walls on the left/right side, there is a trick that is utilized by many tower defense games. The only way the path can be blocked is if there is an unbroken chain of towers stretching from the left-wall to the right-wall. So you just check all the towers to see if any such chain exists.

The valid-tower check can be optimized to be O(1) (!!) by noticing that an invalid tower always connects a left-wall chain to a right-wall chain. So, just keep track of which type of chain each tower is, and disallow towers that connect the two.
> 1 votes

# Answer
While Unity does have built-in path finding, it only works for 3d environments, not for 2d. I have seen some attempts to bend it to work in a 2d scenario, but I really can not recommend those flimsy hacks.

However, stock pathfinding algorithms like A\* or the even simpler (but less performant) Dijkstra's Algorithm are relatively simple to implement yourself with some intermediate programming knowledge. I am not going to write yet another explanation how to implement those algorithms yourself, because the Internet is already full of those which are easy to find with your favorite search engine.

When the player makes a change to their tower layout, calculate a new path from start to finish. This is the new path for the enemies to take. When the pathfinding algorithm fails, then there is no path anymore and you should deny the layout change.
> 2 votes

# Answer
Trying to find path from start to end every time the layout changes is the most straightforward and the first thing you should try. If tested with no serious performance issues, maybe this is the final solution.

Considering that the operation of "try to place" is much more frequent than "place"(It depends on the type of game/target platform. For example, in PC, players often move the mouse quickly when choosing a place to place, resulting in multiple detections in a short period of time), If Detecting every time the mouse is moved, or the coordinates of the grid pointed by the mouse changes, may cause the frame rate to drop. We can try a way to calculate which positions cannot be placed when the layout changes, so that we can directly get the result when trying to place.

Grids can be viewed as undirected graphs, When a point is set as blocking, it is equivalent to deleting a node and its connected edges in the undirected graph:

-\>  -\>

There is a concept of graph theory called Strongly\_connected\_component(AKA `cut vertex`):

> In the mathematical theory of directed graphs, a graph is said to be strongly connected if every vertex is reachable from every other vertex. The strongly connected components of an arbitrary directed graph form a partition into subgraphs that are themselves strongly connected. It is possible to test the strong connectivity of a graph, or to find its strongly connected components, in linear time (that is, Θ(V + E)).

In a (normal) game state, the start point has a path to the end point, and all reachable locations form a strongly connected graph. Now we want to find all the points that can separate the start and end points, ie:

1. The point is a strongly connected component.
2. After removing this point, the starting point and ending point are in different subgraphs.

So we first need to find the strongly connected components of this graph. We can execute the Tarjan's strongly connected components algorithm with the starting point in the game as the starting point of the algorithm. The specific algorithm can be found in many places for reference.

However, we need to make some improvements, because only determining a certain point as a connected point does not ensure that the starting point and the ending point are not in the same subgraph. The core idea of the Tarjan's algorithm is to find a node, **at least a** child node of this node cannot bypass it to reach the root node(named `broken child`). We need to find this node, and **all** `broken child`. In addition, we need to record the `path` from the start point (root node) to the end point during the dfs process. These are all done in the same dfs, so there is no much more overhead compared to the original algorithm.

For each `cut vertex`, test whether it’s `broken child` is included in the `path`. If it does, it means that the start point and end point are not in the same subgraph after splitting, then the cut vertex is valid, and the fort cannot be placed here:

I know these are rather obscure, but if you understand Tarjan's algorithm this is easy to understand. This method only calculates unusable positions when the layout changes, which is very fast when trying to place turrets.
> 0 votes

---
Tags: unity, c#, path-finding, grid, tower-defense
---


# Question
Title: Having trouble trying to figure out why pygame.sprite.Group's draw method isn't working properly, but switching to player sprite does work
## Goal, Description & Scope (when encountered issue) <br>

I was building a testing script to see how implementing different ideas (event handling, update handling, draw method) to loading sprite images, passing data between class objects/attributes, movement mechanics, and the like. When I noticed the `self.all_sprites` instance of `pygame.sprite.Group.draw` method wasn't rendering the player image to the display. I walked through it line by line, threw in some `print` functions to check the script a different points, spent some time looking through Pygame's docs (online & looking inside libs directory to see how Pygame built SpriteGroup objects), StackOverflow, & general to specific search queries of other sites... Still, I have no clue why the SpriteGroup draw method doesn't work, but Player's draw method does. SpriteGroup update works, and everything else seems to run fine, but not drawing to the main display through SpriteGroup's draw method.

### Full code below:

```
import sys
from os import listdir
from os.path import join
import pygame as pg

# support function image loader
def img_loader(path=r'..\tmp'):
    if path:
        img_dir = {}
        ls_files = listdir(path)
        for file in ls_files:
            if '.py' not in file:
                key = file.split('.')[0]
                value = pg.image.load(join(path, file)).convert_alpha()
                img_dir[key] = value
        img_dir['left'] = pg.transform.flip(
            img_dir['right'], True, False)
        img_dir['topleft'] = pg.transform.flip(
            img_dir['topright'], True, False)
        img_dir['bottomleft'] = pg.transform.flip(
            img_dir['bottomright'], True, False)

        img_dir['left_sink0'] = pg.transform.flip(
            img_dir['right_sink0'], True, False)
        img_dir['topleft_sink0'] = pg.transform.flip(
            img_dir['topright_sink0'], True, False)
        img_dir['bottomleft_sink0'] = pg.transform.flip(
            img_dir['bottomright_sink0'], True, False)

        img_dir['left_sink1'] = pg.transform.flip(
            img_dir['right_sink1'], True, False)
        img_dir['topleft_sink1'] = pg.transform.flip(
            img_dir['topright_sink1'], True, False)
        img_dir['bottomleft_sink1'] = pg.transform.flip(
            img_dir['bottomright_sink1'], True, False)
        return img_dir
    else:
        tmp = {}
        return tmp

class Projectile(pg.sprite.Sprite):
    def __init__(self):
        pass

# Player Sprite
class Player(pg.sprite.Sprite):
    def __init__(self, groups):
        super().__init__(groups)
        self.ds = pg.display.get_surface()
        self.img_dir = img_loader()
        self.key_dir = 'bottom'
        self.image_reset = False
        self.pos = pg.Vector2(200, 200)
        self.image = self.img_dir[self.key_dir]#implement
        self.rect = self.image.get_rect(center=self.pos)
        self.direction = pg.Vector2()
        self.speed = 100
        self.projectiles = pg.sprite.Group()

    def key_w(self, delta): self.direction.y -= self.speed * delta

    def key_s(self, delta): self.direction.y += self.speed * delta

    def key_a(self, delta): self.direction.x -= self.speed * delta

    def key_d(self, delta): self.direction.x += self.speed * delta

    def fire(self, delta, pos):
        print('Cannon has fired')
        pass# make bullet & add to self.projectiles w/delayed timer

    def update(self, delta):
        # update bullets before player
        # make bullet class w/update method
        #self.projectiles.update(delta)
        if self.direction.x != 0.0 and self.direction.y != 0.0:
            if self.direction.y < 0.0 and self.direction.x < 0.0:
                self.key_dir = 'topleft'
            elif self.direction.y < 0.0 and self.direction.x > 0.0:
                self.key_dir = 'topright'
            elif self.direction.y > 0.0 and self.direction.x < 0.0:
                self.key_dir = 'bottomleft'
            else: self.key_dir = 'bottomright'
            self.direction *= 0.707107 # equalize diagonal movement
            self.image_reset = True

        else:
            if self.direction.y != 0.0:
                self.image_reset = True
                if self.direction.y < 0.0: self.key_dir = 'top'
                else: self.key_dir = 'bottom'
            elif self.direction.x != 0.0:
                self.image_reset = True
                if self.direction.x < 0.0: self.key_dir = 'left'
                else: self.key_dir = 'right'
            else: pass

        self.pos += self.direction
        self.direction.x, self.direction.y = 0.0, 0.0

    def draw(self, ds):
        # draw bullets before player
        #if self.projectiles.sprites(): self.projectiles.draw(ds)
        #else: pass
        if self.image_reset:
            self.image = self.img_dir[self.key_dir]
            self.rect = self.image.get_rect(center=self.pos)
            self.image_reset = False
            ds.blit(self.image, self.rect)
        else:
            ds.blit(self.image, self.rect)

# Main testing object
class Main:
    def __init__(self):
        pg.init()
        self.display = pg.display.set_mode((400, 400), 0, 32)
        pg.key.set_repeat(25, 25)
        self.time = pg.time.Clock()
        self.all_sprites = pg.sprite.Group()
        self.player = Player(self.all_sprites)

    def run(self):
        # preset vars
        done = False
        paused = False

        # set while loop
        while not done:
            # get framerate
            delta = self.time.tick() / 1000

            # handle Events
            if pg.event.get(pg.QUIT): done = True
            keys = pg.key.get_pressed()
            if keys[pg.K_ESCAPE]: done = True
            if keys[pg.K_SPACE]:
                mouse_pos = pg.mouse.get_pos()
                self.player.fire(delta, mouse_pos)
            if keys[pg.K_w]: self.player.key_w(delta)
            if keys[pg.K_s]: self.player.key_s(delta)
            if keys[pg.K_a]: self.player.key_a(delta)
            if keys[pg.K_d]: self.player.key_d(delta)
            pg.event.clear()

            # handle Updates
            self.player.update(delta)
##            self.all_sprites.update(delta) # Does handle correctly

            # handle Drawing
            _ = self.display.fill('black')
            self.player.draw(self.display) # WORKS, draws to self.display
##            self.all_sprites.draw(self.display) # Doesn't draw to self.display, gives a non-updated image

            # Update main display
            pg.display.update()

# autorun
if __name__ == '__main__':
    test = Main()
    test.run()
    pg.quit()
    sys.exit()

```

### Image Illustration

I need to get the `self.all_sprites` method `draw` fully working, for implementing & testing down the road, especially with multiple sprites (passive, enemies, etc ...)

### Inclosing

Any & all insight would be greatly appreciated, and I would like to express my Thanks for taking the time to help me figure this out.

# Answer
> 1 votes
### Found bug (a user error)

I realized my `self.player.draw` method doesn't get called in the `self.all_sprites.draw` method.

### To fix ...

I can either throw a wrapper class around SpriteGroup (see below)

```
class CustomSpriteGroup(pg.sprite.Group):
    def __init__(self):
        super().__init__()

    # override pygame's Sprite Group default of draw method
    def draw(self, ds):
        for spr in self.sprites():
            spr.draw(ds)

```

In which, creating `self.all_sprites` in `Main.__init__` will need to be rewritten as,
`self.all_sprites = CustomSpriteGroup()`

### Or

A more simple solution, by removing `draw` method from `Player` class and adding a few more lines to `Player.update` method (see below)

```
# Player Sprite
class Player(pg.sprite.Sprite):
    def __init__(self, groups):
##        super().__init__(groups)
        pg.sprite.Sprite.__init__(self, groups)
        self.ds = pg.display.get_surface()
        self.img_dir = img_loader()
        self.key_dir = 'bottom'
        self.image_reset = False
        self.pos = pg.Vector2(200, 200)
        self.image = self.img_dir[self.key_dir]#implement
        self.rect = self.image.get_rect(center=self.pos)
        self.direction = pg.Vector2()
        self.speed = 100
        self.projectiles = pg.sprite.Group()

    def key_w(self, delta): self.direction.y -= self.speed * delta

    def key_s(self, delta): self.direction.y += self.speed * delta

    def key_a(self, delta): self.direction.x -= self.speed * delta

    def key_d(self, delta): self.direction.x += self.speed * delta

    def fire(self, delta, pos):
        print('Cannon has fired')
        pass# make bullet & add to self.projectiles w/delayed timer

    def update(self, delta):
        # update bullets before player
        # make bullet class w/update method
        #self.projectiles.update(delta)
        if self.direction.x != 0.0 and self.direction.y != 0.0:
            if self.direction.y < 0.0 and self.direction.x < 0.0:
                self.key_dir = 'topleft'
            elif self.direction.y < 0.0 and self.direction.x > 0.0:
                self.key_dir = 'topright'
            elif self.direction.y > 0.0 and self.direction.x < 0.0:
                self.key_dir = 'bottomleft'
            else: self.key_dir = 'bottomright'
            self.direction *= 0.707107 # equalize diagonal movement
            self.image_reset = True

        else:
            if self.direction.y != 0.0:
                self.image_reset = True
                if self.direction.y < 0.0: self.key_dir = 'top'
                else: self.key_dir = 'bottom'
            elif self.direction.x != 0.0:
                self.image_reset = True
                if self.direction.x < 0.0: self.key_dir = 'left'
                else: self.key_dir = 'right'
            else: pass

        self.pos += self.direction
        self.direction.x, self.direction.y = 0.0, 0.0

## added from old draw method
        if self.image_reset:
            self.image = self.img_dir[self.key_dir]
            self.rect = self.image.get_rect(center=self.pos)
            self.image_reset = False

## REMOVE ALL BELOW
##    def draw(self, ds):
##        # draw bullets before player
##        #if self.projectiles.sprites(): self.projectiles.draw(ds)
##        #else: pass
##        if self.image_reset:
##            self.image = self.img_dir[self.key_dir]
##            self.rect = self.image.get_rect(center=self.pos)
##            self.image_reset = False
##            ds.blit(self.image, self.rect)
##        else:
##            ds.blit(self.image, self.rect)

```

---
Tags: sprites, python, pygame
---


# Question
Title: Collisions detected prematurely, before rectangles actually touch
I am creating a game with Pygame but my collisions are registering too soon. I'm using this code to end the game when the player collides with a pipe:

```
if player_rect.colliderect(pipe_rect):
    pygame.QUIT
    exit()

```

It works, but it triggers too soon. If the player comes close to the pipe the game ends, even before they collide.

Here is the whole code:

```
import pygame

pygame.init()
gravity = 0
clock = pygame.time.Clock()
jumping = False
fall = 0

screen = pygame.display.set_mode((600,368))

game_background = pygame.image.load("cloud.png").convert_alpha()

player = pygame.image.load("bird.png").convert_alpha()
player_rect = player.get_rect(midbottom = (170,200))

#PIPE IMAGE
pipe_1 = pygame.image.load("pipe1.png").convert_alpha()
pipe_rect = pipe_1.get_rect(midbottom = (500,600))

pipe_2 = pygame.image.load("pipe2.png").convert_alpha()
pipe2_rect = pipe_2.get_rect(midbottom = (500,200))

#set 2
pipe_3 = pygame.image.load("pipe3.png").convert_alpha()
pipe3_rect = pipe_3.get_rect(midbottom = (720,100))

pipe_4 = pygame.image.load("pipe4.png").convert_alpha()
pipe4_rect = pipe_4.get_rect(midbottom = (720,500))

#set 3
pipe_5 = pygame.image.load("pipe5.png").convert_alpha()
pipe5_rect = pipe_5.get_rect(midbottom = (920,600))

pipe_6 = pygame.image.load("pipe6.png").convert_alpha()
pipe6_rect = pipe_6.get_rect(midbottom = (920,200))

#set 4
pipe_7 = pygame.image.load("pipe7.png").convert_alpha()
pipe7_rect = pipe_7.get_rect(midbottom = (1120,500))

pipe_8 = pygame.image.load("pipe8.png").convert_alpha()
pipe8_rect = pipe_8.get_rect(midbottom = (1120,100))

#set 5
pipe_9 = pygame.image.load("pipe9.png").convert_alpha()
pipe9_rect = pipe_9.get_rect(midbottom = (1320,200))

pipe_10 = pygame.image.load("pipe10.png").convert_alpha()
pipe10_rect = pipe_10.get_rect(midbottom = (1320,600))

#set 6
pipe_11 = pygame.image.load("pipe11.png").convert_alpha()
pipe11_rect = pipe_11.get_rect(midbottom = (1520,450 ))

pipe_12 = pygame.image.load("pipe12.png").convert_alpha()
pipe12_rect = pipe_12.get_rect(midbottom = (1520,50))

#set 7
pipe_13 = pygame.image.load("pipe13.png").convert_alpha()
pipe13_rect = pipe_13.get_rect(midbottom = (1720,550 ))

pipe_14 = pygame.image.load("pipe14.png").convert_alpha()
pipe14_rect = pipe_14.get_rect(midbottom = (1720,150))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.blit(game_background,(0,0))

    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_SPACE] and player_rect.bottom >= 0:
           jump = True
           gravity = -7

    gravity += 1
    player_rect.y += gravity

    if player_rect.bottom >= 366: player_rect.bottom = 366
    screen.blit(player,player_rect)

    #pipe 1
    screen.blit(pipe_1,pipe_rect)
    pipe_rect.x -=3
    if pipe_rect.right <= 0: pipe_rect.left = 1200

    #pipe 2
    screen.blit(pipe_2,pipe2_rect)
    pipe2_rect.x -=3
    if pipe2_rect.right <= 0: pipe2_rect.left = 1200

     #pipe 3
    screen.blit(pipe_3,pipe3_rect)
    pipe3_rect.x -=3
    if pipe3_rect.right <= 0: pipe3_rect.left = 1200
     #pipe 4
    screen.blit(pipe_4,pipe4_rect)
    pipe4_rect.x -=3
    if pipe4_rect.right <= 0: pipe4_rect.left = 1200
     #pipe 5
    screen.blit(pipe_5,pipe5_rect)
    pipe5_rect.x -=3
    if pipe5_rect.right <= 0: pipe5_rect.left = 1200
     #pipe 6
    screen.blit(pipe_6,pipe6_rect)
    pipe6_rect.x -=3
    if pipe6_rect.right <= 0: pipe6_rect.left = 1200
     #pipe 7
    screen.blit(pipe_7,pipe7_rect)
    pipe7_rect.x -=3
    if pipe7_rect.right <= 0: pipe7_rect.left = 1200
     #pipe 8
    screen.blit(pipe_8,pipe8_rect)
    pipe8_rect.x -=3
    if pipe8_rect.right <= 0: pipe8_rect.left = 1200
     #pipe 9
    screen.blit(pipe_9,pipe9_rect)
    pipe9_rect.x -=3
    if pipe9_rect.right <= 0: pipe9_rect.left = 1200
     #pipe 10
    screen.blit(pipe_10,pipe10_rect)
    pipe10_rect.x -=3
    if pipe10_rect.right <= 0: pipe10_rect.left = 1200
    #pipe 11
    screen.blit(pipe_11,pipe11_rect)
    pipe11_rect.x -=3
    if pipe11_rect.right <= 0: pipe11_rect.left = 1200
    #pipe 12
    screen.blit(pipe_12,pipe12_rect)
    pipe12_rect.x -=3
    if pipe12_rect.right <= 0: pipe12_rect.left = 1200
    #pipe 13
    screen.blit(pipe_13,pipe13_rect)
    pipe13_rect.x -=3
    if pipe13_rect.right <= 0: pipe13_rect.left = 1200
    #pipe 14
    screen.blit(pipe_14,pipe14_rect)
    pipe14_rect.x -=3
    if pipe14_rect.right <= 0: pipe14_rect.left = 1200

    if pipe_rect.colliderect(player_rect):
        pygame.QUIT
        exit()

   # gravity += 1
    #player_rect.y += gravity

    #if player_rect.bottom >= 366: player_rect.bottom = 366
    #screen.blit(player,player_rect)

    clock.tick(40)
    pygame.display.update()`

```

# Answer
> 0 votes
### The problem

The line `gravity += 1` will make that variable so great it'll slam your player immediately to your base `pipe_rect` prematurely ending your game.

##### To elaborate a bit more ...

Let's look at your framerate, `clook.tick(40)` which means this will loop through 40 times per second. With `gravity` set at `0`, then each loop you apply `gravity += 1`, it'll quickly become 0 to 40 to 80 to etc ... This creates the problem bug, because your `player_rect.y += gravity` line will increasingly pull the `player_rect` faster than it can resist gravity, without repeatedly pressing the spacebar.

### Suggested Solution

##### * Adding a `if` statement to limit gravity variable

Below the line `gravity += 1`, add

```
if gravity >= 10:
    gravity = 10

```

This will give you player a constant pull to the bottom of the screen, but not to fast. The faster the player presses the spacebar key, the easier the bird can resist the gravity effect. 10 is a arbitrary number, it could be any limit you set with an `int`.

---
Tags: collision-detection, python, pygame, aabb
---


# Question
Title: How to use Inkle-style state machines to help with the creation of open world quests?
I've been fascinated by this talk ever since I watched it: GDC Vault Jon Ingold (Inkle) - Narrative Sorcery: Coherent Storytelling in an Open World

It proposes an implementation to simplify the complexity of quests in text-based games, but I bet there are some tools in there that can help any game with quests.

Here's the typical game's quest structure:

And here are some limitations of it:

Here's how this company modeled a quest system that actually has answers to those questions:

It's possible to progress along each of those linked lists independently:

And the current state can indicate some very complex possibilities:

Anyway, it is not my intent to deconstruct this video back into its slides. Just know that everything above is a gross oversimplification. In fact, it may be difficult to answer my question unless you've watched it, but I hope not. Before I ask said question, allow me to present a concrete example:

You start a quest to kill imps in the forest and give the heads to someone who will pay you for them. You can...

1. ...do the quest and get paid.
2. ...wait and steal the heads from somebody else who did the quest.
3. ...kill the man that will pay you and steal the reward.

So basically, a quest starts at one node and branches into three choices. In my mind, this proposed system seems more work than the traditional approach and I'm not seeing the benefits. This is how I would model it using state machines:

```
Imp Quest
o-> "Did the MC meet the man who pays for imp heads?" -> "Give imp heads to man."
o-> "Kill imps"
o-> "Steal heads from somebody else."
o-> "Kill the man and steal the reward."

```

I have `o-> "Kill imps"` on its own because you could kill imps, then steal more from somebody else. In fact, you could do that in the opposite order, therefore, `o-> "Steal heads from somebody else."` needs to be its own list, too?

Most of my quest ideas devolve into lists with a single node and that makes me feel like I'm doing it wrong. Because, at that point, it would be easier to use boolean variables with the traditional quest structure. I must be misunderstanding something from the talk, and I want to know what it is.

Am I modeling these lists incorrectly, am I using a bad example, or am I missing some context that makes this state machine system valuable?

---

Notes:

I inferred from the edit to the title that this might be a Ink language concept so I googled "Inkle State Machines". This resource that might be relevant and/or contain the answer: https://github.com/inkle/ink/blob/master/Documentation/WritingWithInk.md I haven't had time to read it yet.

# Answer
> 2 votes
I believe you should think in terms of the state of the NPCs instead of a quest line. *The player advances the state of the NPCs instead of advancing a quest.*

I would argue that it is a good thing that these quests are becoming wide instead of deep (they are a list of interactions that can happen independently, instead of a sequence of interactions that must happen one after the other).

It means there can be multiple ways the players approaches, or even becomes aware of a "quest", instead of having a single designated quest giver. It also means that you can add alternative ways to do things without messing with existing NPCs. In other words these interactions are decoupled.

So, the fact that your idea of a quest is devolving into a list of interactions *which would not be hard to model with bools* is a good thing.

My take away would be the change of perspective over quest design, plus the idea of having an uniform representation over the state of the world (granted that it does not have to be the representation proposed in the talk).

---

With that in mind, you can have:

The Player:

```
o-> "No Imp heads" -> "Got Imp heads" -> "Got reward for imp heads"
o-> "Does not know about Imp heads reward" -> "Knows about imp heads reward".

```

The NPC who pays for the imp heads:

```
o-> "No reward given" -> "Reward given"

```

The other NPC who might get the reward:

```
o-> "No Imp head" -> "Got Imp heads" -> "Got reward for imp heads"

```

Oh, in fact that last one could be more interesting if we allow to steal the head without killing it:

```
o-> "No Imp head" -> "Got Imp heads" -> "Lost Imp heads"
o-> "No reward" -> "Got reward for imp heads"

```

Here it could lose the imp heads either because it got the reward, or because the player stole them preventing it from getting the reward.

In fact, this require to advance these values in lockstep. For example, getting the reward from the NPC means the player goes from `"Got Imp heads"` to `"Got reward for imp heads"` at the same time as the NPC goes from `"No reward given"` to `"Reward given"`.

Depending on the current state there would be different dialog for the interaction with with NPC, and these interaction would update the states accordingly. For example the NPC that pays for the imp heads could say something different if you already had the head before it told you about the reward.

*Note: I'm assuming all that can be killed already has a way to track that state, so I'm not including `"Alive" -> "Dead"` in any of these.*

---
Tags: game-design, game-mechanics, text-based, quests, statemachine
---


# Question
Title: Generate Xcode project for macOS via the Unity command line
I am trying to export an Xcode project targeting macOS via the Unity3D command line in Continuous Integration.

However, I cannot figure out the right build setting to export an XCode project for macOS through the command line. The Android build target has a specific setting in `EditorUserBuildSettings` to export an Android Studio project, but I am unable to figure out how to do this for macOS.

Has anyone done this before and can help me out?

# Answer
I managed to figure it out based on a thread in the Unity forums.

Some of the build settings are stored in `Library/EditorUserBuildSettings.asset` as a binary file (ignores the project settings for asset serialization as text).

The `EditorUserBuildSettings` has a `SetPlatformSettings` methods which allows you to change arbitrary properties in the build settings. Reverse engineering the editor build settings asset file and using this method allowed me to change this using the command line.

```
var createXCodeProject = EditorUserBuildSettings.GetPlatformSettings("OSXUniversal", "CreateXcodeProject");
Console.WriteLine($"[EditorUserBuildSettings] Create XCode project: {createXCodeProject}");

if (buildPath.EndsWith(".app"))
{
     EditorUserBuildSettings.SetPlatformSettings("OSXUniversal", "CreateXcodeProject", "false");
}
else
{
     EditorUserBuildSettings.SetPlatformSettings("OSXUniversal", "CreateXcodeProject", "true");
}

```
> 2 votes

---
Tags: unity, xcode
---


# Question
Title: Should I use AVX intrinsics or avoid them if possible?
I am working on a C++ game engine (target: Windows PCs). I have a CPU bottleneck that could use AVX to speed things up. It is not a must, but I also don't want to miss out on the opportunity, if AVX can really help to make my engine run faster. However, I see that not many games use it, even though sometimes the AVX requirement is "patched out" of the game, which tells me there might still be a significantly sized player base with old but fast processors. So I am in a dilemma: should I use AVX in my code or not?

I found the list of AVX-supported processors on Wikipedia.

It seems every Intel/AMD processor supporting AVX was manufactured in the past 10 or so years. However, I got a little lost among the many versions of processors. There might be some newer chips that don't support it. I am wondering if I would lose out on a significant number of players if I made my game with AVX intrinsics.

# Answer
You probably want to support CPUs without AVX, unless your game wouldn't be playable on CPUs that don't have it.

If you decide that you do need it, then I'd suggest making it extra clear in the minimum spec requirements, and via an error message when the game is started on a CPU that doesn't have AVX support.

If you look at the Steam Hardware Survey (under "Other Settings"), you'll see that around 95% of Steam users currently have a CPU that supports AVX instructions. That means that requiring a CPU that supports AVX will prevent 5% of Steam users from being able to run your game (and some of those users will buy the game, and then complain that it doesn't work).
> 0 votes

# Answer
Why not both?

Find out the capabilities of the users CPU at runtime and depending on whether or not it supports AVX, run your new AVX code or the legacy code you already have.
> 1 votes

---
Tags: simd
---


title: No vertex shader bound at draw?

text:
# Question
Title: No vertex shader bound at draw?
I tried asking this on reddit but I didn't get any answers so I might as well try here

So I'm making a program to generate some terrain and it's not giving me the results I expected. It's drawing black pillars. Lots of code coming up btw.

This is the article that I'm using https://learnopengl.com/Guest-Articles/2021/Tessellation/Tessellation

Even though it's written in C++ I rewrote it in C, the language I'm using.

This is the vertex shader

```
#version 410 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 tex;

out vec2 tex_coord;

void main()
{
    // set position and sets texture (uv) coordinates
    gl_Position = vec4(pos, 1.0);
    tex_coord = tex;
}

```

This is the fragment shader

```
#version 410 core

in float height;

out vec4 color;

void main()
{
    float h = (height+16)/64.0f;
    color = vec4(h,h,h,1.0);
}

```

This is the tessellation control shader

```
#version 410 core

layout(vertices=4) out;

uniform mat4 model;
uniform mat4 view;

in vec2 tex_coord[];
out vec2 texture_coord[];

void main()
{
    // essentially sets render distance
    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
    texture_coord[gl_InvocationID] = tex_coord[gl_InvocationID];

    if(gl_InvocationID == 0)
    {
        const int MIN_TESS_LEVEL = 4;
        const int MAX_TESS_LEVEL = 64;
        const float MIN_DISTANCE = 20;
        const float MAX_DISTANCE = 800;

        vec4 eye_space_pos_00 = view * model * gl_in[0].gl_Position;
        vec4 eye_space_pos_01 = view * model * gl_in[1].gl_Position;
        vec4 eye_space_pos_10 = view * model * gl_in[2].gl_Position;
        vec4 eye_space_pos_11 = view * model * gl_in[3].gl_Position;

        // "distance" from camera scaled between 0 and 1
        float distance_00 = clamp( (abs(eye_space_pos_00.z) - MIN_DISTANCE) / (MAX_DISTANCE-MIN_DISTANCE), 0.0, 1.0 );
        float distance_01 = clamp( (abs(eye_space_pos_01.z) - MIN_DISTANCE) / (MAX_DISTANCE-MIN_DISTANCE), 0.0, 1.0 );
        float distance_10 = clamp( (abs(eye_space_pos_10.z) - MIN_DISTANCE) / (MAX_DISTANCE-MIN_DISTANCE), 0.0, 1.0 );
        float distance_11 = clamp( (abs(eye_space_pos_11.z) - MIN_DISTANCE) / (MAX_DISTANCE-MIN_DISTANCE), 0.0, 1.0 );

        float tess_level_0 = mix( MAX_TESS_LEVEL, MIN_TESS_LEVEL, min(distance_10, distance_00) );
        float tess_level_1 = mix( MAX_TESS_LEVEL, MIN_TESS_LEVEL, min(distance_00, distance_01) );
        float tess_level_2 = mix( MAX_TESS_LEVEL, MIN_TESS_LEVEL, min(distance_01, distance_11) );
        float tess_level_3 = mix( MAX_TESS_LEVEL, MIN_TESS_LEVEL, min(distance_11, distance_10) );

        gl_TessLevelOuter[0] = tess_level_0;
        gl_TessLevelOuter[1] = tess_level_1;
        gl_TessLevelOuter[2] = tess_level_2;
        gl_TessLevelOuter[3] = tess_level_3;

        gl_TessLevelInner[0] = max(tess_level_1, tess_level_3);
        gl_TessLevelInner[1] = max(tess_level_0, tess_level_2);
    }
}

```

This is the tessellation evaluation shader

```
#version 410 core
layout(quads, fractional_odd_spacing, ccw) in;

uniform sampler2D height_map;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

in vec2 texture_coord[];

out float height;

void main()
{
    // get the texture coordinate of point (x, y, z) in the terrain
    float u = gl_TessCoord.x;
    float v = gl_TessCoord.y;

    vec2 t_00 = texture_coord[0];
    vec2 t_01 = texture_coord[1];
    vec2 t_10 = texture_coord[2];
    vec2 t_11 = texture_coord[3];

    vec2 t_0 = (t_01 - t_00) * u + t_00;
    vec2 t_1 = (t_11 - t_10) * u + t_10;
    vec2 tex_coord = (t_1 - t_0) * v + t_0;

    height = texture(height_map, tex_coord).g * 64.0 - 16.0;

    vec4 p_00 = gl_in[0].gl_Position;
    vec4 p_01 = gl_in[1].gl_Position;
    vec4 p_10 = gl_in[2].gl_Position;
    vec4 p_11 = gl_in[3].gl_Position;

    vec4 u_vec = p_01 - p_00;
    vec4 v_vec = p_10 - p_00;
    vec4 normal = normalize( vec4(cross(v_vec.xyz, u_vec.xyz), 0) );

    vec4 p_0 = (p_01 - p_00) * u + p_00;
    vec4 p_1 = (p_11 - p_10) * u + p_10;
    vec4 p = (p_1 - p_0) * v + p_0 + normal * height;

    gl_Position = projection * view * model * p;
}

```

This is the initialization for GLFW

```
// init glfw
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif // __APPLE__
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// check to see if glfw was initialized
if(!glfwInit())
{
    printf("GLFW is not ok.\n");
}

```

This is where I loaded the height map

```
// height map
unsigned int texture;
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load the image
int width, height, nr_components;
short unsigned int* data = stbi_load_16("textures/river_heightmap.png", &width, &height, &nr_components, 0);
if(data)
{
    // bind texture and specify its data and how to manage it
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16, width, height, 0, GL_RED, GL_UNSIGNED_SHORT, data);

    // set the height map
    set_int(shader_program, "height_map", 0);
    printf("Loaded a height map of %i x %i\n", width, height);
}
else
{
    printf("Failed to load height map\n");
}
stbi_image_free(data);

```

This is where I uploaded the terrain data to the GPU

```
float vertices[1000];
unsigned rez = 20;
for(unsigned i = 0; i <= rez-1; i++)
{
    for(unsigned j = 0; j <= rez-1; j++)
    {
        push_back_float(-width/2.0f + width*i/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*j/(float)rez, vertices); // v.z
        push_back_float(i / (float)rez, vertices); // u
        push_back_float(j / (float)rez, vertices); // v

        push_back_float(-width/2.0f + width*(i+1)/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*j/(float)rez, vertices); // v.z
        push_back_float((i+1) / (float)rez, vertices); // u
        push_back_float(j / (float)rez, vertices); // v

        push_back_float(-width/2.0f + width*i/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*(j+1)/(float)rez, vertices); // v.z
        push_back_float(i / (float)rez, vertices); // u
        push_back_float((j+1) / (float)rez, vertices); // v

        push_back_float(-width/2.0f + width*(i+1)/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*(j+1)/(float)rez, vertices); // v.z
        push_back_float((i+1) / (float)rez, vertices); // u
        push_back_float((j+1) / (float)rez, vertices); // v
    }
}
printf("Loaded %i patches of 4 control points each\n", rez*rez);
printf("Processing %i vertices in vertex shader\n", rez*rez*4);

```

This is where I set up the VAO and VBO

```
unsigned int vao, vbo;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, (float)(sizeof(vertices)/sizeof(vertices[0])) * sizeof(float), &vertices[0], GL_STATIC_DRAW);

// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// texture attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(sizeof(float) * 3));
glEnableVertexAttribArray(1);

glPatchParameteri(GL_PATCH_VERTICES, NUM_PATCH_PTS);

```

This is the main loop and the buffer deletion

```
// game loop
while (!glfwWindowShouldClose(window))
{
    // per-frame time logic and FPS counter
    float current_frame = glfwGetTime();
    delta_time = current_frame - last_frame;
    last_frame = current_frame;

    // fps counter, uncomment if needed
    //printf("%i ms %f FPS\n", (int)delta_time, 1.0f / delta_time);

    // input
    keyboard_input(window);

    // render
    glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // shader
    use_shader(shader_program);

    // view/projection transformations
    mat4 projection = GLM_MAT4_IDENTITY_INIT;
    glm_perspective(glm_rad(ccamera->zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f, projection);
    mat4 view = GLM_MAT4_IDENTITY_INIT;
    camera_get_view_matrix(view);
    set_mat_4(shader_program, "projection", projection);
    set_mat_4(shader_program, "view", view);

    // world transformation
    mat4 model = GLM_MAT4_IDENTITY_INIT;
    set_mat_4(shader_program, "model", model);

    // render terrain
    glBindVertexArray(vao);
    glDrawArrays(GL_PATCHES, 0, NUM_PATCH_PTS*rez*rez);

    // glfw: swap buffers and poll IO events
    glfwSwapBuffers(window);
    glfwPollEvents();
}

// deallocate resources that outlived their purpose
shader_clean_up(shader_program);
// clean up glfw
glfwTerminate();
return 0;

```

These are the screenshots of the RenderDoc report

If you need any more information tell me so I can add more screenshots and code if needed.

Edit: The shader loader, the original code is from here if you wanna have a look at that: https://github.com/CraftingInC/LearnOpenGLInC/blob/master/includes/learnopengl/shader.h

Note: I did change a few things around from the original so here is my version

```
#ifndef SHADER_H_INCLUDED
#define SHADER_H_INCLUDED

#include <GL/glew.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <CGLM/cglm.h>

// loads the shader then copies the data into a char variable and returns the shader id
int load_shader_file(const char* shader_file_name, int shader_type)
{
    FILE* shader_file = fopen(shader_file_name, "rb");
    if(shader_file != NULL)
    {
        char* shader_char;
        fseek(shader_file, 0, SEEK_END);
        size_t total_size = ftell(shader_file);
        rewind(shader_file);

        shader_char = (char*)malloc(total_size + 1);
        fread(shader_char, 1, total_size, shader_file);
        shader_char[total_size] = 0;
        fclose(shader_file);

        GLuint shader_id = 0;
        shader_id = glCreateShader(shader_type);
        glShaderSource(shader_id, 1, (const char**)&shader_char, NULL);
        glCompileShader(shader_id);

        GLint shader_compiled;
        glGetShaderiv(shader_id, GL_COMPILE_STATUS, &shader_compiled);
        if(shader_compiled != GL_TRUE)
        {
            GLsizei log_length;
            GLchar log[1024];
            glGetShaderInfoLog(shader_id, sizeof(log), &log_length, log);
            printf("Error in %s: %s\n", shader_file_name, log);
        }
        else
        {
            return shader_id;
        }
        }
        else
        {
            printf("Unable to open file %s\n", shader_file_name);
        }
        return -1;
}

// checks for shader program errors
void check_for_errors(int shader_program)
{
    int worked;
    char info_log[1024];
    glGetProgramiv(shader_program, GL_LINK_STATUS, &worked);
    if(!worked)
    {
        glGetShaderInfoLog(shader_program, 1024, NULL, info_log);
        printf("Program linking failed: %s\n", info_log);
    }
}

// takes the already loaded shaders and attaches them to the shader program then deletes them (debugs if necessary) and finally returns the shader program
unsigned int load_glsl_shaders(const char* frag_shader_path, const char* vert_shader_path,
const char* tess_control_path, const char* tess_eval_path)
{
    unsigned int fragment, vertex, tess_control, tess_eval, program;
    fragment = load_shader_file(frag_shader_path, GL_FRAGMENT_SHADER);
    vertex = load_shader_file(vert_shader_path, GL_VERTEX_SHADER);
    tess_control = load_shader_file(tess_control_path, GL_TESS_CONTROL_SHADER);
    tess_eval = load_shader_file(tess_eval_path, GL_TESS_EVALUATION_SHADER);
    program = glCreateProgram();
    glAttachShader(program, fragment);
    glAttachShader(program, vertex);
    glAttachShader(program, tess_control);
    glAttachShader(program, tess_eval);
    glLinkProgram(program);
    check_for_errors(program);
    glDeleteShader(fragment);
    glDeleteShader(vertex);
    glDeleteShader(tess_control);
    glDeleteShader(tess_eval);
    return program;
}

// compiles the shaders and shader program (also debugs if necessary) then returns the shader program
unsigned int load_embedded_shaders(const char* vertex_shader_text, const char* fragment_shader_text,
const char* tess_control_text, const char* tess_eval_text)
{
    GLchar vertex_shader, fragment_shader, tess_control_shader, tess_eval_shader, shader_program;
    int compiled;
    char info_log[512];

    // compile fragment shader
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &compiled);
    if(!compiled)
    {
        glGetShaderInfoLog(fragment_shader, 512, NULL, info_log);
        printf("Fragment shader failed: %s\n", info_log);
    }

    // compile vertex shader
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &compiled);
    if(!compiled)
    {
        glGetShaderInfoLog(vertex_shader, 512, NULL, info_log);
        printf("Vertex shader failed: %s\n", info_log);
    }

    // compile tessellation control shader
    tess_control_shader = glCreateShader(GL_TESS_CONTROL_SHADER);
    glShaderSource(tess_control_shader, 1, &tess_control_text, NULL);
    glCompileShader(tess_control_shader);
    glGetShaderiv(tess_control_shader, GL_COMPILE_STATUS, &compiled);
    if(!compiled)
    {
        glGetShaderInfoLog(tess_control_shader, 512, NULL, info_log);
        printf("Tessellation control shader failed: %s\n", info_log);
    }

    // compile tessellation evaluation shader
    tess_eval_shader = glCreateShader(GL_TESS_EVALUATION_SHADER);
    glShaderSource(tess_eval_shader, 1, &tess_eval_text, NULL);
    glCompileShader(tess_eval_shader);
    glGetShaderiv(tess_eval_shader, GL_COMPILE_STATUS, &compiled);
    if(!compiled)
    {
        glGetShaderInfoLog(tess_eval_shader, 512, NULL, info_log);
        printf("Tessellation evaluation shader failed: %s\n", info_log);
    }

    // compile the shader program
    shader_program = glCreateProgram();
    glAttachShader(shader_program, fragment_shader);
    glAttachShader(shader_program, vertex_shader);
    glAttachShader(shader_program, tess_control_shader);
    glAttachShader(shader_program, tess_eval_shader);
    glLinkProgram(shader_program);
    check_for_errors(shader_program);

    // deletes the shaders
    glDeleteShader(fragment_shader);
    glDeleteShader(vertex_shader);
    glDeleteShader(tess_control_shader);
    glDeleteShader(tess_eval_shader);

    // return shader program
    return shader_program;
}

// deletes the shader program
void shader_clean_up(unsigned int shader_program)
{
    glDeleteProgram(shader_program);
}

// uses the shader program
void use_shader(unsigned int shader_program)
{
    glUseProgram(shader_program);
}

// sets boolean values in the shader program / shader(s) that are linked to it
void set_bool(unsigned int shader_program, const char* name, bool value)
{
    glUniform1i(glGetUniformLocation(shader_program, name), (int)value);
}

// sets integer values in the shader program / shader(s) that are linked to it
void set_int(unsigned int shader_program, const char* name, int value)
{
    glUniform1i(glGetUniformLocation(shader_program, name), value);
}

// sets floating point values in the shader program / shader(s) that are linked to it
void set_float(unsigned int shader_program, const char* name, float value)
{
    glUniform1f(glGetUniformLocation(shader_program, name), value);
}

// sets 2 dimensional matrices in the shader program / shader(s) that are linked to it
void set_mat_2(unsigned int shader_program, const char* name, const mat2 mat)
{
    glUniformMatrix2fv(glGetUniformLocation(shader_program, name), 1, GL_FALSE, &mat[0][0]);
}

// sets 3 dimensional matrices in the shader program / shader(s) that are linked to it
void set_mat_3(unsigned int shader_program, const char* name, const mat3 mat)
{
    glUniformMatrix3fv(glGetUniformLocation(shader_program, name), 1, GL_FALSE, &mat[0][0]);
}

// sets 4 dimensional matrices in the shader program / shader(s) that are linked to it
void set_mat_4(unsigned int shader_program, const char* name, const mat4 mat)
{
    glUniformMatrix4fv(glGetUniformLocation(shader_program, name), 1, GL_FALSE, &mat[0][0]);
}

// sets 2 dimensional vectors in the shader program / shader(s) that are linked to it
void set_vec_2(unsigned int shader_program, const char* name, const vec2 value)
{
    glUniform2fv(glGetUniformLocation(shader_program, name), 1, &value[0]);
}

// sets 2 dimensional vectors with 3d space directions in the shader program / shader(s) that are linked to it
void set_vec_2_xyz(unsigned int shader_program, const char* name, float x, float y)
{
    glUniform2f(glGetUniformLocation(shader_program, name), x, y);
}

// sets 3 dimensional vectors in the shader program / shader(s) that are linked to it
void set_vec_3(unsigned int shader_program, const char* name, const vec3 value)
{
    glUniform3fv(glGetUniformLocation(shader_program, name), 1, &value[0]);
}

// sets 3 dimensional vectors with 3d space directions in the shader program / shader(s) that are linked to it
void set_vec_3_xyz(unsigned int shader_program, const char* name, float x, float y, float z)
{
    glUniform3f(glGetUniformLocation(shader_program, name), x, y, z);
}

// sets 4 dimensional vectors in the shader program / shader(s) that are linked to it
void set_vec_4(unsigned int shader_program, const char* name, const vec4 value)
{
    glUniform4fv(glGetUniformLocation(shader_program, name), 1, &value[0]);
}

// sets 4 dimensional vectors with 3d space directions that include the w (the component that scales the other dimensions) in the shader program / shader(s) that are linked to it
void set_vec_4_wyzx(unsigned int shader_program, const char* name, float x, float y, float z, float w)
{
    glUniform4f(glGetUniformLocation(shader_program, name), x, y, z, w);
}
#endif // SHADER_H_INCLUDED

```

Edit 2: Shaders getting loaded

```
unsigned int shader_program = load_glsl_shaders("frag.vert", "vert.vert", "gpu_tcs.vert", "gpu_tes.vert");

```

# Answer
**Vertices array size**

Please, review the array `float vertices[1000];`

You are adding 20 * 20 * 20 = 8000 floats with the function `push_back_float`, so you must be exceeding the array limit.

**Vertex01 and vertex10 swapped**

The order they are defined inside the loop do not match the way they are used inside the shaders.

---

```
vec4 p_00 = gl_in[0].gl_Position;
vec4 p_01 = gl_in[1].gl_Position;       // gl_in in the VBO is the 10
vec4 p_10 = gl_in[2].gl_Position;       // gl_in in the VBO is the 01
vec4 p_11 = gl_in[3].gl_Position;

vec4 u_vec = p_01 - p_00;
vec4 v_vec = p_10 - p_00;
vec4 normal = normalize( vec4(cross(v_vec.xyz, u_vec.xyz), 0) );        // cross product with opposite direction

vec4 p_0 = (p_01 - p_00) * u + p_00;
vec4 p_1 = (p_11 - p_10) * u + p_10;
vec4 p = (p_1 - p_0) * v + p_0 + normal * height;

gl_Position = projection * view * model * p;

```

---

Try changing the order of vertex01 and vertex10 inside the for loops, so they match what shaders are expecting.

---

```
float vertices[1000];  // Increase to rez * rez * 20
unsigned rez = 20;
for(unsigned i = 0; i <= rez-1; i++)
{
    for(unsigned j = 0; j <= rez-1; j++)
    {
        // Vertex00
        push_back_float(-width/2.0f + width*i/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*j/(float)rez, vertices); // v.z
        push_back_float(i / (float)rez, vertices); // u
        push_back_float(j / (float)rez, vertices); // v

        // Vertex10
        push_back_float(-width/2.0f + width*(i+1)/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*j/(float)rez, vertices); // v.z
        push_back_float((i+1) / (float)rez, vertices); // u
        push_back_float(j / (float)rez, vertices); // v

        // Vertex01
        push_back_float(-width/2.0f + width*i/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*(j+1)/(float)rez, vertices); // v.z
        push_back_float(i / (float)rez, vertices); // u
        push_back_float((j+1) / (float)rez, vertices); // v

        // Vertex11
        push_back_float(-width/2.0f + width*(i+1)/(float)rez, vertices); // v.x
        push_back_float(0.0f, vertices); // v.y
        push_back_float(-height/2.0f + height*(j+1)/(float)rez, vertices); // v.z
        push_back_float((i+1) / (float)rez, vertices); // u
        push_back_float((j+1) / (float)rez, vertices); // v
    }
}
printf("Loaded %i patches of 4 control points each\n", rez*rez);
printf("Processing %i vertices in vertex shader\n", rez*rez*4);

```

**Camera position**

Currently located at (vec3)(0.0f, 0.0f, 3.0f); y=0

In the **tessellation evaluation shader**, the height (y coord) is added using the heightMap and it is scaled and shifted.

```
// Comment from the reference learnopengl.com page
// lookup texel at patch coordinate for height and scale + shift as desired
// height_map provides values in range [0.0-1.0]
// scaled by 64.0,  range [0.0,64.0]
// offset by -16.0, range [-16.0, 48.0]
height = texture(height_map, tex_coord).g * 64.0 - 16.0;

vec4 p_00 = gl_in[0].gl_Position;
vec4 p_01 = gl_in[1].gl_Position;
vec4 p_10 = gl_in[2].gl_Position;
vec4 p_11 = gl_in[3].gl_Position;

vec4 u_vec = p_01 - p_00;
vec4 v_vec = p_10 - p_00;
vec4 normal = normalize( vec4(cross(v_vec.xyz, u_vec.xyz), 0) );

vec4 p_0 = (p_01 - p_00) * u + p_00;
vec4 p_1 = (p_11 - p_10) * u + p_10;
vec4 p = (p_1 - p_0) * v + p_0 + normal * height;  // normal is Y axis, scaled by range [-16.0,48.0]

gl_Position = projection * view * model * p;      // position has a y coord in range [-16.0, 48.0]

```

The camera should be above y=48.0 to avoid looking the mesh from below. The map is very huge 2624x1744 (height\_map size). You should also increase the Far plane (100.0f) to look more terrain and avoiding the clipping with far plane.

```
 glm_perspective(glm_rad(ccamera->zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f, projection);

```
> 0 votes

---
Tags: opengl, shaders, glsl, c, debugging
---


# Question
Title: Dealing with Camera "bump" during floating origin reset
I am asking this question because my Google searches have yielded little results. My problem is basically this: I've implemented a very simple smooth follow on my camera to trail the player (who is free to move on all axes). The smooth follow method is as below.

```
        targetPosition = target.position + (target.rotation * offset);
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
        transform.LookAt(target, target.up);
        transform.rotation *= rotationalOffset;

```

I also have a simple "floating origin" implementation that moves all objects back to the world origin if the player crosses a certain threshold (in this case \[100, 100, 100\] for testing purposes). The method for that is:

```
if (isCrossedXThreshold || isCrossedYThreshold || isCrossedZThreshold)
{
    for(int i = 0; i < SceneManager.sceneCount; i++)
    {
        foreach(GameObject rootObj in SceneManager.GetSceneAt(i).GetRootGameObjects())
        {
            rootObj.transform.position -= playerPosition;
        }
    }
}

```

By themselves, they work as they should. However, when working together, the camera will briefly 'bump' towards the player when it crosses the floating origin threshold, making for a not-so-smooth transition back to the origin. From my understanding, this is happening because `smoothTime` creates a delay in repositioning the camera.

How could I go about ensuring a more smooth transition back to the origin without any unwanted camera shakes or bumps?

PS: All player and camera movements are done within the LateUpdate method, if thats relevant.

# Answer
It did not actually have to do with the camera; it was the Player object. I was using a Rigidbody to move the player but was updating its transform on the origin shift. So.... classic mistake.
> 1 votes

---
Tags: unity, camera, movement
---


# Question
Title: How to get Unity InputSystem to use OpenXInput or at least DirectInput for XInput controllers?
I want to workaround the XInput disadvantage of having just four controllers.

I have found out about OpenXInput and compiled it, but I’ve got no idea how to force Unity to use the new DLL, since I did not find any DLL references in InputSystem code.

If it’s not possible, is it at least possible to force those controllers to go through DirectInput, as if they’re non-XInput-compatible? How can that be done?

# Answer
> 0 votes
While not an expert in the unity Input System package, I have extended a few classes there to perform touch operations on mobile.

I'm pretty sure you would need to create your own adapter classes to expose your native dll, or c# functions through defining a new device type in the input system and managing all the input yourself.

https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Devices.html#device-descriptions

---
Tags: unity, input, directinput
---


title: How would I bitmask these tiles?

text:
# Question
Title: How would I bitmask these tiles?
I am using Cup Noobles's Sprout Lands asset pack for my small game. I want to use the wooden house tileset, but I am confused about how to set up its Autotile bitmask in Godot. How can I achieve this?

# Answer
The tileset shown isn't well suited to autotile. Some parts work ok, others somewhat, and some not at all. The nine house tiles are the best suited to autotile, so we'll start with those.

As mentioned in the Godot documentation on tile maps, autotile uses a set of rules to determine which tile to draw based on the content of adjacent cells & the bitmask patterns assigned to the tiles. The modes for the autotile are: 2x2, 3x3 (minimal) and 3x3.

The tiles you have are designed for 3x3 (minimal) (as indicated on the download page), so I'm only addressing that here. Here's an illustration of how the 3x3 (minimal) rules work:

* for our purposes `i` should always be on if there's an automap tile
* for the other bitmask positions:
    + if there's a required neighbor at `X` then `x` is on
    + otherwise it is off

If we apply that to the house tiles, we want to select brick floor when we place a tile surrounded by all eight other tiles:

That means the brick tile has all of its bits masked.

Compare that to the upper right corner of the house. We only want to use that tile if we're placing a tile that has neighbors in positions `H`, `G` & `F`:

So the bitmask for the upper right corner tile would mask bits: `h`,`i`,`g`,`f`

And extending that to the remaining tiles, gives the following:

The front & back walls are potentially a special case because there is a solid version & a version with a window. That means they could both have the same bitmask pattern. But the documentation says the following about this situation:

> If more than one matching bitmask is found, one of them will be selected randomly, using the tile priorities.

So this is going to come down to personal preference. You could include the window wall into the autotile rules & Godot will randomly decide which to use and you will have to manually change anything you don't like afterward. Or you could leave it out of the autotile rules. In that case Godot will always use plain walls and it would be up to you to manually add window walls were desired.

Note that the house tiles in your post don't account for all possible tiling situations. Specifically, they don't provide the tiles necessary to make concave structures. For example to make a house with this outline:

```
┌──┐
│ ┌┘
└─┘

```

You would need to make a tile that looks like this:

That tile would be masked on `a`,`b`,`c`,`h`,`i`,`d`,`g`,`f` (or put differently, everything *except* `e`) so that it could be used as follows:

Note: the license on the free pack prohibits me from distributing derivative works of the sprites, so I'm not going to make & post the actual variants. I free handed that special corner hand to look deliberately bad. If you need variants, it's relatively easy to make better ones using an image editor (Photoshop, Krita, Paint.net, etc), but it's up to you to ensure your use respects the author's license. I only check the freely available sprite pack; it's possible that the paid version already includes the extra sprites for all possible house layouts.

The roof tiles are more complicated because their placement depends not only on whether or not they have neighbors, but also which neighbors they have. For example, consider these two groups of tiles:

As far as bitmasking goes, they group on the up facing group (shown on the left) has the same rules as the down facing group. We know than the ones on the left "go together" & as do the ones on the right. But autotile only uses the bitmasking. As mentioned before, duplicate bitmasking patterns results in random tile selection. So if We try to autotile all the roof parts, autotile will give us a randomize mess.

If want to autotile them, I would consider making one set of tiles for upward facing shingles and another for south facing shingles, as follows:

You can then switch between roof groups as needed. However, by itself, this will give you a layout that has a weird double seam where the two set meet (shown below on the left). To correct that, you need to switch off the autotiling & manually place in a row that joins the two (shown below on the right).

It's up to you to decide if it's worth the inconvenience.

The remaining elements (the door tiles & the chimney) don't make sense to autotile at all. Stamp them in as needed.
> 3 votes

---
Tags: godot, tilesets, tile-bitmasking
---


# Question
Title: Game Displaying In Different Resolution When Built
When I build and run my game, the resolution is different than in editor.

**Note**: **My monitor's display settings are 2560 x 1440.**

My editor's game display is set to Full HD (1920 x 1080).

I have UI positioned just outside of my canvas so that it does not display until needed:

This looks fine in the editor and the UI is not visible.

When I build my game using the settings:

Edit \> Project Settings \> Player \> Fullscreen Mode \> Exclusive Fullscreen This is what I see:

Changing Fullscreen Mode to Windowed and specifying 1920 x 1080, makes it display correctly.

But then if I maximize the window using the above settings it displays incorrectly again:

Additionally, here is my canvas:

I'd like my game to always look the same, displaying in 1920 x 1080 resolution. So, even if the window is maximized, it will just stretch the image, rather than show more of the game, revealing the UI.

Is any one able to provide me with the correct settings I should be using? Thanks so much!

# Answer
> 1 votes
The issue was my Canvas Scaler not being configured correctly.

This was resolved by changing my Canvas Scaler's UI Scale Mode from 'Constant Pixel size' to 'Scale With Screen Size'.

Additionally, I set the 'Reference Resolution' to 1920 x 1080 ( the resolution I'm targeting ), and 'Screen Match Mode' to Expand.

This seems to do the trick for me!

---
Tags: unity, resolution
---


# Question
Title: My character keeps wanting to face the world z axis
My character is facing the direction its moving to, but when it stops moving, it rotates back to facing the world z axis.It rotates back to "how it was".

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

public class ThirdPersonController : MonoBehaviour
{
    public float walkSpeed = 6.0f;
    public float runSpeed = 11.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public float speed = 6f;
    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;
    private Vector3 moveDirection;
    private CharacterController controller;
    private bool isGrounded = false;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    private void Update()
    {

        if (controller.isGrounded)
        {
            if (Input.GetKey(KeyCode.LeftShift))
            {
                speed = runSpeed;
            }
            else
            {
                speed = walkSpeed;
            }

            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");
            moveDirection = new Vector3(horizontal, 0, vertical).normalized;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
            float targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0f, targetAngle, 0f), Time.deltaTime * turnSmoothTime);

        }
        moveDirection.y -= gravity * Time.deltaTime;

        controller.Move(moveDirection * speed * Time.deltaTime);

    }
}

```

please help and thanks.

# Answer
```
// targetAngle gets declared *outside* your Update function,
// so it can remember the angle value between runs.
float targetAngle;

private void Update()
{
     // ...skipping over some unrelated code...

    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");
    moveDirection = new Vector3(horizontal, 0, vertical).normalized;

    // Choose a new `targetAngle` only if the movement input is non-zero.
    // Otherwise, keep using the angle chosen last frame.
    if (moveDirection != Vector3.zero) {
        targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg;
    }

    // No float angle = ... line at all (you never used its value anyway)

    transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0f, targetAngle, 0f), Time.deltaTime * turnSmoothTime);

    if (Input.GetButton("Jump"))
    {
        moveDirection.y = jumpSpeed;
    }

```
> 0 votes

---
Tags: unity, character-controller
---


# Question
Title: How do I recreate the default 2D camera in my Unity project
I was using Unity but my PC shut down suddenly; when I reopened my project, all my GameObjects, including my camera, had disappeared. The good thing is that I created prefabs of all of them (except the camera).

So now I tried making a GameObject with a camera component but it doesn't seem to work like the original: I can't seem to readjust the size of the camera and it suddenly has diagonals running from edge to edge. I couldn't find a solution online and I am wondering if there is a way to remake the original camera.

# Answer
> 0 votes
Click on the “GameObject” drop down menu, then select Camera and it will create the Camera object in the Hierarchy. If you want to make it the main camera in your scene then in the Inspector click on the “Tag” drop down box and select “Main Camera”. Save your changes.

---
Tags: unity, 2d, camera
---


# Question
Title: Recreate red & cyan menu item highlight from Persona 5
I would like to animate two of my UI images in a similar manner to the red and blue images below:

I'd like to accomplish this through script, but I'm not certain if it's possible.

Does anyone have insight on how I can recreate this effect? Thanks!

# Answer
For color, this is basically an additive blending:

Unity has made an additive shader for the particle system, for convenience you can use it directly:

For shapes, this basically draws two quads on the UI and updates their vertex positions via script. Now let's see how to draw polygons on the UI. Here is a simple code. For convenience, I specify that all children of the script transform are the vertices of the polygon, and agree that they are in order.

```
using UnityEngine;
using UnityEngine.UI;

public class UIPolygon : Graphic
{
    private void OnGUI()
    {
        SetAllDirty();
    }
    protected override void OnPopulateMesh(VertexHelper vh)
    {
        if (transform.childCount < 2)
        {
            return;
        }
        vh.Clear();
        foreach (Transform child in transform)
        {
            vh.AddVert(child.localPosition, color, Vector2.zero);
        }
        for (int i = 0; i < transform.childCount - 2; i++)
        {
            vh.AddTriangle(i + 1, i + 2, 0);
        }
    }
}

```

Now, mount this script on a UI object and create 4 children for it:

Then, create a new material, set its shader to additive, and attach it to the polygon.

Then set the color of this polygon to red, duplicate a polygon and set its color to cyan, and adjust the positions of their vertices:

Finally, we attach another script to the polygon to make all its children move randomly within a certain range.

\**Due to the frame rate of the gif, I don't know whether the movement of the vertices is continuous or discrete. Here I simply let it change the position randomly. You can modify it however you want.

```
using System.Collections;
using UnityEngine;

public class UIPolygonChildrenMove : MonoBehaviour
{
    void Start()
    {
        foreach (RectTransform child in transform)
        {
            StartCoroutine(UpdateChildPos(child, child.anchoredPosition));
        }
    }
    IEnumerator UpdateChildPos(RectTransform child, Vector2 prePos)
    {
        while (true)
        {
            child.anchoredPosition = prePos + RandomOffset(30);
            yield return new WaitForSeconds(0.1f);
        }
    }
    private Vector2 RandomOffset(float max)
    {
        return new Vector2(Random.Range(-max, max), Random.Range(-max, max));
    }
}

```

Result:

And you can add some lerp:

```
using System.Collections;
using UnityEngine;

public class UIPolygonChildrenMove : MonoBehaviour
{
    void Start()
    {
        foreach (RectTransform child in transform)
        {
            StartCoroutine(UpdateChildPos(child));
        }
    }
    IEnumerator UpdateChildPos(RectTransform child)
    {
        Vector2 prePos = child.anchoredPosition;
        Vector2 fromPos = prePos;
        Vector2 targetPos = prePos + RandomOffset(30);
        float duration = 0.2f;
        float pastTime = 0;
        while (true)
        {
            pastTime += Time.deltaTime;
            if (pastTime >= duration)
            {
                fromPos = targetPos;
                targetPos = prePos + RandomOffset(30);
                pastTime = 0;
            }
            var t = pastTime / duration;
            child.anchoredPosition = Vector2.Lerp(fromPos, targetPos, t);
            yield return null;
        }
    }
    private Vector2 RandomOffset(float max)
    {
        return new Vector2(Random.Range(-max, max), Random.Range(-max, max));
    }
}

```

Result:

Edit:

Sorry I haven't played Persona 5, I thought the effect would only render on a black background. Now let's try to make it work in any background.

First find the source code of `Mobile/Particles/Additive`. We can see that it simply does an additive blend by `Blend SrcAlpha One`:

```
Shader "Mobile/Particles/Additive" {
    Properties {
        _MainTex ("Particle Texture", 2D) = "white" {}
    }

    Category {
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
        Blend SrcAlpha One
        Cull Off Lighting Off ZWrite Off Fog { Color (0,0,0,0) }

        BindChannels {
            Bind "Color", color
            Bind "Vertex", vertex
            Bind "TexCoord", texcoord
        }

        SubShader {
            Pass {
                SetTexture [_MainTex] {
                    combine texture * primary
                }
            }
        }
    }
}

```

We can use Stencil to mark the stencil buffer, indicating that this pixel is rendered by a specific shader, and then the rendered pixel will read this mark and process it. In general, we need to output the normal color and mark it during the first rendering, and then perform additive blend if we read this mark during the second rendering.

```
Shader "Custom/myAdditive"
{
    Properties {
        _MainTex ("Particle Texture", 2D) = "white" {}
    }

    Category {
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
        Cull Off Lighting Off ZWrite Off Fog { Color (0,0,0,0) }

        BindChannels {
            Bind "Color", color
            Bind "Vertex", vertex
            Bind "TexCoord", texcoord
        }

        SubShader {
            Pass {
                Stencil
                {
                    Ref 1
                    Comp NotEqual
                    Pass Replace
                }
                SetTexture [_MainTex] {
                    combine texture * primary
                }
            }
            Pass {
                Stencil {
                    Ref 1
                    Comp Equal
                }
                Blend SrcAlpha One
                SetTexture [_MainTex] {
                    combine texture * primary
                }
            }
        }
    }
}

```

If `ref` Not Equal `1`, Execute the first pass, output the color directly, and set `ref` to `1`. If `ref` Equal `1`, Execute the second pass, output the color after additive blend.

Result:
> 7 votes

---
Tags: unity, graphics
---


# Question
Title: Can you make a Unity game for the Nintendo Switch for free without actually uploading it to the EShop?
I want to create a Nintendo Switch game that only I can play, but I don't want to go through the process of uploading it to the EShop but connecting the switch to my PC and putting it on that way. Is there a way to do so without paying? I can't find anything about this on Google.

# Answer
> 2 votes
Officially, you could do this after successfully applying for the closed console platform by becoming a registered Nintendo developer. As part of the typical testing & development cycle, you would be running your game on the Switch before releasing it in the EShop. Unity's information for getting your game on the Nintendo Switch can be found here.

Outside of the official path, what you are describing is known as sideloading (transferring files between two local devices) or running homebrew (a term used to describe unauthorized software). This involves many of the same steps as running pirated games and Nintendo is known to have taken aggressive steps to prevent piracy on the Switch platform. Even if you are pursuing this for non-piracy reasons, you may run the risk of getting your device and/or account banned.

For the above reasons, the Switch is not particularly welcoming for hobbyist development. As an alternative, you might want to consider the Steam Deck which allows you to install and play non-Steam games. You can even develop Unity games directly on a Steam Deck.

---
Tags: unity, nintendo
---


# Question
Title: How do I determine parallax scroll factor?
Implementing parallax scrolling is easy enough. This question is about improving its presentation.

Hand-tuning some parallax scroll factors on multiple layers *works*, but parallax scrolling is meant to mimic a property of linear perspective--it has an underlying trigonometric relationship that I'm sure could benefit from the proper math.

Let's suppose my playfield has a parallax scroll factor 1.0, and a camera distance of 1.0. Given any other layer, how can we calculate its scroll factor from its camera distance, or its camera distance from its scroll factor?

# Answer
There's no universal answer to this. The factor is essentially a function between your camera lens and the actual distance to something being observed.

However, assuming your typical projection would be linear this can be simplified to a rule of three:

```
factor = movement / distance

```

This leads to the conclusion that something at focus distance would have a factor of 1.0. Something at half that distance would result in a factor of 2.0, twice the distance a factor of 0.5, etc.

However, considering how this is always an extreme simplification (e.g. typically not using perspective projection/scaling), you should always pick numbers that feel good, not necessarily strict math. For example, more correct values might result in pixel art jumping irregularly due to precision/rounding errors, which might look worse than something moving too fast (by always whole pixels).
> 1 votes

# Answer
Parallax is an attempt to project prospective movement onto an orthographic surface. In other words, it attempts to place a perspective vanishing point that moves with the center of the screen.

True projective accuracy is not possible given the differences between orthographic and perspective views. As shown in green in the following image:

Note that the coordinates are relative meaning (0 to 1).

The projection error is zero at the the center of the screen, and increases outward.

It should be apparent from the graph that a setting sinusoidal parallax factor would minimize the projection error. Try `arccos`.

The same concept applies to the the vertical offset.

The speed becomes the derivative of the new factor's horizontal component + fudge\_factor * the projection error.

As stated in another answer; There is no single perfect solution. Pick the values that appear best.

The distance to the vanishing point is completely arbitrary, and must be normalized prior to its use in `arccos()`.

The application of similar triangles and other identities are required for formal geometrical proof, which I feel are unnecessary given the variance of the solutions possible. In this case an example image is worth one proof.
> 0 votes

---
Tags: camera, trigonometry, parallax-scrolling
---