# Question
Title: In online multiplayer games, can we transfer a player between two local (or even distant) servers while game processes are running on both servers?
Brief intro 1: about me:

I have this question in the back of my mind for a really long period of time, and I am currently very busy in establishing the offline aspects of the game(will take more than a year from now). So, honestly, I haven't found the time to learn properly about the ins and outs of networked game programming. Thus, I need just general answers so that I can estimate what game designs are possible to make.

Brief intro 2: about the type of game:

Without going into great details, the game is an action multiplayer online game that is safe to assume to have the latency requirements that are roughly half as demanding as a typical First Person Shooter. For instance, let's say a shooter is great at lower than 40-to-50 RTT, then my game is roughly at 100-140 RTT would be good for the gameplay. But with a lot of caveats that I won't delve into in this intro. But every caveats warrants specific challenge on the game design proper.

The question:

* Assume the game is running on an AWS or a Google server.
* Assume a game session is running on a single server, with a few hundreds of players.
* Assume another game session is running on another server.
* Now let's further assume that we need to swap players from one server to another server, on the fly.
* This means that the player will probably be disconnected from one server, and reconnect to the next server mid game session!
* \[A\] How long could it take to do so (switch a client connection from one server to another), assuming the RTT between each party and the other is say 100ms?
* \[B\] Finally, will this practice be substantially faster if the transfer happens within one AWS infrastructure in one city, or one building? Am I even allowed to gain that level of control over the service?

# Answer
> 1 votes
\[a\] Depending on how you do the move it will be RTT + any delay on reconnection logic. If the user is connected to SERVER\_A:PORT\_A and you tell them to connect to SERVER\_B:PORT\_B and they receive that message + disconnect + reconnect to the new server then your delay is minimal. If you're hiding the server details from the client and going through some kind of proxy that routes them to the correct location then your delay includes whatever processing/routing logic you include at that layer.

\[b\] It'll be faster within an AWS Region than between regions. But other than that the next level you'll see real consistent improvements will likely be if you're moving them between servers within the same Local Zones. That will be significantly faster than anything else.. but maybe not enough to really matter. Note that it's rare that your clients are connecting directly to your servers and you have no control over what hops their ISPs are taking. It may not be worth the increased price for the better latency you're getting. Especially if your latency requirements are more forgiving.

---
Tags: networking, multiplayer, client-server
---


# Question
Title: How to implement WebRTC in a Godot project that already has communication through WebSockets?
I'm currently working on a fast-paced multiplayer sports game using Godot. The players' movements and actions are already being synchronized with WebSockets and Channels using a Node.js server. I now want to replace (part of) the WebSocket communication and synchronization between the clients by WebRTC to lower latency. I have been looking at this demo project by Godot as I think it may provide what I need.

However, I'm a bit confused about how to proceed and I have two questions based on the assumed knowledge I currently have:

1. Can I re-use the same WebSocket Channel to send WebRTC messages or do I need to create a separate WebRTC Channel for that?
2. How do I know the "address" of other players that I want to send WebRTC messages to? Should I get their id from the channel or use an IP address, or how does that generally work?

If possible, please also let me know whether some my assumptions are wrong and why.

PS. I wanted to add the `webrtc` tag to this question but it does not exist yet and I don't have enough reputation to add it. If there is anyone with enough reputation to add it that would be great.

# Answer
> 1 votes
1. You can not, as far as I'm aware, re-use the same WebSocket Channel to send WebRTC messages. WebSockets are really just a persistent TCP based connection between client/server that allow for bi-directional communication. Infact, if you look at what a WebSocket connection is under the hood - it actually connects as a raw HTTP connection and then passes an `upgrade` header that allows it to transition to a websocket. WebRTC is different and allows for different "modes" in its channels (that correspond to tcp-like or udp-like) which WebSockets just don't support. this answer on stack overflow does a good job of quickly breaking down what these modes are.
2. This is the hardest part of WebRTC. Due to Network Address Translation p2p connections are quite difficult. In some cases they are entirely impossible. You've probably seen terms like STUN, TURN, and ICE thrown around when talking about WebRTC. These protocols are what enable devices behind NAT to communicate with each other either directly, or through a coordinating server. AnyConnect has a really good intro to how these things work and links to all the necessary RFCs. Essentially, this means that to allow peers to discover each other you need to run a service that lets them do that (STUN). In some cases, where they can't directly establish communication, you can optionally provide a service that relays information between the two (TURN).

---
Tags: multiplayer, godot, websocket
---


# Question
Title: How to check if one object's local bounding box contains another
I am currently trying to check whether the first object contains a second.

I first tried to use the bounding box, but it is defined in world space, so it is not working with my rotated cubes.

Then I found mesh bounds, but this is not working totally: nothing happens.

Here is my code:

```
Bounds bounds = GetComponent<MeshFilter>().mesh.bounds;
if (bounds.Contains(target.transform.position))
{
    target.GetComponent<MeshRenderer>().material.color = Color.green;
}
else
{
    target.GetComponent<MeshRenderer>().material.color = Color.white;
}

```

Then I found one more way, but still no luck:

```
bool IsInside(GameObject obj1, GameObject obj2)
{
    Vector3 pos = obj1.transform.position;
    pos = obj2.transform.InverseTransformPoint(pos);
    return obj2.GetComponent<Collider>().bounds.Contains(pos);
}

```

# Answer
> 0 votes
You're still mixing and matching different coordinate spaces.

`Mesh.bounds` is defined in local space. You can't use it to check for containment of a point in world space.

Similarly, `Collider.bounds` is defined in world space. You can't use it to check for containment of a point in local space.

Be sure to read the documentation and understand what coordinate spaces you're working in to avoid this kind of mix-up.

A corrected version of your code would look like this:

```
Vector3 worldTarget = target.transform.position;
Vector3 localTarget = transform.InverseTransformPoint(worldTarget);
Bounds localBounds = GetComponent<MeshFilter>().mesh.bounds;

if (localBounds.Contains(localTarget))
{

```

or

```
bool IsInside(GameObject obj1, GameObject obj2)
{
    Vector3 worldPos = obj1.transform.position;
    Bounds worldBounds = obj2.GetComponent<Collider>().bounds;
    return worldBounds.Contains(worldPos);
}

```

Note how using `local` or `world` in the variable names helps keep track of the spaces being used, letting you quickly double-check that you're matching up local space points with local space bounds, or world space points with world space bounds.

---
Tags: unity, c#, collision-detection, transformation, bounding-boxes
---


# Question
Title: Material Transparency is not showing in the build
I have came across a weird situation. I have a gameobject that has a standard shader material. The material rendering mode is set to Transparent. This is working fine in the Unity editor, but its transparency is not showing in the build mode.

Remember I am creating an asset bundle of the game objects. Then download it in the player. Yes, I know that the shader variant should be included in the build. So I have this standard shader in the build. On more thing I want to share is that I try to debug the player. Then, I found that the Keywords include only `DIRECTIONAL LIGHTPROBE_SH` while the same materail in the editor shows keyword `DIRECTIONAL LIGHTPROBE_SH _ALPHABLEND_ON_EMISSION`.

Remeber we are createing asset bundle in a seperate workspace while rendering the Asset bundle in a separate workspace. Here are the steps

1. Imported the fbx in asset bundle creator workspace and export asset bundle from it.
2. We have a seperate workspace that import the asset bundle on runtime.

**Update:** I fix this issue by when I instantiated the asset bundle I just enable the `_ALPHABLEND_ON` and `_EMISSION` keyworkds on the material. (check my answer) But i don't want this fix because it will add more time in overall asset bundle and downloading and instantaite process.

**Update:** I found that i am creating asset bundle in a seperate workspace and loading it in a different workspace. If i am making the bundle in the scene workspace then, it work fine. **But why? How to resolve this?**

# Answer
I fixed this issue by enabling the \_ALPHABLEND\_ON and \_EMISSION keywords on the material when I instantiated the asset bundle.

```
private void MaterialSettings(GameObject go)
    {
        Renderer[] renderers = go.GetComponentsInChildren<Renderer>();
        foreach (Renderer renderer in renderers)
        {
            foreach (Material material in renderer.sharedMaterials)
            {
                ApplyTransparency(material);
            }
        }
    }

    private static void ApplyTransparency(Material material)
    {

        material.EnableKeyword("_EMISSION");
        material.EnableKeyword("_ALPHABLEND_ON");

    }

```

**However, I do not want to use this fix because it will increase the overall time required for downloading and instantiating the asset bundle.**
> 0 votes

---
Tags: unity, shaders
---


# Question
Title: How to make a child sprite appear to grow and shrink around its center when scaling its parent GameObject in Unity?
I have a GameObject with a Sprite Renderer on it. The Pivot of the Sprite itself is Bottom Left (this can not be changed).

I created a parent to this GameObject, and want to grow and shrink the Scale of this Parent... so that the Sprite Renderer on the child appears to grow and shrink around the center of the sprite. I put a Rect Transform on the parent and set the X and Y pivot to 0.5.

But when I change the Scale of the Paremt gameobject, the Sprite Renderer appears to grow and shrink around the bottom left of the sprite (not the center).

How do I fix this?

# Answer
> 0 votes
I ended up creating two versions of the Sprite: Sprite 1 had the pivot at Bottom Left, and Sprite 2 had the pivot at the Center.

Then I did the following:

1. I made the GameObject's Sprite Renderer switch from Sprite 1 to Sprite 2 (with a centered Pivot).
2. I wrote a function which moved the GameObject position a bit algorithmically to compensate for the change in Pivot location.

Then I was able to grow and shrink the Scale of the GameObject, and the Sprite appeared to grow/shrink from the center of the object.

However I only wanted this to be a temporary change. So I also wrote code to reverse the above changes, so that the GameObject was once again using Sprite 1.

---
Tags: unity
---


title: How to scale down noise intensity?

text:
# Question
Title: How to scale down noise intensity?
I'm currently making a planet and for that, I added noise, to create terrain on the surface. The method I'm using is creating simplex noise (that ends up looking like the image below)

And I write that data to an image file, like the one above this text, and from there, I bind the noise image to my sphere, like below

And finally, through some shader code, I offset some sphere vertices using the noise. The problem I'm experiencing is the noise intensity is way more than I expected or wanted it to be. This is how intense the noise is

As you can see, it looks more like an explosion than a planet, and I don't know how to scale the noise down, so it's not as intense as shown below. I'm using FNL (FastNoise Lite) for the noise for better context. Below is some of my code (the code that's important and specific to this problem)

Here is the function where I create the noise

