title: A*Pathfinding generating wrong path

text:
# Question
Title: A*Pathfinding generating wrong path
I'm building a maze game where there's an enemy ready to pursuit the player if the player gets in his range, I'm using A\*Pathfinding algorithm to do so, and I build the maze in a procedural way, where each block in the maze has a MapLocation with x and z position, so the start position is the enemy pos and goal is the player position, but when the RetracePath is called it generates an incomplete path causing the issue illustrated in the image below, I'm uploading a video to illustrate the problem:

```
IEnumerator Search(Vector3 start, Vector3 goal)
        {
            pathSuccess = false;
            waypoints = new Vector3[0];
            Heap<Path> open = new Heap<Path>(maze.MaxSize);
            HashSet<Path> closed = new HashSet<Path>();

            Path startNode = new Path(maze.GetMapLocation(start), 0, 0, 0, null);
            Path goalNode = new Path(maze.GetMapLocation(goal), 0, 0, 0, null);

            open.Add(startNode);
            lastPos = startNode;

            while (open.Count > 0)
            {
                if (lastPos.Equals(goalNode))
                {
                    pathSuccess = true;
                    break;
                }
                foreach (MapLocation dir in maze.directions)
                {
                    MapLocation neighbour = dir + lastPos.location;
                    if (maze.map[neighbour.x, neighbour.z] == 1) continue;
                    if (neighbour.x < 1 || neighbour.x >= maze.width || neighbour.z < 1 || neighbour.z >= maze.depth) continue;
                    if (IsClosed(neighbour, closed)) continue;

                    float G = Vector2.Distance(lastPos.location.ToVector(), neighbour.ToVector()) + lastPos.G;
                    float H = Vector2.Distance(neighbour.ToVector(), goalNode.location.ToVector());
                    float F = G + H;

                    if (!UpdateMarker(neighbour, G, H, F, lastPos, open))
                        open.Add(new Path(neighbour, G, H, F, lastPos));
                }
                Path pm = open.RemoveFirst();
                closed.Add(pm);

                lastPos = pm;
            }
            yield return null;
            if (pathSuccess)
            {
                waypoints = RetracePath(startNode);
            }
            PathRequestManager.Instance.FinishedProcessingPath(waypoints, pathSuccess);
        }

        bool UpdateMarker(MapLocation pos, float g, float h, float f, Path prt, Heap<Path> open)
        {
            foreach (Path p in open)
            {
                if (p.location.Equals(pos))
                {
                    p.G = g;
                    p.H = h;
                    p.F = f;
                    p.parent = prt;
                    return true;
                }
            }
            return false;
        }

        bool IsClosed(MapLocation marker, HashSet<Path> closed)
        {
            foreach (Path p in closed)
            {
                if (p.location.Equals(marker)) return true;
            }
            return false;
        }

        Vector3[] RetracePath(Path startNode)
        {
            Path begin = lastPos;
            List<Vector3> path = new List<Vector3>();
            while (!startNode.Equals(begin) && begin != null)
            {
                path.Add(begin.Position(maze));
                begin = begin.parent;
            }
            path.Reverse();
            return path.ToArray();
        }

public MapLocation GetMapLocation(Vector3 position)
        {
            MapLocation mapLocation = new MapLocation((int)position.x / scale, (int)position.z / scale);
            return mapLocation;
        }
public List<MapLocation> directions = new List<MapLocation>() {
                                            new MapLocation(1,0),
                                            new MapLocation(0,1),
                                            new MapLocation(-1,0),
                                            new MapLocation(0,-1) };

```

The maze is generated like this:

```
public class Recursive : Maze
    {
        public override void Generate()
        {
            Generate(5, 5);
        }

        void Generate(int x, int z)
        {
            if (CountSquareNeighbours(x, z) >= 2) return;
            map[x, z] = 0;

            directions.Shuffle();

            Generate(x + directions[0].x, z + directions[0].z);
            Generate(x + directions[1].x, z + directions[1].z);
            Generate(x + directions[2].x, z + directions[2].z);
            Generate(x + directions[3].x, z + directions[3].z);
        }

    }

public byte[,] map;
 public virtual void Generate()
        {
            for (int z = 0; z < depth; z++)
                for (int x = 0; x < width; x++)
                {
                   if(Random.Range(0,100) < 50)
                     map[x, z] = 0;     //1 = wall  0 = corridor
                }
        }

```

I already tried using Manhattan's Distance and it didn't make any difference:

```
float H = Mathf.Abs(neighbour.x - goalNode.location.x) + Mathf.Abs(neighbour.z - goalNode.location.z);

```

MapLocation:

```
public class MapLocation
    {
        public int x;
        public int z;

        public MapLocation(int _x, int _z)
        {
            x = _x;
            z = _z;
        }

        public Vector2 ToVector()
        {
            return new Vector2(x, z);
        }

        public Vector3 ToVector3(Maze maze)
        {
            return new Vector3(x * maze.scale, 0, z * maze.scale);
        }

        public static MapLocation operator +(MapLocation a, MapLocation b)
            => new MapLocation(a.x + b.x, a.z + b.z);

        public override bool Equals(object obj)
        {
            if ((obj == null) || !this.GetType().Equals(obj.GetType()))
            {
                return false;
            }
            else
            {
                return x == ((MapLocation)obj).x && z == ((MapLocation)obj).z;
            }
        }

        public override int GetHashCode()
        {
            return 0;
        }
    }

```

# Answer
The `GetMapLocation` was rounding the results down instead of up, misleading the path, so now I added some verification to see not only if the block is valid but round it up like this:

```
public MapLocation GetMapLocation(Vector3 position)
{
    int x = (int)Math.Round(position.x / scale, MidpointRounding.AwayFromZero);
    int z = (int)Math.Round(position.z / scale, MidpointRounding.AwayFromZero);

    // Check if the position is out of bounds
    if (x < 0 || x >= width || z < 0 || z >= depth)
    {
        return null;
    }

    // Check if the position is already a valid map location
    if (map[x, z] == 0)
    {
        return new MapLocation(x, z);
    }

    // Search for the closest valid map location
    int minDistance = int.MaxValue;
    MapLocation closestLocation = null;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < depth; j++)
        {
            if (map[i, j] == 0)
            {
                int distance = (i - x) * (i - x) + (j - z) * (j - z);
                if (distance < minDistance)
                {
                    minDistance = distance;
                    closestLocation = new MapLocation(i, j);
                }
            }
        }
    }
    Debug.Log(closestLocation.x + " " + closestLocation.z);
    return closestLocation;
}

```
> 0 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: Why is my color on my obj not showing in Unity!
I've been trying to import my full-color obj files to unity for a while now, but I can't get them to be in color. All of the colors show up in Meshlab, but not in Unity. All of the youtube videos I have watched have said that I need some sort of texture file but my obj doesn't have one. It is just the obj and it somehow has color in Meshlab. Is there some sort of setting I need to change in Unity? If I need a texture file for it to work, is there a way I can extract the texture file(s) from the obj?

# Answer
> 0 votes
Thanks for the link. It did not work with .obj. But after I open the obj in MeshLab, exported as .dae and imported to Unity, it worked!

---
Tags: unity, obj
---


# Question
Title: Unable to access an instanced health system
I am having an issue with a health system I am making for my game. I have been at it for 3 days now and have not made much progress. For reference, I am following this tutorial by code monkey: Code Monkey Health Tutorial. The goal is to have two buttons, one for healing and one to damage the player, and a Text Mesh Pro UI Text to show the health of the player, just for testing purposes. Unlike the tutorial, the buttons and text are just on a canvas, not attached to the player, as I am setting it up as a form of a HUD system. also, forgive the formatting, during troubleshooting, I was more focused on trying to fix my issue and my code became a bit of a mess. Sorry for that.

I have three scripts

```
    using UnityEngine;

    public class HealthSystem
    {
        private int _health;
        private int _healthMax;

        public HealthSystem(int healthMax)
        {
            this._healthMax = healthMax;
            _health = healthMax;
            Debug.Log("healthSystem Created");
        }
        public int GetHealth()
        {
            return _health;
        }
        public void Damage(int damageAmount)
        {
            _health -= damageAmount;
            if (_health < 0) _health = 0;
        }
        public void Heal(int healAmount)
        {
            _health += healAmount;
            if (_health > _healthMax) _health = _healthMax;
        }
    }

```

```
    using UnityEngine;

    public class GameHandler : MonoBehaviour
    {
        private HealthButtons _healthButtons;

        private void Start()
        {
            HealthSystem _healthSystem = new HealthSystem(100);
            Debug.Log("Health = "+_healthSystem.GetHealth());
            _healthButtons.Setup(_healthSystem);
        }
    }
}

```

```
using UnityEngine;
using TMPro;

    public class HealthButtons : MonoBehaviour
    {
        [SerializeField]
        private TextMeshProUGUI numberText;
        private static HealthSystem _healthSystem;
        private int intToStringHealth;

        public void DamageButton()
        {
            _healthSystem.Damage(10);
            Debug.Log(_healthSystem.GetHealth());
        }
        public void HealButton()
        {
            _healthSystem.Heal(10);
            Debug.Log(_healthSystem.GetHealth());
        }
        public void Setup(HealthSystem healthSystem)
        {
            if (healthSystem == null) Debug.Log("healthSystem");
            Debug.Log(healthSystem);
            _healthSystem = healthSystem;
            Debug.Log("Setup is running");
        }
        private void Update()
        {
            intToStringHealth = _healthSystem.GetHealth();
            numberText.text = intToStringHealth.ToString();
        }
    }

```

my issue currently is Im trying to create an instance of `HealthSystem` in `GameHandler`, which I am successful in, then pass the information to `HealthButtons` using `_healthButtons.Setup()`. This is where I become unsuccessful as I am getting a NullReferenceException error.

from my efforts of troubleshooting currently, I have determined I am not calling the instance correctly, but I do not want to use code monkey's libraries. I have tried making all classes monoclasses and attaching them to game objects and using SerializeFields for all my variables, which does work, but I am not sure that is best practice as I do know linking everything up in the inspector can be a chore if something goes wrong.

This tells me the solution should be fairly simple, I am just not able to articulate the question into google to get the correct answer. It may be a bit overkill just to test a function, but I would like to understand what I am doing wrong and get better. Thank you very much for your help.

# Answer
I found the answer. Philipp was very helpful in getting me to the fastest answer, but the answer I was looking for was to reference the UI canvas, then use a `GetComponent` to get to the `HealthButtons` script. I ended up using a `SerializedField` and a `Debug.Log()` and determined that I was never calling `HealthButtons` correctly. Below is the updated code.

