title: Seams between tiled cube unity

text:
# Question
Title: Seams between tiled cube unity
Hello i'm generating voxel map but seams are appearing between tile ONLY in camera mode, in the editor everything work fine.

Here in the editor camera:

Here the player camera:

So i guess it has something to do with camera setting here is what i have so far:

Edit: I know this kind of issue can be caused by mipmapping i'm pretty sure my texture is not generating mipmap right now:

Code for the chunk generation

```
using UnityEngine;
using UnityEngine.Rendering;

namespace World
{
    public class Chunk
    {
        private static readonly int x_length = 16;
        private static readonly int z_length = 16;
        private static readonly int y_length = 32;

        public MeshRenderer MeshRenderer;
        public MeshFilter MeshFilter;
        public GameObject ChunkObject;

        private Block[] chunkBlock;
        private readonly Vector2 _pos;

        private Vector3[] _vertices;
        private int[] _triangles;
        private Vector2[] _uvs;

        private int _verticesIndex;
        private int _trianglesIndex;
        private int _uvsIndex;

        public Chunk(int xPos, int yPos, WorldSpace worldSpace)
        {
            _pos = new Vector2(xPos, yPos);
            ChunkObject = new GameObject("Chunk:" + _pos.x + "|" + _pos.y);

            ChunkObject.transform.SetParent(worldSpace.transform);
            MeshRenderer = ChunkObject.AddComponent<MeshRenderer>();
            MeshFilter = ChunkObject.AddComponent<MeshFilter>();
            MeshRenderer.material = worldSpace.texAtlas;

            _vertices = new Vector3[x_length * z_length * y_length * 8];
            _triangles = new int[x_length * z_length * y_length * 36];
            _uvs = new Vector2[x_length * z_length * y_length * 8];

            chunkBlock = new Block[x_length * y_length * z_length];
        }

        public void GenRandom(float xStart, float yStart, float scale)
        {
            for (int i = 0; i < chunkBlock.Length; ++i)
            {
                Vector3 vecBlock = new Vector3(0, 0, 0);
                vecBlock.x += i % (x_length * z_length) % x_length;
                vecBlock.z += i % (x_length * z_length) / x_length;
                vecBlock.y += i / (x_length * z_length);
                float height = Mathf.PerlinNoise((xStart*16 + vecBlock.x)/scale, (yStart*16 +vecBlock.z)/scale);
                chunkBlock[i] = new Block(vecBlock.y < height*y_length ? 0 : 1); //TODO: Change to random
            }
        }

        public void Draw()
        {
            FillMeshDataBuffer();

            Mesh mesh = new Mesh();

            mesh.indexFormat = IndexFormat.UInt32;
            mesh.SetVertices(_vertices, 0, _verticesIndex);
            mesh.SetTriangles(_triangles, 0, _trianglesIndex, 0);
            mesh.SetUVs(0, _uvs, 0, _uvsIndex);

            mesh.RecalculateNormals();

            MeshFilter.mesh = mesh;

            ChunkObject.transform.position = new Vector3(_pos.x * x_length, 0f, _pos.y * z_length);
        }

        void FillMeshDataBuffer()
        {
            _verticesIndex = 0;
            _trianglesIndex = 0;
            _uvsIndex = 0;

            for (int i = 0; i < chunkBlock.Length; ++i)
            {
                if (chunkBlock[i].isSolid)
                {
                    if (i % (x_length * z_length) - x_length < 0 ||  i - x_length < 0
                        || !chunkBlock[i - x_length].isSolid)
                    {
                        AddFace(0, i);
                        AddUv(chunkBlock[i].Type, 0);
                    }
                    if (i % (x_length * z_length) + x_length > x_length * z_length - 1
                        || !chunkBlock[i + x_length].isSolid)
                    {
                        AddFace(1, i);
                        AddUv(chunkBlock[i].Type, 1);
                    }

                    if (i + x_length * z_length > x_length * z_length * y_length - 1
                        || !chunkBlock[i + x_length * z_length].isSolid)
                    {
                        AddFace(2, i);
                        AddUv(chunkBlock[i].Type, 2);
                    }
                    if (i - x_length * z_length < 0
                        || !chunkBlock[i - x_length * z_length].isSolid)
                    {
                        AddFace(3, i);
                        AddUv(chunkBlock[i].Type, 3);
                    }

                    if (i % (x_length * z_length) - 1 < 0
                        || i % (x_length * z_length) % x_length == 0
                        || !chunkBlock[i - 1].isSolid)
                    {
                        AddFace(4, i);
                        AddUv(chunkBlock[i].Type, 4);
                    }
                    if (i % (x_length * z_length) + 1 > x_length * z_length - 1
                        || i % (x_length * z_length) % x_length == x_length - 1
                        || !chunkBlock[i + 1].isSolid)
                    {
                        AddFace(5, i);
                        AddUv(chunkBlock[i].Type, 5);
                    }
                }
            }
        }

        void AddFace(int face, int pos)
        {
            Vector3 vertex = VoxelMeshData.VoxelVerts[VoxelMeshData.VoxelTris[face, 0]];
            vertex = AddPos(vertex, pos);
            AddVertexInVertices(vertex);

            vertex = VoxelMeshData.VoxelVerts[VoxelMeshData.VoxelTris[face, 1]];
            vertex = AddPos(vertex, pos);
            AddVertexInVertices(vertex);

            vertex = VoxelMeshData.VoxelVerts[VoxelMeshData.VoxelTris[face, 2]];
            vertex = AddPos(vertex, pos);
            AddVertexInVertices(vertex);

            vertex = VoxelMeshData.VoxelVerts[VoxelMeshData.VoxelTris[face, 3]];
            vertex = AddPos(vertex, pos);
            AddVertexInVertices(vertex);

            AddTriangleInTriangles(_verticesIndex - 4);
            AddTriangleInTriangles(_verticesIndex - 3);
            AddTriangleInTriangles(_verticesIndex - 2);
            AddTriangleInTriangles(_verticesIndex - 2);
            AddTriangleInTriangles(_verticesIndex - 3);
            AddTriangleInTriangles(_verticesIndex - 1);
        }

        Vector3 AddPos(Vector3 vertexIn, int pos)
        {
            Vector3 vertex = new Vector3(vertexIn.x, vertexIn.y, vertexIn.z);
            vertex.x += pos % (x_length * z_length) % x_length;
            vertex.z += pos % (x_length * z_length) / x_length;
            vertex.y += pos / (x_length * z_length);
            return vertex;
        }

        private void AddVertexInVertices(Vector3 vertex)
        {
            _vertices[_verticesIndex] = vertex;
            ++_verticesIndex;
        }

        private void AddTriangleInTriangles(int triangle)
        {
            _triangles[_trianglesIndex] = triangle;
            ++_trianglesIndex;
        }

        void AddUv(int type, int face)
        {
            int offset = BlockTypeData.UVData[type,face]; int posX = offset % VoxelMeshData.TextureAtlasSizeInBlocks;
            int posY = offset / VoxelMeshData.TextureAtlasSizeInBlocks;
            float startX = posX * VoxelMeshData.NormalizedBlockTextureSize;
            float startY = posY * VoxelMeshData.NormalizedBlockTextureSize;
            AddUvInUvs(new Vector2(startX, startY));
            AddUvInUvs(new Vector2(startX, startY + VoxelMeshData.NormalizedBlockTextureSize));
            AddUvInUvs(new Vector2(startX + VoxelMeshData.NormalizedBlockTextureSize, startY));
            AddUvInUvs(new Vector2(startX + VoxelMeshData.NormalizedBlockTextureSize, startY + VoxelMeshData.NormalizedBlockTextureSize));
        }

        private void AddUvInUvs(Vector2 uv)
        {
            _uvs[_uvsIndex] = uv;
            ++_uvsIndex;
        }
    }
}

```

# Answer
Using some info i found here How to remove seams from a tile map in 3D? I implemented a texel correction thingy in my AddUv Method

```
        void AddUv(int type, int face)
        {
            int tilesetWidth = 32;
            int tilesetHeight = 32;
            Vector2 texelCorrection = new Vector2(1f / tilesetWidth , 1f / tilesetHeight);
            int offset = BlockTypeData.UVData[type,face];
            int posX = offset % VoxelMeshData.TextureAtlasSizeInBlocks;
            int posY = offset / VoxelMeshData.TextureAtlasSizeInBlocks;
            float startX = posX * VoxelMeshData.NormalizedBlockTextureSize;
            float startY = posY * VoxelMeshData.NormalizedBlockTextureSize;
            AddUvInUvs(new Vector2(startX, startY) + texelCorrection);
            AddUvInUvs(new Vector2(startX + texelCorrection.x, startY + VoxelMeshData.NormalizedBlockTextureSize - texelCorrection.y));
            AddUvInUvs(new Vector2(startX + VoxelMeshData.NormalizedBlockTextureSize - texelCorrection.x, startY + texelCorrection.y));
            AddUvInUvs(new Vector2(startX + VoxelMeshData.NormalizedBlockTextureSize, startY + VoxelMeshData.NormalizedBlockTextureSize) - texelCorrection);
        }

```

Edit: This solution only works for short distances, if you want no seams to appear and you have a similar use case, turn off the default unity anti-aliasing + use the Sprite texture type. Then you can remove the texture correction which becomes unnecessary.
> 2 votes

---
Tags: unity, 3d, voxels, seams
---


# Question
Title: How to update the UI system in unity after changing a triangle in code
I am trying to write a real time Line Graph Renderer using the UI system in Unity 2019. Meaning I need to change the data on the fly and have the graph update.

What i have found is that OnPopulateMesh is not being called unless i Physically update the properties via the inspector, if i do it via the Update method in the rubbish test example below, the Triangle drawn on the screen does not update at all (despite the values in the inspector updating), the triangle will jump to it's new position, if i update something else on the script via the inspector.

Anyone know what i should use to update this via c#?

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

public class TriangleRenderer : Graphic
{
    public List<Vector3> Verts = new List<Vector3>
    {
        new Vector3(-100, -100, 0),
        new Vector3(-100, 100, 0),
        new Vector3(100, 100, 0)
    };

    protected override void OnPopulateMesh(VertexHelper vh)
    {
        vh.Clear();

        if(Verts.Count != 0 && Verts.Count % 3 == 0)
        {
            for(int i = 0; i < Verts.Count; i+=3)
            {
                vh.AddVert(Verts[i], Color.white, Vector2.zero);
                vh.AddVert(Verts[i+1], Color.white, Vector2.up);
                vh.AddVert(Verts[i+2], Color.white, Vector2.one);
                vh.AddTriangle(i, i + 1, i + 2);
            }
        }
    }