```
#ifndef NOISE_H_INCLUDED
#define NOISE_H_INCLUDED

#include <FastNoiseLite/C/FastNoiseLite.h>
#include <time.h>

void write_noise_2d(int w, int h, int channels_num)
{
        // create random seed for noise
        srand(time(NULL));
        float seed = (float)rand()/RAND_MAX;
        // initialize noise
        fnl_state noise = fnlCreateState();
        noise.noise_type = FNL_NOISE_OPENSIMPLEX2;
        noise.octaves = 8;
        noise.lacunarity = 2.0f;
        noise.gain = 0.5f;
        noise.seed = (int)seed;
        printf("Seed: %i\n", seed);
        noise.fractal_type = FNL_FRACTAL_FBM;
        // create data array for noise
        float* noise_data = malloc(w * h * channels_num * sizeof(float));
        int index = 0;
        // create noise throughout the entire image
        for(int x=0; x<w; x++)
        {
            for(int y=0; y<h; y++)
            {
                noise_data[index++] = (1 + fnlGetNoise2D(&noise, x, y)) * 128;
            }
        }

        stbi_write_jpg("textures/noisemap.jpg", w, h, channels_num, noise_data, w * channels_num);
        free(noise_data);
}

#endif // NOISE_H_INCLUDED

```

Here is the code where I use the noise data

```
// write noise data from FNL to texture
write_noise_2d(512, 512, 2);
// now we load the noise map back into the program to be used later
unsigned int texture;
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
// from what I heard no need to specify gl_repeat because that is the default
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_MIPMAP);

// image stats
int width, height, num_channels;
// load image
unsigned char* data = stbi_load("textures/noisemap.jpg", &width, &height, &num_channels, 0);
if(data)
{
    // image options
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_SHORT, data);
    glGenerateMipmap(GL_TEXTURE_2D);

    // send to the GPU for processing
    set_int(earthlike, "noisemap", 0);
    printf("Loaded noise map of %i by %i\n", width, height);
}
else
{
    printf("Failed to load noisemap\n");
}
// deallocate data that's no longer needed
stbi_image_free(data);
remove("textures/noisemap.jpg");

```

Here's where I apply the noise data to the sphere (offset the sphere vertices)

```
#version 450 core

// determines what type of tessellation to do
layout(triangles, equal_spacing, cw) in;

// input from control shader
in vec3 vertex_coord[];
// output vec
out vec3 vert;
// simplex noise goes here
uniform sampler2D noisemap;
// allows for object transformations
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

out float height;

void main()
{
    // gets barycentric coordinates from the triangles
    vec3 x = gl_TessCoord.x * vertex_coord[0];
    vec3 y = gl_TessCoord.y * vertex_coord[1];
    vec3 z = gl_TessCoord.z * vertex_coord[2];
    // used for texturing, terrain, and other various maps (moisture, temperature, etc.)
    height = texture(noisemap, vec2(vec3(gl_TessCoord.x, gl_TessCoord.y, gl_TessCoord.z))).r;
    // makes every triangle an equal distance from the center through normalizion (that's how spheres are formed)
    vec3 pos = normalize(x + y + z) * height;
    // output tessellated shape
    gl_Position = projection * view * model * vec4(pos, 1.0);
}

```

# Answer
> 1 votes
One simple approach is to bracket your noise between a minimum and maximum value - here expressed as the elevations of the deepest valley or undersea trench on your planet vs the peak of the tallest mountain:

```
float deepestValley = 0.8f;
float highestMountain = 1.2f;
float heightRange = highestMountain - deepestValley;

float noise = texture(noisemap, gl_TessCoord.xy).r;

float height = deepestValley + heightRange * noise;

```

By changing the first two numbers there, you change the overall radius of the planet and the sharpness of its features.

---
Tags: opengl, shaders, glsl, sphere, simplex-noise
---


# Question
Title: Noise in compute shader related to threadsPerGroup
I have been working on a metaball compute shader for roughly 3 months now, and the only issue I have to resolve is noise in the output Dest\[id.xy\]. I also asked GPT 4 about the crux of the issue and how to fix it, to no avail. I really need help from someone who has substantial experience with compute shaders. The issue is the noise as you can see:

When I change the threadsPerGroup to a lower number like 1, there is much less noise, but now the game is ridiculously laggy. Furthermore, there is still some noise, which is not the behavior I want.

ChatGPT mentioned memory grouping as a potential solution, and I have no idea how to use them, and the documentation or tutorials for Unity compute shader programming is practically non-existent. Please help me to understand how to minimize noise while maximizing game performance at the same time, without relying on the `threadsPerGroup`, so that I can have many threads while still maintaining the integrity of the computations done in the compute shader.

MainCameraController.cs

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

[RequireComponent(typeof(Camera))]
public class MainCameraController : MonoBehaviour
{
    //Game Object Manager
    public GameObject objectManager;
    private ObjectManagerController objectManagerController;
    //Shader
    private ComputeShader metaballComputeShader;
    private Camera _mainCamera;
    public Camera _depthCamera;
    public Camera _operationCamera;
    //Compute Shader variables
    private int threadsPerGroup = 8;
    private int kernelHandle = 0;

    //List to maintain game objects
    private List<GameObject> colorSlimes = new List<GameObject>();
    private RenderTexture depthTextureArray;
    private RenderTexture colorTextureArray;

    void Awake() {
        //depthTextureArray = new Texture2DArray(_mainCamera.pixelWidth, _mainCamera.pixelWidth, 1, TextureFormat.ARGB32, true, false);
        //colorTextureArray = new Texture2DArray(_mainCamera.pixelWidth, _mainCamera.pixelWidth, 1, TextureFormat.ARGB32, true, false);
        Debug.Log("Awake for Main camera.");
        objectManagerController = objectManager.GetComponent<ObjectManagerController>();

        //Initialize texture arrays
        colorTextureArray = objectManagerController.colorTextureArrayGlobal;
        depthTextureArray = objectManagerController.depthTextureArrayGlobal;

        //Initialize Shader
        metaballComputeShader = objectManagerController.metaballComputeShaderGlobal;

        //Initialize color slime List
        colorSlimes = objectManagerController.colorSlimesGlobal;
    }

    void Start()
    {
        kernelHandle = metaballComputeShader.FindKernel("CSMain");
    }

    // private void Reset()
    // {
    //     _mainCamera = GetComponent<Camera>();
    // }

    // private void OnEnable() {
    //     Debug.Log("OnEnable for main camera.");
    //     if (!_mainCamera) _mainCamera = GetComponent<Camera>();

    //     if (_mainCamera) _mainCamera.depthTextureMode |= DepthTextureMode.Depth;
    //     _mainCamera.transparencySortMode = TransparencySortMode.Orthographic;
    // }

    // private void OnDisable()
    // {
    //     if (_mainCamera) _mainCamera.depthTextureMode = DepthTextureMode.None;
    // }

    // private void OnDestroy()
    // {
    //     if (_mainCamera) _mainCamera.depthTextureMode = DepthTextureMode.None;
    // }

    //Apply metaball effect
    public void OnRenderImage(RenderTexture src, RenderTexture dest) {
        Debug.Log("Metaball Shader");
        //Thread control
        int threadGroupX = Mathf.CeilToInt(src.width / (float)threadsPerGroup);
        int threadGroupY = Mathf.CeilToInt(src.height / (float)threadsPerGroup);

        //depthTextureArray.dimension = UnityEngine.Rendering.TextureDimension.Tex2DArray;
        //depthTextureArray.enableRandomWrite = true;
        //depthTextureArray.volumeDepth = colorSlimes.Count;
        //depthTextureArray.Create();

        //colorTextureArray.dimension = UnityEngine.Rendering.TextureDimension.Tex2DArray;
        //colorTextureArray.enableRandomWrite = true;
        //colorTextureArray.volumeDepth = colorSlimes.Count; ?
        //colorTextureArray.Create();

        //Prepare buffers
        //Initialize array of 25s
        ComputeBuffer minimumDistanceValueBuffer = new ComputeBuffer(colorSlimes.Count, sizeof(float));
        //Maybe the problem is due to the clash between SetData from c# and resetting
        //This value from shader.
        // List<float> minimumDistances = new List<float>();
        // for(int i = 0; i < colorSlimes.Count; i++) {
        //     minimumDistances.Add(20);
        // }
        //minimumDistanceValueBuffer.SetData(minimumDistances);
        ComputeBuffer minimumDistancePixelBuffer = new ComputeBuffer(colorSlimes.Count, sizeof(float)*4);

        //Make a writable copy of src and dest
        RenderTexture srcWritable = new RenderTexture(src.width, src.height, 32, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default){ useMipMap = false };
        srcWritable.enableRandomWrite = true; // Set the UAV usage flag
        srcWritable.Create();

        RenderTexture destWritable = new RenderTexture(srcWritable);
        destWritable.Create();
        RenderTexture.active = src;
        Graphics.Blit(src, srcWritable);

        //Fill compute shader
        metaballComputeShader.SetTexture(kernelHandle, "Src", srcWritable);
        metaballComputeShader.SetTexture(kernelHandle, "Dest", destWritable);
        metaballComputeShader.SetBuffer(kernelHandle, "MinimumDistancePixelBuffer", minimumDistancePixelBuffer);
        metaballComputeShader.SetBuffer(kernelHandle, "MinimumDistanceValueBuffer", minimumDistanceValueBuffer);
        metaballComputeShader.SetFloat("MaxWidth", src.width);
        metaballComputeShader.SetFloat("GameObjectListCount", (float)colorSlimes.Count);
        metaballComputeShader.SetFloat("MaxHeight", src.height);
        metaballComputeShader.SetTexture(kernelHandle, "ColorTextureArray", colorTextureArray);
        metaballComputeShader.SetTexture(kernelHandle, "DepthTextureArray", depthTextureArray);
        metaballComputeShader.Dispatch(kernelHandle, threadGroupX, threadGroupY, 1);

        //Write metaball effect to final dest
        Graphics.SetRenderTarget(destWritable);
        Graphics.Blit(destWritable, dest);

        RenderTexture.active = null;
        minimumDistancePixelBuffer.Release();
        minimumDistanceValueBuffer.Release();
        srcWritable.Release();
        destWritable.Release();
        Debug.Log("Metaball effect complete!");
    }
}