```
using UnityEngine;

    public class HealthSystem
    {
        private int _health;
        private int _healthMax;

        public HealthSystem(int healthMax)
        {
            this._healthMax = healthMax;
            _health = healthMax;
            Debug.Log("healthSystem Created");
        }
        public int GetHealth()
        {
            return _health;
        }
        public void Damage(int damageAmount)
        {
            _health -= damageAmount;
            if (_health < 0) _health = 0;
        }
        public void Heal(int healAmount)
        {
            _health += healAmount;
            if (_health > _healthMax) _health = _healthMax;
        }
    }

```

```
using UnityEngine;

    public class GameHandler : MonoBehaviour
    {
        private GameObject canvas;

        private void Start()
        {
            canvas = GameObject.Find("DebugCanvas");
            HealthButtons _healthButtons = canvas.GetComponent<HealthButtons>();
            Debug.Log(_healthButtons);
            HealthSystem _healthSystem = new HealthSystem(100);
            Debug.Log("Health = "+_healthSystem.GetHealth());
            _healthButtons.Setup(_healthSystem);
        }
    }

```

```
using UnityEngine;
using TMPro;

    public class HealthButtons : MonoBehaviour
    {
        [SerializeField]
        private TextMeshProUGUI numberText;
        private HealthSystem _healthSystem;
        private int intToStringHealth;

        public void DamageButton()
        {
            _healthSystem.Damage(10);
            Debug.Log(_healthSystem.GetHealth());
        }
        public void HealButton()
        {
            _healthSystem.Heal(10);
            Debug.Log(_healthSystem.GetHealth());
        }
        public void Setup(HealthSystem healthSystem)
        {
            if (healthSystem == null) Debug.Log("healthSystem");
            Debug.Log(healthSystem);
            _healthSystem = healthSystem;
            Debug.Log("Setup is running");
        }
        private void Update()
        {
            intToStringHealth = _healthSystem.GetHealth();
            numberText.text = intToStringHealth.ToString();
        }
    }

```

Again, thank you so much philipp for making me realize I was focused on the wrong part of the problem.
> 0 votes

# Answer
You have a variable `private HealthButtons _healthButtons;` in your GameHandler script, but you are not setting it to anything in code. And you wouldn't be able to set it in the inspector, because it is neither `public` nor does it have the `[SerializeField]` property. So you probably get a NullReferenceException, because you are trying to call the method `.Setup` on a variable that is still uninitialized.

The simplest way to fix this problem and get you going would be to change that variable to public, go to the inspector and assign the HealthButtons to the "Health Buttons" field of your GameHandler.

Although personally I have the philosophy that mechanics should not know about the UI that visualizes them. I find it a much more flexible and robust architecture when the UI is completely self-sufficient and finds the mechanics it visualizes by itself. Or even better, to implement loose coupling through UnityEvents set up in the inspector.

Regarding your doubts about linking up things in the inspector: This is standard practice in Unity. A common beginners mistake is to distrust the Unity editor and trying to set up everything in code. But my experience is that the more you do via inspector and the less you do via code, the higher the flexibility of your components. You also gain a much faster your iteration speed, because anything exposed via inspector can be changed while the game is running. Anything you do via code require that you stop the game, make your code change, and restart it.
> 1 votes

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


# Question
Title: Why is Visual studio 2022 intellisense not working on unreal engine 4.27?
I am new to unreal engine. Whenever I add a new class on unreal engine and open it in visual studio 2022 the intellisense doesn't seem to work for instance if I write #include "" it does not show me all the components. I have added the game development with C++ in visual studio installer?

# Answer
> 0 votes
I'm facing the same issue. I found a temporary fix for it though; try using \<\> instead of "".

# Answer
> 0 votes
Looking at the docs. VS 2019 is the best suited for Unreal version 4.27.

https://docs.unrealengine.com/4.27/en-US/ProductionPipelines/DevelopmentSetup/VisualStudioSetup/

---
Tags: unreal-4
---


# Question
Title: How do I send data from client to server using LiteNetLib
I started with the example client and server from here and modified the client to send a response back to the server... which never arrives. What am I doing wrong? How do I do this?

Server:

```
using LiteNetLib;
using LiteNetLib.Utils;

Console.WriteLine("=== Server ===");
EventBasedNetListener listener = new EventBasedNetListener();
NetManager server = new NetManager(listener);
server.Start(9050);

listener.ConnectionRequestEvent += request => {
    if (server.ConnectedPeersCount < 10 /* max connections */)
        request.AcceptIfKey("SomeConnectionKey");
    else
        request.Reject();
};

listener.PeerConnectedEvent += peer => {
    Console.WriteLine("We got connection: {0}", peer.EndPoint); // Show peer ip
    NetDataWriter writer = new NetDataWriter();                 // Create writer class
    writer.Put("Hello client!");                                // Put some string
    peer.Send(writer, DeliveryMethod.ReliableOrdered);             // Send with reliability
};

listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) => {
    Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
    dataReader.Recycle();
};

while (!Console.KeyAvailable) {
    server.PollEvents();
    Thread.Sleep(15);
}

server.Stop();

```

Client:

```
using LiteNetLib;
using LiteNetLib.Utils;

Console.WriteLine("=== Client ===");
EventBasedNetListener listener = new EventBasedNetListener();
NetManager client = new NetManager(listener);
client.Start();
var serverPeer = client.Connect("localhost", 9050, "SomeConnectionKey");

listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) => {
    Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
    dataReader.Recycle();
};

NetDataWriter writer = new NetDataWriter();                 // Create writer class
writer.Put("Hello server!");                                // Put some string
serverPeer.Send(writer, DeliveryMethod.ReliableOrdered);    // Send with reliability

while (!Console.KeyAvailable) {
    client.PollEvents();
    Thread.Sleep(15);
}

client.Stop();

```

# Answer
You can use `client.SendUnconnectedMessage(packet,peer.EndPoint)` to send message to a fix endpoint - in your case the endpoint is the server.
> 1 votes

---
Tags: c#, networking, litenetlib
---


# Question
Title: Google Play requires new apps to have API level 33 (starting on Aug, 21, 2023). Can these apps be installed and played on phones with lower API's?
Today (**March 21, 2023**), Google sends out an email to developers as follows:

> Starting **August 31, 2023**: New apps and app updates must target API level 33 to be submitted to Google Play (Wear OS must target API 30).

If users have old phones with API level 27, or API level 28, can the new apps still be installed and played successfully on their old phones ?

# Answer
My understanding is that Google Play requires the **target** API to be 33 or above. Your **minimum** API will control if your app can be installed on phones with a lower API.

So if you want your app to be installable to Android API level 27 (for example) you'd have to use that as your **minimum** API level.

You can find more information about the difference between the target API and minimum API on the following StackOverflow question: What is the difference between min SDK version/target SDK version vs. compile SDK version?
> 1 votes

---
Tags: android, api
---


# Question
Title: glPatchParameteri(GL_PATCH_VERTICES, 4) causes access violation
I'm trying to create a tessellated terrain, for this purposes I'm following the LearnOpenGL tutorial: https://learnopengl.com/Guest-Articles/2021/Tessellation/Tessellation

However, when I set the number of vertices per patch, with `glPatchParameteri(GL_PATCH_VERTICES, 4)`, I have an acces violation exception. I use GLAD and I have created a Terrain class to set the terrain data to send to the GPU. Here the code of terrain class:

```
#include "TerrainGeneration.h"
TerrainGeneration::TerrainGeneration(int numberOfPatches) :
numberOfPatches{numberOfPatches}
{
  const int newSize = 4 * numberOfPatches * numberOfPatches;
  vertices.reserve(newSize);
  GenerateTerrainPatches();
  SetupDataBuffers();
}

void TerrainGeneration::GenerateTerrainPatches()
{
  float FnumberOfPatch = static_cast<float>(numberOfPatches);
  for(int i = 0; i < numberOfPatches; i++)
  {

    for (int j = 0; j < numberOfPatches; j++)
    {
        float Fi = static_cast<float>(i);
        float Fj = static_cast<float>(j);
        TerrainVertex FirstVertex;

        FirstVertex.Position = glm::vec3
        {
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * Fi / FnumberOfPatch,
            0.0f,
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * Fj / FnumberOfPatch
        };

        FirstVertex.UVCoord = glm::vec2
        {
            Fi / FnumberOfPatch,
            Fj / FnumberOfPatch
        };

        FirstVertex.Normal = glm::vec3
        {
            0.0f,
            1.0f,
            0.0f
        };

        TerrainVertex SecondVertex;

        SecondVertex.Position = glm::vec3
        {
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * (Fi + 1.0f) / FnumberOfPatch,
            0.0f,
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * Fj / FnumberOfPatch
        };

        SecondVertex.UVCoord = glm::vec2
        {
            (Fi + 1.0f) / FnumberOfPatch,
            Fj / FnumberOfPatch
        };

        SecondVertex.Normal = glm::vec3
        {
            0.0f,
            1.0f,
            0.0f
        };

        TerrainVertex ThirdVertex;

        ThirdVertex.Position = glm::vec3
        {
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * Fi / FnumberOfPatch,
            0.0f,
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * (Fj + 1.0f) / FnumberOfPatch
        };

        ThirdVertex.UVCoord = glm::vec2
        {
            Fi  / FnumberOfPatch,
            (Fj + 1.0f) / FnumberOfPatch
        };

        ThirdVertex.Normal = glm::vec3
        {
            0.0f,
            1.0f,
            0.0f
        };

        TerrainVertex FourthVertex;

        FourthVertex.Position = glm::vec3
        {
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * (Fi + 1.0f) / FnumberOfPatch,
            0.0f,
            -TERRAIN_DIM / 2.0f + TERRAIN_DIM * (Fj + 1.0f) / FnumberOfPatch
        };

        FourthVertex.UVCoord = glm::vec2
        {
            (Fi + 1.0f) / FnumberOfPatch,
            (Fj + 1.0f) / FnumberOfPatch
        };

        FourthVertex.Normal = glm::vec3
        {
            0.0f,
            1.0f,
            0.0f
        };
        vertices.emplace_back(FirstVertex);
        vertices.emplace_back(SecondVertex);
        vertices.emplace_back(ThirdVertex);
        vertices.emplace_back(FourthVertex);
    }
 }
}

void TerrainGeneration::SetupDataBuffers()
{
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);

  glBindVertexArray(VAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);

  glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(TerrainVertex),
  vertices.data(), GL_STATIC_DRAW);

  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)0);
  glEnableVertexAttribArray(0);

  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)(3 *
  sizeof(float)));
  glEnableVertexAttribArray(1);

  glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)(5 *
  sizeof(float)));
  glEnableVertexAttribArray(2);

  //---Here the exception occurs!---
  glPatchParameteri(GL_PATCH_VERTICES, 4);

}

void TerrainGeneration::DrawTerrain()
{
  glDrawArrays(GL_PATCHES, 0, 4 * numberOfPatches * numberOfPatches);
}

void TerrainGeneration::DeleteBuffers()
{
  glDeleteBuffers(1, &VBO);
  glDeleteVertexArrays(1, &VAO);
}

```