    bool flipped = false;
    private float speed = 2f;
    private Vector3 orig;
    private float freedom = 100f;

    protected override void Start()
    {
        base.Start();
        orig = Verts[2];
    }

    private void Update()
    {
        if (flipped)
        {
            Verts[2] = new Vector3(Verts[2].x + Time.deltaTime * speed, Verts[2].y, Verts[2].z);
        }
        else
        {
            Verts[2] = new Vector3(Verts[2].x - Time.deltaTime * speed, Verts[2].y, Verts[2].z);
        }

        if (Verts[2].x > orig.x + freedom || Verts[2].x < orig.x - freedom)
        {
            flipped = !flipped;
            Verts[2] = new Vector3(Mathf.Clamp(Verts[2].x, orig.x - freedom, orig.x + freedom), Verts[2].y, Verts[2].z);
        }
    }

```

}

# Answer
> 2 votes
Thanks to @DMGregory's response, I was able to get this working using the SetVerticesDirty() method from the UnityEngine.UI.Graphic class.

So to get the above horrible code udating the triangles in realtime, i could simply modify the update method as follows:

```
private void Update()
{
    if (flipped)
    {
        Verts[2] = new Vector3(Verts[2].x + Time.deltaTime * speed, Verts[2].y, Verts[2].z);
    }
    else
    {
        Verts[2] = new Vector3(Verts[2].x - Time.deltaTime * speed, Verts[2].y, Verts[2].z);
    }

    if (Verts[2].x > orig.x + freedom || Verts[2].x < orig.x - freedom)
    {
        flipped = !flipped;
        Verts[2] = new Vector3(Mathf.Clamp(Verts[2].x, orig.x - freedom, orig.x + freedom), Verts[2].y, Verts[2].z);
    }
    SetVerticesDirty();
}

```

---
Tags: unity, unity-ui
---


# Question
Title: Changing Ambient Light settings in Environment window does not affect scene after baking LightMap
My settings:
Unity version - Unity 2021.1.12f1
Lightmap Lighting Mode - Bake indirect
Render Path - URP

I want to change Ambient Light in Environment window while I have baked LightMap. Is it possible?

# Answer
Coloring shadows is possible when using post-processing effects. I did not find any other options.
> 0 votes

---
Tags: unity, rendering, lighting, shadows
---


# Question
Title: In a top down 3d game, how can I simulate snow without actually covering entire world in the particle system?
I am making a city builder, which has the classic camera features of any other city builder, move around, zoom, rotate, etc.

The problem Im facing atm is with snow. Snow falls really slowly, so if I make my snow vfx follow my camera and set it to "world" space, the camera outruns the snow (i.e there is no snow in the view for a few seconds until the vfx catches up) unless I make the vfx cover the entire world, which would be horrible for performance.

If I set the snow vfx to "local space" it just looks awful since the snow particles then actually follows the camera.

Is there some solution to this I'm missing where I can use a smaller bounds vfx to save on performance, while still keeping snow in camera view at all times?

# Answer
> 2 votes
As usual, the easiest option was the one that worked best.

My issue at first was that I had the snow fall from a rectangle above the camera. When I changed it to a 200x200 box around the camera with volume spawning instead, it looks quite natural and now moves quite well with the camera.

---
Tags: unity
---


# Question
Title: Unity 2D Script affects all current objects in a Scene
I looked around for a fix because I am sure it's either super simple of a fix or something that is commonly run across but nonetheless it's about time I asked straight up.

This is my code in the script. It's growing plants based on time but I'm mostly just Trying out Time based events and ran into a bit of a problem. When I click on one plant, the other 2 get harvested. Here is the code I ended up with:

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

public class betterPlantGrowthController : MonoBehaviour
{
    // This is a small location where to keep all pre-read and mostly prm Varables such as Time or Public Varables.
    // ======================Varables=============================

    public SpriteRenderer spriteRenderer;
    public Sprite[] spriteArray;
    public float time_ = 0;
    public double growthTime = 0;

    private int currentArrayNumber = 0;
    private bool currentlyGrowing = true;

    // ===========================================================

    void Update() // This updates every frame of the game/programe and will be where most your code ends up
    {
        if (currentlyGrowing == true)
        {
            time_ += Time.deltaTime; // Updates ever Sec

            if (time_ >= growthTime)
            {
                time_ = 0;
                currentArrayNumber += 1;
            }

            spriteRenderer.sprite = spriteArray[currentArrayNumber]; // Renders The Current Sprite/Plant-stage

            if (currentArrayNumber == 4) { currentlyGrowing = false; }
        }

        if (currentlyGrowing == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

                RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);

                if (hit.collider != null)
                {
                    currentArrayNumber = 0;
                    spriteRenderer.sprite = spriteArray[currentArrayNumber]; // Reseting the Render
                    currentlyGrowing = true;
                }
            }
        }
    }
}

```

It's a super simple wait till it grows and then clicks on it. Again, when they all reach stage 4 (the last stage) then click on it, they all revert to stage 0 (first stage) even tho there are multiple objects running in the game. Any ideas? Or suggestions on how to make it so that only the one clicked is updated/changed?

# Answer
> 2 votes
Philipp points out the way how to do it with the IPointerClickHandler, this approach uses the `OnMouseDown` suggested from DMGregory and some small improvements - mainly readablility, dont be afraid to name your variables longer, once you come back in the future you wont have a hard time trying to figure out what you meant.

```
using UnityEngine;

public class PlantController: MonoBehaviour {

    public SpriteRenderer spriteRenderer;
    public Sprite[] plantGrowStateSprites;

    [SerializeField]
    private double growthTimePerStage = 0;

    private float _timeInCurrentGrowState = 0;
    private GrowState _currentGrowState = GrowState.Seed;
    private bool _currentlyGrowing = true;

    enum GrowState {Seed = 0, Growing = 1, Blossom = 2, Unripe = 3, Mature = 4};

    void Update() {
        Growing();
    }

    private void Growing() {
        if (!_currentlyGrowing) return;
        _timeInCurrentGrowState += Time.deltaTime;
        if (_timeInCurrentGrowState >= growthTimePerStage) {
            _timeInCurrentGrowState = 0;
            _currentGrowState += 1;
        }
        spriteRenderer.sprite = plantGrowStateSprites[(int) _currentGrowState];
        if (_currentGrowState == GrowState.Mature) { _currentlyGrowing = false; }
    }

    private void Harvest() {
        if (_currentGrowState == GrowState.Mature) {
            _currentGrowState = GrowState.Seed;
            spriteRenderer.sprite = plantGrowStateSprites[(int) _currentGrowState];
            _currentlyGrowing = true;
        }
    }

    public void OnMouseDown() {
        Harvest();
    }
}

```

# Answer
> 1 votes
The problem is that when you do a raycast using the mouse position, you are just checking if that raycast hit *anything*, not if it hit the collider of this particular plant. The collider does not even need to be the collider of a different plant. Any collider you have in your scene will satisfy the condition `if (hit.collider != null)`.

You need to make sure that the collider you are checking against is the one of this particular plant.

How do you get that collider?

When this script is on the same object it controls, then you can do so with `GetComponent<Collider>()`. But it seems like you've built a controller script which is designed to receives the object it controls in a public property, so the script is not necessarily on the object it controls. So you might have to make the controller of the plant another public field.

---

But while this *should* work, you should also be aware that your solution is rather inefficient. It probably works fine with just 3 plants in the scene. But when you have 1000 plants in your scene, then you have 1000 controllers which will all perform the exact same raycast and receive the exact same result which they will then compare against their particular collider. This could cause a notable stutter each time the player clicks. A better solution could be to have a script which only exists once in the scene which is responsible for handling all mouse clicks and notifies the object that was clicked. There is actually a build-in solution for this: The `PhysicsRaycaster`/`PhysicsRaycaster2D` component on the camera, an `EventSystem` component somewhere in the scene (gets created automatically as soon as you add an UI canvas, by the way) and MonoBehaviours implementing the `IPointerClickHandler` interface.

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


title: How to send SDF equation to GPU shader?

text:
# Question
Title: How to send SDF equation to GPU shader?
I am working on a sandbox app that model stuff using SDF and its operators. I want to do the actual rendering on GPU. So once the SDF is defined (ex. box union with sphere, etc.) how do I push it to the GPU?

What currently comes in my mind is to define all possible SDF functions also on the GPU shader and map them to short command strings, send an array of commands to GPU (union, box, sphere, etc.) and call the mapped functions. Is there a better way?

# Answer
Normally the way this would be done is to compose the code you want your SDF shader to evaluate, as text or shader intermediate language, then ask the graphics driver to compile the generated code into a bespoke shader.

That's for instance how all the SDF demos on ShaderToy work: at runtime, on page load or after a modification by the user, the user-provided shader text is compiled to a new shader and executed.
> 1 votes

---
Tags: shaders, voxels, signed-distance-field
---


# Question
Title: Unity with VS Code: .sln generated is missing assemblies. Only .sln generated by Studio works (with Code as well)
**After every Unity update** I have a lot of problem with **missing assemblies** in **Visual Studio Code**.

```
The type or namespace name "UI" does not exist in the namespace "UnityEngine"

```

But after some messing around, somehow it always becomes fixed. I updated Unity again and now after wasting hours I decided to do it the right way and find out the source of the problem.

As it turns out the problem is simply that the `.sln` generated when the **external editor is VS Code** is just simply **missing a lot of assemblies**: (and its icon is VS10 instead of VS15)

Here's the full difference: Link

If I switch the **external editor to VS Studio** and click **Regenerate Project Files**, the `.sln` is now **full of assemblies**. (if I would just switch to it, it wouldn't touch the sln)

So now I switch back to VS Code, voilá it works because the assemblies are in the `.sln`.

**BUT** for some reason if I **restart Unity** the `.sln` is always **regenarated** because possibly it detects that it has been generated by VS Studio while the current editor is VS Code.

**So it's missing the assemblies every time I restart Unity.**

Now at least I know that **every time I launch Unity**,

1. I have to switch to VS Studio,
2. click Regenerate Project Files,
3. and then switch to VS Code.

But before the update it was fine. It's always like this and then somehow it becomes fixed automatically at startups as well.

What's causing this, how could I fix it? Thanks in advance!

# Answer
> 1 votes
Finally Unity answered:

> Looking at the file structure of this project, it seems that .csproj files are enabled to be generated for many packages.

So they suggested the following fix which **indeed solved it:**

* In the Unity editor, with the broken project opened, navigate to Edit \> Preferences... \> **External Tools**.
* Under "Generate .csproj files for:", **uncheck any checked boxes**.
* Click "**Regenerate project files**".
* **Restart VS Code**.

And for some reason I can still access my git packages in my IDE so then I don't know what "Git packages" checkbox is for.

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


# Question
Title: find one meter to scale in earth heightmap
I have a heightmap that scales from 0 to 255. the map is only for elevation (discluding water and ice) what would be the appropriate way to calculate the scale of one meter? heightmap below

# Answer
> 1 votes
If the final image came from this tutorial (as suggested in the comments), which in turn used these topography & bathymetry resources there's a few things that need to be addressed.

First, the tutorial states:

> For the topography map, I altered the contrast so that the mountains were less pronounced compared to the rest of the land.

That means that some of the original information for the elevations above sea level is lost. Specifically, some slopes will be steeper than indicated by the original data.

Next:

> ... I used Gimp’s Alpha Separation tool to make sure the sea layer occupied the lower 50% of the grayscale tones, and the land layer the upper 50% (so the sea would definitely map to indentations rather than outward features)

This means that 50% represents sea level in the final image. Everything below 50% is underwater while everything above 50% is above.

This complicates the scale because bathymetry portion of the image was originally scaled from -8000m to 0m while the topography portion was scaled from 0m to 6400m. The total data range is -8000m to 6400m. But 50% of that range isn't sea level! To deal with this, we need to normalize the lower & upper values separately and map each back onto its respective range. Assuming a 0 to 255 pixel representation, the elevation scale would be something like this:

```
data = pixel / 255;
if (data <= .5)
   return (1-(data / .5)) * -8000;
else
   return ((data / .5) - 1) * 6400;

```

Note: it's probably a good idea to guard the divisions in order to ensure the intermediate results have been bounded to the 0 to 1 range.

The final consideration is:

> I did some manual editing with the paintbrush tool to remove any remaining black lines around the continents. This gave a smoother shading for coastal shelves so that these gradually disappeared beneath the ocean layer rather than dropping down abruptly.

Again, this means that some of the data represented in the image isn't going to match the original source data.

To echo the suggestion in the comments: if you want accuracy, I would strongly recommend starting with the source data and creating your own composite image.

---
Tags: javascript, html-canvas, heightmap
---


title: How to force a sub-optimal path

text:
# Question
Title: How to force a sub-optimal path
I'm currently trying to develop a "Taxi-Driver" AI that intentionally makes sub-optimal pathing decisions. I need to have my driver go from point A to point B using a *sub-optimal* but still *logical* path. "Logical" in this case isn't a well-defined condition per-se but it is instead defined as a path that would make sense to a passenger (player).

Here's an example where

* **Green = Optimal**
* **Red = Suboptimal but "logical"**
* **Blue = Suboptimal but "illogical"**

I'm currently using A\* so I tried modifying node weights but I couldn't find a way to come up with a logical value for the weight. I've also tried to sometimes pick a random open node (in the right direction) instead of calculating the closest node. However this (understandably) made the pathing look even more illogical.

If it can be done I'd like an A\* solution but I'm open to other solutions as well (even non-pathfinding solutions!). It is fine if a solution doesn't always give a sub-optimal path for certain conditions (e.g. only one path possible; all paths are the same length etc).

# Answer
> 3 votes
Your red path follows a pretty simple decision metric.

1. At each intersection, first evaluate which paths can reach the goal, and eliminate any that can't - this stops the algorithm from getting stuck in dead ends.
2. Next, evaluate which paths lead "toward" the goal (ie. the dot product of the path direction with a vector pointing to the goal is greater than zero). If at least one path leads toward the goal, eliminate any that don't.

At the first intersection, the goal is both north and east of us, so both the north and east roads pass this filter.

The south road travels opposite the direction to the goal, so it is eliminated (taking this eliminated path is what makes the blue route look illogical)
3. If there are multiple paths remaining, eliminate the shortest path(s) (plural because there may be ties), making sure to retain at least one valid option in the event that all routes are tied.

This eliminates the green route from the first intersection, leaving only one choice, the "sub-optimal but logical" red route.
4. Choose arbitrarily or randomly from the remaining options, in case you have several.

Note though that there are maps where this will still give you the shortest path, if no opportunities to pick a longer-but-still-logical path present themselves at any single intersection.

# Answer
> 4 votes
You can do this by forcing your A\* heuristic to be inadmissible.

An admissible heuristic is any heuristic which is strictly less than the true shortest path length. An example of an admissible heuristic is the euclidean distance to the target.

Admissible heuristics guarantee the optimal solution. So how do you garauntee a sub-optimal solution? You make your heuristic **over-estimate** the cost to the goal. Want to also make your paths a bit random? Inject (pseudo)randomness into the heuristic.

Here's an insane heuristic that might get you what you want:

```
float heuristic(Node A, Node goal) {
   return Distance(A, goal) +
          Distance(A, goal) * abs(sin(A.position.x * goal.position.y));
}

```

This heuristic has a big chance of overestimating the path length to the goal because it adds this crazy periodic pseudo-random infaltion to distance calculation. By increasing the magnitude of that pseudo-random signal you can force the algorithm to choose suboptimal or random looking paths.

EDIT:

Another way I can think of is this:

1. Find the optimal path with A\*
2. Pick a random cell along the optimal path and disallow it.
3. Find a new optimal path with a new map given from (2)
4. If a path can't be found clear the "unallowed" cells, and repeat 2 for until you've reached K iterations. If a path can't be found after K iterations, give up and just return the optimal path.
5. Otherwise return this new (sub-optimal) path.

# Answer
> 0 votes
You aren't really forcing a sub-optimal path, **you're optimizing for something different.**

"Logical" isn't well defined because "something that would make sense to a passenger" could mean different things to different passengers. However, it seems safe to assume that all passengers would have some logic behind what they find reasonable. You could find one sub-optimal solution, or even use different algorithms for different drivers depending on your goals. Either way, the difference from an optimal solution would ideally be based in how you want this AI to be perceived by the player.

UPS famously started using computer planning for driver routes decades ago, and this article gives some good examples:

> The earliest versions of Orion focused on getting the best mathematical results, with insufficient regard for the interests of the driver or the customer, who value some level of routine. For example, regular business customers who receive packages on a daily basis don’t want UPS to show up at 10 a.m. one day, and 5 p.m. the next. And a customer who is expecting a shipment of frozen food needs delivery as soon as possible, even if efficiency demands that someone gets priority.

The most well known feature is that they try and avoid left turns whenever possible due to time spent idling waiting for opposing traffic to clear. So in your example, if you introduced a penalty for left turns, the red line would instead go straight for two blocks before turning right and heading due south to the goal. Depending on the exact position of the goal, this could even appear more logical.

Other ideas you could throw into a situation like this would be areas with traffic jams, construction, or any other excuse to add a bit of higher cost to certain blocks that would nudge the pathfinder to avoid them without completely ruling them out when it makes sense.

---
Tags: ai, path-finding, behavior
---


# Question
Title: 3D Asset Creation. "Joining" parts VS Hidden/Redundant Faces?
I am trying to create a Laser Cannon in 3D art program Maya. It is for use in a game made in Unreal Engine.

I have this same 'problem' with many aspects of my 3D CG Art but this is just one simple example of the problem.

I'm unsure whether it is better to chop all faces out and link the meshes together, or indeed just have the two (or more) objects intersect each-other (which seems to be a much simpler way to create the art (including doing the UV mapping, texturing, etc).

The cannon looks fine to me as it is, but I wonder if this will cause problems using this approach going forward. Many tutorials I watch they go to much trouble to chop out all of the faces and join the barrel to the mounting dome.

Should I stop doing this and start joining them?

Thank you for any advice.

# Answer
> 1 votes
First of all, combine the meshes. Such that what we expect to be a single object arrives as a single thing in the engine. There is no technical limitation preventing an object from having disconnected triangles. So when I say "combine meshes" I don't mean removing internal faces and linking surfaces.

---

Do you need to render this model with depth test disabled?

*For example, you might want to render a weapon in a first person shooter with depth test disabled as a solution for the weapon clipping through objects in the world (there are other solutions to that problem.*

If you answered yes. Then you don't want any internal faces. So cut and remove them.

---

Do you need to render this model with transparency?

*For example, perhaps you want to have it fade in and fade out.*

If you answered yes. Then you don't want any internal faces, they would be visible with transparency. So cut and remove them.

---

Will cutting the faces result in more faces than you had before?

*For example, you can model a wall with two triangles. Let us say there is a stair on the wall, covering a large area of it. If you want to cut the wall to only the visible part, you will be making the wall with a series of small triangles, when the wall only required two before.*

If you answered yes. That is an argument for not cutting them, because it means you are increasing the polygon count.

Common wisdom is to eliminate any internal faces to increase performance. However, any modern engine will support a depth pre-pass so hidden faces aren't a performance problem. On the other hand, more triangles might result in worse performance.

---

As per joining them, you should consider if the model will be rigged and animated, and how. Having separate pieces might give you the desired result (i.e. it is a mechanical piece, or you are going for that artistic style), otherwise you probably want to join them.

---

Now, imagine you went with one option but turns out actually you need the other option. Which of the two options when turning out to be wrong, results in less total effort counting the effort to fix it?

Let us say the version that is made of multiple pieces takes `x` amount of effort to make.

Then the version that have the parts cut - and possibly joint - takes that same effort `x` plus some extra effort `y` for cutting and joining, for a total of `x + y`.

Now, if you initially did the the version with multiple pieces and it turns out you need the other, you do that same `x + y` effort, except you didn't do it in one go.

But if you initially did the other one, and you need to cut it into multiple pieces - and possibly fill the holes - you are going to need the same `x + y` effort plus some `z` effort for splitting and patching, for a total of `x + y + z`. That is worst. *This is also an argument for keeping a version of the model before going into cutting and joining, just in case.*

So, you can start making the version with multiple pieces, and only do the cutting and joining if you have a reason to. *Be it performance, or animation, or some rendering tricks, or whatever.*

---

And finally that brings me to this: If you can try the models in engine, do so. You want to find out any unforeseen problems that may arise from importing to the engine.

If you don't know how or where the model will be used, on one hand you have possibly it looking wrong sometimes (e.g. without depth test, or with transparency), and on the other you have possibly worse performance (i.e. polygon count). So it makes sense to err on the side of correctness.

But if you do know. So you can get feedback and improve your process it to better fit the use case. Now, is this for a client? If it is, perhaps you can ask the client. If it isn't… Did you or your team make proof of concept without custom models? *It makes sense to test mechanics with simple geometric shapes or generic models before making custom art.* So, try the models there, or get somebody to do it.

---
Tags: 3d, 3d-meshes, maya
---


# Question
Title: Libgdx pre-rendering Bitmap font to pixmap texture causes slow in-game rendering
Im using libgdx scene2d to render 2d actors. Some of these actor groups originally included scene2d Label actors for rendering static text. The Labels work fine but drawing ~20 of them on the screen at once drops the frame rate by 10-15 frames, resulting in noticeably poor rendering while dragging.

I'm attempting to avoid the Labels by pre-drawing the text to textures, and rendering the textures as scene2d Image actors. I'm creating the texture using the code below. (Inspired by Libgdx FPS drop drawing alot of text)

I assumed, and have read, that textures are often faster. However when I replaced the Labels with the texture, it had the same, if not worse, effect on the frame rate. Oddly, I'm not experiencing this when adding textures from a file, which makes me think I'm doing something wrong in my code. Is there a different way I should be pre-rendering these pieces of text?

```
BitmapFont font =  manager.get(baseNameFont,BitmapFont.class);
GlyphLayout gl = new GlyphLayout(font,"Test Text");

int textWidth = (int)gl.width;
int textHeight = (int)gl.height;
LOGGER.info("textHeight: {}",textHeight);
//int width = Gdx.graphics.getWidth();
int width = textWidth;
//int height = 500;
int height = textHeight;

SpriteBatch spriteBatch = new SpriteBatch();

FrameBuffer m_fbo = new FrameBuffer(Pixmap.Format.RGB565, width,height, false);
m_fbo.begin();
Gdx.gl.glClearColor(1f,1f,1f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Matrix4 normalProjection = new Matrix4()

        .setToOrtho2D(0, 0, width,  height);
spriteBatch.setProjectionMatrix(normalProjection);

spriteBatch.begin();

font.draw(spriteBatch,gl,0,height);

spriteBatch.end();//finish write to buffer

Pixmap pm = ScreenUtils.getFrameBufferPixmap(0, 0, (int) width, (int) height);//write frame buffer to Pixmap

m_fbo.end();

m_fbo.dispose();
m_fbo = null;
spriteBatch.dispose();

Texture texture = new Texture(pm);
textTexture = new TextureRegion(texture);
textTexture.flip(false,true);
manager.add(texture);

```

# Answer
> 2 votes
The cause of this slowness was my misunderstanding about Libgdx culling. Scene2d *does not* automatically cull objects outside of the view frustum. Therefore my hundreds of shapes and labels were having `draw()` called when they weren't even visible in the camera. My short term fix for this was that I test whether an object is within the frustum during `draw()`, and as soon it's not visible I call setVisible(false) which tells GDX to skip the draw. I think a more elegant solution would be to set the culling area on the stage, but I would need to adjust it as the user pans the camera. I have not tested this since I've gotten past my current performance issues, but I believe it should work.

The answer comes from the same question on StackOverflow.

---
Tags: libgdx, performance, scene2d
---


# Question
Title: GPU Instanced Transparent Mesh Not Rendering
I'm trying to render a bunch of clouds via gpu instancing. This works perfectly fine with the default HDRP Lit Shader, and I get the following result:

However, as soon as I change the surface type from Opaque to Transparent, even at 100% opacity, the clouds all disappear, and I get this:

We can see that all the clouds are still being instanced, because their shadows are visible on the ground below, making it black. However, the actual clouds are not rendered at all, when they should still be fully visible.

I am rendering the clouds with the following line, on a script which takes in the ball mesh and white material.

```
Graphics.DrawMeshInstanced(cloudMesh, 0, cloudMat, batch.Select((a) => a.matrix).ToList());

```

Screenshot of broken material (which works fine if changed from transparent to opaque):

# Answer
> 1 votes
GPU instancing for transparent objects is broken right now. This is a bug on Unity's side.

I asked for a status update on the Unity forum in this post here: https://forum.unity.com/threads/drawmeshinstanced-not-working-with-transparent.1071062/

---
Tags: unity, rendering, gpu
---


# Question
Title: Given a 3D grid-based map system, how to find the middle point of an edge of the mesh of a tile on the grid
I have a grid-based map system. The grid is aligned to the X and Z axes. The tiles on said map are 3-dimensional, but flat, and can be located anywhere on the Y-axis.

If I need to get a Vector3 of the middle point of any extremity edge of the mesh of any given tile, how would I do that?

Update: adding further detail to elaborate further,

being as I am trying to find the middle point of 2 axes ON the edge of the mesh, it cannot be the average of all vertices on the edge. Example below:

Taking the above polygon as the example, assume that we are trying to find the middle point of the left-most edge (the edge with the smallest x value).

There are 3 vertices on this edge: (0, 0, 0) (0, 0, -0.52) (0, 0.3, -1)

Being as we are trying to find the point on a given edge, we can solve for 2 axes fairly easily. The X-axis will be at 0, being as we have chosen this edge. The Z-axis will be the average of the smallest and the largest vertices divided by 2 for the middle point of this axis. But the Y axis is going to vary for every possible permutation. If we took the average of all of our given Y values in this example, the result would be 0.1 - however, looking at the example, I know that the desired result should be 0, because I am searching for the middle point *on the mesh edge*, and at 0x, -0.5z, the edge is at 0y.

How do I solve this for any given potential problem like this?

# Answer
> 1 votes
From the picture I understand you want the point highlighter in green. Yet the tile has three vertex on that side instead of two.

Taking your example data, the vertex coordinates are:

```
p1.x = 0;   p1.y = 0;   p1.z = 0;
p2.x = 0;   p2.y = 0;   p2.z = -0.52;
p3.x = 0;   p3.y = 0.3; p2.z = -1;

```

Since we are looking at a side where `x = 0`. We know the solution must also have `x = 0`. Alright, let us get rid of the `x` column:

```
p1.y = 0;   p1.z = 0;
p2.y = 0;   p2.z = -0.52;
p3.y = 0.3; p2.z = -1;

```

Now, the side we are looking at goes from `z = 0` to `z = -1`. Thus, the solution must have `z = -0.5`, correct?

So, where does that fall? `z = -0.5` is between `p1.z = 0` and `p2.z = -0.52`. So, we can get rid of the rest of rows:

```
p1.y = 0;   p1.z = 0;
p2.y = 0;   p2.z = -0.52;

```

*If you have more vertex along the side, organize them by the relevant axis (`z` in this case), find between which two the value you have is, and then get rid of the rest. The point we are looking for is between those two vertex.*

Now, how far along is `z = -0.5` is between `p1.z = 0` and `p2.z = -0.52`?

Well, let us see:

```
w = (z - p1.z)/(p2.z - p1.z)

=>

w = (-0.5 - 0)/(-0.52 - 0)

=>

w = (-0.5)/(-0.52)

=>

w = 0.5/0.52 = 0.961538461538

```

Our `z = -0.5` is about `96%` along the way from `p1.z = 0` to `p2.z = -0.52`. So we want a point that is about `96%` between `p1` and `p2`, we can do this with linear interpolation. Let us use that to interpolate the `y` values, and we have our `y`:

```
y = p1.y + w * (p2.y - p1.y)

=>

y = 0 + w * (0 - 0)

=>

y = 0

```

Yeah, it is `y = 0`, as expected.

---
Tags: 3d, mesh, grid
---


# Question
Title: Entity Component Systems - component cross-lookup vs denormalization
This is my first project using ECS design and I come from a RDMS background for reference.

I'm building a ecology simulation that spans multiple planets, with the following ECS structure:

**Entities & Components**

* Planet (Components: Year)
* Biome (Components: Planet (Link to planet this biome is in))
* Species (Components: Population, Growth Rate, Biome (Link to biome they reside in))

**Systems**

* TimeSystem (Adds +1 to the year component every N ticks)
* PopulationGrowthSystem (Updates the Population component for each species *if a year has passed on the planet*)

**Question:**

I'm struggling with how the PopulationGrowthSystem should filter which Species Populations to update on each iteration.

Iterating through each Population component requires me to do a Species Entity-\>Biome Component-\>Planet Component lookup to check the year, which is terribly inefficient.

I've considered de-normalizing by putting something like year\_last\_updated in the Population Component, but it doesn't feel clean.

I've also considered just updating Population components every N-ticks, but Year needs to always be updated before the population is updated, and to my reading on proper ECS design, I shouldn't depend on the Systems being run in order.

I feel like I'm missing something obvious in how I'm approaching this.

# Answer
If I were to do this I would consider two approaches. It sounds like you considered the second option already but maybe the first one suits your design better.

1. Time Manager takes responsibility

I would add `EndYear()` method to the `PopulationGrowthSystem` and update like this.

```
TimeManager::update()
{
  for (component : Components)
    component.iterate();
  if (endYear)
    for (populationComponent: PopulationComponents)
      populationComponent.endYear();
}

```
2. Components take responsibility

In this case the component would take a parameter with the world state. I would probably use a struct with all the data in the game and pass a parameter by reference.

```
TimeManager::update()
{
  g_worldData.endYear = endYear;
  for (component : Components)
    component.iterate(g_worldData);
}

PopulationComponent::iterate(WorldData& data)
{
  if (data.endYear) ...
}

```
> 1 votes

---
Tags: entity-component-system
---


# Question
Title: Unity3D problem convert view input from PC to mobile
I have the FPS game project that works great for PC with a new input system, but I want to convert all of the new input that I've created to work on mobile too, so I make more binding and attach it at the `OnScreenStick` and `OnscreenButton` it works but except for `view` actions, the free look originally from `Delta[Mouse]`

the `view is Vector2 control type`.

so I added a new binding to `view` actions Delta\[TouchScreen\] for mobile input, it works with `OnScreensStick` but it's slower than a mouse view.

this is my script looks like :

```

private Default_Input defaultInput;

private Vector3 newCameraRotation;
private Vector3 newPlayerRotation;

public CharacterSettingModel playerSettings;

public Transform camHolder;
public Vector2 input_View;

private void Awake()
{
        defaultInput = new Default_Input();
        defaultInput.Character.View.performed += e => input_View = e.ReadValue<Vector2>();

        defaultInput.Enable();

        newCameraRotation = camHolder.localRotation.eulerAngles;
        newPlayerRotation = transform.localRotation.eulerAngles;
}

private void CalculateView()
{
        newCameraRotation.y += playerSettings.ViewXSentivity * (playerSettings.ViewXInverted ? -input_View.x : input_View.x) * Time.deltaTime;
        transform.localRotation = Quaternion.Euler(newPlayerRotation);

        newCameraRotation.x += playerSettings.ViewYSentivity * (playerSettings.ViewYInverted ? input_View.y : -input_View.y) * Time.deltaTime;
        newCameraRotation.x = Mathf.Clamp(newCameraRotation.x, viewClampYmin, viewClampYmax);

        camHolder.localRotation = Quaternion.Euler(newCameraRotation);
}

```

I wonder why it can happen?

# Answer
> 1 votes
Different input devices for the same action can provide a different "feel", which is often undesired but inherent in that not all input devices are created equal. But you can adjust for that by adding processors to individual binding in your input actions asset. When one input method feels "slower" than another, then the "Scale" processor might be able to fix that.

Note that processors can be assigned on three different levels: The action, the binding and the control. Think carefully about where you want to add it to avoid unintended side-effects.

---
Tags: unity
---


# Question
Title: When should I use velocity versus addForce when dealing with player objects?
I'm confused about these two methods in the Unity framework. Both make the player object move, stop, change direction, etc. When should one be used over the other and when is one appropriate?

# Answer
> 15 votes
You'd use `velocity` to move the object at a constant rate (for example a bullet) and `AddForce()` to add movement (for example a spaceship thruster). Also note there are two "types" of movement; force and impulse. For a spaceship thruster you'd use impulse.

# Answer
> 38 votes
Although there's already an accepted answer, I think there are some additional details worth covering.

**Using Velocity**

When you set velocity, you're overriding absolutely everything else that might affect that object's movement. In some situations this is desirable, such as setting the initial velocity of a bullet once at the moment it's fired, as in trojanfoe's example. Just be wary, because when used in the wrong situations it can cause issues:

* If multiple sources/scripts try to modify the same Rigidbody's velocity by setting it directly (ie. `body.velocity = foo`), then whichever one runs last wins, and the others have zero effect. This can lead to order of update bugs, in particular causing entities to hover or fall slowly (because downward acceleration due to gravity gets overridden before it can accumulate)
* If you're setting velocity every frame, collisions with other objects can be a bit weird. It's as though your object is being propelled by an engine with infinite torque - no matter how much velocity it loses on an impact, it's back up to top speed on the very next physics step, and its velocity isn't deflected away from the impact. This can lead to launching objects you collide with, or small objects being able to push huge ones much more easily than it seems like they should, or objects sliding slowly along static barriers instead of deflecting away/along them.

Both of these effects can be desired sometimes. For example, when I'm making Kinect games and I want the player's virtual avatar's limbs to be able to interact with the physics scene, I usually move those bodies using direct velocity setting. Because the player's actual hand is in a known place and didn't slow down from collision with that virtual object, their virtual hand needs to do the same to stay in alignment, so in this case we actually *want* to override all other physics effects to get it there.

**AddForce and Friends**

AddForce and similar helper functions, by contrast, are made to cooperate with everything else going on in the physics world. If multiple sources/scripts AddForce to a Rigidbody, all of those effects get added together to create a net change in the object's movement (which, depending on how it's calculated, may also be order-independent). This helps avoid one script completely stomping some other physics effect.

AddForce comes in four flavours by specifying the optional ForceMode parameter, which are useful for different things:

```
ForceMode       |   Use
-----------------------------------------------------------------------
Force (default) |   Accelerate an object over 1 time step, based on its mass.
                |   Units: Newtons = kg * m/s^2
                |
Acceleration    |   Accelerate an object over 1 time step, ignoring its mass. (like gravity)
                |   Units: m/s^2
                |
Impulse         |   Instantaneously propel an object, based on its mass
                |   Units: N * s = kg * m/s
                |
VelocityChange  |   Instantaneously propel an object, ignoring its mass
                |   (like body.velocity = foo, except multiple scripts can stack)
                |   Units:  m/s

```

If you're trying to model a continuous push over time (eg. something you're applying every FixedUpdate), like a car driving or a rocket burning or a gravity well pulling, you want Force or Acceleration. (Depending on whether you want heavy objects to accelerate slower)

If you're modelling a sudden, sharp change in motion, like firing a bullet, recoiling from an explosion, or bouncing off a barrier, then you more likely want Impulse or VelocityChange.

Using AddForce helps you achieve more physical realism, but it can also require that you spend more time thinking through the physics of your behaviour. For instance, if you want your body to have a finite acceleration up to a target speed, so that it reacts more realistically to collisions than setting the velocity every frame, you'll probably want a calculation similar to this helper function:

```
public static void AccelerateTo(this Rigidbody body, Vector3 targetVelocity, float maxAccel)
{
    Vector3 deltaV = targetVelocity - body.velocity;
    Vector3 accel = deltaV/Time.deltaTime;

    if(accel.sqrMagnitude > maxAccel * maxAccel)
        accel = accel.normalized * maxAccel;

    body.AddForce(accel, ForceMode.Acceleration);
}

```

The reason I call all of these "helper functions" is that technically you could achieve all the same ends with:

```
 body.velocity += suitablyCalculatedDeltaV;

```

(*I think*. It's possible Unity's PhysX/Box2D-based physics solvers buffer changes through AddForce separately, but I haven't seen obvious consequences of this)

So at the end of the day, what these functions really get us is *clarity of intent*. When I want to apply a gradual force, I don't need to remember to multiply my deltaV by Time.deltaTime and divide by mass, I just say I want ForceMode.Force and it's handled in a correct & consistent way. And when I or someone else comes to iterate on my code later, it's immediately clear what I meant, without needing to decode the time and mass calculations to figure it out.

# Answer
> 6 votes
In addition to **trojanfoe's** answer, Angry Birds vs Car Racing. Two major and different examples of these methods (`AddForce` and `velocity` respectively). For example, in Angry Birds use of velocity is little more difficult as you would have to set Projectile trajectory by your self, like,

When I use AddForce in Angry Birds, I would use,

`_birdRigidbody.AddForce(new Vector2(5,5));`

While when I use velocity then I would handle trajectory using

`x = v*t*Cos(theta)
 y = v*t*Sin(theta) - 0.5 * g * t *t`

Or something like this.

While in Car Racing game you would have to control speed all the time, not like Angry Birds i.e. Shoot and all. So in that scenario handle `velocity` is more useful than `AddForce`.

Hope you understand. At least little bit.

# Answer
> 0 votes
> Rigidbody Velocity and Rigidbody Addforce are two confusing functions in Unity 3D and often beginners fail to understand their difference. In This Article, we are going to discuss the difference between RigidBody.velocity and RigidBody.addforce.
>
> In both cases, whether it is Addforce or velocity function we are going to use the term force to explain them.
>
> When we are using Rigidbody.velocity , then, in that case, we are adding force to our object but this force will only move the object unless and until we keep applying force.
>
> For example
>
> body.velocity= new Vector3(0,0,5);
>
> Let say you have added 5f in z position and that force will be added when you'll press W key. So When you will press W key the object will instantly start at the speed of 5. It's like the same if you are adding force using this function on a car, that car will start at the speed of 5.
>
> body.velocity= new Vector3(0,0,200);
>
> And if you let say change the value to 200 and then after saving press W. Car will start running at the speed of 200 from starting which is not possible in real world.
>
> Now If you talk about Rigidbody.addforce
>
> By Continuing our Car example. if you add the force of 200 to car
>
> body.addforce(0,0,200);
>
> The Car will not start moving at the speed of 200 if we press W but it starts from slow and then increases its speeds and stops according to the value of Drag.
>
> Rigidbody.addforce starts slow and then speed up, just like you are dragging a heavy table, first you will start pushing that table, the table will just move a little bit from its position but if you keep pushing that table it will starting moving & if you leave that table it will cover some distance depending on surface and that's the same rigidbody.addforce do.
>
> You can use Rigidbody.velocity where you just want to move your object to react instantly like player jump & the result of that force will vanish just after the jump and you can use Rigidbody.addforce where you need slow start and then the continuous movement like a rocket. If you use Rigidbody.addforce in jump , Player/Object will remain in space for a while and then will come back to ground .

(source)

# Answer
> 0 votes
Adding to existing answers. From what I tested, it seem `AddForce` is buffered PER script. Meaning doing :

```
r.AddForce(Vector3.one);
r.velocity = Vector3.zero;

```

In the same script, will stop your rigidbody as you expect it to.

But if you do the same, each line in a different script, making sure they run in the correct order using Script execution order panel of Unity. It will keep moving.

However, replacing `AddForce` by his equivalent:

```
float v = (force / rigidbody.mass) * Time.fixedDeltaTime;
rigidbody.velocity += v;

```

Make it behave as expected.

I don't know if I missed something, because this is a quite strange behavior.

---
Tags: unity
---


title: LWJGL2 Camera Movement Stutter

text:
# Question
Title: LWJGL2 Camera Movement Stutter
I'm having quite some trouble with camera stutter in my LWJGL2 game. The stutter only occurs when moving the camera. When it stands still, the scene is rendered smoothly. I could verify that by animating the trees in the wind, and they don't stutter.

Also, I can confirm that the stutter was not introduced by the screen recording software, however I suspect that the recording made the stutter even worse.

My game uses delta-time multiplied with the velocities that are changed using the keyboard or directly by code.

Things I've already tried without success:

* Turn VSync on
* Remove all unrelated code
* Try with 30fps cap and 60fps cap

It's also not related to my graphics drivers since a different LWJGL2 project based on the same engine runs smoothly.

I'm also running some background threads to handle networking and am reusing Vec3 and Mat4 instances when calculating projection and translation matrices.

Any ideas on what could cause the stutter?

# Answer
> 0 votes
Nevermind, after searching for hours I found the error. I was periodically calling a cpu-intense method that refreshed the minimap. After moving the execution of this method into an own thread, the stutter disappeared. It's also worth mentioning that the stutter was appeared periodically so it makes perfect sense now why this happened.

---
Tags: opengl, java, camera, lwjgl
---


# Question
Title: Animation and Movement -- Prototyping Efficiently
I'm a solo dev working on prototyping my game's movement system. My character is intended to be agile and lightweight, with quick movement options and a knack for climbing.

As we know, the key to prototyping any game mechanic is efficiency. Get the minimum viable product together ASAP so you can test, iterate, and retest until you get it right. As such, producing quality art assets in the prototyping phase is generally a big no-no.

But here's the problem: A huge part making a movement system fun comes from elements that we would sooner classify as polish. In my case, this predominantly comes from acrobatic and fluid character animations. Empirically, it would be safe to say that other polish elements like particle effects, sound, and so on would also contribute to the intrinsic fun of moving through the world.

So now, I'm caught between a rock and a hard place: I can ignore animation and focus solely on how the character feels, but lose out on "finding the fun," or I could develop animation alongside my movement system but hamper my iteration time.

Have other developers run into this problem? If so, what are some ways that you have gone about addressing it?

# Answer
**Motivation as a Resource**

As a solo dev one of your single most precious resources is motivation. If adding polish to certain aspects of the game is going to increase your joy of working on the project, then I wouldn't be surprised if the personally rewarding route actually ends up simultaneously being the most efficient one.

**On The Philosophy of Grey Boxing**

In terms of iteration on the game design, I think it's hard to cleanly detangle the game's system design from the aesthetics of the game's theme, art and any mechanical juice or QoL you add. This de-tanglement might be easier in certain genres: say turn-based abstract strategy board games (chess?), or perhaps strategy card games (hearthstone). Nevertheless, I think in a lot of cases, especially with real-time games, grey boxing is a fundamentally flawed approach to development.

As a general philosophy I think it's impossible to iterate on design completely separately from it's aesthetics. Design and Aesthetics are in conversation with each other and this should be reflected in your dev process. This is of course if your primary concern is the experience of the player and not systems design in the abstract as a more academic endeavor (which is totally valid but is just different).

In large companies where various displines might only ever talk to eachother through leads or producers you have to cut down on two-way dependencies and construct a clear pipeline where system design, level design, art, movement physics etc. are neatly arranged. This is what must be done for the realities of production. But as a solo dev you're responsible for all of these aspects of the game anyways so this isn't an issue.

**Conclusion**

I would say if the movement system is core to your game and is novel, you probably should try to polish it to properly verify that it can work and feel as intended. If it's a movement system that is found in a ton of other games that you enjoy, then it's already verified that it *can* work and you can polish it later. In that case invest resources into unknown aspects of the prototype.
> 1 votes

---
Tags: animation, movement, prototyping
---


title: Godot bake NavMesh not working

text:
# Question
Title: Godot bake NavMesh not working
I have a layout similar to the official Godot NavMesh example program. It is:

```
-Main scene (Navigation node)
|
|-NavigationMeshInstance
||
||-MeshInstance
|
|-Enemy
|-Player

```

Whenever I try to bake a NavMesh, it loads, and nothing appears. All parameters in the Navigation Mesh in the available slot are default. Is there anything I'm doing wrong? Every guide, doc, or tutorial I saw didn't seem to diverge from what I have.

If you need any additional information, please ask.

# Answer
Most likely cause is that the geometry (the `MeshInstance` in this case) is too small.

---

First look at the property `cell/size` (the property Size under Cell). Which is the step for the coordinates of the navigation mesh. The default value is 0.3.

Then look at the property `region/min_size` (the property Min Size under Region). Which is the square root of how many cells a region must have.

---

So if you added a `MeshIntance` with a `CubeMesh` of the default dimensions, it is 2 by 2 by 2. So it has an up face of 2 by 2. In there we can fit 6 by 6 cells of 0.3. For a total of 36 cells. Ah, but the minimum region size is 8, that means that it needs at least 64 cells. So Godot will NOT create that region.

You can either:

* Make the `MeshIntance` bigger.
* Make the `cell/size` smaller.
* Make the `region/min_size` smaller.

---

Another thing is whether or not the region would be big enough for the "Agent". You can see in the `NavigationMesh` resource, under "Agent" the properties:

* `agent/height` (the default value is 2)
* `agent/radius` (the default value is 0.6)
* `agent/max_climb` (the default value is 0.9)
* `agent/max_slope` (the default value is 45)

This is what Godot will use to decide what areas are navigable. You will want to set these to match whatever will be moving using the navigation mesh.

**Addendum**: If I'm not mistaken, what actually happens is that the area is considered smaller by the radius. So the 2 by 2 face is reduced to 0.8 by 0.8 and then the rules I said above apply. *I'm not entirely sure because I calculate that the minimum square area with the default settings that generates region should be 3.6 by 3.6, but in testing I find 3.5 by 3.5. Perhaps due to something about rounding to cells is my best guess.*

---

*By the way, also check `geometry/parsed_geometry_type` is what you want. By default it is set to use `MeshIntance`, but you may want to use physics objects instead.*
> 1 votes

---
Tags: godot, navmesh, gdscript
---


title: Depth does not writes in texture

text:
# Question
Title: Depth does not writes in texture
I am doing volumetric fog. In the first pass I write down the depth of the front polygons of the cube, in the second pass I write down the depth of the back polygons of the cube, in the third pass I set two textures with depth and calculate the difference - this is the intensity of the fog. For checking, I set the first depth texture in the shader and see that the background on the screen is white (that is right, the texture is cleared 1.0), but in the place where the cube is zero depth, the cube is a solid color.

That is, the depth is not written into the texture. What to do?

```
    D3D11_DEPTH_STENCIL_DESC dsDesc;
    ZeroMemory(&dsDesc, sizeof(dsDesc));

    dsDesc.DepthEnable = true;
    dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc = D3D11_COMPARISON_LESS;

    dsDesc.StencilEnable = false;
    dsDesc.StencilReadMask = 0xFF;
    dsDesc.StencilWriteMask = 0xFF;

    hr = m_pd3dDevice->CreateDepthStencilState(&dsDesc, &m_DepthStencilStateFog);

    D3D11_TEXTURE2D_DESC descDepth;
    ZeroMemory(&descDepth, sizeof(descDepth));
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_R32_TYPELESS;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = m_pd3dDevice->CreateTexture2D(&descDepth, NULL, &m_pTextureDepthFront);
    if (FAILED(hr))
    {
        return;
    }

    hr = m_pd3dDevice->CreateTexture2D(&descDepth, NULL, &m_pTextureDepthBack);
    if (FAILED(hr))
        return;

    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    ZeroMemory(&descDSV, sizeof(descDSV));
    descDSV.Format = DXGI_FORMAT_D32_FLOAT;

    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
    hr = m_pd3dDevice->CreateDepthStencilView(m_pTextureDepthFront, &descDSV,

&pDepthStencilView_Front);
    if (FAILED(hr))
    {
        return;
    }

    hr = m_pd3dDevice->CreateDepthStencilView(m_pTextureDepthBack, &descDSV,

&pDepthStencilView_Back);
    if (FAILED(hr))
        return;

    D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
    ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc));

    shaderResourceViewDesc.Format = DXGI_FORMAT_R32_FLOAT;
    shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
    shaderResourceViewDesc.Texture2D.MipLevels = 1;

    hr = m_pd3dDevice->CreateShaderResourceView(m_pTextureDepthFront,

&shaderResourceViewDesc, &m_shaderResourceViewDepthFront);
    if (FAILED(hr))
    {
        return;
    }

    hr = m_pd3dDevice->CreateShaderResourceView(m_pTextureDepthBack,

&shaderResourceViewDesc, &m_shaderResourceViewDepthBack);
    if (FAILED(hr))
        return;

```

    struct VS_OUTPUT_DEPTH
    {
           float4 Position : SV_POSITION;
           float TexDepth: TEXCOORD0;
    };

    VS_OUTPUT_DEPTH vs_depth( float4 Position : POSITION )
    {
          VS_OUTPUT_DEPTH Output;

          Output.Position = mul( Position,mxRes  );
          Output.TexDepth=Output.Position.z/55;

          return( Output );
    }
//------------------------------------------------------------------------------------
// Pixel Shader
//------------------------------------------------------------------------------------
struct PS_OUT
{
    float4 color : SV_Target;
    float depth : SV_Depth;
};

PS_OUT ps_depth(VS_OUTPUT_DEPTH input)
{
        PS_OUT output = (PS_OUT)0;

        output.depth = input.TexDepth;

        return output;
}

```
</code></pre>

# Answer
> 1 votes
Forgot setup min max depth in viewport, now it works:

```
D3D11_VIEWPORT vp;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
...
m_pImmediateContext->RSSetViewports( 1, &vp );

```

---
Tags: textures, directx11, depth
---


# Question
Title: Why is spacebar causing Unity to fire last OnClick() event
I have a turn based roguelike with input issues that are driving me nuts.

I use the Unity Input/GetAxis() for keyboard input. I recently added a skill bar with clickable buttons that pass an int parameter to a simple class when clicked.

The problem I am having is that the OnClick() event, on the last button that was clicked, fires whenever the SPACE bar is pressed.

What could cause this? I do not have space set on any of the input Axes (I did originally and both the axes attached to SPACE and the OnClick() would fire)

Edit: The code is below. It is called by the OnClick() handler on the button in the inspector. If you run the project and press SPACE nothing happens. Then if you click a button the Debug.Log fires. Then press SPACE again and the debug fires again with the same button number as was last clicked.

```
public class SkillClickNotifier : MonoBehaviour
{
    [HideInInspector]
    public int SkillClicked;

    public void ButtonClicked(int skill)
    {
        Debug.Log("Button Clicked: "+ skill);
        // SkillClicked = skill;
        // GameManager.Notifications.PostNotification(this, "SkillClicked");
    }
}

```

# Answer
> 1 votes
I found the answer and am answering it myself in the hope it will help someone in the future.

In the Unity Button control there is a property called Navigation that defaults to Automatic. This is to allow keyboard navigation and was causing my issue when the Space bar was pressed. The correct setting for me was None.

# Answer
> 1 votes
When you click on the button, there will then be a color surrounding it, telling the user that the button is now the selected UI item. Hitting `Space` at this point "activates" the UI item.

This will not necessarily solve the issue, but clicking off the screen will remove the selection, and so when you'll press `Space` again, the `OnClick` event will not fire.

# Answer
> 0 votes
For those who are using the UI Toolkit:

```
var root = GetComponent<UIDocument>().rootVisualElement;

root.RegisterCallback<NavigationSubmitEvent>((evt) =>
{
    evt.StopPropagation();
}, TrickleDown.TrickleDown);

```

There's also a Cancel- and MoveEvent which might interest you.

---
Tags: unity
---


# Question
Title: Interpolating between positions unfeasible at 30 frames per second?
I am working on a 3D platformer in Unity and I am targeting Android devices. The game consists of a lot of objects smoothly interpolating from the bottom of the screen to the top.

This whole time I've been testing my game at 60 fps and the performance was quite good. However, when I tested the game at 30 fps, the interpolation of the objects was no longer smooth.

I initially thought that I have way too many objects in my scene and this might be affecting the interpolating performance. So I created a new project which only has the interpolation stuff and object pooling (you can download it here). But even then, the interpolation wasn't smooth at 30 fps. Here's the code I'm using for interpolating the object:

```
void FixedUpdate()
{
   rb.MovePosition(transform.position + transform.up * Time.fixedDeltaTime * speed);
}

```

I'm using the object's Rigidbody to interpolate it. I've already set the rigidbody to "Interpolate" and I turned on "isKinematic".

I first thought that the interpolation isn't smooth since I'm using Rigidbody. So I ditched the rigidbody and used `transform.Translate` instead. But even then the interpolation wasn't smooth. Next I tried `Vector3.Lerp`. Nope. That didn't work either. The stutter was still there. I even tried `Vector3.MoveTowards`. That didn't work. The interpolating was still laggy. I even tried turning on GPU instancing for the objects being interpolated (since they all use the same material). That didn't do it either.

Next I started playing around with the fixed timestep (in the Time settings). I thought that maybe if I set the timestep to 0.033, then the objects will interpolate smoothly at 30 fps. But that didn't work either.

I think it's really bizarre that a simple interpolation performs so poorly at 30 fps on an Android device. If the interpolation is only for a short distance, then you don't always notice the stutter. But like I said, in my game the objects have to interpolate from the bottom of the screen all the way to the top. In this case, you can clearly see the laggy movement during interpolation.

Is it possible that long distance interpolation is simply unfeasible for Android devices at 30 fps? How do so many Android game developers manage to achieve good performance at 30 fps? Feel free to download the new project I mentioned which only has the interpolation stuff and the object pooling. It is available here. It's a very simple projects. It only has the prefab that should be interpolated, the material for the prefab, the script for interpolating the prefab, the spawning and object pooling system (for spawning the prefab), and the script for setting frame rate to 30. That's it.

Below a gif of the objects' interpolation. It's not as shaky in reality (since I had to use a bad screen recorder and compress the gif) but it's still pretty close to how the objects move at 30 fps.

# Answer
There are 3 things you are possibly seeing happen (with a bonus fourth at the end)...

1. You are not updating the screen as often as you should
2. You are not updating the position as often as you should
3. You are just trying to do too much at 30 FPS, and 30 FPS can't keep up.

To that end...

1. Confirm you are really updating at 30 FPS
2. Confirm you are really updating the position a least 30 FPS
3. If you are doing both, then think about redesigning your game concept to slow it down

Here is one other thing to consider.

Imagine you're updating your graphics every 30 ms, and your position every 20. Frame update is on the left, position update on the right...

```
0
      20
30
      40
60    60
      80
90
      100
120   120
      140
150
      160
180   180

```

You can see that sometimes you will get two moves for a frame update, which will cause a jerky motion. Despite the suggestions I have up front, I'm wondering if what you're seeing is a reflection of this kind of uneven sampling.
> 0 votes

# Answer
I think this article summarizes the problem you are seeing FIX YOUR (UNITY) TIMESTEP!

You could calculate your `fixedDeltaTime` like:

```
Application.targetFrameRate = 30;
Time.fixedDeltaTime = 1 / Application.targetFrameRate;

```

---

Just to clear up some possible misunderstandings:

The fixed time step has nothing to do with the update or with when a current frame is drawn.

The fixed time step is only for the fixed update in which the physical calculations are performed. The fixed part is to ensure that the physical objects behave more reliably, even if you drop some frames.

Order of execution for event functions

On the other hand, there is Update, where calculations are performed, and after they are completed, no matter how long it took, the frame is finally drawn.

Also, you don't need to include the Library folder when you upload a project as it can be restored locally. I would recommend using a version control system like Git and storing projects on a server to ease collaboration. There is also a `gitignore` file in version control that excludes all files that do not need to be tracked (uploaded and downloaded).

For the frame stats you can use the profiler and or click the stats button on the top right of your game view window.
> 0 votes

---
Tags: unity, android, interpolation
---


# Question
Title: Relationship between equal-magnitude quaternions with different components
What is the relationship called between two quaternions that are equal in magnitude, but different in component values? They are not necessarily unit quaternions.

# Answer
Typically *all* quaternions we use for rotation are equal in magnitude, since we're most often using only unit quaternions.

There are two different unit quaternions corresponding to any 3D orientation you might choose, and all of them have a magnitude of 1, so just knowing that two of these quaternions have the same magnitude does not tell us anything about the orientations they represent.

More usefully, you can think of a unit quaternion as representing a rotation of \\$\theta\\$ radians about an axis indicated by a unit vector \\$\vec a = (a\_x, a\_y, a\_z)\\$ as having components...

$$w = \cos \frac \theta 2\\ x = a\_x \sin \frac \theta 2\\ y = a\_y \sin \frac \theta 2\\ z = a\_z \sin \frac \theta 2$$

So you if you want to examine the relationship between two quaternions, you can compare the directions of their imaginary x, y, z components to determine their axes of rotation, and compare the arc cosines of their real w components to determine their rotation angles.

The same applies to non-unit quaternions too, just normalize them first. The absolute magnitude doesn't change the orientation they represent. Some systems use this value for scale, other systems discard it entirely.
> 1 votes

---
Tags: quaternion
---


# Question
Title: Gameobject does not derive from MonoBehaviour
I am trying to put a gameobject into a prefab. Unity says "You are trying to save a Prefab that contains the script 'NPCDebugInfo', which does not derive from MonoBehaviour. This is not allowed. Please change the script to derive from MonoBehaviour or remove it from the GameObject 'yourgameobject'.

However, I don't see what I should do.

The script in question looks like this:

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

using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;

public class NPCDebugInfo : MonoBehaviour
{
    public Transform ThePlayer;//public so that we see it in the IDE. If we don't want that, make it private

    ...

```

I don't know what Unity really means and wants from me. What could I do to make this error message go away?

ps: For a clean test, I have created an empty gameobject and tried put my script onto it. Unity says "The script is an editor script."

So I will first find out what goes on here and why the script is actually on the other gameobject.

Thank you!

# Answer
I found my mistake:

The script was NOT in the "Editor" folder at first. Then, at some point, I moved it into the "Editor" folder. I didn't notice which effect this had.

Now when I take a look at a game object which uses this script, I can see that it actually doesn't work anymore:

After I moved the script from the Editor folder to a "normal" folder, the error message went away, and I could proceed as I wanted to.
> 2 votes

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


# Question
Title: Check if a 90 degree rotation will cause a collision
I'm practicing Unity by developing a 2D game where the player has to stack tetrominoes falling from the sky. The problem I've ran into is that upon a 90 degree rotation of the falling piece, the piece sometimes overlaps with the existing tower causing two pieces to be stuck together.

I would like to check if this overlap will happen before rotating my piece.

I'm aware that such a problem would probably be solved by rotating a copy "shadow" object and checking for collision and yet I have found no way to check if an object is colliding directly after spawning it. I'm also aware of the `Physics2D.OverlapBox` method but I'm really looking for a way to predict collision with a more complicated 2D shape.

Current code for the shadow collider attempt:

```
GameObject shadow = new GameObject();

shadow.transform.position = currentTetrisPiece.transform.position;
shadow.transform.rotation = currentTetrisPiece.transform.rotation;

PolygonCollider2D shadowCollider = shadow.AddComponent<PolygonCollider2D>();

PolygonCollider2D currentCollider = currentTetrisPiece.GetComponent<PolygonCollider2D>();
shadowCollider.isTrigger = true;
shadowCollider.points = currentCollider.points;

shadow.transform.RotateAround(rotationPoint, new Vector3(0, 0, 1), 90);

Physics2D.SyncTransforms();

bool collided = shadowCollider.IsTouchingLayers();

if (!collided)
{
    currentTetrisPiece.transform.RotateAround(rotationPoint, new Vector3(0, 0, 1), 90);
}

```

# Answer
From: Collider2D.IsTouchingLayers

"It is important to understand that checking if colliders are touching or not is performed against the last physics system update i.e. the state of touching colliders at that time. If you have just added a new Collider2D or have moved a Collider2D but a physics update has not yet taken place then the colliders will not be shown as touching. The touching state is identical to that indicated by the physics collision or trigger callbacks."

The physics loop doesn't know about the change when you check for collision. You should wait for a physics update or simulate it.

Physics.Simulate \- for simulating physics manually.

You should also check out this thread that started with the same problem as yours: Instant Collision Checking.

Rigidbody.SweepTest \- This is probably what you are looking for, but the problem there is no analog for rotation. Someone here: SweepTest for rotation came up with a hack to achieve this but I haven't tested it myself, so I will copy it here.

Collider2D.Cast \- a 2D alternative to SweepTest.

\[by "forcepusher"\]

```
var rigidbodyCompoennt = GetComponent<Rigidbody>();
var initialRotation = rigidbodyCompoennt.rotation;
rigidbodyCompoennt.rotation = rotationSweep;
var sweepHits = rigidbodyCompoennt.SweepTestAll(new Vector3(0f, 0.01f, 0f));
rigidbodyCompoennt.rotation = initialRotation;

```

The main idea is to rotate your object, then after a sweep test with unnoticeable movement - reset rotation back to normal.
> 0 votes

---
Tags: unity, collision-detection
---


# Question
Title: How do I store a branching board game path in python
I thought a fun way for my son and I to learn and improve our python programming skills respectively is to digitize one of his (and my and my mom's when we were his age) favorite board games, "Hey Pa! There's a goat on the roof". When I suggested the idea, I didn't remember that the game board had three branching paths that connect and diverge in different ways and now I am flummoxed on how to store the board position for the players logically.

Ultimately, you're trying to get from the goat pen on the left to the barn in the upper right. There's "power up" cards that can warp you around the board to the haystack / flower bed / wood pile / etc, so each position needs to be numbered. Since there's an uneven number of spaces in the three tracks, and the top and middle one meet at two different points, I didn't think an array would work. I couldn't wrap my head around how to use consecutive integers cleanly.

What are your thoughts on how we can make this work?

# Answer
> 0 votes
The method described in this answer can certainly work and is incredibly flexible. For example, that method would allow modifying the board at runtime! If you know you do not need that level of flexibility though, you can make things (subjectively) simpler by tailoring the code to your specific use case.

For example, if we wanted to allow moving on this board:

```
     3--4--5
    /  /
0--1--2

```

Then the following implementation which hard-codes in the split and join could be used:

```
SPLIT = 1
JOINS_TO_FOUR = [2,3]
LAST_SPACE = 5

def moves_from(space_index):
  """Returns an array of the space indexes of the moves that can
  be made from this space index.
  """
  if space_index == SPLIT:
      return [2,3]
  elif space_index in JOINS_TO_FOUR:
      return [4]
  elif 0 <= space_index < LAST_SPACE:
      return [space_index + 1]
  else:
      return []

```

# Answer
> 3 votes
Use an array of board space objects whose members include an array of other board space objects that it connects to. Then build a model of the board out of them.

In pseudocode:

```
object BoardSpace
    int Index
    array BoardSpace Connections()
    function AddConnection(BoardSpace space)
        Connections.AddElement(space)

```

So in your main program you have

```
array BoardSpace TheBoard()
function InitBoard
    for i = 0 to 9 # Let's say there are 10 spaces on the board
        TheBoard(i) = new BoardSpace
        TheBoard(i).Index = i

    # Board now has its objects, set up the connections:
    TheBoard(1).AddConnection(TheBoard(2))
    TheBoard(1).AddConnection(TheBoard(3))
    TheBoard(2).AddConnection(TheBoard(1))
    TheBoard(3).AddConnection(TheBoard(1))
    # etc, set up all connections.

```

In this example, space 1 connects to spaces 2 and 3. There are way more efficient ways to do this, but this idea can help you get going.

---
Tags: game-design, python, board-game
---


title: ECS - should everything be a system?

text:
# Question
Title: ECS - should everything be a system?
I've just recently started working with LibGDX and Ashley, and I find it to be really useful and I like working with the whole entity/component/system workflow. But I've been starting to layout the GUI and other aspects of the interface that dont exactly, to me, seem like they should be entities.

When using an ECS should EVERYTHING in your game be an entity with components/a system to control them?

# Answer
> 2 votes
Yes, all game objects should be entities with an appropriate component set, and each component should have a system that controls it.

The whole idea of ECS architecture is compartmentalisation of tasks, and to favour *composition over inheritance*(google that phrase).

The benefit of this is you do not need a whole load of derived game objects which may or may not have an API that you do not wish to use, and completely avoids the inheritance based "deadly diamond" problem. This makes the architecture extremely flexible, and keeps the entity class extremely simple.

Furthermore, if you wish to create say, UI entities, then you can simply create them with a different component set, which has no relevance to the game world, but is of interest to the graphics and input systems.

I could go on and on about the benefits of this design philosophy, which would turn this answer into a wall of text, so I will stop here and say to check this link, which will give you some more general information about the pattern, including it's drawbacks.

# Answer
> 1 votes
Stumbled on this old question and the short answer is “no”. Put only things in there that make sense. If you have something like a tilemap you don't need each tile to be an entity and iterate over that each frame. You could simply pass something like Tile\[\]\[\] to a RenderSystem to integrate drawing entities alongside it. The same goes for Gui, just hand it the necessary entities or complete entity engine.

OOP is still very powerful but like ECS just use it where it makes sense. You could however design everything for ECS, nothing wrong with that but usually takes more effort. The ECS architecture keeps things separated from each other which is very good.

---
Tags: libgdx, entity-system, design-patterns, ashley
---


# Question
Title: How to keep server-client clocks in-sync for precision networked games like Quake 3?
I'm working on a 2D top-down-shooter and doing my best to copy concepts used in networked games like Quake 3.

* I have an authoritative server.
* The server sends snapshots to clients.
* Snapshots contain a timestamp and entity positions.
* Entities are interpolated between snapshot positions so movement looks smooth.
* By necessity, entity interpolation occurs slightly "in the past" so that we have multiple snapshots in which to interpolate between.

The problem I'm facing is "clock synchronization".

* For simplicity-sake, let's just pretend for a moment that there is zero latency when transferring packets to and from the server.
* If the server clock is 60 seconds ahead of the client clock, then a snapshot timestamp will be 60000ms ahead of the client local timestamp.
* Therefore, entity snapshots will collect and sit for about 60 seconds before the client sees any given entity make his moves, because it takes that long for the client clock to catch up.

I've managed to overcome this by calculating the difference between the server and client clock each time a snapshot is received.

```
// For simplicity, don't worry about latency for now...
client_server_clock_delta = snapshot.server_timestamp - client_timestamp;

```

When determining how far along into the interpolation the entity is, I simply add the difference to the client's current time. The problem with this however, is that it will cause jerkiness because the difference between the two clocks will abruptly fluctuate due to snapshots arriving quicker/slower than others.

How can I synchronize the clocks closely enough that the only perceivable delay is that which is hard-coded for interpolation, and that which is caused by ordinary network latency?

In other words, how can I prevent interpolation from starting too late or too soon when clocks are significantly desynchronized, without introducing jerkiness?

*Edit: According to Wikipedia, NTP can be used to synchronize clocks over the internet to within a matter of a few milliseconds. However, the protocol seems complicated, and perhaps overkill for use in games?*

# Answer
After searching around, it seems that synchronizing the clocks of 2 or more computers is not a trivial task. A protocol like NTP does a good job but is supposedly slow and too complex to be practical in games. Also, it uses UDP which won't work for me because I'm working with web-sockets, which don't support UDP.

I found a method here however, which seems relatively simple:

It claims to synchronize clocks to within 150ms (or better) of each other.

I don't know if that will be good enough for my purposes, but I haven't been able to find a more precise alternative.

Here's the algorithm it provides:

> A simple clock synchronization technique is required for games. Ideally, it should have the following properties: reasonably accurate (150ms or better), quick to converge, simple to implement, able to run on stream-based protocols such as TCP.
>
> A simple algorithm with these properties is as follows:
>
> 1. Client stamps current local time on a "time request" packet and sends to server
> 2. Upon receipt by server, server stamps server-time and returns
> 3. Upon receipt by client, client subtracts current time from sent time and divides by two to compute latency. It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta. (So far this algothim is very similar to SNTP)
> 4. The first result should immediately be used to update the clock since it will get the local clock into at least the right ballpark (at least the right timezone!)
> 5. The client repeats steps 1 through 3 five or more times, pausing a few seconds each time. Other traffic may be allowed in the interim, but should be minimized for best results
> 6. The results of the packet receipts are accumulated and sorted in lowest-latency to highest-latency order. The median latency is determined by picking the mid-point sample from this ordered list.
> 7. All samples above approximately 1 standard-deviation from the median are discarded and the remaining samples are averaged using an arithmetic mean.
>
> The only subtlety of this algorithm is that packets above one standard deviation above the median are discarded. The purpose of this is to eliminate packets that were retransmitted by TCP. To visualize this, imagine that a sample of five packets was sent over TCP and there happened to be no retransmission. In this case, the latency histogram will have a single mode (cluster) centered around the median latency. Now imagine that in another trial, a single packet of the five is retransmitted. The retransmission will cause this one sample to fall far to the right on the latency histogram, on average twice as far away as the median of the primary mode. By simply cutting out all samples that fall more than one standard deviation away from the median, these stray modes are easily eliminated assuming that they do not comprise the bulk of the statistics.

This solution appears to answer my question satisfactorily well, because it synchronizes the clock and then stops, allowing time to flow linearly. Whereas my initial method updated the clock constantly, causing time to jump around a bit as snapshots are received.
> 14 votes

# Answer
Basically, you cannot fix the \[entire\] world and, eventually, you will have to draw the line.

If the server and all clients share the same frame-rate, they just need to synchronize upon connecting, and occasionally, thereafter, especially after a latency event. Latency does not affect the flow of time or the PC's ability to measure it so, in many cases, rather than interpolate, you must extrapolate. This creates equally unwanted effects but, again, it is what it is and you must choose the least of all available evils.

Consider that in many popular MMO's, lagging players are visually obvious. If you see them running in place, directly into a wall, your client is extrapolating. When your client receive's new data, the player (on their client) may have moved a considerable distance and will "rubber-band" or teleport to a new location (the "jerkiness" you mentioned?). This happens even in major, name-brand games.

Technically, this is a problem with the player's network infrastructure, not your game. The point at which it goes from one to the other is the very line you have to draw. Your code, on 3 separate computers, should more-or-less record the same amount of elapsed time. If you don't receive an update, it should not affect your Update() frame-rate; if anything, it should be faster since there is probably less to update.

"If you have crummy internet, you cannot play this game competitively."
That is not passing-the-buck or a bug.
> 1 votes

# Answer
Synchronizing clocks is the wrong idea to take here. You really want to synchronize simulations. You do this by creating a simulation that has deterministic behavior on both the client and server. The first step to deterministic simulation is using a game loop with a fixed timestep see: https://gafferongames.com/post/fix\_your\_timestep/

Once you have a fixed timestep deterministic loop, each tick can be deterministically reproducible. You can then reset the client to a tick from the server and replay the same behavior on the client.
> 1 votes

# Answer
This is all very game specific, but in general:

Unless you're doing fixed timestep synchronized simulation like in fighting games where each frame is extremely important, there's no reason to synchronize clocks or state *exactly* between server and client. The client just needs to see something that's good enough for them to understand what's happening. The physical limit that latency introduces means they can *never* be perfectly synchronized unless everyone is viewing everything in the past, which again, is only useful for frame-dependent gameplay mechanics like Street Fighter et al have.

Even in a fast-paced shooter, it's not important to synchronize most state. It's only important that if you get a headshot, the server gives it to you in most or all cases. This is done via interpolating (ideally) or extrapolating (worst case, when snapshot not received in time, or for unimportant entities to save bandwidth) on the client-side, as you described in your question. The other half of the equation is server-side latency compensation to account for the fact that clients are seeing enemies in the past, and it decides if their attack should be successful based on a past world state, rather than the present one, to be fair to the client, up to some reasonable limit (i.e. max latency you support).

GafferOnGames has already been linked in an answer above, but +1 to the many great articles there.

In addition, Gabriel's series is one of, if not *the*, best resources currently available for explaining how this all works, with sample code.

So yeah.. asking "what's the best way to synchronize clocks in networked games" is essentially the XY problem, because the real answer is that you almost certaintly don't need to.

* In a fighting game, you sychronize frames, and you do it by simply making everyone wait until they received all of the data for a given frame before rendering (though modern fighting games are actually starting to move toward extrapolation by cleverly abusing the "charge up" frames of their animations, watch this talk about GGPO if you want to learn more about that).
* For real-time competitive games like CS:GO, Overwatch, etc. you do much more interpolation/extrapolation of basically everything in the scene, and "fix" the error on the server-side by calculating ray vs. hitbox in the past. Watch this talk about Overwatch if you want to learn more about FPS games).
* In most other games, you can most likely get away with interpolation, hardly any extrapolation, and no server-side compensation, because it's not fast enough or competitive enough for ~150ms of delay to matter as long as it renders *some approximation* smoothly.

The whole playlist that both of those video links are in is an excellent resource for more context about various types of games and how they're network architecture is laid out.
> 1 votes

---
Tags: networking, server, client-server, synchronization, socket
---