```

MetaballComputeShader.compute

```
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    //Dest[id.xy] = float4(1,1,1,1);
    // Convolution:
    //  1  0 -1
    //  2  0 -2
    //  1  0 -1
    //25x25 matrix
    //13th pixel == center x == center y
    //For every pixel, after doing operations on itself, start from itself's
    //id.xy - 13~self~+11
    //First check whether this pixel is opaque
    //Src[id.xy]
    //DepthTextureArray.Load(uint3(id.xy, i))
    //color = //either Src[id.xy] if first or DepthTextureArray.Load(uint3(id.xy, depthSearchCount++)) for the rest
    //If Src is not opaque, rest assured.
    if(int(id.x) - startX < 0 || int(id.x) + startX >= MaxWidth || int(id.y) - startY < 0 || int(id.y) + startY >= MaxHeight) {
        //Overflow prevention.
        //For now, ignore screen edges.
        return;
    }
    //RWStructuredBuffer<float4> minimumDistancePixelBuffer;

    float4 MinimumDistancePixelBufferTest[2];
    for (int i = 0; i < (int)GameObjectListCount; i++) {
        MinimumDistanceValueBuffer[i] = 20;
        //Value here must be equal to value set in
        MinimumDistancePixelBufferTest[i].rgba = float4(1, 1, 1, 1).rgba;
        //minimumDistancePixelBuffer[i] = float4(0.5,0.5,0.5,0.5);

    }

    //Dest[id.xy] = Src[id.xy];
    float4 srcPixel = Src[id.xy];
    if(!all(srcPixel <= nullColor)) {
        int numberOfVisibleObjectsAtCurrent = 0;
        for(int i = 0; i < GameObjectListCount; i++) {
            float4 colorAtDepth = ColorTextureArray.Load(uint3(id.xy, i));
            if(!all(colorAtDepth <= nullColor)) {
                if(all(colorAtDepth != srcPixel)) {
                    srcPixel += colorAtDepth;
                }
                numberOfVisibleObjectsAtCurrent++;
            }
        }
        //Dest[id.xy] = srcPixel / numberOfVisibleObjectsAtCurrent;
        //Dest[id.xy] = Dest[id.xy] / GameObjectListCount;
        //Dest[id.xy] = Src[id.xy];
        return;
    }
    else {
        //Is Src[id.xy] at that location visible? If not, move on
        //int2(-13, -13)
        //Since we're now subtracting,
        //Dest[id.xy] = Src[id.xy - int2(25, 0)];
        //Dest[id.xy] = float4(1,1,1,1);
        bool emptyMatrix = true;
        //Something's wrong with the for loop
        //[loop]
        //Problem had to do with using startX and startY instead of 25(actual number)
        //Maybe Unity compute shaders are too dumb to recognize initialized variables
        //Don't necessarily have to unroll, but use numbers instead of variables when defining
        //condition in for loop.
        for(int i = -24; i <= 25; i++) {
            for(int j = -24; j <= 25; j++) {
                //int2 currentPosDelta = int2(r, g);
                float4 srcPixel = Src[id.xy - int2(j, i)];
                //float4 minimumDistancePixel = float4(0,0,0,0);
                //minimumDistancePixel.rgba = srcPixel.rgba;
                //Dest[id.xy] = Src[id.xy - int2(15, 0)];
                if(!all(srcPixel.rgba <= nullColor.rgba)) {
                    //This means we have found an opaque pixel in the
                    //25x25 convolution matrix
                    //What I want to do:
                        //Update minimum distance for each game object based on
                        //
                    //emptyMatrix = false;
                    //Line below makes noise in game view
                    //No longer makes noise
                    float minimumDistance = CalcMinimumDistance(int2(id.xy - int2(j, i)), int2(id.xy));
                    //[unroll(2)]
                    for(int k = 0; k < (int)GameObjectListCount; k++) {
                        float4 minimumDistancePixel = ColorTextureArray.Load(uint3(id.xy - int2(j, i), k));

                        //minimumDistance < MinimumDistanceValueBuffer[k] &&
                        //minimumDistance < MinimumDistanceValueBuffer[k] &&
                        //&& !all(minimumDistancePixel.rgba <= nullColor.rgba)
                        if(any(minimumDistancePixel.rgba > nullColor.rgba) && minimumDistance < MinimumDistanceValueBuffer[k]) {
                            //No more noise
                            MinimumDistanceValueBuffer[k] = minimumDistance;
                            //The line below works fine.
                            //Setting MinimumDistancePixelBuffer anything other than 1,1,1,1 causes noise
                            //For some stupid reason, the value I set here must agree with the values I set in the beginning of the function
                                //
                            MinimumDistancePixelBufferTest[k].rgba = float4(0.5,0.5,0.5,0.5).rgba;
                            // Add a memory barrier here to ensure proper synchronization
                            GroupMemoryBarrierWithGroupSync();
                            //float4(1,1,1,1).rgba;
                            //emptyMatrix = false;
                            // we've checked that this works
                            emptyMatrix = false;
                        }
                    }
                    //Noise had to do with sizeof(float) in a compute shader slightly larger
                    //than the actual sizeof(float) in compute shader.

                    //float minimumDistance = CalcMinimumDistance(id.xy - int2(j, i), id.xy);

                    //Sample Depth Texture at that location: iterate through the z of that id.rg
                    //To see all the game objects that the pixel is part of.
                        //A minimum distance will be calculated for each game object.
                    //float minimumDistance = CalcMinimumDistance(id.xy - int2(j, i), id.xy);
                    // for(int b = 0; b < 2; b++) {
                    //     srcPixel.rgba = ColorTextureArray.Load(uint3(id.xy - int2(j, i), b)).rgba;
                    //     if(minimumDistance < MinimumDistanceValueBuffer[b] && !all(srcPixel <= nullColor)) {

                    //         MinimumDistanceValueBuffer[b] = minimumDistance;
                    //         MinimumDistancePixelBuffer[b].rgba = srcPixel.rgba;

                    //     }
                    //     minimumDistancePixel.rgba += srcPixel.rgba;
                    // }

                    //Dest[id.xy] = minimumDistancePixel / GameObjectListCount;
                    //emptyMatrix = false;
                    //emptyMatrix = false;
                }
            }
            //Dest[id.xy] = float4(1,1,1,1);
        }
        //emptyMatrix = false;

        //At this point, either emptyMatrix or we have all the information needed to apply to this pixel
        if(!emptyMatrix) {
            //Dest[id.xy] already stores average Src of the location with min dist
            //Metaball calculation
            //double not supported
            float avgDistance = 0;
            float4 totalColor = float4(1, 1, 1, 1);
            float avgColorRed = 0;
            float avgColorBlue = 0;
            float avgColorGreen = 0;
            float avgColorAlpha = 0;

            //Maybe think about storing each rgba in a separate float
            //Simple average
            int averageCounter = 1;
            for(int i = 0; i < (int)GameObjectListCount; i++) {
                if(MinimumDistanceValueBuffer[i] < 20) {
                    avgDistance += MinimumDistanceValueBuffer[i];
                    //totalColor.rgba = MinimumDistancePixelBuffer[i].rgba;
                    //Dest[id.xy].rgba += MinimumDistancePixelBuffer[i].rgba;
                    //avgColorGreen += MinimumDistancePixelBuffer[i].g;
                    //avgColorBlue += MinimumDistancePixelBuffer[i].b;
                    //avgColorAlpha += MinimumDistancePixelBuffer[i].a;
                    //averageCounter++;
                    //totalColor = tmpColor
                }
            }
            avgDistance /= averageCounter;
            //float4 avgColor = round(totalColor / averageCounter);
            // avgColorRed = avgColorRed / averageCounter;
            // avgColorGreen = avgColorGreen / averageCounter;
            // avgColorBlue = avgColorBlue / averageCounter;
            // avgColorAlpha = avgColorAlpha / averageCounter;
            //float4 avgColor = float4(avgColorRed, avgColorGreen, avgColorBlue, avgColorAlpha);
            if(avgDistance < 10) {
                //Dest[id.xy] = avgColor;
                //Storing avgColor in Dest causes noise.
                //What is noise?
                    //Dest[id.xy] is not fixed
                    //MinimumDistancePixelBuffer[0] is not fixed
                    //At the end of the nested for loop, MinimumDistancePixelBuffer[0] must be fixed to the
                    //minimum distance from game object 0 to a pixel in the convolution matrix.
                    //The problem with the algorithm right now:
                    //
                Dest[id.xy] = MinimumDistancePixelBufferTest[1];
            }
            // for(int i = 0; i < (int)GameObjectListCount; i++) {
            //     MinimumDistanceValueBuffer[i] = 20;
            // }

            // if(totalWeight > 0) {
            //     Dest[id.xy] = accumulatedColor / totalWeight;
            // } else {
            //     Dest[id.xy] = srcPixel;
            // }
            // float dynamicThreshold = count > 0 ? (totalDistance / (25.0f * count)) : 0;
            // if(dynamicThreshold > 0.4) {
            //     Dest[id.xy] = weightedColor / accumulatedColor / totalWeight;;
            // }
            //game object0Color * distanceN + game object1Color * distanceN-1 ... / aggregate distance
            //This order does not necessarily follow order of creation for game objects
            //Dest[id.xy] = float4(1,1,1,1);
        }
        // else {
        //     Dest[id.xy] = Src[id.xy];
        //     //Dest[id.xy] = float4(1,1,1,1);
        // }
        //Pixel color of game object with min distance will be multiplied by max distance
        //average = each game object's rgba * (minOfMin/)
        //Dest[id.xy] = float4(1,1,1,1);
        //Dest[id.xy] = Src[id.xy];
        return;
    }
}