Thanks everyone.

# Answer
I have solved the problem. I post the solution for the future. I have chanced the Application.cpp code from:

```
// glfw: initialize and configure
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```

To:

```
// glfw: initialize and configure
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```

The tessellation shader is only available starting by OpenGL 4.0.
> 1 votes

---
Tags: opengl, c++, terrain, terrain-rendering, tessellation
---


# Question
Title: Most efficient method to render hundreds of thousands to millions of stationary particles
I am making an app to visualize data, I am new to Unity but have an extensive background with Blender.

I have written my script to read in data and plot those points. In this example its ~528k points. However, the performance is very bad, If I used distance based rendering I get an FPS of ~16 on a very beefy computer

I can get ~35FPS if I remove the distance rendering but then I get bleed through from particles behind those in front.

I've read about VFX Graph but my understanding is that this is not very C# based? But I'm not certain.

How can I increase the performance? Considering how well Blenders viewport handles 10 million particles I feel like there must be a trick I'm missing here to handle all of the particles. Is it related to materials? Is there a way to make the materials "dumber"?

# Answer
> 2 votes
The classic Unity particle engine (aka "Shuriken") doesn't make a lot of use of GPU acceleration. The visual effect graph (VFX graph) is far better in that regard resulting in superior performance in many use-cases. There are some demos that demonstrate how it's able to handle millions of particles in real-time. And not just as a static point cloud, but with the particles actually doing stuff. So it might be suitable for your use-case.

If you want to create a VFX graph particle system based on a set of pre-computed particle positions and properties, then you might want to use a point cache. A point cache requires that you convert your data into a pCache file. I unfortunately can not help you with that because I have no idea about the format your data is currently in or what tools you have available to convert it. But the format is pretty straight-forward, so it shouldn't be too difficult to build an own conversion program.

You can then import that `.pCache` file into your Unity project as an asset. You can then integrate that point cache into a VFX graph by:

1. Creating a Point Cache node
2. Assigning your pCache asset to it
3. Creating a "Single Burst" block to the "Spawn" node.
4. Wiring up the "Point Count" property of your point cache to the "Count" property of the Single Burst block
5. Creating a "Set Position from Map" block in the "Initialize Particles" node.
6. Wiring the "position" property of the point cache node to the "Attribute Map" property of the "Set Position from Map" block.
7. (optional) If you want to transform the data in your point cache based on some runtime property, then you can do that by putting a couple arithmetic operator nodes between the point cache node and the set position node (Operator\>Math\>Arithmetic).
8. Repeating steps 5 to 7 for any other properties you have in your pCache file which you want to be represented in your visualization

For more information, please refer to the documentation about point caches in the VFX graph.

---
Tags: unity
---


# Question
Title: Unity's Animation Rigging Override on Rig with Optimize game objects enabled
I’m working on a top down third person shooter game and was trying to add recoil animations that we can easily tweak through code for all of the different guns available. I wanted to do this through Unity’s animation rigging overrides but was running into some limitations.

Firstly, character models have been set up with **optimize game objects** enabled in the fbx settings due to which animation rigging straight up refuses to work. As far as I’m aware animation rigging does not work when optimizing game objects is enabled as it expects the default bone hierarchy implementation.

I tried to work around this by removing the optimize game objects setting for the character models. This allowed the animation rigging to work but caused the character skins system to break. Basically the current system allows the user to change character skins by replacing the mesh in the skinned mesh renderer. This only works when optimize game objects is enabled for all of the fbx models as it uses the same bone structuring across all fbx files, allowing meshes to be used interchangeably.

Here is the error I get when trying to change the mesh on runtime when optimize game objects is disabled in the fbx settings.

Keeping in mind the limitations I’ve mentioned above, are there any workarounds I can use to get the functionality I desire?

# Answer
> 0 votes
My approach to this would be to create the recoil animation in Blender as the most intense one, put it on a separate animation layer in the animator controller and tweak its intensity through the weight of that animation layer.

When multiple animations on different layers affect the same bones, then the layer weights will decide how those animations are blended. So when you have a pose on layer A that places the arms in the neutral position and an animation in layer B that moves the arms from the neutral position to the recoil position and back, then the weight of the lower layer decides how much the arms will move.

You can also sync the speed of the recoil animation with the fire rate of the weapon. You can do that in the animator controller by going to the inspector of the recoil animation state and setting a property to act as a "Multiplier" for the "Speed".

---
Tags: unity, rigging
---


# Question
Title: cyclic dependency error in roblox survival game
# Description

In my game, I have have 3 module files: "PlayerList.lua", "PlayerData.lua" and "WorldData.lua".

1. PlayerList.lua = a list of PlayerData classes (requires PlayerData)
2. PlayerData = a table with data related to the player
3. WorldData = a table to keep track of world data and functions that are related to modifying the game world i.e. spawning structures and physical items in

Require path: WorldData \<-\> PlayerList \<-\> PlayerData

`PlayerData` requires `WorldData` because the function `PlayerData:GiveItem()` needs to drop an item on the ground (into the workspace) if the inventory is full.

### PlayerData.lua

```
local WorldData = require(game.ServerStorage.Rojo.WorldData)

function PlayerData:GiveItem(player: Player, itemId: string, amount: number | nil)
    ...
    if inventory is full then
        WorldData:CreateItem()
    end
    ...
end

```

And in `WorldData`, I need to require the `PlayerList` to get the player's information and add it to their inventory:

### WorldData.lua

```
local PlayerList = require(game.ServerStorage.Rojo.PlayerList) -- cyclic dependency!!

function WorldData:CreateItem(id: string, cframe: CFrame)
    ...
    local prompt = Instance.new("ProximityPrompt")
    prompt.ActionText = "Pick Up"
    prompt.MaxActivationDistance = 10
    prompt.Triggered:Connect(function(player: Player)
        -- give player the item
        PlayerList:GetPlayer(player):GiveItem(player, id)

        model:Destroy()
        self.Items[uuid] = nil
    end)
    ...
end

```

# What I have tried

I know this is a problem with my code structure so I have tried moving code around to their own files like `Inventory.lua` but I ended up having the same problem but with different files.

Ex. WorldData.lua \<-\> Inventory.lua

I have tried using singletons + dependency injection as chatgpt suggested but I couldn't really figure out how to get that to work.

I would like to keep world code and player code in their own files so it's easier to organize and scale my code base as I add more features which is why I have set them up like this.

# Answer
> -1 votes
From what I can tell what you just did is that you created a dependency with requirements with two different definitions but in two separate dependencies of world data and player data. I think in order to get around the loop of circular dependency is to split the circle entirely from itself and make a brand new abstraction for each world and player data so that one doesn't clash with each other making an error.

After making the first class, PlayerData.lua, which relies upon WorldData then making sure that the second class, WorldData.lua does not convene into PlayerData.lua.

When you run the script I suspect that PlayerData.lua compiles and once it sees WorldData.lua in its line it will try to compile that too. Of course that will cause it to run PlayerData.lua again and then complie WorldData.lua...

My solution to this might be lengthy and time consuming but unless someone with more experience shows us how to use Field Injections I think the best course of action is to delete every dependency related to WorldData.lua and PlayerData.lua and start fresh avoiding that error in the first place. If you need help writing code for getting around that I will keep in check.

---
Tags: software-engineering, lua, roblox
---


# Question
Title: Rendering 3D Scene Without PBR heedlessly
I am a beginner in computer graphics so I might have some terminological errors in my question. For an art project, I have a scene of modified planes with textures on them. The textures are taken from their designated folder, and they are updated with a different script now and then.

I want to render this scene whenever the textures are updated and save the image to another file. I don't need physics-based rendering, I don't need lights or shadows, I just need to see the scene with textured planes on the output rendered image and I want to run this on a server so It should be rendered headlessly.

What kind of strategy should I follow?

# Answer
> 0 votes
For this application you want to look at stand-alone rendering software used by CG artists or hobbyists, like Blender or POV-Ray (and probably many others that I don't have the names of). They are overkill in rendering capability, but will be straightforward to script to do what you want, since “change some inputs and re-render” is a basic sort of workflow.

Some alternatives to this:

* Use a game engine. This will be easy to set up but have lots of interactivity features that are actively unhelpful for your purpose.
* Write a program using graphics APIs directly for this purpose. This is fairly straightforward *as graphics programming goes*, but will involve lots more learning and programming than convincing POV-Ray to do what you want.
* Find a web browser that will run headless and use CSS 3D transforms to arrange your images. I don't know what the state of the field here is.

---
Tags: 3d, rendering, image
---


# Question
Title: Development pattern for interactive in-game tutorials
Interactive in-game tutorials often interrupt game flow and override standard behavior in a way that can be difficult to implement cleanly.

For example, imagine we have an action game and we want a tutorial to play when the player first takes damage:

> ```
> (When player first takes damage)
> [Pause Gameplay and zoom to player]
> Dialog: "You just took damage!"
> Dialog: "When you take damage, your health depletes:"
> [Highlight health bar, animate health dropping]
> Dialog: "Let's drink a potion to restore some health! Press I to open your inventory."
> (Wait for player to press I)
> [Show Inventory screen]
> Dialog: "Click a potion to drink it!"
> (Wait for player to click a potion)
> Dialog: "Using a potion consumes it and restores some health."
> [Remove one potion from inventory. Highlight health bar, animate health restoring]
>
> ```

A common way I see this implemented is by scattering conditionals throughout the code, e.g.:

```
public class Player : MonoBehavior {
    //...
    void OnCollisionEnter(Collision collision) {
        var damageSource = collision.gameObject.GetComponent<IDamageSource>();
        if (damageSource != null) {
            HP -= damageSource.Damage;
            var tutMan = TutorialManager.Instance;
            if (tutMan.Active && tutMan.CurrentStep == TutorialStep.WaitingForDamage) {
                tutMan.GoToStep(TutorialStep.PlayerTookDamage);
            } else {
                PlayPainSound();
            }
        }
    }
}

```

This approach can end up very messy, as it creates coupling, pollutes the gameplay code with tutorial logic, and adds performance overhead for checking if a tutorial is currently active.

We can reduce coupling using events, but that doesn't as easily let us skip or modify default behavior:

```
    void OnCollisionEnter(Collision collision) {
        var damageSource = collision.gameObject.GetComponent<IDamageSource>();
        if (damageSource != null) {
            HP -= damageSource.Damage;
            tookDamageEvent.Invoke(this, damageSource); //tutorial manager listens for this
            //we can no longer skip this code:
            PlayPainSound();
        }
    }

```

One potential alternative would be to create tutorial-specific components, such as `TutorialPlayer`, that extend the normal class and override with tutorial-specific logic where needed. However, this would require us to maintain separate prefabs with the tutorial-specific components, or be able to dynamically swap the components at runtime.

Another potential alternative is to add temporary components that have a higher execution order and block the default behavior, e.g.:

```
[RequireComponent(typeof(Player))]
public class TutorialPlayerCollisionDetector : MonoBehavior {
    void OnCollisionEnter(Collision collision) {
        var damageSource = collision.gameObject.GetComponent<IDamageSource>();
        if (damageSource != null) {
            var tutMan = TutorialManager.Instance;
            if (tutMan.Active && tutMan.CurrentStep == TutorialStep.WaitingForDamage) {
                GetComponent<Player>().DisableCollisions();
                tutMan.GoToStep(TutorialStep.PlayerTookDamage);
                Destroy(this);
            }
        }
    }
}

```

However, that approach can only interrupt Unity event functions such as `OnEnable()` and `OnCollisionEnter()`, not direct function calls.

Is there a standard pattern for implementing interactive tutorials that interrupt or replace normal game logic?

# Answer
> 28 votes
The best way I know how to do this is to have a notion of an "action queue".

When you want to cause an effect that might need to be pre-empted by something else, instead of executing the effect directly in the method you're running, you add the effect onto a global action queue.

Later in the frame, the action queue can tick, running any number of action-modifiers that inspect the queued items and decide whether to re-order them, cancel them, or insert new events in front. Then it can dequeue actions and run them one at a time, until it empties the queue or it encounters an action that forces it to wait for a transition to complete or to receive UI input. The remaining actions can just sit in queue, persisting from frame to frame until their turn comes or another action invalidates them.

This is particularly powerful for things like digital trading card games where the effect of one card could trigger an ability of another card to then react to, supersede, invalidate, or modify the original card's effects - especially if those modifications aren't just numeric but could add steps to the UI flow like prompting the player to select a target.

This can keep tutorial-specific code out of the majority of your scripts entirely. Instead, they just report their actions to the queue, with whatever labels the tutorial triggers might find interesting. Then the tutorial manager can be implemented as one of the action-modifiers that processes the queue before execution: if it sees an action labelled in a way that matches one of its tutorial rules (like "action: damage response"), it can leap into action and replace that block or chain, without needing to hook event listeners into every system that feeds this queue.

# Answer
> 11 votes
If you want to completely decouple the tutorial logic from the regular game logic, then you might need to redesign your software architecture to an event-based architecture. You already seem to know how `UnityEvent`s work, but an event-based architecture means that you use them much more extensively to separate the detection of a condition from all the different reactions to it. If you follow this paradigm thoroughly through your whole software architecture, then you gain a lot more flexibility because every separate reaction to an event is loosely coupled.

That means that when something in your game happens, like the player receives 10 damage, then you don't reduce the HP there and then. You invoke an event (`tookDamagedEvent.Invoke(this, 10)`). Each event can have multiple subscribers. So each reaction to the event should be a separate handler. In this case:

* Reducing the players `HP`
* Updating the health bar
* Playing the pain sound
* Showing the tutorial

would **all** be **separate** methods subscribed to this event.

OK, but how does that help us to change behavior at runtime?

Remember that you can also add and remove event subscriptions at runtime via `tookDamagedEvent.AddListener(handlerMethod)` and `tookDamagedEvent.RemoveListener(handlerMethod)` or activate and deactivate event listeners assigned via inspector with `tookDamagedEvent.SetPersistentListenerState(index, state)`. And when you declare the `tookDamagedEvent` as `public`, then systems like the TutorialManager can just do so themselves without the invoking MonoBehavior having to be aware of their existence. And they can even subscribe or unsubscribe handlers belonging to *other* objects. So the tutorial system can also temporarily remove/deactivate the listener for the pain sound and restore it after the tutorial is over. So by turning the sound into yet another event reaction, you **do** enable the tutorial system to "skip or modify default behavior".

---
Tags: unity, architecture, design-patterns, tutorials
---


# Question
Title: Creating RTV for each array slice of a Texture2DArray
I'm trying to implement depth peeling onto a 2D texture array, where each array slice corresponds to a depth layer. In order to do this, I'd like to draw to subsequent array slices of this texture, while using the previous slice for depth testing.

This seems impossible without copying subresources in between each draw, which I'd like to not do. I found this question, where the answer suggests using the `MipSlice` parameter to access the array slice. This seems like a mistake, as the subresources guide states clearly that mip slices select the miplevel for each array slice. I'd guess that in the case of mismatching texture types, like using a single array slice as its own resource, this would select the miplevel of that array slice. But it doesn't make sense to use the mip slice to access the entire resource as if by subresource index.

Even if you can do this, would the API know how far to increment the pointer into the GPU resource? Shouldn't incrementing the mip slice be telling the API to increment the pointer by less, to account for the smaller size (each mipslice has dimensions half that of the previous)?

# Answer
> 0 votes
I think the docs are a bit ambiguous - however;

https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11\_tex2d\_rtv

The Texture2D part of the RTV Description "Specifies the subresource from a 2D texture to use in a render-target view." and the mipSlice property "The index of the mipmap level to use mip slice."

The Subresources Guide tells you what the value of mipSlice should be in a TextureArray - a combination of mip level and array index obtained from CalcSubresource().

A texture array or texture containing mips, is a collection of subresources. I think the RTV mipSlice property would be better called "subresourceID" - but it works for me.

---
Tags: directx, rendertexture, directx12
---


title: How to procedurally compose shaders?

text:
# Question
Title: How to procedurally compose shaders?
I read several times that shaders can be composed by the engine on the fly, depending on graphical settings. How is this generally done?

# Answer
A common way that shaders are adapted depending on settings is through compiler directives like define macros and conditional compilation.

You can see a lot of examples of this if you look through the shader code of a free-to-use game engine like Unity (not specifically written in OpenGL-style glsl, though they use transpilers to output their shader code to OpenGL-compatible versions):

```
output.screenUV = output.positionCS.xyw;
#if UNITY_UV_STARTS_AT_TOP
output.screenUV.xy = output.screenUV.xy * float2(0.5, -0.5) + 0.5 * output.screenUV.z;
#else
output.screenUV.xy = output.screenUV.xy * 0.5 + 0.5 * output.screenUV.z;
#endif

```

This lets the shader adapt to different graphics APIs' conventions on where the (0, 0) point of a texture is: top-left for DirectX-like APIs, and bottom-left for OpenGL-like.

Here `UNITY_UV_STARTS_AT_TOP` is a macro that gets replaced by a constant during compilation. When invoking the shader compiler, the engine will include a shader source file with the needed constants for the platform/graphics API it's targeting. For instance, in `D3D11.hlsl` there's a line saying:

```
#define UNITY_UV_STARTS_AT_TOP 1

```

So when the compiler gets to `#if UNITY_UV_STARTS_AT_TOP`, that compiles to `#if 1` (ie. "yes") and the first version of the code gets compiled into the resulting shader, and the second version gets skipped over by the compiler.

If we were compiling this for OpenGL, we'd instead have defined this macro to be zero, and the first version of the code would be skipped over, compiling the second version into the resulting shader.

These macros can also define whole blocks of code - functions that do different things depending on needs, variable declarations that change their format or syntax to match what the platform wants, etc.

A deep material and lighting system will use these types of compiler switches for all sorts of things, including:

* Whether a feature is supported on a given graphics card. If not, replace the code that uses the feature with code that emulates the feature, or uses a graceful fallback instead.
* Whether this material is being lit by a spot- or point light (rays diverge) or a directional light (rays parallel) - this would swap out the math that calculates the lighting vector and attenuation factors, while leaving the code that *uses* these values to actually compute the colour common to both paths.
* Whether the material uses a particular feature, like detail maps. If not, the code that applies them can be compiled out of its shader entirely, rather than leaving a runtime branch that will never be taken.
* Whether the player has enabled an optional feature, like parallax occlusion mapping. If so, the code to do it is included. If not, it's stripped out or replaced with a cheaper fallback.

...etc.

This can result in a lot of code handling all these different cases, so in a large engine this will usually be parcelled off into several separate shader files that individual material shaders simply "include", rather than copy-pasting all this logic into every shader and creating a maintenance nightmare.

On modern graphics APIs, to save load times, a lot of this compilation is done in advance at edit/build time, stamping out the permutations of the shaders the engine will need for the given game content in a more efficient "intermediate representation" that can be digested by the graphics driver faster than parsing files upon files of human-readable code.

It's also possible to compile shaders from raw text, allowing you to just concatenate together a string with whatever code you want it to run. This is commonly how it's done in JavaScript for WebGL apps since we don't have a binary build in the same way as a native app. But for non-web applications, this is something you'd usually do only if you need extremely open-ended shader editing at runtime, like if you were making a shader graph material editor for users to create their own bespoke material effects. If you just want to apply some small, fixed set of settings tweaks, conditional compilation handles that in a more structured way, with fewer complications like needing to come up with non-colliding variable names in each block of code that's concatenated-on.
> 2 votes

# Answer
Different shaders are compiled/loaded depending on the settings selected. This is generally why games ask you to restart the game, so the correct shader can be loaded when the game boots and why you can't change some settings while the game is running, i.e. only from the main menu.
> -1 votes

---
Tags: opengl, c++, shaders, opengl-es3
---


# Question
Title: How do you make a object that always follow another object?
I'm trying to make a game object follow another game object and switch to another when a button is pressed. But right now it just seems to change the position when the button is pressed but it doesn't follow the object. How can I make it follow the other object?

```
public Transform PosObjOne;

public Transform PosObjTwo;

public Transform PosObjThree;

void Update () {
    if (Input.GetButtonDown("UseVr"))
    {
        PosObjThree.position = PosObjTwo.position;
    }

    if (Input.GetButtonDown("NoVr"))
    {
        PosObjThree.position = (PosObjOne.position);
    }
}
```

# Answer
> 1 votes
Well right now the position only gets set when you press the button, so there is no continuous loop that is setting the position after pressing your button once.

To keep the object at the other object's position you could make use of a boolean that is set to true once you press the button, and revert back when you press the other button again. Then in na if statement check the boolean's value and set the correct position.

For example:

```
public Transform PosObjOne;
public Transform PosObjTwo;
public Transform PosObjThree;
bool FollowOne = true;

void Update () {
    if (Input.GetButtonDown("UseVr")) {
        FollowOne = false;
    }

    if (Input.GetButtonDown("NoVr")) {
        FollowOne = true
    }

    if(FollowOne) {
        PosObjThree.position = PosObjOne.position;
    } else {
        PosObjThree.position = PosObjTwo.position;
    }
}

```

# Answer
> 0 votes
There is a little problem with the code. When you press the button "UseVR" *PlayerThree* does follow *PlayerTwo* but only for as long as the button is **pressed**. As you stop pressing the button, the `if` statement is `false`, and it stops following PlayerTwo, and same happens with the follow PlayerOne's `if` statement. So we need to insert a concept that follows the expected Player even after the button is pressed once. So making a `bool` variable, `childOf_Two` will solve the problem.

Declare the variable `childOf_Two` after declaration of three `Transform` variables.

```
private bool childOf_Two;

void Update () {
    if (Input.GetButtonDown("UseVr"))
    {
        childOf_Two = true;
    }
    if (Input.GetButtonDown("NoVr"))
    {
        childOf_Two = false;
    }
}

```

Now we know that `childOf_Two` will be true just after the button is pressed, and will be `true` for as long as you do not press another button. So now we want our PlayerOne to follow PlayerTwo after `childOf_Two` is `true`. So we will say that,

```
if (childOf_two == true)
{
    PosObjThree.position = PosObjTwo.position;
}
if (childOf_two == false)
{
    PosObjThree.position = PosObjOne.position;
}

```

We will write this inside `Update()` after the previous code. So now it will follow PlayerTwo as long as the value of `childOf_Two` stays `true` and will be same for PlayerOne.

Hope this helped.

# Answer
> 0 votes
you just can change reference to FollowGoal by any moment you want.

Transform FollowGoal;
Transform Enemy1;
Transform Enemy2;

void Update()
{
    if(Input.GetKeyDow(KeyCode.1))
    {
        FollowGoal= Enemy1;
    }

    if(Input.GetKeyDow(KeyCode.2))
    {
        FollowGoal= Enemy2;
    }

    Transform.position= Vector3.MoveTowards(transform.position, FollowGoal.position,speed);
}
```

# Answer
> 0 votes
Using physics joints may be the simplest approach to having one object follow another. Here is the Unity documentation on pyhsics joints: https://docs.unity3d.com/Manual/Joints.html

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


title: Help with understanding Vector3 math

text:
# Question
Title: Help with understanding Vector3 math
I was making a 3rd person player controller in Unity.

Would

```
Vector3 inputDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

```

be the same as

```
Vector3 inputDirection = new Vector3(horizontalInput, 0.0f, verticalInput)

```

?

I'm pretty new to Vectors, and would like help understanding how or how they aren't the same.

# Answer
> 0 votes
This expression:

```
inputDirection = orientation.forward * verticalInput + orientation.right * horizontalInput

```

can only equivalent to this:

```
inputDirection = new Vector3(horizontalInput, 0.0f, verticalInput)

```

if `orientation.forward` is `Vector3(0.0f, 0.0f, 1.0f)` and `orientation.right` is `Vector3(1.0f, 0.0f, 0.0f)`.

Which I cannot guarantee to be true. Why? Because `orientation` is a variable, and thus it might… well… vary. Using `orientation` allows you to have the input be… well… oriented differently. For example, to make it relative to move a character in a direction relative to where the camera is pointing or to move a vehicule according to its current orientation, and so on.

---

Ok, so you say you want to understand vectors. You need to start with these operations:

* Vector-Scalar product
* Vector addition

---

**Vector-Scalar product**

So, when you have a Vector-Scalar product such as this:

```
v * f

```

Is equivalent to this:

```
Vector3(v.x * f, v.y * f, v.z * f)

```

Thus, this:

```
orientation.forward * verticalInput

```

Is equivalent to this:

```
Vector3(
    orientation.forward.x * verticalInput,
    orientation.forward.y * verticalInput,
    orientation.forward.z * verticalInput
)

```

And this:

```
orientation.right * horizontalInput

```

Is equivalent to this:

```
Vector3(
    orientation.right.x * horizontalInput,
    orientation.right.y * horizontalInput,
    orientation.right.z * horizontalInput
)

```

---

**Vector addition**

If you add two vectors like this:

```
a + b

```

It is equivalent to this:

```
Vector3(a.x + b.x, a.y + b.y, a.z + b.z)

```

So when you have this:

```
Vector3(
    orientation.forward.x * verticalInput,
    orientation.forward.y * verticalInput,
    orientation.forward.z * verticalInput
) + Vector3(
    orientation.right.x * horizontalInput,
    orientation.right.y * horizontalInput,
    orientation.right.z * horizontalInput
)

```

It is equivalent to this:

```
Vector3(
    orientation.forward.x * verticalInput + orientation.right.x * horizontalInput,
    orientation.forward.y * verticalInput + orientation.right.y * horizontalInput,
    orientation.forward.z * verticalInput + orientation.right.z * horizontalInput
)

```

---

**Wrapping up**

So how can

```
Vector3(
    orientation.forward.x * verticalInput + orientation.right.x * horizontalInput,
    orientation.forward.y * verticalInput + orientation.right.y * horizontalInput,
    orientation.forward.z * verticalInput + orientation.right.z * horizontalInput
)

```

Be the same as this:

```
inputDirection = new Vector3(horizontalInput, 0.0f, verticalInput)

```

Well, it implies that:

```
horizontalInput == orientation.forward.x * verticalInput + orientation.right.x * horizontalInput

0.0f == orientation.forward.y * verticalInput + orientation.right.y * horizontalInput

verticalInput == orientation.forward.z * verticalInput + orientation.right.z * horizontalInput

```

And thus:

```
orientation.forward.x == 0.0f
orientation.right.x == 1.0f

orientation.forward.y == 0.0f
orientation.right.y == 0.0f

orientation.forward.z == 1.0f
orientation.right.z == 0.0f

```

Which is how I get this:

```
orientation.forward = Vector3(0.0f, 0.0f, 1.0f)

orientation.right = Vector3(1.0f, 0.0f, 0.0f)

```

---

**Learning material**

I'm going to send you to 3Blue1Brown video series on Linear Algebra.

*I have written an Introduction to Vector Algebra and How to Work With Arbitrarily Oriented Vectors before, which you go over if you rather my writing.*

---
Tags: mathematics, vector
---


# Question
Title: Is there a clear distinction between Game Loop and Gameplay Loop?
I'm wondering if Game Loop and Gameplay Loop are equal tho I feel like Game Loop has a larger scope than Gameplay Loop, or Gameplay Loop is called Game Loop for short. Anyone knows the origin of the two game-design concepts?

# Answer
The term "game loop" usually refers to the programming pattern that is the core of most game engines, while the term "gameplay loop" is a game design concept about how game and player interact. However, in a pure game design context, you sometimes have people say "game loop" when they actually mean "gameplay loop". So when you are talking specifically about game design and not about the implementation, the two terms are synonymous.

If you want to differentiate between gameplay loops at different scales of the design, then it is common to refer to them as "inner gameplay loops" and "outer gameplay loops". For example, when you design a 4X game like civilization, then you might describe an inner gameplay loop of picking units and moving units, while having an outer gameplay loop describing the turn progression (move units -\> manage cities -\> click next turn -\> watch opponent actions -\> read event messages). Or in an MMORPG you might have an inner gameplay loop of "pick enemy -\> kill enemy -\> collect loot" while you have an outer gameplay loop of "talk to questgiver -\> go to quest location -\> kill enemies -\> return to questgiver".
> 4 votes

---
Tags: game-design, terminology
---


title: How to execute early depth test

text:
# Question
Title: How to execute early depth test
I have trouble applying early depth test in my engine, to prevent fragment shader to be (fully) executed for fragments that will be overwritten anyway, because other fragments, drawn later, will be in front of them.

First, I do a depth only pass and write its result to a texture. This step seems correct (I already use it for SSAO).

Second, I do the main rendering pass. Here, each fragment shader begins by comparing the current depth value to the early depth test value, every fragment being further than the early depth test value being discarded.

My implementation (see below) makes me loose performance, and wrongly discards fragments depending of the epsilon used to compare the depth values. Any idea of what I do wrong?

I use OpenGL 3.3, in a forward rendering engine.

**Relevant fragment shader code:**

```
float linearize_depth(float depth,float near,float far)
{
  float ndc = depth * 2.0 - 1.0;
  float linearDepth = (2.0 * near * far) / (far + near - ndc * (far - near));
  return linearDepth;
}

void earlyDepthTest(vec2 fragPos, vec2 screenRes)
{
  vec2 res = gl_FragCoord.xy / vec2(800, 800);

  float earlyDepthNormalized = linearize_depth(texture(cameraDepthMapTexture, res).r, 0.1, 1024.0);
  float currentDepthNormalized = linearize_depth(gl_FragCoord.z, 0.1, 1024.0);
  float depthDifference = currentDepthNormalized - earlyDepthNormalized;

  if(depthDifference > 0.1)
    discard;
}

void main()
{
  earlyDepthTest(gl_FragCoord.xy, vec2(800, 800));

  // All fragment shader processing
}

```

# Answer
It sounds like you're using a technique called "Z pre-pass".

This is usually not implemented in the fragment shader. Instead, we re-use the depth buffer from the first depth-only pass as the depth buffer for the actual rendering pass. (ie. make sure you don't clear the depth between passes, or that you copy the old depth buffer over if you're rendering to a new destination)

We then set the render state's depth test, something like...

```
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

```

This is enough for the rasterization pipeline to perform the depth threshold on our behalf, before the fragment shader is even invoked, and abort further processing of whole 2x2 quads of fragments that end up being occluded.

Note that if your fragment shader outputs a modified depth (using gl\_FragDepth), that can disable early depth testing, since the GPU doesn't know the depth it should use for testing until after the fragment shader runs.
> 1 votes

---
Tags: opengl, shaders, depth-buffer
---


title: How to get current scene name?

text:
# Question
Title: How to get current scene name?
I want to acquire scene name to apply it in a condition.

I have an int variable 'audioplay' that is going to determine which AudioClip to play.

I tried

```
if (Scene == "main") {
    audioplay = Random.Range (1, 3);
} else if (Scene == "menu") {
    audioplay = 3;
}

```

But I get the error "error CS0118: 'UnityEngine.SceneManagement.Scene' is a 'type' but a 'variable' was expected".

# Answer
The SceneManagement namespace gives access to the active scene:

```
using UnityEngine.SceneManagement;

var currentScene = SceneManager.GetActiveScene();
var currentSceneName = currentScene.name;

```

In your code, I'm assuming that Scene has been returned from GetActiveScene, so you just need to change it to Scene.name.
> 6 votes

# Answer
Since this answer still appears high on Google I think it should be noted that, for multi scene projects, the *current scene* is not necessarily the active scene. So, this code will give the name of the scene the GameObject is currently part of:

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class Example : MonoBehaviour
{
    void Start()
    {
        Debug.Log(gameObject.scene.name);
    }
}

```
> 3 votes

# Answer
Been trying to do this one lately... Hope this helps :\<

Here's the code for getting the current scene, I put in on my go to another scene button.

```
public void goToScene(string scene)
{
  SceneManager.LoadScene (scene);
  var currentScene = SceneManager.GetActiveScene();
  var currentSceneName = currentScene.name;
  gotoPreviousScreen.previousScene = currentSceneName;
  Debug.Log(currentSceneName);
}

```

Here's the code to go to the previous scene

```
public void goToScene(string scene)
{
  SceneManager.LoadScene (scene);
  var currentScene = SceneManager.GetActiveScene();
  var currentSceneName = currentScene.name;
  gotoPreviousScreen.previousScene = currentSceneName;
  Debug.Log(currentSceneName);
}

```

And this is the code where I save the scenes, which I later call

```
public static string previousScene;

public static bool getScene { get { return previousScene != null; } }

```
> -1 votes

---
Tags: unity, scenemanager
---


title: Destroy and instantiate player prefab

text:
# Question
Title: Destroy and instantiate player prefab
I am new to game development. I am trying to change the player prefab every X seconds. For that, I am destroying the previously spawned prefab and instantiating a new prefab. But I don't know how to DESTROY THE PREFAB (not the empty game object on which the script is attached)

This is my code :

```
[SerializeField]
public GameObject[] objectToSpawn;

public float ChangeInterval = 5;
public float timer;

private void Update()
{
    int Rand = Random.Range(0, objectToSpawn.Length);
    GameObject spawnPrefab = objectToSpawn[Rand];

    timer += Time.deltaTime;
    if (timer >= ChangeInterval)
    {

        Instantiate(spawnPrefab, transform.position, Quaternion.identity);

        timer -= ChangeInterval;
       }
    Destroy(gameobject);

}

```

Please tell me how can I destroy the prefab. Also is this the correct approach for it?? Thank You.

# Answer
What you want is not to destroy the prefab (the asset in your file system that tells you what properties this object should have), but to destroy the spawned *instance* of that prefab - the new copy of it that you've created in your scene.

`Instantiate()` returns a reference to this instance, so save it in a variable so you know what object to destroy later.

You can also do this without an `Update()` method or `timer` variable, like so:

```
// Use a coroutine instead of ticking Update every frame.
IEnumerator Start() {
    // Store the interval in seconds between prefab changes.
    var delay = new WaitForSeconds(ChangeInterval);

    // Repeat forever.
    while (true) {
        // Select a prefab to spawn only when it's time to spawn one.
        int prefabIndex = Random.Range(0, objectToSpawn.Length);
        var prefab = objectToSpawn[Rand];

        // Spawn that prefab and capture a reference to this new copy.
        var instance = Instantiate(prefab, transform.position, Quaternion.identity);

        // Return control to the main game loop until it's time to spawn again.
        // (This prevents the infinite loop from making the game hang).
        yield return delay;

        // Delete the last instance we spawned.
        Destroy(instance);

        // Resume from the top of the loop.
    }
}

```
> 1 votes

---
Tags: unity, c#, gameobject, prefabs
---


# Question
Title: What's the purpose of this cross product and dot product in triangle clipping code?
I have this code that inserts a triangle into the drawing list. The `PHD_VBUF` structure stores one x,y,z vertex. If the vertex is behind the front plane, then `clip = -128` at that vertex. That is, if the vertex has `clip < 0`, then `visible_zclip()` is called, but I don’t understand what the function does.

It finds the normal to the polygon - the cross product of vertices 1 and 3. Then it determines on which side of this polygon vertex 2 lies. So what? I can't understand. What can we learn from knowing whether vertex 2 is in front of the plane or behind this plane?

```
// Code inserts or reject a triangle into the drawing list
// (Here we have a quad with four vertices)
if ((pV1->clip|pV2->clip|pV3->clip|pV4->clip)<0)
{
  if (!visible_zclip(pV1,pV2,pV3))
    return; //skip the triangle

   // More code, also handling the other triangle in the quad...

```

```
int visible_zclip(PHD_VBUF *vn1, PHD_VBUF *vn2, PHD_VBUF *vn3)
{
  // Cross product of point 1 and 3 with the origin to get plane through origin,
  // then see which side of this plane point 2 lies on
  float a,b,c;

  a = (vn1->yv * vn3->zv) - (vn3->yv * vn1->zv);
  b = (vn1->zv * vn3->xv) - (vn3->zv * vn1->xv);
  c = (vn1->xv * vn3->yv) - (vn3->xv * vn1->yv);

  if ((a * vn2->xv) + (b * vn2->yv) + (c * vn2->zv) < 0.0f)
    return(1);

  return(0);
}

```

# Answer
> 1 votes
This is a check for the direction the triangle is facing, which is determined by its winding order. That is, if you trace your finger across the screen from the projected position of vertex 1 to vertex 2 to vertex 3 and back to 1, have you gone clockwise or counter-clockwise?

Triangles that wind in one direction are considered to be "front facing" and should be visible to the camera. Triangles that wind in the opposite direction are taken to be "back facing" - like looking out through a model from a viewpoint inside it. Usually those triangles will be hidden behind the front side of the model anyway, so we don't waste time drawing them.

This one is written in a way I'm not so familiar with, since it seems to be working with vertices in eye space, not in projected space. That's why instead of computing the z coordinate of the projected coordinate in screen space, it's instead computing a different normal. I imagine that's so that it can skip doing the work of clipping and projecting this triangle if it's going to be invisible anyway.

In this case, the normal it's computing belongs to a different triangle: one passing through vertex 1, vertex 3, and the origin (where the camera is). If vertex 2 is on one side of this plane, the original triangle will appear to wind clockwise from the camera's point of view. If vertex 2 is on the other side of this plane, the original triangle will appear to wind counter-clockwise. Only one of these will be visible, and the other case can be discarded.

---
Tags: c++, graphics, linear-algebra, clipping, software-rendering
---


# Question
Title: glm::eulerAngles gives unexpected output for quaternion
I used the euler-\>mat4-\>quat to give the right result, but euler-\>quat gives the wrong result - is there something I did wrong?

glm::quat q(glm::radians(glm::vec3(0, 90, 0)));
glm::vec3 e = glm::eulerAngles(q);
e = degrees(e);

cout << e.x << " " << e.y << " " << e.z << endl;
// Outputs:  0 90 180
// Expected: 0 90 0

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

glm::quat q = glm::toQuat(glm::eulerAngleXYX(0.0f, glm::radians(90.f), 0.0f));
glm::vec3 e = glm::eulerAngles(q);
e = degrees(e);

cout << e.x << " " << e.y << " " << e.z << endl;
// Outputs: 0 89.9802 0

```
</code></pre>

# Answer
> 0 votes
```
quat EulerToQuat(float roll, float pitch, float yaw) // roll (x), pitch (Y), yaw (z)
{
    // https://en.wikipedia.org/wiki/Conversion_between_quats_and_Euler_angles

    quat q;

    float cr = cos(roll * 0.5);
    float sr = sin(roll * 0.5);
    float cp = cos(pitch * 0.5);
    float sp = sin(pitch * 0.5);
    float cy = cos(yaw * 0.5);
    float sy = sin(yaw * 0.5);

    q.w = cr * cp * cy + sr * sp * sy;
    q.x = sr * cp * cy - cr * sp * sy;
    q.y = cr * sp * cy + sr * cp * sy;
    q.z = cr * cp * sy - sr * sp * cy;
    return q;
}
quat EulerToQuat(const vec3 &v)
{
    return EulerToQuat(v.x, v.y, v.z);
}

```

I am using the method provided by wiki.for now

```
vec3 e(0.f ,90.f, 0.f);
quat q = EulerToQuat(radians(e));
e = degrees(eulerAngles(q));
cout << e.x << " " << e.y << " " << e.z << endl;
// Result : 0,89.9802,0,

```

---
Tags: opengl, rotation, quaternion, glm, euler-angles
---


# Question
Title: How to find the distance to the middle of the road from the car's current position?
I have the car's current position `Vector3` and an API that gets me the closest point on the middle of the road to any `Vector3` parameter I send it like

```
Vector3 returnCenterOfRoad(Vector3 positionToCalculateFrom)

```

so I thought calculate two relative vectors, one from car's position to a point returned from that method a little ways down the road called `pointC` and then call that method using the car's current position called `pointB` (the car's current position would be `pointA`). Now I can get relative vectors from A to C and B to C and I know when vectors start from the same point but end up away from each other, I can do something like AC - BC but what about in this case when they start away but go to the same point?

Is this even the right way to calculate the current distance to the middle of the road?

Also, how do I know if it's on the right half or left half of the road if the track snakes around so the car's orientation changes, the left half could be right half or vice versa depending on where on the track the car currently is.

Edit: I also have another method

```
Vector3 returnLineTangentToCenterOfRoad(Vector3 myPoint)

```

So if I send in my current car position as `myPoint`, that method will return a unit vector, lets call it `tanUnitVec` that is tangent to the closest "center of the road" point from `myPoint` which I can draw using debug.drawline as a vector `(myPoint + tanUnitVec) * scalar`. Visuzalized with scalar of 2f, I can see that this tangent line is pointing to the origin in the XZ plane and the track is procedurally generated to be in anywhere of the 4 quadrants.

I also have the car's `transform` in WCS, `Velocity`, `Angular velocity`, `speed`.

Everything mentioned the beginning is also in WCS.

Here is an image of a yellow line I drew with `myPoint` as my car's current position and redline with `myPoint` offset forwards a bit from my car. You can see the faint white line that is the origin so the car's current position is in quadrant 1 and moving forwards to quadrant 4 with z-axis up and down and x-axis left to right.

# Answer
If you have two points in the same coordinate system (like, say, the world coordinate system), then the vector from one to the other is just their difference, and the distance between them is the magnitude of that vector. i.e.:

```
Vector3 roadCenter = returnCenterOfRoad(carPosition);
Vector3 fromRoadToCar = carPosition - roadCenter;
float distanceFromRoad = fromRoadToCar.magnitude;

```

No third vector somewhere father down the road required. (You can think of the "tail" of both the `carPosition` and `roadCenter` vectors as sitting at the world origin - so they "start from the same point")

> I know when vectors start from the same point but end up away from each other, I can do something like AC - BC but what about in this case when they start away but go to the same point?

When in doubt, draw it:

`B - A` is the vector from `A`'s tip to `B`'s tip when both vectors start tail-to-tail, or the vector from `B`'s tail to `A`'s tail when both vectors start tip-to-tip. (Really there, you're measuring `(-A) - (-B)`, flipping which end of each is the "tip" gets you back to the tail-to-tail case).

Now, to figure out if the car is to the left or right of the road, we use the tangent to the road and a cross product:

```
Vector3 roadForward = returnLineTangentToCenterOfRoad(roadCenter);
// Using left-hand rule:
// - pose your left hand so your straightened fingers point "up" (1st argument)
// - turn so that as you bend your fingers they curl "forward" (2nd argument)
// - in this pose, your straightened thumb points "right" (output)
Vector3 roadRight = Vector3.Cross(Vector3.up, roadForward);

// Now we check whether we're on the positive or negative side
// of the plane with this normal passing through the road center.
float projection = Vector3.Dot(roadRight, fromRoadToCar);

if (projection > 0) {
    // Car is on the right side of the road.
} else if (projection < 0) {
    // Car is on the left side of the road.
} else {
    // Car is *perfectly* centered on the road.
}

```
> 1 votes

---
Tags: unity, linear-algebra, racing
---


# Question
Title: Can you create input actions using more than one key in the editor with the new Input System?
The new input system documentation says it's possible to add actions that require input combinations within the editor or code. I only see an option to add one binding path per action within in the Actions UI.

From the documentation:

> ... require the left trigger to be held and then the A button to be pressed and held for 0.4 seconds?
>
> ```
> var action = new InputAction();
> action.AddBinding("/<gamepad>/leftTrigger")
>     .CombinedWith("/<gamepad>/buttonSouth", modifiers: "hold(duration=0.4)");
>
> ```
>
> Again, setting this up with the inspector in the editor is an alternative to dealing with the path strings directly.

# Answer
Multiple simple (i.e. one key/button) bindings per single InputAction is currently possible. Complex (multiple keys per single) binding was possible too but at some point there was a major rework of the new InputSystem. And to my best knowledge after the rework that feature no longer exists (as of today, ver 0.2.0). The guys working on the InputSystem said they plan to add it again.

P.S. There is customization available through Interactions but its relatively limited (as of ver 0.2.0) And i read that they will be doing additional pass to refine them.
> 1 votes

# Answer
According to the most recent documentation on GitHub, it is possible to configure one or two modifiers. With some luck, I can try it today..
> 1 votes

---
Tags: unity
---


# Question
Title: Trying to rotate a 2D kinematic object along its Z axis when its Y rotation is exactly 180 degrees causes massive rotation swings
I have some code that allows an object to be rotated back and forth on its Z axis, but am having issues when the object has an initial Y rotation of exactly 180 degrees while also trying to rotate it using `Rigidbody2D.MoveRotation()`. To be specific, the object spazzes out and rotates wildly all over the place.

If I change how I rotate the object by using `transform.rotation = someValue`, this problem never occurs. Likewise, changing the initial Y rotation to 179.9 or 180.001 alleviates the issue.

It is important for this code to work regardless of the Y rotation, as certain scenes in my game dynamically spawn these rotating objects in a variety of initial rotations. I am using the 180 degree Y rotation to mirror/flip some of the objects.

```
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class RotateBackAndForth2D : MonoBehaviour
{
    [SerializeField] private float rotationDegrees = 45;
    [SerializeField] private float rotationTime = 5;

    private new Rigidbody2D rigidbody;

    private Quaternion minRotation;
    private Quaternion maxRotation;

    private void DoRotation()
    {
        float rotationDelta = Mathf.PingPong(Time.time / rotationTime, 1);
        rotationDelta = Mathf.SmoothStep(0, 1, rotationDelta);

        Quaternion targetRotation = Quaternion.Slerp(
            minRotation,
            maxRotation,
            rotationDelta);

        // Doesn't work sometimes
        rigidbody.MoveRotation(targetRotation);

        // Always works
        // transform.rotation = targetRotation;
    }

    private void FixedUpdate()
    {
        DoRotation();
    }

    private void OnEnable()
    {
        minRotation = Quaternion.Euler(new Vector3(
            transform.eulerAngles.x,
            transform.eulerAngles.y,
            transform.eulerAngles.z - rotationDegrees));
        maxRotation = Quaternion.Euler(new Vector3(
            transform.eulerAngles.x,
            transform.eulerAngles.y,
            transform.eulerAngles.z + rotationDegrees));
    }

    private void Awake()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        rigidbody.bodyType = RigidbodyType2D.Kinematic;
    }
}