```

# Answer
ComputeShaders are related to `ThreadGroups` and loops should be avoided as much as possible

If you want to dispatch on only one `threadGroup` `.. yourShader.Dispatch(1,1,1)`, then, you limit to 32x32 max texture/matrix. then the max numthreads per group you can run (asuming the shader is compiled on sm5) is 1024: `[numthreads[x,y,z)]` where x\*y\*z=1024

###### Your case

if running on `[numthreads(8,8,1)]` with `..Dispatch(1,1,1)` will cover only 8x8 pixels of `Dest[]` texture.

* Make sure that `Dest[]` is a 8x8 texture otherwise you wont cover all the texture
* Make sure `Dest[]` dimension is of power of two, if let's say is 10x10, last two row&column wont be covered

###### Example:

Assume you want to manipulate a texture/matrix of resolution 96x96

GPU:`[numthreads(32,32,1)]`

CPU:`..Dispatch(ceil(Tex.Width/32, ceil(Tex.Height/32), 1)` -\> `.. yourShader.Dispatch(3,3,1)`.

This dispatch will cover the entire texture by running 1024 numthreads 3 times on X, 3 times on Y, 1 on Z. Here, we have to dispatch 3,3,1 because we cannot have `numthreads > 1024` ~~\[numthreads(96,96,1)\]~~
> 0 votes

---
Tags: unity, c#, hlsl, compute-shader
---


title: mix and matching hats and hairstyles

text:
# Question
Title: mix and matching hats and hairstyles
I making a character creation scene, I learned how armors work and how to cut the players in pieces to mix and match everything.... but matching hair styles with hats is incredibly tedious... since every gender and race has at least 12 hair styles and females have can have up to 38 hair styles...

am I like supposed to take every single hair style and making a different version for every single hat/helmet to fit with it? or are the better systems?

From the mmos I have played, I noticed that no one affronted this problem. most big game development studios just ignore this problem.... in most MMOS if you wear a hat it either clips horribly through the hair or you just can't wear headgear at all.... and in other games like lineage or tera, every hat as a default hair style so say if you picked hairstyle 1 in character creation then in game find a hat and wear it, your hair will switch to maybe hairstyle 12... like you maybe choose a bald character but then wear a pirate hat and suddently have long hair

# Answer
> 1 votes
It takes work. Are you "supposed" to do it...? Well, no. As you have pointed out many games avoid the problem. It could have made sense to them to start with the minimum viable version of the feature, and only expand on if if they find demand from the players.

Think about it form the point of view of those studios. They could pay artists to do this tedious work, right? It could be hard to financially justify it without a direct return on investment (i.e. selling them on micro-transactions). But if they find out in practice that there is demand, there might be a price players are willing to pay.

---

Now, you don't have to do all or nothing.

You can use bone attachments for the hats, so you are not making every combinations. That leaves you at risk of clipping... To address that, you could ban the use of hats on hairstyles that would result in clipping.

Furthermore, establish guidelines to make hairstyles and hats such that they avoid clipping. Then you can offer a selection of hairstyles that work with hats, and others that don't (which would be the extravagant ones, since they are not constrained by the guidelines to avoid clipping).

So no hat would make hair appear, players would have more than one option for hairstyle using hats, and no hat would cause clipping, and extravagant hairstyles still exist.

---

And why would a hairstyle not work with hats? Well, that is what happens in reality... Or, if you prefer, think that adding a hat to the hairstyle modifies it.

Which would translate to having a version of the hairstyle that works with hats, and another that does not. And you might even automatically switch between them.

Furthermore, if the versions of the hairstyles that work with hats are only used when the player has a hat. Then creating them could be as simple as removing the parts of the geometry that could cause clipping.

---
Tags: 3d, blender, godot
---


# Question
Title: Struggling to launch my player backwards after it comes into contact with an enemy object
I am pretty new to Unity... watched quite a few of Brackey's and other YouTube videos along with a lot of research. I have been trying to add an impulse to my player so that after it comes in contact with an enemy my player will be launched backwards. I have tried setting the horizontal speed to zero for a short time as the character impulse takes effect... Still not working. The 2D rigid body has a mass of 100, a gravity scale of 10, and continuous collision detection. Plz hlp...

Further Details, in case it helps:

* It is a 2D mobile game that I'm building on Unity version 2021.3.18f1
* I have added a virtual joystick that converts the input into a normalized vector3 InputDirection.
* Code has been written in CSharp.

```
  private void OnCollisionEnter2D(Collision2D col)
  {

  if (col.collider.tag == "Ground")
  {
      canJump = true;
  }

  if (col.collider.tag == "Slime")
  {
      EnemyCollision(1000000, 15, 0.5f);
  }
  if (col.collider.tag == "Crocodilian")
  {
      EnemyCollision(10000000, 25, 1.0f);

  }

  }

  private void EnemyCollision(int hitForce, int damage, float time) {
      TakeDamage(damage);
      speed=0;
      if(facingDirection != Vector3.right){
          rb.AddForce(Vector2.right * hitForce, ForceMode2D.Impulse);
      } else {
          rb.AddForce(Vector2.left * hitForce, ForceMode2D.Impulse);
      }
      StartCoroutine(EnableMovementAfterDelay(time));
 }

  private IEnumerator EnableMovementAfterDelay(float delay)
{
    yield return new WaitForSeconds(delay);
    speed = 80f;
//speed is multiplied by the InputDirection.x vector inside Update(). So, by setting it to 0, I am hoping it stops movement.
// Looks like this: rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);
}

```

# Answer
> 0 votes
Your mistake appears to be here:

> //speed is multiplied by the InputDirection.x vector inside Update(). So, by setting it to 0, I am hoping it stops movement.
>
> // Looks like this: rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);

This would do the exact opposite of what you hope it would do. `horizontalInput * 0` is 0. So you set the horizontal speed to a value of 0. Which means that you explicitly tell the rigidbody to stop where it is.

If you want the player to be in a "pushed away" state where its velocity is controlled by the physics engine, then you need to leave the velocity as it is, so the physics engine can control it.

A quick and easy way to do that is to just add a `bool` flag with a name like "playerControlEnabled" to the script that controls the player movement and have your "EnemyCollision" code set and unset that flag. When that variable is `false`, you simply skip the code that manipulates the player velocity by wrapping it in a `if(playerControlEnabled) {` block.

There are many other solutions to combine physics-driven and player-driven movement. Some of them might result in much better game-feel than this simple on-off switch. Like interpolating between the physics velocity and the player input velocity, adding the two together or changing the player controls to also use `AddForce` instead of directly manipulating the velocity. But explaining all of these would break the scope of this answer.

# Answer
> 0 votes
So, I have now managed to solve all of the issues (With major help from Mr. Philipp)-\>

1. Instead of adding an impulse to the object. I have emulated that behavior using transformations. After a time delay the object's position is offset by a certain amount. This way the motion can be controlled by the time stamps and the distance it is being offset by.
2. You can mess around with the time stamps and distances more easily. Here is my code and the adjustments that work for me. At the bottom I have included the if/else statements in my Update() that toggles the movementInput on and off.

```
 private void EnemyCollision(float push, int damage, float time)
 {
   TakeDamage(damage);
   beenHit = true;
   PushBack(push);
   StartCoroutine(EnableMovementAfterDelay(time)); // enable movement after 0.5 seconds
   }
 public void PushBack(float offset)
 {
   if(facingDirection == Vector3.right)
 {
   transform.position += new Vector3(-offset * 0.5f, 0, 0);
   DelayedOffset(new Vector3 (-offset,0, 0), 0.6f);
   DelayedOffset(new Vector3 (-offset,0, 0), 0.5f);
   DelayedOffset(new Vector3 (-offset,0, 0), 0.2f);
 } else {
   transform.position += new Vector3(offset, 0, 0);
   DelayedOffset(new Vector3 (offset,0, 0), 0.6f);
   DelayedOffset(new Vector3 (offset,0, 0), 0.5f);
   DelayedOffset(new Vector3 (offset,0, 0), 0.2f);
 }
 }

 //After a certain amount of time should offset the position
 private IEnumerator DelayedOffset(Vector3 offset, float delay)
 {
   yield return new WaitForSeconds(delay);
   transform.position += offset;
 }

 private IEnumerator EnableMovementAfterDelay(float delay)
 {
   yield return new WaitForSeconds(delay);
   beenHit = false; // restore horizontal movement
 }

 //The code inside of Update() for toggling joystick movement on and off.
 if(beenHit){
     speed = 1.0f;
     horizontalInput = rb.velocity.x;
 } else {
     speed = 160.0f;
     horizontalInput = InputDirection.x;
 }
 rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);

```

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


# Question
Title: How would you model quests in the database for the most variability?
I am using Postgres to create an Online RPG.

I am creating a game and I want quests to be as variable as possible. I am wondering if JSONB is the solution. The alternative is to create a bunch of different flags for quest types like:

is\_kill, is\_speak\_to\_npc, is\_gather\_resource, is\_...

Not sure what else would be there at this point but you get the idea.

Wondering if using JSONB will be an issue when trying to query for quests in the future. Any ideas are appreciated.

# Answer
> 0 votes
I created tables that store various sections of the quests in a row, rather than trying to store in some sort of JSONB or other format. You can't query nicely in those unless you have things split out into parts already.

Having said that, I pass back to my game client in a JSON format, but handle that on the server end.

I also split out quest sections into individual rows, so that a single quest can have multiple sections, requirements and potentially have to be performed in a specific order or concurrently. That allows my game client to know which quest part is active at any given time, making it easier to track advancements and progress, but also opening up different requirements as needed.

Lastly, I'd point out that whether you store the data in a normal row format, or each quest as an object ready to be passed to your game really, in the grand scheme of things, doesn't matter. You might have a different interface for your editor setup, and a different one for clients to query.

I have a development interface that lets my editor query, pass data, modify results etc but transform that when I promote the data, so that the load on the client-servers is minimised. Horses for Courses mate.

---
Tags: mmo, quests
---


# Question
Title: Event listeners in code vs persistent event listeners inspector
This is by far the biggest thing I always find myself going in circles over and can never seem to find an approach I'm happy with - setting up regular UnityEvent listeners from code vs. setting up "persistent event listeners" (Unity's term for event listeners we add to a UnityEvent in the Unity Inspector).

Let's say, as a very simple example, we've got a platformer where the player can pick up coins. We might have a player class that looks like this:

```
public class Player : MonoBehaviour {
    [SerializeField] private UnityEvent collectedCoinEvent;
    public UnityEvent CollectedCoinEvent => collectedCoinEvent;

    private void OnCollisionEnter(Collision collision) {
        var coin = collision.transform.GetComponent<Coin>();
        if (coin != null) {
            coin.ReturnToPool();
            collectedCoinEvent.Invoke();
        }
    }
}

```

Say we then add a `CoinTracker` which tracks the coins collected. Here are two ways we could write the class:

1. For use with a persistent listener from the inspector:

```
public class CoinTracker : MonoBehaviour {
    [SerializeField] private TMP_Text coinsText;
    private int coins = 0;

    //this function is called by a persistent listener on the Player's
    //collectedCoinEvent in the Inspector
    public void AddCoin() {
        coins++;
        coinsText.text = coins.ToString();
    }
}

```

This solution reduces coupling and makes it easier for someone who is not a programmer to set up the event logic. However, it makes navigating and understanding the code more difficult. Our IDE will show that there are 0 references to `AddCoin()` and 0 references to the `CollectedCoinEvent` property. Figuring out what happens when `collectedCoinEvent` is invoked is not too difficult (check the Inspector) but it's much more difficult to figure out what persistent event listeners might be calling the `AddCoin()` function.

2. Add the event listener from code:

```
public class CoinTracker : MonoBehaviour {
    [SerializeField] private TMP_Text coinsText;
    [SerializeField] private Player player;
    private int coins = 0;

    private void Awake() {
        Assert.IsNotNull(player);
        player.CollectedCoinEvent.AddListener(AddCoin);
    }

    private void AddCoin() {
        coins++;
        coinsText.text = coins.ToString();
    }
}

```

With this approach, since we add the event listener in code, we can easily follow the event flow in our IDE using features such as "find references". However, we've created coupling - the CoinTracker needs a reference to the Player instance. Additionally, team members who only work with the Editor and not with code wouldn't be able to add or remove event logic.

3. A third approach uses an intermediary class for events, as an alternative to approach #2. This requires changes to the `Player` as well.

```
public class GameEventService : MonoBehaviour {
    private UnityEvent collectedCoinEvent = new UnityEvent();
    public UnityEvent CollectedCoinEvent => collectedCoinEvent ;
}

public class Player : MonoBehaviour {
    [SerializeField] private GameEventService gameEventService;

    private void OnCollisionEnter(Collision collision) {
        var coin = collision.transform.GetComponent<Coin>();
        if (coin != null) {
            coin.ReturnToPool();
            gameEventService.CollectedCoinEvent.Invoke();
        }
    }
}

public class CoinTracker : MonoBehaviour {
    [SerializeField] private TMP_Text coinsText;
    [SerializeField] private GameEventService gameEventService;
    private int coins = 0;

    private void Awake() {
        Assert.IsNotNull(player);
        gameEventService.CollectedCoinEvent.AddListener(AddCoin);
    }

    private void AddCoin() {
        coins++;
        coinsText.text = coins.ToString();
    }
}

```

With this approach, we've eliminated coupling directly between `CoinTracker` and `Player`, but both classes are now coupled to `GameEventService`. While I've used UnityEvents for the example, we could do the same thing with C# events. As with #2, team members who only work with the Editor and not with code wouldn't be able to add or remove event logic.

---

Is there a right answer here? A rule for when to use a particular approach? A better alternative?

# Answer
> 1 votes
Inspector links and "classic" events both have their use IMO (I'm not a fan of event managers). The general rule that I like is inspector event links inside the same prefab and code links for the more "distant" connections.

Persistent UnityEvent links allow for creating very small/universal components that can then be linked through inspector in countless ways to achieve many different complex behaviors (especially if you limit the possible event parameter types to the few most often used ones). But as you said they are a bit difficult to track, that is why I think it is best to limit inspector links to the same prefab and keep them contained. In other words no adding of inspector event links in the scene itself. BTW I look similarly and at the inspector references, as prefab inner wiring.

Lets say the coin example - inspector link inside the coin prefab that starts some particle effect when collected and code link for the distant UI overlay that displays the number of collected coins.

---
Tags: unity, events
---


# Question
Title: Keeping object a fixed distance from the ground, buggy behavior
I'm trying to make a script that will keep my object exactly 1 meter from the ground. So far I've got the following code :

```
using UnityEngine;
using System.Collections;

public class HoverScript : MonoBehaviour {

    public Transform target;
    public float hoverDistance;
    void Start () {}

    void Update () {}

    void FixedUpdate ()
    {
        if (Physics.Raycast(transform.position, Vector3.down, hoverDistance))
        {
            RaycastHit hitInfo;
            Physics.Raycast(transform.position, Vector3.down, out hitInfo, hoverDistance);
            float correction = hoverDistance-hitInfo.distance;
            //Debug.Log(correction);
            //Debug.Log(target.position);
            target.position = new Vector3(target.position.x, target.position.y+correction, target.position.z);
            //Debug.Log(target.position);

        }
    }
}

```

Basically, if the raycast hits, then it finds the distance of the hit. If it's .9 and the hoverDistance is 1, it would push the object up by .1, and keep checking every update. It seems like it would work, but I get this result : http://www.gfycat.com/IllfatedMediocreAquaticleech

In case the link goes down, basically the object falls like normal because of gravity until the distance is reached, then it slows down dramatically and slowly sinks into the ground.

The objects are set up like this

```
gameObject(has hover script, rigidbody, the camera following script)
 |
 ----> mesh(just a mesh, mesh renderer, and collider)

```

The target of the script is the parent gameObject.

Any ideas why this script isn't working?

# Answer
> 1 votes
If you replace your `transform.position = vector...` with `rigidbody.MovePosition( vector... )` this will give you better results. It will also interpolate (if you have interpolation on for your rigidbody) so it looks smooth between your `FixedUpdate`.

Here's the doc page: https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html

# Answer
> 0 votes
Switch to kinetic mode in the rigid body. Then Gravity is disabled for that Object. And remove the empty Start and Update functions. They are slowing down the game for no reason.

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


# Question
Title: How to limit forces based on linear velocity
I'm trying to develop a system where there are two types of velocity limits.

1. The velocity that a rigid body can achieve on its own.
2. The velocity cap which is reachable by interference with other forces.

(Bear in mind the physics aren't 100% realistic).

For example,

* Hard limit is 1000.
* Spaceship A can travel up to 300 pixels per second.
* Spaceship B can travel up to 600 pixels per second.

So on its on spaceship A will only be able to go at 300, but if spaceship B were to tail gate and start ramming A, then A will go a bit faster.

In any case, regardless of the forces, nothing can go faster than the hard limit.

Now the hard limit is very easy to implement:

```
public override void _IntegrateForces(PhysicsDirectBodyState2D state)
{
    base._IntegrateForces(state);

    state.LinearVelocity = state.LinearVelocity.LimitLength(MaxLinearVelocity);
}

```

The part im having such trouble with, is capping the forces, for limit 1:

```
if (
    (LinearVelocity.X >=  MaxAppliedForceLinearVelocity && directionalForce.X > 0) ||
    (LinearVelocity.X <= -MaxAppliedForceLinearVelocity && directionalForce.X < 0)
) {
    directionalForce = new Vector2(0, directionalForce.Y);
}

if (
    (LinearVelocity.Y >=  MaxAppliedForceLinearVelocity && directionalForce.Y > 0) ||
    (LinearVelocity.Y <= -MaxAppliedForceLinearVelocity && directionalForce.Y < 0)
) {
    directionalForce = new Vector2(directionalForce.X, 0);
}

ApplyCentralForce(directionalForce.Rotated(Rotation));

```

Now something like just the above **might** work OK assuming that the ship is moving on only one axis, but the velocity could exceed it if moving along two axis. The problem is that the forces need to **stop** in one direction to allow gains in the other direction, and to autocorrect itself because forward movement may be more powerful than lateral movement.

The hard limit works, but individual ships and missiles, must not exceed their own limit unless something else impacts them. This is my problem. Thank you.

# Answer
1. Get current velocity
2. Add new self\_input
3. Clamp the result to `max(current, self_max)` (current might be 450, self-max is 300, therefore, you are clamping to 450).
4. Set the resulting velocity to the object
5. Repeat 1-4, but replace self\_input with extern\_input and self\_max with extern\_max.

The only gotcha you don't see with your code is that you can do it twice. Once for global max (then apply input forces) and second time for the `local max` or `current velocity`, which ever is bigger.

Pseudocode version:

```
base._IntegrateForces(state);
state.LinearVelocity = state.LinearVelocity.LimitLength(MaxLinearVelocity);
applyInputForces();
MaxControlVelocity = Max(state.LinearVelocity,MaxAppliedForceLinearVelocity);
state.LinearVelocity = state.LinearVelocity.LimitLength(MaxControlVelocity);

```
> 0 votes

---
Tags: physics, mathematics, godot, motion
---


title: Reduce Unity Editor loading times

text:
# Question
Title: Reduce Unity Editor loading times
* Open project =\> Wait
* Start / stop game =\> Wait
* Change script =\> Wait
* Move object from project view =\> Wait
* You blink too often =\> WAIT even more !

And so on and so on.... And the bigger the project gets the more you have to wait.

I feel like I am going insane with all this waiting. I am seriously loosing my sanity here when even the slightest thing requires a million of years loading time.

What I have done so far to mitigate all this:

* Use Hot reload for partially reducing script reloads
* Enabled manual project refresh instead of automatic one from visual studio
* Enable "enter play mode" and disabled "reload domain" and "reload scene"
* Disabled autosave/refresh for light baking
* Disabled prefab auto save

What I want to find out:

* Is there a way to boost allocated memory to Unity ? It isnt an elegant solution but it will be a good start.
* How to disable the automatic Unity reload every time I move a script inside the Project window ?
* Any other way to speed up this cursed program before I loose my sanity completely

PC Specs: CPU : Intel(R) Core(TM) i7-7820X CPU @ 3.60GHz Ram : 32.0 GB V\_Card : NVIDIA GeForce GTX 1080 Ti Storage: SSD with NVME

Unity ver: Unity 2021.1.

Reload times:

* "Reloading script assemblies" + 15 sec
* "Compiling C# scripts" milliseconds.

# Answer
OK, finally after more than a year I found what was messing with my load times !!

I have "Easy Save 3" plugin from the Unity store. The manager object in the scene was glitching out. I deleted it and everything is lightning fast now. You must delete it and not disable. Disable does nothing and I was fooled by that when checking my components for problems before.

It was giving me problems even before, but never that much. I figured it was Unity not being optimized since the slowdown happened gradually and I have seen lots of similar topics blaming Unity.

Hopefully this will help anyone else who has similar problems.
> 2 votes

---
Tags: unity, performance, loading
---


# Question
Title: How to reference assets between multiple asset bundle in Unity?
I am trying to figure out how to properly package my bundles. My goal is to try and avoid necessary duplication of assets and cut down on download time of the assets by having smaller bundles. The current problem is that I am not sure how would bundle A reference assets from bundle B that it is depended on. Example in my case are lets say fonts. I have bundle A and B that should use fonts from Fonts bundle. I was under impression that unity would figure this referencing out on its own if I just load them all but that doesn't seem to be the case. How would I make this work do I need to maybe use addressables (I never used them so I am not sure if this could be one of use case for them)?

# Answer
Loading bundle with common assets before main asset bundle seams to work on smaller scale so it was probably issue with my loading method. One thing I did noticed is that Unity didn't pull all my shader assets for the text when I moved them in a separate bundle so that caused missing reference. So make sure you have them in your bundle if you are experiencing font issues.
> 0 votes

---
Tags: unity, c#, assetbundle, addressable
---


# Question
Title: Why is interpolation passed into the rendering routine when the position and speed are related to the update routine?
I've read this in several well known articles, including this one:

http://www.koonsolo.com/news/dewitters-gameloop/

Under the Interpolation and Prediction subheading is the description of the formula. I'm currently using the suggested game loop from the article (without passing in the interpolation). I get why interpolation is used, but I'm having trouble understanding why it is applied during rendering, and how it relates to my game.

I'm presently using pure tile based movement for 32x32 tiles. So my player moves from tile A to tile B so long as tile B can be occupied, and at a fixed rate of 1 pixel per 10ms. The state is "walking" until the player moves the full 32 pixels, at which point the state is "stopped". This all happens in a standard timer, but all during my update routine. My rendering routine simply takes the player's position and renders it onto the map. There is no "speed" per say in that equation that is accessible. So how would I use interpolation?

# Answer
> 2 votes
Combining a physics engine that uses a fixed time-step with a variable-timed rendering loop can lead to very choppy movement. Sometimes you have two physics frames between two renders, sometimes none at all and you render the same thing twice. This can lead to choppy movement and scrolling.

The solution to that is to pass not just the current but also the last game-state to the rendering engine and a delta-time variable that states how many milliseconds the current game-state is in the past. That allows the rendering engine to either interpolate or extrapolate object positions accordingly, which results in much smoother movement.

For example:

* Last tick: object was at horizontal position 3.0
* Current tick: object is at 5.0
* Time information: We are 30% between current tick and the next tick

When the rendering engine uses extrapolation, it would calculate that the object is moving with a velocity of 2.0 units per tick, so it now draws it at 5.6 units. When the rendering engine uses interpolation, then it will linearly interpolate between the last and the current tick and place the object at 3.6 units.

But because the player has a pretty good gaming rack, just a few millisecond later the frame is finished and we want to draw another one. Time advanced to only 70% to the next physics frame. So we draw the object at 6.4 (extrapolation) or 4.4 (interpolation).

As you can see, passing timing information to the rendering engine allows us to give the impression that the game runs with a much higher physics framerate than it actually does, resulting in much smoother rendering.

# Answer
> 1 votes
That article seems to be written around a variable framerate. This is okay for rendering, but many parts of a game are time-dependent (want to avoid huge jumps in time). Variable framerate is especially bad for physical simulation. To avoid such issues most parts of a game can be updated at a fixed timestep, while rendering can be updated at maximum FPS.

You take previous positions from the game, and current positions and interpolate between the two to form a smooth animation for animating the sub-steps between two simulation loops.

If you want more detail I wrote a better article here. See the section on time stepping.

---
Tags: 2d, animation, interpolation
---


# Question
Title: error X3671: loop termination conditions in varying flow control cannot depend on data read from a UAV
I have a problem with converting my pixel shader to compute shader. The error is in this piece of code:

```
 [numthreads(32,32,1)]
 void CS_PostDeferredReflex( uint3 nGid : SV_GroupID,
     uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID )
 {
   if (any(nDTid.xy >= float2(SM_SCREENX, SM_SCREENY))) return;
   uint Output = UAVDiffuse0[nDTid.xy];
   float4 ColorOut = float4(Output&0x000000FF, (Output&0x0000FF00)>>8,
                       (Output&0x00FF0000)>>16, (Output&0xFF000000)>>24)*INV255;
   float D = txDepth1.Load(uint3(nDTid.xy,0), 0);D=(D==1)0:D;
   if (ColorOut.a*D == 0) return;

```

Which gives the following:

`error X3671: loop termination conditions in varying flow control cannot depend on data read from a UAV`

Here the UAV `UAVDiffuse0` is a `R32UINT` that is unpacked as `RGBA ColorOut`.

If the alpha value is zero (or the Depth not \[0\<D\<1\]) I don't need to go further. The compiler is unhappy with the last line where the exit is based on the UAV read. I don't understand why we have this limitation.

# Answer
> 1 votes
The answer is effectively to use \[allow\_uav\_condition\] but in the right place

what does not work is to place the condition before the if statement even if it is where I need it

```
 [allow_uav_condition]
 if (ColorOut.a*D == 0) return;

```

in the code I have a loop so what works is to place the condition before the loop, even if in the loop I have no test against the UAV, just write to it.

```
 ...code
 if (ColorOut.a*D == 0) return;
 ...code
 [allow_uav_condition]
 for ()
 {
   ....code
 }

```

# Answer
> 0 votes
Finally I set the A channel of my UAV into another texture which solve the problem but it is annoying as this needs an extra 8 bit resource and my UAV alpha channel is now useless.

---
Tags: directx11, deferred-rendering, compute-shader
---


# Question
Title: What is the best way to store unique data for tile types?
To store specific data unique to each tile type, what is the best way to do this?

Say a tile has an ID corresponding to data concerning its name, block strength, texture, health, etc; how could this be done? I am considering using parallel arrays to store this data, but would like to know if there are other solutions.

# Answer
You can use 2 vectors; one to store the info and another as the tilemap just storing ids:

```
using TileID = unsigned int;
std::vector<TileID> tile_map {};

struct TileInfo {
  TileID id {};
  std::string name {};
  int strength {};
  Sprite sprite {};
  // etc...
};

std::vector<TileInfo> tiles_info {};
// put your tiles' id like:
for (std::size_t i = 0; i < DIFFERENT_KINDS_OF_TILES; ++i) {
  TileInfo current_tile_info {};
  current_tile.id = i;
  // the rest of the tile info should be manually added somewhere else
  tiles_info.push_back(current_tile_info);
}

// so you can do something like:
for (const auto& tile: tile_map) {
  draw(tiles_info[tile].sprite);
}

```

As said in the comments before, it's not the **best** method, just another way to do it.
> 0 votes

---
Tags: c++, world-editor, raylib
---


# Question
Title: How to capture a signed displacement using an analog trigger?
The details of my particular problem are a bit convoluted, but take this similar scenario:

I want the player to be able to control the velocity of the character in some direction using only an analog trigger on a controller, being able to move forward and backward. In some sense this is very straightforward: the smallest value of the analog range of the trigger can correspond to the fastest possible backward velocity, and the highest value the fastest possible forward velocity (these being equal in magnitude), the rest can be linearly inrepolated.

The problem is that in the trigger's neutral position the value is already extremal. So with this approach, the player would have to keep the trigger about halfway pulled when they want to remain still, which is awkward to say the least. One solution I've thought about is is using a bumper or even some other button as a modifier. If the bumper is held, pulling the trigger moves the character backward, and if not, moves it forward.

But I'm already pressed for controller real-estate as is (in particular **both sticks are non-negotiably taken**). Can you think of a clever solution to this?

# Answer
If you absolutely must use only one trigger and want to avoid having to hold a precise intermediate value to stay still, without a discontinuity in the middle of the input domain, you can also opt to double-cover part of the output range:

In this version:

* Leaving the trigger at its neutral position maps to zero output (stationary)
* Slightly squeezing the trigger begins to accelerate backwards
* Holding the trigger 1/3 of the way maps to 100% reverse speed
* Pushing past 1/3 slows down again, until reaching 2/3 which is again zero output
* Pushing past 2/3 of the way begins to accelerate forward
* Holding the trigger at 100% maps to 100% forward speed

This is a bit awkward, but it means that rest and 100% forward speed, the outputs that a player will probably want to be using most often, map to the extremes that are easiest to hold, and there are no sudden discontinuities in between. 100% reverse speed is awkward to hold precisely, but hopefully it accounts for a minority of your gameplay.

A formula to achieve this is:

```
output = abs(input - 1f/3f) * 3f - 1f;

```

We can make it a little easier to hold the extremes (stationary, full forward, and full reverse) by flattening the curve where it crosses through those points (the "soft" version graphed above):

```
output = (0.5f * cos(3f * PI * input) - 0.5f) * (input < 2f/3f ? 1f : -1f);

```

---

Another option you could try is to use some hysteresis, where you use one of two different mapping curves depending on recent input history.

One version of this would be that with the trigger in the neutral position, you read zero output. If you gradually squeeze the trigger, you begin accelerating forward, and once you're in "forward mode" you can use the whole analog range of the trigger to vary your forward speed. But if you return to neutral, then snap the trigger to max quickly, you "shift gears" into reverse mode, and you can then feather-out the trigger to vary your reverse speed.

In the version below, I use a mapping where in reverse gear both 0% and 100% input map to zero, so you can snap the trigger without moving immediately, then gradually ramp up your reverse speed by letting go a little, and return to neutral / get ready to switch back to forward by letting it out all the way.

```
public float modeSwitchThreshold = 0.9f;
public int modeSwitchTicks = 2;
public float deadZoneMin = 0.05f;
public float deadZoneMax = 0.95f;

bool _currentModeIsReverse = false;
int _ticksSinceNonZero = 0;

float UpdateSignedDisplacement(float input) {
    float normalized = (input - deadZoneMin) / (deadZoneMax - deadZoneMin);
    normalized = max(0, min(input, 1));

    if (input == 0f) {
        _ticksSinceNonZero = 0;
        _currentModeIsReverse = false;
        return 0f;
    }

    _ticksSinceNonZero++

    if (_ticksSinceNonZero <= modeSwitchTicks && input > modeSwitchThreshold) {
        _currentModeIsReverse = true;
    }

    if (_currentModeIsReverse) {
        // Soft peak at 50% input -> -100% output,
        // sloping smoothly to 0 at the extremes.
        return 4f * (0.5f - input) * (0.5f - input) - 1;
    } else {
        // Straight line from 0 -> 0 to 1 -> 1
        return input;
    }
}

```

The version presented above is just an experimental starting point, and will likely need a lot of iteration and playtesting to find a mapping that feels good. The aim is just to demonstrate the core idea of the mode switch, and how you can use it to map both positive and negative speeds to your liking.
> 1 votes

# Answer
I can only think of two possibilities:

1. Use one trigger for forward and the other for reverse
2. As you noted, use a modifier button which reverses the thrust direction when held.
> 0 votes

---
Tags: control, controllers
---


# Question
Title: How to retain links between assets when merging two projects into one?
We have a common Model library where different models/textures are stored. We use this library for our new project. Here is the scenario: Two individuals started separate projects and are now merging them into one. Both of them added models from the common library. However, when they merge their work into a third project by importing each other's package (model/material package), some models lose their materials and appear pink, even though the materials are present and not lost. I tried to identify the problem and found a warning message when importing the same model:

```
File exists in the project, but with a new different GUID. Will override existing asset...

```

I discovered that Unity operates models based on GUIDs. So, if two different workspaces added the same material and you attempt to merge them into a single project, only the latest GUID will remain, causing your model to lose the material reference. Is there any available way to recover the material? Or i have to change the workflow, which is not possible.

# Answer
> 0 votes
Make sure you enable asset metadata.

Every asset in a Unity project is accompanied by a corresponding file of the same name with the additional extension `.meta`.

When you exchange assets between projects, copy their corresponding meta-files with them. The meta-file contains the GUID of the asset file of the same name. So when you copy both the meta-file and the asset into the project, then the asset will get the GUID from the meta-file instead of a newly generated one.

The meta-file also contains the import settings, which can also be crucial for certain asset types.

---
Tags: unity, materials
---


# Question
Title: Weird result whe nusing OMSetRenderTargetsAndUnorderedAccessViews
My render pass consist in four passes.

3 first have 2 rendertargets and two unordered access view.

RTV0 = RG88 //store normal.xy

RTV1 = R32 //store depth

UAV0 = R32UINT //store color1

UAV1 = R32UINT//store color2

4th has one RTV and one UAV.

RTV0 = RG88//store normal.xy

UAV0 = R32UINT//store color1

I’m setting viewport and scissor rect as the screen size. So I set OMSetRenderTargetsAndUnorderedAccessViews(2, RTVs, DSV, 2, 2, UAVs, NULL) for the 3 first and OMSetRenderTargetsAndUnorderedAccessViews(1, RTVs, DSV, 1, 1, UAVs, NULL) for the last.

In my shader

```
    RWTexture2D<uint> UAVDiffuse0  : register( u2 );
    RWTexture2D<uint> UAVDiffuse1  : register( u3 );

    struct PS_INPUT
    {
        float4 Pos : SV_POSITION;
        float3 Norm : NORMAL;
        float4 Col : COLOR0;
        float2 Tex : TEXCOORD0;
        float3 Tan : TANGENT;
        float3 BiN : BINORMAL;
    };

    struct PS_DEFERRED
    {
        float2 NormalSSR : SV_TARGET0;
        float Depth : SV_TARGET1;
    };

    Float4 psdeferred (PS_INPUT Input)
    {
    PS_DEFERRED Output;
    Some code to calculate Data and N from Input
    //SM_SCREENX and Y are the screen sizes
        UAVDiffuse0[Input.Tex*float2(SM_SCREENX,SM_SCREENY)] = Data;
        UAVDiffuse1[Input.Tex*float2(SM_SCREENX,SM_SCREENY)] = Data&0xFFFF7FFF;
        Output.NormalSSR = mad(N.xy,0.5,0.5);
        Output.Depth = Input.Pos.z+0.00003f;
    }

    struct PS_DEFERRED2
    {
        float2 NormalSSR : SV_TARGET0;
    };
    Float4 psdeferred2 (PS_INPUT Input)
    {
    PS_DEFERRED2 Output;
    Some code to calculate Data and N from Input
        UAVDiffuse0[Input.Tex*float2(SM_SCREENX,SM_SCREENY)] = Data;
        Output.NormalSSR = mad(N.xy,0.5,0.5);
    }

```

Things work fine for the RTVs but are weird for UAVs as shown in the picture. In my previous code I was using RTV only and everything was working fine so I’m sure that the Data and N calculations are correct. I’m surely missing something. I have no debug errors.

# Answer
> 0 votes
I fill stupid... The answer was there already. We need to use the SV\_POSITION xy as UAV coordinates for writing the right pixel.

---
Tags: hlsl, deferred-rendering, rendertargets
---


# Question
Title: How can I visualize the players health without creating too much UI clutter?
Many games with health systems will always display the amount of health in a head-up display. A good example is Hollow Knight, which has a detailed head-up display in the upper left corner:

Some games don't have health/lives at all, and so they don't need to display the number of lives on the interface. A classic example here is Super Mario Bros, where you usually only have one life and therefore don't need no health display.

Super Mario Brothers has a creative solution for if and when you get a second life. If you eat a Super Mushroom, Super Mario Bros will super-size your sprite into Super Mario. If you lose your second life, you turn back into the normal-sized Mario. In that way, the size of your sprite represents your number of lives.

I'm making a video game, and I plan to display the amount of Lives a player has left in my video game on the screen in a head-up display. But a constant head-up display will clutter the screen, so I'm looking for a more elegant solution.

My initial thought was to *only* show the number of Lives when the player takes damage (i.e. gets a question wrong). The number of lives left would flash up on the screen in a temporary head-up display, and then fade away.

Are there any video games that only show the amount of Lives/Health when the player gets damaged? Wondering if this model has been tried before, and if it works well. Thank you!

# Answer
A lot of 3D platformers comes in mind that handle this system, where they hide the health bar at full health, when you've taken damage, the health bar stays on screen until you've restored it again.

For example: Donkey Kong 64 did they had a life system shown as Melons, but if the melons are at full health they'll disappear, and only appear on the pause menu, this also happens at the Super Mario 64, Super Mario Sunshine and Super Mario Galaxy.

An argument why it's often in 3D platformers is because you want to use that space to look around for secrets or collectables, having a large healthbar would obstruct that vision often.

Those healthbars are also pretty static and don't change often, so you already know how much life you have even when it's not visible on screen. Though if the number does (temporarely) change, then it's better to keep that change visible on screen, like the mushroom in Super Mario Galaxy that doubles your health.
> 2 votes

# Answer
I can't think of a game that totally hides the UI but I'm sure it's been done. There are a few that make it subtle but still useful. The Long Dark is a highly immersive game. The UI is unobtrusive enough to forget about. Health information flashes up in a warning message when there is a concern or damage so that you remember to take care of yourself. If you want more details you press a button and bring up a big UI.

There are also games that give the user a choice about what to show. For example Wurm Online allows users to choose which of dozens of UI elements to show. The Health bar has a bunch of stats on it but many can be individually shown or hidden. It's nice to have that level of control of the information.

Some games try to make the health bar more artistic in an attempt to make it blend in better or be more attractive, but I think sometimes that makes it harder to read which then forces the player to pay closer attention to it, which defeats the purpose.
> 1 votes

---
Tags: ui-design, user-experience
---


# Question
Title: How to glue objects together so they move as one?
I'm making a puzzle game and can't find ANY solution on how to glue parts so I can move them together as a unit. :(

1. I tried to making them depend like parent and a child, but when I touch the child, the parent doesn't move or rotate.
2. I tried to make a `List<>()` in each part but it didn't work as well. Too much code and resources needed.

# Answer
> 2 votes
### Attach all objects with one common "Root" object

From what I understand, you want to connect objects together so that they can act like one object and be moved around. Here's a way to do this:

* Each object has a `parent` variable (similar to what you already tried). If that variable is empty, the object has no parent.
* If object `a` and object `b` are about to be attached together, decide which one of them should be the parent. Let's assume for this example we want object `a` to become the parent.
* Make object `b`'s `parent` variable point to object `a`.
* Whenever the user is about to move, rotate or otherwise transform an object, search recursively through the object's `parent` value, until you find an object with no `parent` value (the root object).
* Transform that root object, as their transformations should affect all children, making it look like they all move as one object.

### Example

Let's say we have objects `a`, `b` (with `a` as the `parent`) and `c` (with `b` as the `parent`).

* If you are about to move `a`, do it as normal, and it should affect all children.
* If you are about to move `b`, check its `parent` which is `a`, which doesn't have a `parent` (it's the root object) so move that.
* Similarly if you are about to move `c`, check its `parent` which is `b`, whose parent is `a`, which doesn't have a parent, so move `a` again.

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


# Question
Title: Calculate offset when attaching a game object to edge of another game object
I am doing a sort of hook, where whenever the hook collides with something, it retracts itself and pulls the the object it collided with back along with it.

But the objects the hook can collide with are not the same sizes, so I can't just create a fixed spawn point and assign that transform to the hooked game object, as some of them would clip the hook and others would be too far away.

So I need to find out what the offset should be, based on the size of the hooked game objects, but I don't know how to calculate it. Especially since the hook can also be rotated, so just offsetting on the y axis for example is not enough, since it might also need to be offset on the x-axis - Pic explaining it:

So any advice on how to calculate the offset (I have my bounds.size to use), and then apply it correctly on both the X and Y axis so the attached game object doesn't clip my hook?

# Answer
So I finally figured out how to calculate the correct offset on both the x and y axis. It was due to my lack of knowledge on vectors..

I had to find the magnitude of the hooked game object and then multiply that by half (so I have half the size of the gameobject) and store that in a var called offsetDistance.

Then I multiply my position with -offsetDistance and then it works. Code used to solve it:

```
        float offsetDistance = spriteRenderer.bounds.size.magnitude * .5f;

        Vector3 hookPos = hook.transform.position;
        Vector3 hookDirection = hook.transform.up;

        Vector3 spawnPos = hookPos + hookDirection * -offsetDistance;
        transform.position = new Vector2(spawnPos.x, spawnPos.y);

```
> 0 votes

---
Tags: unity, 2d, vector
---


# Question
Title: In Unity editor, how to import package from github?
In the latest Unity editor 2021.3.25f1 LTS, I'm trying to directly import the following package from github:

https://github.com/yasirkula/UnityNativeFilePicker/releases/tag/v1.3.0

But when I import directly in package manager (add package from git URL), I always got the following eror:

```
[Package Manager Window] Cannot perform upm operation: Unable to add package [https://github.com/yasirkula/UnityNativeFilePicker/releases/download/v1.3.0/NativeFilePicker.unitypackage]:
  Package name 'https://github.com/yasirkula/UnityNativeFilePicker/releases/download/v1.3.0/NativeFilePicker.unitypackage' is invalid. [InvalidParameter].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions () (at /home/bokken/build/output/unity/unity/Editor/Mono/EditorApplication.cs:356)

[Package Manager Window] Error adding package: https://github.com/yasirkula/UnityNativeFilePicker/releases/download/v1.3.0/NativeFilePicker.unitypackage.
UnityEditor.EditorApplication:Internal_CallUpdateFunctions () (at /home/bokken/build/output/unity/unity/Editor/Mono/EditorApplication.cs:356)

```

No further information is given, clearly the name resolving is faulty. The name should be `UnityNativeFilePicker`, is it a unity bug? What can be done to correct it?

# Answer
> 3 votes
You haven't used the correct URL. As described in the repository's README, the correct URL is https://github.com/yasirkula/UnityNativeFilePicker.git

The documentation shows that the URL should be to the `.git` page, not to the Releases page.

---
Tags: unity, unity-ui, version-control
---


# Question
Title: Unity shader is changing the selectable area to the original texture it used
I know a little about shaders, but not much. I cobbled one together to to light my sprites, and it's working great if not for one thing:

I originally tested the shader with a chair texture. I made a new material from that same shader with all different inputs that are distinctly table-shaped, but unity insists on making the clickable area the same shape and position of the original chair. I have no idea why.

When I set the alpha cutoff to zero, it uses the entire quad again. Based on this, I'm guessing somehow the alpha of the original texture is filtering through somehow.

I can set the cutoff to zero for the time being, but I still want to know what's happening if anyone could help me understand

Edit: setting the alpha cutoff to zero makes the display a square again but the clickable area is still the same as the little chair in the corner there:

# Answer
> 1 votes
The shader had a few inputs marked as `[HideInInspector]`. When I removed the flag, the `_MainTex("BaseMap", 2D)` was set to the diffuse chair texture.

Mystery solved.

---
Tags: unity, shaders, materials
---


# Question
Title: Optimizing Tax Revenue In City Builder Game
I am currently developing a city builder game that incorporates a tax revenue system, allowing players to redeem their city's tax revenue every 24 hours. I want to create a mathematical model for tax collection that optimizes the players' experience from a game design perspective. The game targets a wide demographic of players, ranging from young children to adults, so I aim to make the system intuitive and engaging without discouraging players. Additionally, I want to incorporate a progression curve into the model.

Some of the variables that need to be considered in the tax revenue system include:

* Fixed tax rate (I am unsure about the appropriate range)
* Service coverage (fire, police, health stations)
* Average land value
* Population
* Players experience (level, xp)

I would appreciate guidance on where to start mathematically in order to develop this tax revenue model. How can I strike a balance between intuitiveness and complexity to ensure an enjoyable gaming experience for players of all ages?

Thank you!

# Answer
> 0 votes
Partial answer:

> * Fixed tax rate (I am unsure about the appropriate range)

The "appropriate range" for the tax rate depends on how the rest of the economy is balanced. Here's how I'd approach determining this value:

First, decide how much you want things to cost and implement the economy for buying/building things. You can base other numbers around these values, so there's no "right answer" here - pick numbers that you think are appropriate.

Before you've implemented any form of revenue, simply give the player a massive amount of starting cash. Play the game for a while, get a feel for how fast you want the game to be paced (e.g. how much the player can build per day). Watch how fast you're spending money to get an idea of how much revenue the player will need per day (you might want to record your daily spending so you can create charts/graphs to help you analyze it).

Once you've determined how you want to pace the game and how much cash the player will need to spend in order to maintain that pace, you can start balancing tax revenue around those target numbers. If you're aiming for a broad player base rather than hardcore realism enthusiasts, I'd say that it's important to achieve specific numbers but not *how* you achieve those specific numbers.

Of course, this is an iterative process, since as the city grows, the player's tax revenue will increase. You'll most likely find that you have to be constantly tweaking and rebalancing numbers as you go. For example, you might come up with a rough balance that you like, and later realize that roads are too expensive relative to buildings, but find that lowering the price of roads has a butterfly effect on the overall balance. Or you might determine that the player is making far too much revenue in a large city and you need to increase services costs to counter this.

You will be doing a *lot* of torturous analysis and balancing (or equally torturous, developing an algorithm to analyze and balance for you); to quote Boromir, "you will beg for death before the end!" The more complex your tax system is, the harder it will be to balance. I'd recommend starting simple and adding complexity later if you have time and feel that it's necessary.

---
Tags: mathematics, game-design
---


# Question
Title: How to create an Editor class for a generic class
For all my MonoBehaviour scripts, instead of them inheriting from MonoBehaviour they inherit from a generic class like so:

```
public abstract class MonoBase<T> : MonoBehaviour where T : MonoBase<T> { }

public class Example : MonoBase<Example> { }

```

Now, I would like to make an editor script for all those MonoBase classes, and the closest I have gotten to a solution that will compile is :

```
[CustomEditor(typeof(MonoBase<>))]
public class MonoBaseEditor<T> : Editor where T : MonoBase<T>
{
    public override void OnInspectorGUI() {
        this.DrawDefaultInspector();

        MonoBase<T> myScript = (MonoBase<T>)this.target;
        if (GUILayout.Button("Build Object")) {
        }
    }
}

```

But of course it doesn't really work.

Am I missing something or is there really no way to make a generic editor class like it's mentioned in an answer here.

# Answer
> 5 votes
Well, you can make an Editor class for it, but Unity can't instantiate a generic one, when you instantiate a generic class, you must specify the generic type, as example, when you try do do this C# will throw an error: `List<> l = new List<>();`. And there is no way for Unity to safely assume or guess what T should be.

---

You can get it to work by creating a custom editor for each T, so that Unity can instantiate the custom editor where T is known, see the other answer of Ed Marthy on how to do this

---

We can also make a regular Editor, we just can't cast target to `MonoBase<T>` because we don't know T, And if you did know for sure that T is `Example` in this case, you should just write a custom editor for `Example` instead of `MonoBase<>` in the first place...

The closest thing you can cast 'target' to is the (Non-generic) type that `MonoBase<>` inherrits (MonoBehaviour in your example).

```
[CustomEditor(typeof(MonoBase<>), true)] // <-- the 'true' is important, it makes sure that classes that inherrit MonoBase use this editor aswell
public class ExampleEditor : Editor
{
    public override void OnInspectorGUI()
    {

        if (GUILayout.Button("Build Object"))
        {
            MonoBehaviour possible = (MonoBehaviour)target;
            Debug.Log(possible.name);
        }
    }
}

```

---

In your case, because the T in `MonoBase<T>` has to be a `MonoBase<T>` itself. You really can't cast to anything MonoBase. If the where clause of T would be something like `where T : MonoBehaviour` instead of `where T : MonoBase<T>`, and you would be willing to use an interface rather then abstract class, then you could make it so you can cast target to `IMonoBase<MonoBehaviour>`. Using the answer to this question.

```
public interface IMonoBase<out T> where T : MonoBehaviour
{
    IMonoBase<T> ExampleMethod();
}

public abstract class MonoBase<T> : MonoBehaviour, IMonoBase<T> where T : MonoBehaviour
{
    public abstract IMonoBase<T> ExampleMethod();
}

public class Example : MonoBase<Example>
{
    public override IMonoBase<Example> ExampleMethod()
    {
        return this;
    }
}

```

Editor script:

```
[CustomEditor(typeof(MonoBase<>), true)]
public class ExampleEditor : Editor
{
    public override void OnInspectorGUI()
    {
        if (GUILayout.Button("Build Object"))
        {
            IMonoBase<MonoBehaviour> test = (IMonoBase<MonoBehaviour>)target;
            IMonoBase<MonoBehaviour> example = test.ExampleMethod();
            Debug.Log(example is IMonoBase<Example>);
        }
    }
}

```

# Answer
> 6 votes
Another option I’ve used is to have separate editor classes for each class, but they all extend from the base editor class and do nothing themselves.

```
public class MonoBaseEditor<T> : Editor where T : MonoBase<T>
{
    public override void OnInspectorGUI() {
        this.DrawDefaultInspector();

        MonoBase<T> myScript = (MonoBase<T>)this.target;
        if (GUILayout.Button("Build Object")) {
        }
    }
}

[CustomEditor(typeof(Example))]
public class ExampleEditor : MonoBaseEditor<Example>
{}

[CustomEditor(typeof(AnotherClass))]
public class AnotherClassEditor : MonoBaseEditor<AnotherClass>
{}

[CustomEditor(typeof(ThirdClass))]
public class ThirdClassEditor : MonoBaseEditor<ThirdClass>
{}

```

# Answer
> 1 votes
This actually works more simply now with more recent versions of Unity. You don't need to worry about the filename matching and you just need an interface for OnInspectorGUI()

e.g.

```
// ScriptableIndex<T> : General purpose ScriptableObject automatic indexer
public class ScriptableIndex<T> : ScriptableObject, IScriptableIndex where T : ScriptableObject

public interface IScriptableIndex
{
    public void OnInspectorGUI();
}

[CustomEditor(typeof(ScriptableIndex<>), true)]
public class EditorScriptableIndex : Editor
{
    public override void OnInspectorGUI()
    {
        IScriptableIndex editObject = target as IScriptableIndex;
        if ( editObject != null )
            editObject.OnInspectorGUI();
    }
}

```

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


# Question
Title: does it matter to send less data over network in a realtime multiplayer game?
I know it matters but...

i know in networking there are packet size limits. for example, most UDP libraries enforce max packet size of around 65535.

can I write on the network as much as possible until it exceeds the size of this limitation?

my question is about clarity and is less error-prone. most of the network layer source code I see is about reading bytes in order one by one to read the data of floating numbers.

if there is not much data getting transformed in my game can I simply use simple formats like JSON or their adding characters can reduce network speed?

# Answer
The simple rule the thumb: The more you transmit, the slower it is. But if that is noticeable on your game is another matter. It depends as well what kind of data you submit/ get.

JSON just makes it easier for us to interpret the data but that can be a weak point in a final game (easier to manipulate the data when it is easy to understand). If you are planning to allow the community to create mods for your game, giving them access to easy to understand JSON data structure can be a plus for your game. If you just use JSON because JSON, you risk into running automation/ bots/ data manipulation.

For some data JSON might be a bonus, usually initial data like inventory data, stats, quest text or monster info.

You as the dev should know exactly what kind of data is coming, parsing JSON from client side is therefore not really needed.
> 2 votes

# Answer
So you can technically just write until you hit the max. But UDP is lossy - so there’s a chance that whole packet will just disappear into the ether. In addition the large packet will likely include quite a bit of state. If you’re attempting to send something every 1/x of a second you’re probably not going to have enough things to fill that packet size: at least for things that need to update that quickly.

JSON as a format is fine for human legibility, but the side effect is that it is verbose. As @Zibelas said, if this legibility is important then you absolutely should use a more verbose format.

For a lot of games, however, the sheer number of objects that need to be synced between server/client means looking at less verbose formats. In addition, if inputs/changes are REALLY important - you can send multiple time delta updates in a single packet.

Packet 1 could contain updates 1-6 Packet 2 could contain updates 2-7 Packet 3 could contain updates 3-8

That way if any one packet doesn’t arrive, you still have a lot of data duplicated.
> 1 votes

---
Tags: unity, c#, socket, litenetlib
---