```

# Answer
> 1 votes
Your problem is in how you compute your min and max rotations.

Euler angles are half-decent for human data entry, but they are miserable for doing math in because they necessarily contain wrap-around points. Compute your quaternions using quaternion math instead:

```
minRotation = transform.rotation
    * Quaternion.Euler(0 0, -rotationDegrees);

maxRotation = transform.rotation
    * Quaternion.Euler(0 0, rotationDegrees);

```

This takes the object's current rotation and applies a delta of `±rotationDegrees` around its local z axis, similar to what you were trying to do with the Euler angles.

---
Tags: unity, rotation
---


# Question
Title: Frame duration varies by a millisecond every few frames
When I run the program at 60 fps, I get 0.016 seconds per frame most of the time, then 0.017 s once every few frames. A similar thing happens for 30 fps, varying between 0.033 and 0.034 seconds per frame.

Should my framerate and frame duration be stable? Even when nothing different is happening in each frame?

```
while (m_bRunning)
{
    m_Timer.Start();

    m_frameStart = SDL_GetTicks();

    m_frameCount += 1;

    HandleEvent(e);

    Update();

    Draw();

    m_Timer.Pause();

    if(m_frameDelay >= m_Timer.GetTicks())
    {
        SDL_Delay(m_frameDelay - m_Timer.GetTicks());
    }

    m_deltaTime = (double(SDL_GetTicks() - m_frameStart)/1000.f);

    return m_bRunning;
}

```

# Answer
If you are using V-Sync in the renderer via flag `SDL_RENDERER_PRESENTVSYNC` then the 0.001 difference is nothing you can control because of how communication between GPU and CPU works. However, if you are halting your loop with a `Sleep()` function to get to 0.016s, assuming you do your calculations correctly, you should know that any `Sleep()` call is never accurate. I.e. `Sleep(1 : milliseconds)` is never guaranteed to last exactly 1 millisecond because of how kernels and their task scheduling works. When you call `Sleep()` your cpu does some other work in another place, unrelated to your process (it can take more than 1ms for it to resume your process).
> 0 votes

---
Tags: c++, sdl2, frame-rate, deltatime
---


# Question
Title: What is the advantage of using Element Buffer Objects, if any?
I'm following the amazing LearnOpenGL tutorials and noticed that Element Buffer Objects, which were mentioned and used in the Hello Triangle chapter, never appear again. So my question is, **is using Element Buffer Objects good practice and/or does it provide a performance advantage over just specifying the data for each Vertex manually?** I'm very curious about this, and any information would be helpful. Thank you for your time!

# Answer
> 0 votes
EBOs are memory efficient. i.e: It takes you 8 floats to define a basic square instead of 12. For 2D games you could get away with VBOs only, however, the efficiency becomes apparent in 3D where you have 100,000ths polygons to render each frame.

---
Tags: opengl, rendering, graphics
---


title: Timeline state changes when paused

text:
# Question
Title: Timeline state changes when paused
I'm working on a Timeline sequence in Unity (not to be confused with the Animator). There are several animation tracks playing different animations at different parts of the scene.

At one point in the timeline, I send a signal that pauses the Timeline's own `PlayableDirector`. The Timeline pauses as expected, but the animation state of one of the objects with an animation track seems to revert to an earlier part of the timeline. I've tried messing with the Hold settings but it doesn't make any difference. What's wrong?

# Answer
> 2 votes
I needed to add transitions to the Animator component, or set the 'Animator Controller' field to null.

Animation tracks on the Timeline play Animation sequences on Animators in the scene. If the Animator has an Animator Controller asset selected, the Timeline normally overrides the state machine flow of the Animator component. However, when the Timeline *pauses*, control returns to the Animator. If the Animator doesn't include any transitions to the animation state that was playing when the Timeline paused (meaning the Animator on its own would never reach that state), it will revert to the default state.

In this example, there is no transition from Part 1 to Part 2 or Part 3. We can use this Animator on a Timeline, and play any of the three animations from the Timeline, but if the Timeline ever pauses, the Animator will immediately revert to "Part 1".

Note that if we have an Animator Controller selected in the Animator component, pausing the Timeline will return control to the Animator, which may cause the Animator Controller to advance to a new state and continue playing animations that you don't want it to play. If you don't want the Animator to do anything when the Timeline is paused, set the 'Animator Controller' to null. The Timeline can still play animations on the Animator when the 'Animator Controller' field is null.

---
Tags: unity, animation
---


# Question
Title: How do I create the Spirit Phase Walk effect in Dead by Daylight?
I am wondering how do I create the Spirit's phase walk effect from Dead by Daylight in Unity?

This video demonstrates the effect I'm trying to create.

# Answer
> 1 votes
It looks like the character just teleports around randomly while chasing. Once the spirit stops teleporting around they resume the chase and face the player again, running towards the player Then it looks like it's just rendering as transparent geometry, fading out as it shifts around.

---
Tags: unity
---


# Question
Title: Start debug window on other monitor than the Godot editor
When starting my game for debugging, I'd like to have **the *game* pop up at my second monitor** (still in "Windowed" mode), instead of on top of the Godot editor window itself. I've tried several things to get this to work:

* Drag the debug window to another screen, restart it (hoping it'd "remember" its last position)
* In Project Settings under Display, Window: try "Primary Screen Center" with `0`, `1`, `2` for "Initial Screen"
* In Project Settings under Display, Window: try "Other Screen Center" with `0`, `1`, `2` for "Initial Screen"
* Same as above but now with "Fullscreen" (which I don't want, but just for testing purposes)
* Same as above but now with the Godot editor on my other monitor
* Search Project Settings for "Monitor" and "Screen" to find other related options
* Go through all options in the "Debug" menu (none seem relevant)

None of these worked. Which probably means I'm doing something wrong because "Other Screen Center" should at least have *some* effect, according to the tooltips even exactly the effect I'm looking for?

I've tried searching online but I mainly land on "Multi-monitor editor support" or similar threads. Although that feature would also be nice, I don't need full multi-monitor and floating window support for the editor; just the game needs to go to my second monitor.

I'm running **Godot 4.0** on **Windows 10 Pro x64**, and have **two 2560x1440 monitors**.

# Answer
> 9 votes
Look in the "**Editor**" menu, option "***Editor Settings***...", then **Run \> Window Placement \> Screen**.

---
Tags: editors, screen, godot-4
---


title: Parameter "isMoving" does not exist

text:
# Question
Title: Parameter "isMoving" does not exist
I was following tutorial video but somehow end up error like this

This is the code

Any clue where is the problem, I tried changing things but still no different...

# Answer
One possible explanation for this warning would be that the AnimatorController you show in your screenshot is not actually the AnimatorController that is attached to the Animator referenced in your code. Did you assign the AnimatorController asset you are editing to the field "Controller" in the inspector of the Animator of the object this script is on?
> 0 votes

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


# Question
Title: Godot root motion is calculated incorrectly?
I'm trying to set up root motion in Godot but it's not giving the expected result.

This is the original animation:

After setting up the AnimationTree to use the root bone, the character correctly stays in place, but the interpreted movement is not at all what it should be:

As you can see, it just wiggles side to side (which is an expected part of the animation), but it doesn't move forward.

I can't figure out what could be causing it. As I understand it the motion is calculated by looking at the location keyframes of the root bone, so what could be going wrong?

Edit: I notice that the RootMotionView floor drops away if I uncheck "Zero Y", which doesn't happen with the model I have that's working correctly:

# Answer
> -1 votes
this is normal, you need to code the kinematic or character controller to move your character about

the function get\_root\_motion\_position gives how much to move\_and\_slide each frame.... myself i'm still trying to get the rotation correct this depends on the model animations i believe

---
Tags: animation, godot-4, root-motion
---


# Question
Title: Graphical issue when using a depth pre-pass
I have implemented the Z pre-pass technique into my engine, leading to a 2x performance improvement in a test scene.

However, the technique darkens the objects (but not the skybox), introduces z-fighting, and causes weird artifacts at the border of objects:

Here is the same picture without z pre-pass (performance divided by 2, but no visual bug):

Here is the depth framebuffer setup:

```
  GLCall(glGenFramebuffers(1, &cameraDepthMapFBO));

  GLCall(glGenTextures(1, &cameraDepthMapTexture));
  GLCall(glBindTexture(GL_TEXTURE_2D, cameraDepthMapTexture));

  // If I put GL_FLOAT instead of GL_UNSIGNED_INT here, it doesn't work.
  GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
               SCR_WIDTH, SCR_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL));

  GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
  GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));

  GLCall(glBindFramebuffer(GL_FRAMEBUFFER, cameraDepthMapFBO));
  GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, cameraDepthMapTexture, 0));

  GLCall(glDrawBuffer(GL_NONE));
  GLCall(glReadBuffer(GL_NONE));
  GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));

```

I then do a z pre-pass where I render the scene on the cameraDepthMapFBO framebuffer:

```
  GLCall(glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT));
  GLCall(glBindFramebuffer(GL_FRAMEBUFFER, cameraDepthMapFBO));
  GLCall(glClear(GL_DEPTH_BUFFER_BIT));

  // ... all draw commands

  GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));

```

Finally, in the main rendering pass, I copy the depth data from the pre-pass into the main depth buffer, and I render the scene.

```
  // Clear screen, define viewport
  GLCall(glClearColor(0.01f, 0.01f, 0.01f, 1.0f));
  GLCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
  GLCall(glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT));

  // Copy depth framebuffer onto main depth buffer
  glEnable(GL_DEPTH_BUFFER_BIT);
  GLCall(glBindFramebuffer(GL_READ_FRAMEBUFFER, cameraDepthMapFBO));
  GLCall(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
  GLCall(glBlitFramebuffer(0, 0, SCR_WIDTH, SCR_HEIGHT, 0, 0, SCR_WIDTH, SCR_HEIGHT, GL_DEPTH_BUFFER_BIT, GL_NEAREST));

  // Set depth settings
  glEnable(GL_DEPTH_TEST);
  glDepthMask(GL_FALSE);
  glDepthFunc(GL_LEQUAL);

  // ... all draw commands

  // Restore depth settings
  glDepthMask(GL_TRUE);

```

Observations:

1. I have tested to copy the cameraDepthMapFBO via a shader instead of simply using glBlitFramebuffer. It leads to the same result.
2. The depth map itself seems correct, because I already use it for SSAO.
3. In the framebuffer setup phase, I have noted that it stops working if I put "GL\_FLOAT" instead of "GL\_UNSIGNED\_INT" as glTexImage2D parameter.

Any idea of what could be wrong?

# Answer
> 3 votes
There were two problems with my code, thanks @DMGregory for having pointed them out.

**1 - The depth buffer also need to be multisampled if the main rendering pass has MSAA.** The solution I have found is to render the depth pre-pass and the main rendering pass on an off-screen FBO containing multisampled color and depth texture buffers. Then I copy this color buffer to the default color buffer. It works fine.

**2 - Z-fighting is caused by precision errors between the early-z pass and the final pass.** These precision errors can be due to slightly different code in the shaders. Even if their result should be the same, minor differences, even in operations order or small other factors, can be sufficient to bring slightly different results after compilation. This problem could be approached by using the glsl "invariant" keyword, which states that the code should be compiled as it is, without optimizations. I haven't been successful with this solution though. This problem can also be tackled by adding an offset to the depths rendered in the early-z pass, which resolves it with a negligible performance hit.

Early depth pass vertex shader:

```
vec3 FragPos = vec3(model * vec4(aPos, 1.0));
gl_Position = projection * view * vec4(FragPos, 1.0);
gl_Position.z += 0.001; // Offset

```

The only downside of this offset is that fragments between the real depth and the depth + offset will also have the possibility to be rendered, but this is negligible considering the small offset size.

If anyone has a better answer, I would be glad to accept it.

---
Tags: opengl, depth-buffer
---


# Question
Title: Web build not respecting Monospace SystemFont for Godot Label
I want a label to use a `monospace` SystemFont but the Web build is not respecting this setting.

Here's steps to reproduce my situation:

1. Create a new Godot 4.0.1 project
2. Add two `Label` controls in a `VBoxContainer` with some text
3. Give the second text a "LabelSettings", with a `SystemFont` set to `Monospace`
4. Save the main scene and set it as the default scene in project settings
5. Export for the Web with default settings
6. Use `npm install -g serve` to serve with a `server.json` file:

```
{
    "headers": [{
        "source": "**/*",
        "headers": [
            {
                "key": "Cross-Origin-Embedder-Policy",
                "value": "require-corp"
            }, {
                "key": "Cross-Origin-Opener-Policy",
                "value": "same-origin"
            }
        ]
    }]
}

```
7. Run `serve .` to serve it at `http://localhost:3000`
8. Open the game

* **Result**: both fonts show with the same font
* **Expected**: second label should use a monospace font (which *does* work if the game is run in debug mode or as Windows Desktop Runnable export)

**How can I make Web builds use a monospace font, preferably without including custom font files?**

---

Here's some screenshots of what I described above. In the editor:

And the unexpected Chrome output:

Note that I'm on Windows. Firefox shows the exact same behavior by the way.

# Answer
Currently `SystemFont` is not supported on web exports.

I quote the documentation:

> **Note**: This class is implemented on iOS, Linux, macOS and Windows, on other platforms it will fallback to default theme font.

Thus, you will have to embed the fonts.

---

The developers ran into an issue with the fonts in web platforms. Since Godot renders to a canvas (it is not applying the font to web elements with CSS), they need to read the font data, which is not available in most browser (and, of course, they can't access the local file system).

Apparently there could be a way, but at the time of writing it is Chrome only: queryLocalFonts. *I believe they want a Firefox solution before going ahead with the feature, but I don't speak for them.* So you would had to embed the fonts to have an uniform experience across browsers anyway.
> 8 votes

---
Tags: text, fonts, web, godot-4
---


title: Best way to extend Unity Rigidbody?

text:
# Question
Title: Best way to extend Unity Rigidbody?
I am designing a physics class library for Unity and would love to be able to hook and inject functionality into Unity's `Rigidbody` class, but it's my understanding that there is no way to do this directly while still being able to target all platforms.

I thought the next best thing might be to create a new class that inherits directly from `Rigidbody`. However, it looks like Unity has prevented this from occurring in anything but the `UnityEngine` namespace by requiring the `internal sealed ExtensionOfNativeClassAttribute` on anything that inherits native classes. Furthermore, Unity does not serialize inherited classes well.

So, in review, I'm not able to hook into `Rigidbody` directly (please correct me if this is wrong!), and I'm not able to inherit from `Rigidbody` directly (please correct me if this is wrong as well!). I think the next best option is to:

1. Create a new Monobehavior, let's say it's called `ModRigidbody`, which makes a parallel implementation of all of `Rigidbody`'s members. This class does not actually inherit from `Rigidbody`, but merely has members with all the same names/signatures as `Rigidbody`.
2. On `ModRigidbody` add the attribute `[RequireComponent(typeof(Rigidbody))]`. Now I can add functionality to some ModRigidbody's members as I see fit, and have other members simply 'pass through' to `transform.GetComponent<Rigidbody>()`.
3. Have any end users (programmers) change all of their references to `Rigidbody` over to `ModRigidbody`.

To me, this feels quite sloppy. Is there a way to mod the functionality of `Rigidbody` so that future users of this library will not have to change all of their `Rigidbody` over to `ModRigidbody`?

# Answer
Unity doesn't generally allow extending its built-in classes. But, if you mean to *add* functionalities to a standard class rather than *overriding* some, you can use C# Extension Methods: they allow you to add features without creating a new derived type. You can find a well-written guide on Extension Methods in Unity on the GameDeveloper website.

Instead of using, say, a helper class that forces you to write ugly code like this:

```
GameObjectHelper.WannabeInstanceMethod(gameObject, someArgument);

```

you can instead *extend* a class' functionalities with EMs and get a nicer function call signature:

```
gameObject.WannabeInstanceMethod(someArgument);

```

### Declaring An Extension Method

Create a non-generic, non-nested static class, and add a static method whose first argument has the `this` keyword referring to the calling data object:

```
public static class GameObjectExtensions
{
    public static void WannabeInstanceMethod(this GameObject gameObject, int argument)
    {
        // Implementation goes here
    }
}

```

Though declared as static, this will be invoked as if it were an instance method:

```
gameObject.WannabeInstanceMethod(someArgument);

```

You will find many examples on the internet about how to use Extension Methods in your code. Beyond GameObjects, you can also use EMs on Vectors and Lists, as explained in this blog post by MonoFlauta.
> 3 votes

---
Tags: unity, 3d, design-patterns
---