# Question
Title: Unity Mirror Networking Audio Behaves Differently on Host and WebGL Client
I am creating a system in Unity using Mirror Networking which will only require one host/server and one client. It is a WebGL build so the client will connect on a browser. I want to send commands from the server to play audio clips on the client without the client being able to control anything. The audio is questions an avatar is asking the user. Due to another constraint (Lip Sync setup) I have one `AudioSource` and one long audio clip which contains all the questions and is played by pressing the space bar. So rather than playing each audio clip separately, the audio clip is unpaused and paused. It will pause itself after a set time when the question line is finished and then I press the enter key to unpause the `AudioSource` for the next question (and again, each line will pause itself after a set time which is the length of the individual question).

Before I added Mirror or any networking component to the project this worked fine in WebGL, but now the audio will not behave the same. I tried it in Google Chrome and Microsoft Edge. It will play/unpause when I press the space/enter keys and it will pause but after the first two lines (which play correctly) it will start to skip ahead a few seconds every time I unpause it. I used the WebGL development build to check that the `AudioSource.time` is correct before it is unpaused but it still will play the wrong part of the audioclip. It almost seems like the audio clip is still running even after it has been paused because the longer I wait the further into the clip it will play, but it is not a direct second:second relationship, even if I play lines closely after each other it seems to skip ahead further and further each time.

In this Networking case are there two different AudioSources (One for the server and one for the client)? Though how could the debug log show the correct `AudioSource.time` (in Unity editor and the browser) but then it is unpaused at a different time? Is the client version of the AudioSource running in the background so the time is increasing even though the audio has been paused? It doesn't make sense to me but I am quite new to Unity, especially Mirror and network programming in general. Or could this be some issue with WebGL? I think it probably isn't solely a WebGL issue since this part was working in WebGL before I added any networking component to the project.

When I build it as a Windows project instead of WebGL, it works perfectly. So I am unsure if it is an issue with my networking code. Could it be an issue specifically caused by using Mirror or networking with a WebGL build?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class SoundTracker : NetworkBehaviour
{
    public AudioSource soundFX;
    public int count = 0;

    // Update is called once per frame
    void Update()
    {
        if (isServer != true) return;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            count = 0;
            startSound();
            StartCoroutine(SoundWaiter(33.5f));
        }

        if (Input.GetKeyDown(KeyCode.Return))
        {
            float[] lineDurations = { 3.2f, 4.75f, 4.5f, 5f, 4f, 5.5f, 5.5f, 3.8f, 8.6f, 2.9f };
            playSound();
            StartCoroutine(SoundWaiter(lineDurations[count]));
            count = count + 1;
        }
    }

    [Server]
    IEnumerator SoundWaiter(float duration)
    {
        yield return new WaitForSeconds(duration);
        pauseSound();
    }

    [ClientRpc]
    void startSound()
    {
        soundFX.Play();
    }

    [ClientRpc]
    void playSound()
    {
        soundFX.UnPause();
    }

    [ClientRpc]
    void pauseSound()
    {
        soundFX.Pause();
    }
}

```
</code></pre>

# Answer
> 0 votes
I am still unsure exactly why Mirror Networking behaves differently with WebGL than the Windows build in this situation (I am using the simple web transport which is recommended for working with WebGL) but I managed to find a work-around for this situation.

If I set `AudioSource.time` to the starting time of each audio line before unpausing, I am able to play it line by line rather than it not pausing and running in the background in the client.

Thanks a lot to @Zibelas who helped improve my understanding of what was going on with the networking code and narrowing down the issue.

<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class SoundTracker : NetworkBehaviour
{
    public AudioSource soundFX;
    public int count = 0;
    float timeStamp = 0;

    // Update is called once per frame
    void Update()
    {
        if (isServer != true) return;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            count = 0;
            startSound();
            StartCoroutine(SoundWaiter(33.5f));
        }

        if (Input.GetKeyDown(KeyCode.Return))
        {
            float[] lineDurations = { 3.2f, 4.75f, 4.5f, 5f, 4f, 5.5f, 5.5f, 3.8f, 8.6f, 2.9f };
            timeStamp = 33.5f;
            for (int i = 0; i < count; i++)
            {
                timeStamp = timeStamp + lineDurations[i];
            }
            playSound(timeStamp);
            StartCoroutine(SoundWaiter(lineDurations[count]));
            count = count + 1;
        }
    }

    [Server]
    IEnumerator SoundWaiter(float duration)
    {
        yield return new WaitForSeconds(duration);
        pauseSound();
    }

    [ClientRpc]
    void startSound()
    {
        soundFX.time = 0;
        soundFX.Play();
    }

    [ClientRpc]
    void playSound(float startTime)
    {
        soundFX.time = startTime;
        soundFX.UnPause();
    }

    [ClientRpc]
    void pauseSound()
    {
        soundFX.Pause();
    }
}
```

---
Tags: unity, networking, webgl, audio, mirror-networking
---


# Question
Title: Unity 2d with the Android platform crashes with the urp package
I’m new to developing lights in Unity, I looked at the tutorials and decided to use the URP package. When installing the package, the project crashed at first, but then I restarted and the textures became strange (bright colors). This project initially had an Android platform without a URP package.

I decided to try to create a new 2d test project with a windows platform. The URP package works fine until I install the platform on Android. Unity immediately crashes and it is impossible to enter the project

# Answer
The problem was in the outdated driver on the video adapter, I updated it to the new version and everything worked. Maybe it will help someone,

https://discussions.unity.com/t/amddxgsafreecompiledshader-unity-2022-3-14f1-2d-with-the-android-platform-crashes-with-the-urp-package/315276/3
> 0 votes

---
Tags: unity, unity-urp
---


# Question
Title: Detect if a key other than "this" key has been pressed
I'm wondering if there is a way to detect if the key being pressed is NOT matching a specific `KeyCode`.

I tried using: `!(Input.GetKeyDown(exampleKeyCode))`, but that also detects if the key is being released.

I also tried using
`(!(Input.GetKeyDown(exampleKeyCode)) && !(Input.GetKeyUp(exampleKeyCode))`
but that doesn't work because when a key is not down it is up, and when it is not up it is down.

# Answer
You can first check whether "any" key has been pressed, then check if the key you're listening to has *not*, to respond only to presses that were *not* that key.

```
if (Input.anyKeyDown) {
    if (Input.GetKeyDown(exampleKeyCode)) {
        Debug.Log("The example key (and maybe others) was pressed this frame");
    } else {
        Debug.Log("One or more keys were pressed this frame, but not the example key.");
    }
}

```

Note however that `anyKeyDown` does not reset until all keys have been released. So if I hold `A` it will return `true` once. If I then press `B` while still holding `A`, it will continue reading `false`. Only once I release all keys then press a key in that "no keys held" state will it fire `true` again.

If you want to more robustly identify all key presses that were not "this" key, even while a key is held, you can switch to Unity's new Input System package, which is more powerful. There's a thread here discussing ways to implement this kind of functionality with that package.
> 4 votes

---
Tags: unity, c#, input, keyboard
---


# Question
Title: What is the best way to implement a scene manager?
I'm trying to create a scene manager system for a small framework I'm writing on top of SDL2. I have implemented a scene management system that works, but I am not sure if it is structured how it should be.

**What I am doing:**

I am following an OO approach where each scene inherits from "IScene", an abstract class with the standard `on_load`, `on_update`, etc. methods. These scenes are managed by a scene manager class, which stores a map of `int` ids and `IScene*` scene pointers. Here is the code to go with this explanation:

```
namespace se {
    class IScene;
}

namespace se::managers {
    class SceneManager {
        public:
            SceneManager();
            ~SceneManager();

            void add_scene(int scene_id, IScene* scene);
            void remove_scene(int scene_id);
            IScene* pop(int scene_id);
            IScene* get_scene();
            void set_scene(int scene_id);
        private:
            std::map<int, IScene*> scenes;

            int active_scene;
            IScene* active_scene_ptr;
    };
}

```

scene.h

```
namespace se {
    class IScene {
        public:
            IScene(
                IApp* app
            );
            virtual ~IScene();
            virtual void on_load() = 0;
            virtual void on_unload() = 0;
            virtual void on_scene_enter() = 0;
            virtual void on_scene_exit() = 0;
            virtual void on_update() = 0;
            virtual void on_draw() = 0;
        protected:
            IApp* app;
    };
}

```

**The Problem:** In order to get this relationship to work, I had to forward declare `IScene` in `scenemanager.h` to avoid a cyclic dependency. This is because I want `IScene` to be able to change the active scene from within its own `on_update` method. I read some threads that said forward declaration to avoid this issue can be considered a "code smell" because it's a sign of tight coupling.

**What I would like to know**

1. Is my approach okay?
2. What would be a better approach?

Thank you for your time!

P.S. This is my first time ever posting on Stack Exchange. If there's anything about this post that is structured wrong/unclear please let me know so I can fix it in the future.

# Answer
Forward declaring is totally OK. The alternative would be exactly what you pointed out, cyclic dependencies (assuming that you have `#include` in your `IScene.h`). You're saving compile time with your approach. However when you write interfaces you should try to keep them abstract from the rest of the code and not include much in them, hence the name "abstract classes".
> 0 votes

# Answer
One possible alternative, given that the only reason for the forward declaration is because you want `IScene` to be able to change the active scene from within its own `on_update` method, is to have `on_update` return some data indicating whether or not the scene should be changed, and which scene to change it to, if so.

This option would require implementing the ability to create an `IScene` given only that data. If you have a fixed set of scenes, then the scene to change to could be represented by an enum. If you want to support an open set of scenes, such that new ones can be added without updating an enum definition, then you would need a more complicated lookup mechanism, if you wanted to pursue this option.

Consider whether this is worse or better than the forward declaration.
> 0 votes

# Answer
I am far away from being a pro, so excuse me if this is nonsense... But how about seeing a scene as a node and the manager as a kind of graph? The graph/manager could have a method to "search" a scene/node in the map, wich could be called from any scene/node.

I dont see forward declaration as a problem in any kind.
> 0 votes

---
Tags: c++, software-engineering, sdl2, scenemanager
---


# Question
Title: OnCollisionStay outputs strange contactpoints
I am currently trying to make a pen draw on a paint. I am searching for contact points on the paint but there is too much contact points than expected.

I'm not sure to properly understand how collisions are detected. Only one side of the cube touches the paint, but four points are returned and seem to correspond to each corner of the cube projected onto the plane.

```
 private void OnCollisionStay(Collision collision)
    {
        Debug.Log(collision.transform.tag);
        if (collision.transform.CompareTag("Paint"))
        {
            Debug.Log("Pen enter collision with paint");
            foreach (ContactPoint contact in collision.contacts)
            {
                Debug.Log(contact.thisCollider.transform.name + " " + contact.otherCollider.transform.name);
                Debug.DrawRay(contact.point, contact.normal, Color.white);
            }
        }
    }

```

# Answer
What ended up being my issue is that OnCollisionStay() can call multiple times per FixedUpdate. It actually calls per collision. So my collider had two collisions, making my contact point counter incorrect.

Considering that, it also means if you store your contacts/GetContacts() outside of the OnCollisionStay() function, it will also get overwritten.

So the basic rule here is to not populate variables with GetContacts() outside of the scope of OnCollisionStay. Instead keep those variables local, and aggregate them manually if you need them in a different public scope.

```
[RequireComponent(typeof(Collider))]
public class CharacterColliderData2 : MonoBehaviour {
    public ContactPoint[] ContactPointsAggregated = new ContactPoint[8];

    // to avoid allocation
    private ContactPoint[] contactPoints = new ContactPoint[4];
    public int contactPointCount = 0;

    private void OnEnable() {
        contactPoints = new ContactPoint[4];
        contactPointCount = 0;
    }

    private void FixedUpdate() {
        contactPointCount = 0;
        ContactPointsAggregated = new ContactPoint[8];
    }

    // can run many times before FixedUpdate calls again
    private void OnCollisionStay(Collision collisionInfo) {
        int startingCount = contactPointCount;
        int collisionContactPointCount = collisionInfo.GetContacts(contactPoints);
        contactPointCount += collisionContactPointCount;

        for (int i = 0; i < collisionContactPointCount; i++) {
            ContactPoint contactPoint = collisionInfo.GetContact(i);
            ContactPointsAggregated[startingCount + i] = contactPoint;
        }
    }
}

```
> 1 votes

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


# Question
Title: Optimal Approach for Transmitting and Rendering Large Pixel Art Game Maps in Unity
I'm working on a pixel art game in Unity, and my backend (Which is actually written on Golang) has generated a massive dataset of tiles for a 1000 by 1000 world (it could be even more). I'm wondering about the best approach for transmitting and rendering this map on the Unity client side. Should I consider making a copy of the entire world as an asset for the client, or is it more appropriate to send the map data as JSON or Proto files and parse it in chunks? I'm looking for insights on performance, bandwidth efficiency, and overall best practices for handling large game maps. What strategies have you found effective in similar scenarios, and what considerations should I keep in mind for optimizing the player's experience?

# Answer
What I would suggest in this case is the following:

* Rendering details like pixel colour, are usually not crucial to game logic. Since you will need to render the 1000x1000 map as a texture, it is best that you send it as a compressed image. PNG for example makes use of RLE compression and is thus lossless (i.e.it loses no detail when being decompressed for display, unlike JPG). Or you can come up with your own compression scheme. 1 byte per pixel indexed colour would be my suggestion, rather than 4 byte RGBA colour. You then have to decide how often this map is allowed to change, and thus how often you have to send out map updates to the various players. These updates to the map colours can be either deltas (efficient) or absolute states (easy to do, but costly to send over network).
* Game data in each chunk (map pixel): you will want to be more selective about, because it could get quite large if it exists for every one of 1000x1000=1M tiles. This is what I call "Area of Interest" around the player(s). You likely don't want to hold gigabytes of data about every single tile (pixel, chunk) on your map, if players are not active in 99% of those tiles. Sure, you could store it all, but the more data you store, the more cache misses you have retrieving that data from main memory, etc. It can often be faster to just *forget* data in cells where players are no longer active, and then *regenerate* that data when you return. Things won't look exactly the same, but in many games this isn't necessary to create an immersive experience. Minecraft for example forgets monsters and how much damage you've done to a block, but it does store deltas showing which blocks were actually added / removed (and of what type). If a lot of terrain editing has been done over time, Minecraft savefiles can become absolutely enormous and 3rd party tools may be used to clean up saved chunks that aren't being used anymore.
* The simplest scheme to set up area of interest around players is a `n x n` sliding window of chunks, where `n==2` or `n==3`. `3x3` is the easiest for beginners. You may also then need to deal with cases where the `n x n` neighbourhood around *different* players overlaps, so as not to process the same chunk twice.

So you have some game design decisions to make before you can proceed.
> 1 votes

---
Tags: unity, 2d, procedural-generation, tilemap, content-generation
---


title: Simple Circuit System

text:
# Question
Title: Simple Circuit System
I want to make a simple circuit system in Godot. Here's what I mean by that. (The circuit isn't realistic)

I just want a `battery` object and a `wire` object. The batter will supply `x` amount of power to a wire. Then all the wire can transfer it to other wires to be used with other objects to be implemented later. Here is what I was trying currently:

I had a wire object with an area checking all four sides for things to power. If it can be powered, it powers it with `x` amount of power. The batter does this to the wires, and the wires do it to other wires. This doesn't work though. The major problem is that when the battery stops powering the wire, the wires power each other.

I can't think of good solution. (Interaction between objects doesn't have to be instant). I also want it be flexible as I want wires to be able to contain other data other than power, but this isn't a necessity and could figure this out myself. Any ideas?

# Answer
One option is to group all the connected wires into a single logical network that handles distributing power. This has the advantage of being very cheap *except* when dealing with removing connections that may end up splitting the network or when adding things can join 2 networks.

Another option is to model actual power flow where each wire has an internal energy storage and can pass that energy on to the next wire to equalize everything out. This makes it easier to model the more "realistic" aspects of power management like bottlenecks and distance-based inefficiencies if that is your jam.
> 3 votes

# Answer
**tl;dr:** model the circuit network as a linear system of equations to easily solve for the current and voltage at every node using off-the-shelf linear algebra software.

---

It depends how realistic you want the simulation to be. In the real world, wires aren't "supplied power" by a battery, but are actually nodes in a circuit. If you connect a battery to a light bulb with a wire, the wire is more or less just a connection between the light bulb and the battery, so modeling the wire itself isn't important. You "just" have to keep track of which circuit elements are connected to which others. Of course, this analogy eventually breaks down at a certain level of realism.

As mentioned by others, the easiest way to model this is to pretend that all connected wires are a single node, and all circuit elements connected to that node are effectively connected directly to one another.

If you want to model actual power flow through the circuit, you have to start thinking of the wires themselves as elements in the circuit. A light bulb has a certain *resistance*, which means that, given some voltage across its terminals, some amount of *current* will flow through it. The amount of current is described by Ohm's Law: `I (current) = V (voltage) / R (resistance)`. Wires also have resistance-- it's just that the resistance is usually very small.

Once you start modeling the network this way, you can do other interesting things. For example, you may want to specify a maximum amount of current that a wire can supply without breaking. The amount of power dissipated in a resistor (or light bulb or wire or anything with resistance) in watts is `P = I^2 * R = V^2 / R`. The more power dissipated, the hotter the wire gets. You could give the maximum current directly (as is done for various wire gauges in the real world), or even model the temperature of the wires themselves (see below, as this is a bit of a tangent).

It may seem impossible to calculate the voltages and currents through a huge network of wires and resistive circuit elements this way, but it's actually possible to reduce the network to a system of linear equations. There exists free software which can solve these systems extremely quickly and efficiently and, once done, gives you the current and voltage through every node, not matter how the circuit is arranged. You can use this information to determine if your battery is powerful enough to power your circuit, whether or not to blow up or melt wires that are carrying too much current, etc.

You may also want to model the equivalent series resistance (ESR) of your battery. The more current the battery has to supply, the weaker the measured voltage of the battery will be. You can think of the ESR as like a resistor inside the battery before you can connect to its terminals. Adding this resistor to your system of equations will model that weakness effectively for free.

There are other factors that you could model if you really wanted to, like parasitic inductance and capacitance, reactive power and power factor (particularly important for industrial applications like factories), the skin effect, and many other electrical engineering details that wouldn't really contribute to gameplay for anyone but power engineering nerds like me :)

---

To model the temperature increase from dissipated power, you need the heat capacity for that substance. This describes the amount of energy required to raise the temperature of a given mass of that substance by some number of degrees. For example, the specific heat of aluminum is 0.89 J/g °C, which means that every joule of energy dissipated will increase the temperature of one gram of that substance by one degree Celsius. A watt is one joule per second, so dissipating 1 kW through a 1 kg wire for 60 seconds will increase the temperature by `(1000 J/s)*(60 s)/(0.89 J/g °C)/(1000 g) = 67.42 °C`.

Of course this is complicated further by modeling how that wire will transfer the thermal energy away as it is heating, so it's probably not modeling the wire to this level unless you're really interested :)
> 1 votes

---
Tags: godot, gdscript, godot-4
---


# Question
Title: How is a Spherical Harmonics Lightmap generated?
I have successfully generated a single color lightmap using ray tracing. For each texel in the lightmap, I trace into the hemisphere (using the normal) and capture the incoming light. This single color lightmap can't take normal mapping into account.

I have found this site for an explanation how SH are generated but I have a question regarding that.

In a code listing, the author does this:

```
SH9Color genLightingCoefficientsForNormal(const glm::vec3& N, const glm::vec3& L)
{
    SH9 SHCoefficients = genSHCoefficients(N);
    SH9Color result;
    for (size_t i = 0; i < result._coefficients.size(); ++i)
    {
        result[i] = L * SHCoefficients[i];
    }
    return result;
}

```

I am confused what the `SH9Color` contains. My assumption is that `SH9Color`itself is just a `float3[9]`. I.e. an array of colors. But since it's an array of colors, how would that be stored in a texture? I would need 9 RGB textures to represent that. Thats a lot of space opposed to what I assumed to be only 3 (9 coefficients)

How are Spherical Harmonics Textures actually generated?

# Answer
The example you linked isn't generating a lightmap, but a light *probe*. As they say in the Future Work section:

> The next thing I’d like to do is take this spherical harmonic concept and use it to implement **light probes** distributed in my scene. I’m curious to see how it all looks because, for now, the comparisons in the last section were made using a **single light probe** at the center of the scene (i.e., we generated maps with respect to world space location \[0, 0, 0\]).

When rendering with light probes, we generally have a sparse graph of sample points in our scene for which we've calculated spherical harmonics coefficients, and we interpolate between them.

Because each probe is responsible for encoding the way light hits different surfaces over a wide area, we need a lot of coefficients to accurately encode that info. But since our probe graph is reasonably sparse, we don't mind storing too many coefficients, because we only need to store them for a "small" number of probes.

The situation with lightmaps is somewhat the opposite: we have a *dense* grid of samples, often every half or quarter meter along every surface in the scene. But because they're so tightly spaced, each sample doesn't need to store quite as much subtlety about the variation in light at that spot: that can come through in the differences in light captured at adjacent sample points. So we can afford to discard some of the higher-order coefficients without too noticeable a loss of fidelity.

This GDC presentation about the use of spherical harmonics lightmaps in Star Wars Battlefront II shows they used only the first four coefficients for each of R, G, and B, or 12 values in all, compared to 27 if using all nine coefficients from the sample in the question.

They stored the L0 (average illumination) coefficients in the RGB channels of one high dynamic range texture. Then the L1 coefficients were stored in three low dynamic range textures. That means the shader needs just 4 texture taps to reconstruct the lighting, instead of 9.

Since lightmaps tend to be quite spatially coherent, they used block compressed formats for both: BC6HU for L0 (8 bits per pixel), and BC7 (8 bpp) or BC1 (4 bpp) for the 3xL1s. So that's just 20-32 bits per pixel of lightmap. A 4096x4096 resolution chunk of lightmap would cost you 40-64 MB of VRAM using that scheme, so it's quite doable. And the presentation slides show that you can get some beautiful visuals even with those aggressive reductions in raw data.

Importantly, they used this only for indirect lighting, and still evaluated direct lighting separately, which helps keep high frequency details that this approximation scheme crunches.
> 1 votes

---
Tags: graphics, lightmap, spherical-harmonics
---


# Question
Title: Getting the scalar speed from an X and Y velocity
Given a `Vector2(x,y)` that represents an object's velocity, like so:

```
let angle = Math.PI / 2;
let speed = 500;
let velocity = new Vector2();

velocity.x = Math.cos(angle) * speed;
velocity.y = Math.cos(angle) * speed;

```

How can you retrieve the speed?

```
let angle = Math.atan2(velocity.y, velocity.x);
// let speed = ???

```

# Answer
> 0 votes
Was able to get the answer as:

```
let speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2)

```

---
Tags: physics, algorithm, vector, linear-algebra, trigonometry
---


# Question
Title: Simulated light for a 2D tile-map with just SDL2?
I'm working on a 2D tile-map RPG with C++17 and SDL2 + SDL\_Image.

There are daily cycles, weekly cycles and seasons. Even a kind of weather engine provides atmosphere. The moods and times of day are conveyed very well via a semi-transparent additional layer that I render over the other layers. To do this, i modulate the colors of this layer depending on the time of day, season or weather. So far so good...

Such a village looks really bad at night without lighting! Unfortunately, the pure SDL2 library does not support light without the use of OGL (which I have no idea about). Apart from the fact that I could of course create tiles for an illuminated version of the map (which I don't want to), i was thinking about a possible solution in which i somehow render the last layer "with holes" that are more transparent than the rest and Maybe the color tends more towards yellow.

But I have no idea how to implement something like that without forcing the device to its knees. And at 3 fps the game is definitely a lot of fun.

I need theortical help please!

# Answer
*I think* what you want is to create a black texture with the same size as your screen, set it as the render target, render blurry white circles to it at the locations of the light sources, with the blend mode set to 'add'.

Then render this texture on top of your scene, with the blend mode set to 'modulate' (which is how SDL calls multiplication that ignores alpha).

This will give you the effect of the screen being black by default, with things only being visible through blurry 'holes' near the light sources.

You can vary the default lighting by replacing black with a lighter color, and vary light source colors.
> 1 votes

---
Tags: c++, 2d, tilemap, game-loop, sdl2
---


# Question
Title: Handling movement on sloped surfaces - clamping character to sloped surface
I've noticed that a lot of people seem to have this issue but I've yet to find an actual working solution - when a rigidbody-based character controller (I'm not using Unity's character controller) moves down a sloped surface, they will bounce/bunny hop on the way down instead of staying on the surface. I'm building a 3d platformer and ran into this issue - I've tried a fair amount of things but nothing seems to work cleanly. I managed to find a 2D solution here but I can't seem to get it to work cleanly in 3D. Here is my code:

```
    void NormalizeSlope()
{
    // Attempt vertical normalization
    if (isGrounded)
    {
        RaycastHit hit;
        if (Physics.Raycast(floorCheck.position, Vector3.down, out hit, groundCheckDistance))
        {
            if(hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f)
            {
                // Apply the opposite force against the slope force
                // You will need to provide your own slopeFriction to stabalize movement
                rigidbody.velocity = new Vector3(rigidbody.velocity.x - (hit.normal.x * 0.4f), rigidbody.velocity.y, rigidbody.velocity.z); //change 0.6 to y velocity

                //Move Player up or down to compensate for the slope below them
                Vector3 pos = transform.position;
                pos.y += -hit.normal.x * Mathf.Abs(rigidbody.velocity.x) * Time.deltaTime * (rigidbody.velocity.x - hit.normal.x > 0 ? 1 : -1);
                transform.position = pos;
            }
        }
    }
}

```

With that, I get varying results on surfaces with different slopes. Also, my character jitters. On some slopes, my character even slowly inches their way up the surface. Has anyone else run into this issue? Does anyone have a working solution for this problem?

# Answer
> 0 votes
In general rigidbody physics is appropriate to model non-living things, while a completely different system of bone and animation based physics is usually used on living things and things which behave like living things (like robots or zombies).

For example, if you drop a stone on the side of a hill you can model what will happen using a very simple system, but if you drop a hamster on the side of a hill you would need to model that using a completely different system.

What I'm trying to say is that if you want to model something like walking using rigidbody physics in a way that looks at all realistic then you're going to have to resign yourself to *far* more than 4 lines of code.

The best algorithm I've seen for modeling walking using rigidbodies involves putting a sphere collider on the front of the foot and another one on the heel. For each step you then keep that part of the foot descending until one collider collides. The knees them move in a sinusoidal pattern driving the feet up and down, and the hips use their own sine wave to drive the knees back and forth.

# Answer
> 0 votes
If you don't want your character to jump on the slope, like it is done by physics engine and make him stick to the ground (If I understood your question correctly). I would not use rigidbody gravity in that case and would not move character by adding force or velocity. I would have created own gravity system and just turn it on whenever player decides to jump, but turn it off if the player hits the ground. Then I would raycast the ground in area that character covers and take normals to rotate player to it and move him towards his transform.forward in world space. Also remember to stick your player to the position of the ground he is standing on when he rotates.

If you want your player to slide down, than it would be better to forget about rotation, if it's a simulation of real life sliding and actually use rigidbody and gravity, but then just right after the slope, when the normal changes or what make your player to stick to `hit.position` where hit is a variable of `RaycastHit`. It will make your character to stick to any surface when slope changes. But remember that maybe you want it to save it's speed when using velocity or `AddForce`, then you want to change only `y` position and also change the velocity on `y` to 0.

# Answer
> 0 votes
Perhaps using Vector3's ProjectOnPlane method could help you.
From the docs: "Projects a vector onto a plane defined by a normal orthogonal to the plane."

By providing your rigidbody's velocity and the normal direction of the hit flooring, you can project your velocity to be parallel to the floor. Take for example:

```
Vector3 forceDirection = new Vector3(0, 0, 1);

void FixedUpdate()
{
    Vector3 force = forceDirection;

    // if there's a floor beneath us
    if (Physics.Raycast(transform.position, Vector3.down, 2f, out RaycastHit hit))
    {
        // Project our force direction to be parallel to the floor
        force = Vector3.ProjectOnPlane(force, hit.normal);

        // This means the force we're adding is now following the slopes angle
    }

    rigidBody.AddForce(force);
}

```

You can visualize this like drawing an arrow representing your direction vector above your sloped plane. If a light source was placed directly above the arrow, its shadow cast on the plane would be our projected vector

# Answer
> 0 votes
This is a very easy solve. All you have to do is apply a downward force if you are in the air. First, you have to detect if you are actually on a slope, assuming you have a "jump" in your game.

```
bool OnSlope()
{
    if (Physics.Raycast(transform.position, Vector3.down, out
    hit, /*half of your player's height and add about a sixth of your player height*/))
    {
        float angle = Vector3.Angle(Vector3.up, hit.normal);
        return angle != 0;
    }

    return false;
}

```

You then want to make a system so that it doesn't put downward force when you jump, only when you are bouncing. I don't know what your jumping mechanics look like, create a boolean that turns true when you jump, and turns false when you touch the floor, but DO NOT make it so that when it is off the ground it turns false, or it ruins the whole point.

```
void Jump()
{
    bool exitingSlope = true;
}
void Update()
{
    if (!isGrounded)
        exitingSlope = false;
}

```

(might look something like this depending on the rest of your code) It would definitely be helpful if you put the rest of your code. Now then you want to actually add force:

```
if (OnSlope() && !exitingSlope)
    {
        GetComponent<RigidBody>().AddForce(Vector.down * /*I'd recommend 80f to 400f depending on your player speed*/, ForceMode.Force);
    }

```

---
Tags: unity, physics, 3d, platformer, rigid-body-dynamics
---


# Question
Title: How to get consistent collision impulse values for colliding rigid bodies in Godot?
I'm writing a game where you can pick and throw objects and depending on the force of the impact they break.

Using the get\_contact\_impulse method to calculate the breaking point gives me very consistent results, but only for a single rigid body. When two rigid bodies collide, one of them reports the correct impulse, the other reports really low values, close to 0.

As an example, this is the same collision being reported by both objects:

```
SimpleCube_A2 collide with SimpleCube_A force 18.338762
SimpleCube_A collide with SimpleCube_A2 force 0.0180135

```

I believe this happens because once the second object runs its IntegratePhysics, the impact has already been solved by the first object (but this is just a guess).

I could just call a method on the second object, but since both objects will be reacting to the impact, I would have to add some bookkeeping to make sure the calls don't get recursive, nothing difficult but could be more error prone.

So I'm wondering if there's a solution where both objects can detect the "same" impulse, but without talking to each other. I don't mind having to calculate the impact myself or something like that, as long as it's reliable enough.

# Answer
> 0 votes
You could make each object compute its own impulse using linear momentum change. This solution uses Signals and tracks state variables manually. It works for linear momentum only, but you can extend it to include angular momentum too.

Add a script to a rigid body. A variable will store the object's linear velocity before updates at each physics frame:

```
extends RigidBody3D

var prev_velocity: Vector3

func _physics_process(_delta: float) -> void:
    prev_velocity = linear_velocity

```

To configure the rigid body to emit signals when colliding with another body, from the Inspector, set *Contact Monitor* to **True** and *Max Contacts Reported* to a value larger than **0** (I set it to **4** just in case). Depending on the object shape, you may want to enable *Continuous CD* too.

Now, connect the `body_entered` Signal of the rigid body to its own Script in a new Receiver Method. This method will be emitted automatically *after* the physics engine has resolved all collisions. Therefore, the rigid body will figure out what impulse was applied to turn its previous velocity into the current one:

```
func _on_body_entered(body: Node) -> void:
    var impulse = mass * (linear_velocity - last_velocity)
    print(name + " collide with " + body.name + " force " + str(impulse.length()))

```

The above means: physics engine applied a force of `impulse` magnitude for physics process' `delta` seconds to the object as a result of resolving all collision pairs, causing its linear velocity to switch from `prev_velocity` (previous frame) to `linear_velocity` (current frame).

The above snippet works when the object collides both with static bodies and other rigid bodies. RB pairs will compute impulses that will explain their final velocities.

If "strange numbers" start appearing, this is due to the fact that I didn't take angular momentum into account, so total momentum is still there in the Physics Server but wasn't computed in my custom script.

---
Tags: rigidbody, godot-4
---


# Question
Title: Getting a pixel of Sprite at the cursor position in Unity
Summary: I've been trying to figure out a way to use simple box colliders as a nice and efficient "first pass" collider. For the "second pass", I want to check that the area clicked has an alpha value \> 10%. I know this is generally possible with graphics programming, but I'm struggling to find a way to do this in Unity2D with packed sprites (packed via the native Sprite Packer tool).

What I was hoping to do (but Unity will not allow) would've been something like...

```
// Check to see if a point intersects with a solid color
private bool CheckPoint()
{
    Vector2 cursorWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    //foreach (Collider2D col2D in Physics2D.OverlapPointAll(cursorWorld))
    foreach (RaycastHit2D hit in Physics2D.RaycastAll(cursorWorld, Vector2.zero))
    {
        if (hit.collider.gameObject != gameObject) continue;

        foreach (SpriteRenderer sprRend in hit.collider.gameObject.GetComponentsInChildren<SpriteRenderer>())
        {
            Texture2D tex = (Texture2D)sprRend.sprite.texture;

            // this is the missing link; easy with 3d, but impossible with 2d?
            Vector2 pixelUV = hit.??????;

            int uvX = (int)(pixelUV.x * tex.width);
            int uvY = (int)(pixelUV.y * tex.height);

            Color hitColor = tex.GetPixel(uvX, uvY);

            if (hitColor.a > 0.1) return true;
        }
    }

    return false;
}

```

---

So far: I've been able to find some solutions for doing this with (3D) meshes and 3D colliders. However, the 2D colliders do not include the UV data that would be needed to make this work.

Someone was also able to get this working for their specific game using SpriteManager2 (which we're not using since Unity 4.3 makes SM2 mostly unnecessary) and posted their solution here... http://answers.unity3d.com/questions/17903/detecting-mouseclick-on-pixels-in-sprite-using-sm2.html and I think the same approach might work with minor adaptations for Unity2D, but I'm thinking there might be a more robust approach.

I'm also looking at trying to do something like http://answers.unity3d.com/questions/687116/what-is-the-easiest-way-to-convert-raycasthit2d-to.html but even if I can calculate the local UV, that wont help me with the real UV for the packed sprite unless I can somehow get the sprite's UV offset into the sheet.

# Answer
> 1 votes
I can't give exact code because I've not done this myself yet (may make a good exercise with the new 2D functionality) but I can see the outlines of how you would implement this.

First off, detect which sprite was clicked either using good ol' OnMouseDown. Use Input.mousePosition along with the sprite's transform to determine where the cursor is on the sprite.

With that, use properties of the sprite to figure out the exact pixel; I'm not sure off the top of my head which ones you'd use, but the script reference for Sprite mentions stuff like 'rect' and 'textureRectOffset'

Finally get the Texture2D with the sprite's 'texture' property and call GetPixel()

# Answer
> 0 votes
Below I've posted something I mocked up going for deformable pixel terrain. You may be able to get something from it... You may not... Either way, It can obtain the pixels of an image around the mouse position. The names are pretty self explanatory but if you don't understand something, post a comment here.

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

[RequireComponent (typeof (SpriteRenderer))]
public class BitmapMask : MonoBehaviour
{
    public Texture2D spriteTexture;
    public Texture2D maskedTexture;
    public int diameter = 50;

    public List <bool> mask;

    private float _width;
    private float _height;
    private Sprite _image;
    private SpriteRenderer _spriteRenderer;

    private Color[] tempColors;
    private Color[] maskColors;

    void Start ()
    {
        _spriteRenderer = GetComponent <SpriteRenderer> ();
        maskColors = maskedTexture.GetPixels ();

        _image = GetMaskedSprite (spriteTexture, maskedTexture);

        _spriteRenderer.sprite = _image;

        _width = _image.bounds.size.x * _image.pixelsPerUnit;
        _height = _image.bounds.size.y * _image.pixelsPerUnit;
    }

    void Update ()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

        mousePos += (Vector2)_spriteRenderer.sprite.bounds.extents;
        mousePos *= _spriteRenderer.sprite.pixelsPerUnit;

        if (Input.GetMouseButton (0))
        {
            ChangePixels ((int)mousePos.x, (int)mousePos.y, diameter, Color.black);
        }

        if (Input.GetMouseButtonDown (1))
        {
            ChangePixels ((int)mousePos.x, (int)mousePos.y, 50, Color.white);

        }
    }

    Sprite GetMaskedSprite (Texture2D spriteTexture, Texture2D maskTexture)
    {
        Texture2D texture = new Texture2D (spriteTexture.width, spriteTexture.height);
        Color[] spriteColors = spriteTexture.GetPixels ();

        tempColors = new Color[spriteTexture.width * spriteTexture.height];

        for (int y = 0; y < maskTexture.height; y++)
        {
            for (int x = 0; x < maskTexture.width; x++)
            {
                bool masked = (maskColors[x + y * maskTexture.width]) == Color.white; // change to white and change actual image

                if (masked)
                {
                    tempColors[x + y * maskTexture.width] = new Color (0, 0, 0, 0);
                }
                else
                {
                    tempColors[x + y * maskTexture.width] = spriteColors[x + y * maskTexture.width];
                }
            }
        }
        texture.SetPixels (tempColors);
        texture.Apply ();

        return Sprite.Create (texture, new Rect (0, 0, texture.width, texture.height), new Vector2 (0.5f, 0.5f));
    }

    void ChangePixels (int centreX, int centreY, int diameter, Color color)
    {
        int radius = diameter / 2;
        int a;
        int b;

        for (int y = centreY - (diameter/2); y < centreY + (diameter/2); y++)
        {
            for (int x = centreX - (diameter/2); x < centreX + (diameter/2); x++)
            {
                if (x < 0 || y < 0 || x >= _width || y >= _height) continue;

                a = x - centreX;
                b = y - centreY;

                if ((a * a) + (b * b) <= (radius * radius))
                    maskColors[x + y * maskedTexture.width] = color;
            }
        }

        ChangeSprite (GetMaskedSprite (spriteTexture, maskedTexture));
    }

    void ChangeSprite (Sprite updatedSprite)
    {
        _spriteRenderer.sprite = updatedSprite;
    }

}

```

Basically it takes in a spriteTexture and a maskedTexture. The masked texture gets altered to either black or white around the mouse position when a click is detected. The masked texture is then used to determine whether pixels from the sprite Texture should be shown, obviously based on the colour.

It may not exactly be what you're looking for but its a start in the right direction. Oh yeh and its not optimized and I have no idea about the bugs...

Goodluck.

# Answer
> 0 votes
This is a super old question, but I was struggling with this for a while, used the code from Savlon's answer and then found it wouldn't work if I moved or scaled the object at all. After hours of fiddling around I have fixed the code so this should work even better now. The start of the update function assumes that the sprite is at (0, 0, 0) and of scale (1, 1, 1). To adjust for positioning and scaling, the code should actually look like this:

```
Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

float scale = transform.localScale.x; //transform of sprite's gameobject
Vector2 extentsAdjusted = _spriteRenderer.sprite.bounds.extents * scale;
mousePos += extentsAdjusted - (Vector2)transform.position;
mousePos *= _spriteRenderer.sprite.pixelsPerUnit / scale;

```

Note that this only works if the resizing is the same in x and y, so if you stretch the object then I'm not sure how the code would change. Hopefully this change to the code will help the next person to stumble across this thread to save a few hours of struggle!

---
Tags: c#, unity, collision-detection, textures, input
---


# Question
Title: How do I Rigidbody.AddForce(Vector3) in Unreal Engine?
I am coming from the Unity Engine, and trying to get my feet wet with Unreal Engine 4.8.x. I want to add a one-time force to an object. To accomplish this in Unity 5, I would use:

```
void Start(){
    GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, 5));
}

```

Explanation:

> `GetComponent<Rigidbody>()` retrieves the `Rigidbody` Component. The `Rigidbody` is already attached to the `GameObject`. The `AddForce` method is called on the `Rigidbody`, and applies the force of a `Vector3`. The parameters of the `Vector3` indicate the force on each axis which is applied. In the example above, the `GameObject` would move forward on its z-axis.

How would I accomplish this same thing in Unreal Engine 4? I would appreciate if you can elaborate on what exactly is happening in the code as well. I currently have an empty AActor script, and I am struggling to find out what to put in my BeginPlay() method.

```
void AMyActor::BeginPlay()
{
    Super::BeginPlay();
    //What goes here?  Why?
}

```

As CobaltHex pointed out, UPrimitiveComponent has a `UPrimitiveComponent.AddForce(FVector, BoneName)` method. However, I cannot figure out how to use it. The real objective of this question is as a basic introduction to programming with Unreal Engine. I chose AddForce, because it is an extremely commonly used method with a visible effect (in Unity). All of the existing tutorials are either with an older version of unreal (which has different scripting) or are using blueprints (which has no scripting). That is why I am trying to figure out what the actual code would be and what that code does.

Specifically, I am looking for an answer which tells me what code is missing from my Unreal Engine script, and what that code does, similiarly as is presented with my Unity Engine example.

# Answer
See https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Components/UPrimitiveComponent/index.html

It has all kinds of functions (Similar to unity). One being AddForce.

Also, some physics is handle by Nvidia's Physx but I don't know how much of that you would interact with
> 2 votes

# Answer
If you want to add a one-time force to the object you should use the **AddImpulse** function instead of the **AddForce**, because AddForce applies a force continually.

To use the AddImpulse function you need the static mesh of the AActor first because is the one that contains the physics. Also **check if the mesh has the Collisions/Physics active** in the viewport of the Blueprint.

If you come from Unity, by looking at the Vector you use to apply the Force, you may want to move it in the Forward axis, but take into consideration that in *Unreal Engine the Forward axis is the Y not the Z so you may want to use the FVector(0.0f, 5.0f, 0.0f)*. In case that wasn't your intention, I've used the exact same Vector you used in Unity in this sample code.

Here is an example of what you could do:

```
void AMyActor::BeginPlay()
{
    Super::BeginPlay();

    //Get the static mesh of the chosen Actor
    UStaticMeshComponent* StaticMesh = Cast<UStaticMeshComponent>(GetRootComponent());

    //If the static mesh is valid apply the given force
    if (StaticMesh)
    {
        /*Create the Vector with the force to use*/
        FVector ForceToAdd = FVector(0.0f, 0.0f, 5.0f);

        /*When you want to apply a force you always need to multiply it's value by the
        mass of the object that the object is applied to.*/
        StaticMesh->AddForce(ForceToAdd * StaticMesh->GetMass());
    }
}

```

You can find more info here: https://www.orfeasel.com/adding-force-to-an-actor/
> 1 votes

# Answer
I think this is what you want:

It's adds a movement vector to the pawn.
> -2 votes

---
Tags: c++, physics, unreal
---


# Question
Title: How to properly split damage against armor?
I am developing a third-person shooting style game and I want to implement an armor system. The system that I have envisioned does not reduce the damage to 0, but by half. So the incoming damage is 50%. The armor takes the other 50% of damage and is reduced by that amount. Players pick up armor items from the map.

The issue that I'm encountering is an edge case where the damage \> armor. Here's what I have tried thus far:

Attempt 1:

```
-- Performs damage reduction based on armor, if any.  Automatically
-- adds the armor attribute to the humanoid if it doesn't already
-- exist.
local function processArmor(target, damage)
    -- Check if the player actually has armor.  If not
    -- then return full damage.
    local armor = target.human:GetAttribute("Armor")
    if armor == nil or armor == 0 then
        if armor == nil then
            target.human:SetAttribute("Armor", 0)
        end
        return damage
    end

    -- If the player does have armor > 0, then reduce the incoming
    -- damage.
    local d2 = damage / 2
    local t = d2
    d2 -= armor
    armor -= t - d2
    damage = d2

    -- Update armor stat and return.
    target.human:SetAttribute("Armor", armor)
    return damage
end

```

Attempt 2:

```
-- Performs damage reduction based on armor, if any.  Automatically
-- adds the armor attribute to the humanoid if it doesn't already
-- exist.
local function processArmor(target, damage)
    -- Check if the player actually has armor.  If not
    -- then return full damage.
    local armor = target.human:GetAttribute("Armor")
    if armor == nil or armor == 0 then
        if armor == nil then
            target.human:SetAttribute("Armor", 0)
        end
        return damage
    end

    -- If the player does have armor > 0, then reduce the incoming
    -- damage.
    if damage == armor then
        armor = 0
    elseif damage < armor then
        armor -= damage
    elseif damage > (armor * 2) then
    else
        local t = damage - armor * 2
        damage -= armor
    end

    -- Update armor stat and return.
    target.human:SetAttribute("Armor", armor)
    return damage
end

```

Attempt 3:

```
-- Performs damage reduction based on armor, if any.  Automatically
-- adds the armor attribute to the humanoid if it doesn't already
-- exist.
local function processArmor(target, damage)
    -- Check if the player actually has armor.  If not
    -- then return full damage.
    local armor = target.human:GetAttribute("Armor")
    if armor == nil or armor == 0 then
        if armor == nil then
            target.human:SetAttribute("Armor", 0)
        end
        return damage
    end

    -- If the player does have armor > 0, then reduce the incoming
    -- damage.
    local d2 = damage / 2
    if armor == d2 then
        damage = d2
        armor = 0
    elseif armor > d2 then
        damage = d2
        armor -= d2
    else
        -- damage / 2 > armor
        damage = ((d2 - armor) * 2) + armor
        armor = 0
    end

    -- Update armor stat and return.
    target.human:SetAttribute("Armor", armor)
    return damage
 end

```

Target is just a table that contains references to the parts of the player that was hit. In this case, I'm using the Humanoid under the player's character model. Attempt 3 seems to be the best bet, but under testing, the formula under the `else` seems to reduce to `damage -= armor`.

What I expect to see the the incoming damage cut in half. So if player 1 uses a weapon that does 20 damage against player 2, if player 2 has armor, the damage that player 2 see is 10, and the armor value is reduced by 10 (the other half of the damage). This I have mostly correct, except if the armor value is less than half the damage. I'm not sure if I got that correct or not. What I'm seeing is if the armor is 5 and the damage is 20, player 2 is getting 15 damage. I'm not sure if that's correct or not. Currently the formula is:

\\$damage = (((damage / 2) - armor) * 2) + armor\\$

I have done some research on the subject, but everything that I've found so far involves RPG style games. At this point, I'm looking for suggestions.

# Answer
> 4 votes
If I've understood correctly, I'd do this as a two step process...

Calculate how much the armor absorbs, then apply the rest to the player.

Something like:

```
total_damage = 100
armor = 25

damage_to_armor = min(armor, total_damage / 2)
damage_to_person = total_damage - damage_to_armor

```

In the above scenario, you'd get 25 to the armor (destroying it) and the remaining 75 to the player.

For scenarios where armor \>= damage / 2, you get a 50:50 split.

When armor = 0, you get 100% damage to the player.

---
Tags: mathematics, algorithm, lua, roblox
---


# Question
Title: In Unreal Engine 5, how do I include and use UPlayMontageCallbackProxy::CreateProxyObjectForPlayMontage in C++?
I want to play my `UAnimMontage` via C++, and in particular, want to make use of the conveniences of `UPlayMontageCallbackProxy`.

Looks like in theory, I can use `UPlayMontageCallbackProxy::CreateProxyObjectForPlayMontage`, but anytime I use it, I just get linker errors:

```
0>YCharacterVaulting.cpp.obj: Error LNK2019 : unresolved external symbol "public: void __cdecl UPlayMontageCallbackProxy::PlayMontage(class USkeletalMeshComponent *,class UAnimMontage *,float,float,class FName)" (?PlayMontage@UPlayMontageCallbackProxy@@QEAAXPEAVUSkeletalMeshComponent@@PEAVUAnimMontage@@MMVFName@@@Z) referenced in function "public: void __cdecl UYCharacterVaulting::Traverse(void)" (?Traverse@UYCharacterVaulting@@QEAAXXZ)

```

I’ve already updated my `Build.cs` so that the module is included:

```
PrivateDependencyModuleNames.AddRange(new string[] {"AnimGraphRuntime", "MotionWarping"});

```

Any ideas on how I can fix the linker error? Thank you!

# Answer
I never used the `UPlayMontageCallbackProxy` but `Error LNK2019` usually means you are lacking the include.

Looking at the docs, you should add `#include "PlayMontageCallbackProxy.h"` to your file (as well as the `AnimGraphRuntime` Module that you already have in the `Build.cs`).

Is the include added to your file? If so, could you share the function you are using?
> 0 votes

---
Tags: c++, animation, unreal, unreal-5
---


# Question
Title: Red thing inside of capsule object that shows when running the game in Unity
There is a red thing inside of my capsule object that shows when running the game in Unity. How do I make it invisible? I have tried looking at the capsule collider, but I couldn't find anything to make it invisible. Please take a look at the screenshots added to this question.

# Answer
> 3 votes
This is a gizmo drawn by one of the scripts you have running in this scene. Look for functions called `OnDrawGizmos` or `OnDrawGizmosSelected`. They'll be calling `Gizmos.DrawWireSphere` to draw this item, so you can comment out that line if you never want to see this.

You can also click the "Gizmos" button in the top bar of your Game tab to turn off drawing of gizmos in the game view.

---
Tags: unity
---


# Question
Title: Inconsistent Speed Of A Projectile Traveling On A Bezier Curve
**What I'm doing:**

I'm moving a projectile to it's target along a Bézier curve with one control point.

The projectile moves from `Transform` **A** to `Transform` **B** with the curve created by control's `Transform`'s position. I'm using this method so that I can change how the projectile's arc or path looks depending on the enemy's position.

**The issue:**

The projectile travels from **A** to **B** successfully, however, my issue is depending on the curve the speed can be inconsistent and an unwanted 'easing' effect can occur.

Here's an example in the image below. Because of control's position, you can see the wirespheres begin to bunch up and smoosh together. As the projectile travels from **A** to **B**, it will gradually move slower as the wirespheres become closer together.

---

**Here are the two scripts I am using to accomplish this:**

```
public class QuadraticCurve : MonoBehaviour
{
    public Transform A;
    public Transform B;
    public Transform Control;

    public Vector3 evaluate(float t)
    {
        Vector3 ac = Vector3.Lerp(A.position, Control.position, t);
        Vector3 cb = Vector3.Lerp(Control.position, B.position, t);
        return Vector3.Lerp(ac, cb, t);
    }

    private void OnDrawGizmos()
    {
        if(A == null || B == null || Control == null)
        {
            return;
        }

        for (int i = 0; i < 20; i++)
        {
            Gizmos.DrawWireSphere(evaluate(i / 20f), 0.1f);
        }
    }
}

```

---

```
public class ProjectileAttack: MonoBehaviour
{
    public QuadraticCurve curve;

    private IEnumerator MoveTheDart()
    {
        // Set the target
        _curve.B.transform.position = ImpactPosition.position;

        while (sampleTime < 1f)
        {
            sampleTime += Time.deltaTime * newSpeed;
            projectile.position = curve.evaluate(sampleTime);
            yield return null;
        }
    }
}

```

---

**What I need assistance with:**

I believe `v1`= ac & `v2` = cb. Would L be a number I pick that would decide how much it moves each frame?(almost like speed)

I imagine `Length` is separate from `L`. If so, what would `Length` be?

Thank you so much to anyone taking the time!

# Answer
Well, unfortunately I wasn't able to figure this out. But I didn't want to abandon this thread without closing the loop.

If you are on Unity 2022 LTS you can simply use the Unity Spline package. It does all of the math calculations for linear speed out of the box:

https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/index.html
> 0 votes

---
Tags: unity, mathematics, animation, linear-algebra, beziers
---


# Question
Title: Fixing thing on unanchored object in Roblox
I am currently creating a car game in Roblox which has many ramps. For visual fun, I have created an unanchored (movable) burning car laying next to it so it looks like a car already tried this extreme ramp and crashed. I want the fire to move with the car when the car is getting pushed. I am new to Roblox game dev (ca. 3 days).

The scene structure of the burning car:

(The two black painted objects are objects that are not related to this burning car and thus are irrelevant for this question.) The three **Model \> Part \> Fire** things are the fires, the MeshPart below them is the actual car.

This is how the car looks like:

The fires are anchored. If I unanchor them, they fall off the map (they don't have a collider so touching the fire/car won't cause problems). When I anchor them, they are fixed on the current location and only the car moves away.

# Answer
When it comes to unanchored objects, Roblox allows for **welding** objects together so they move as one entity. If you want the fire to move with the unanchored car, you can weld the Parts which contain the fire to the car, allowing them to move as one entity.

There are a couple of ways you can go about doing so:

1. You can use a `WeldConstraint` object and insert one into each Part which has the fire effect. Once you've done so, you can edit the `Part0` and `Part1` properties, and select the Car and respective parts with the object selector. Check the Roblox documentation if this is troubling. https://create.roblox.com/docs/reference/engine/classes/Weld
2. There is a Constraints tab in the Model section in the top bar which allows you to draw these welds between parts. Make sure to select `WeldConstraint` in the drop down menu at the top of the section, and then use your mouse to select the two parts you want to weld.

Just a reminder to unanchor all of the parts you want welded! Anchoring one of those parts will lock the entire model in place. Let me know if you have any further questions. :)
> 1 votes

---
Tags: roblox
---


# Question
Title: How to tell whether an expression is independent from frame rate?
I'm working on a videogame where part of the logic involves increasing a value each render frame (a render frame is equivalent to a simulation step where the result is drawn on the screen).

Frames can have varying time steps between them, commonly named "delta time".

I am wondering if there is a general approach to determining whether the expression that updates the value is "pinned" to real time, meaning that running one frame with delta time `x` is equivalent to running `n` frames with delta times adding up to `x`.

I have thought about this extensively for a few days now, but haven't reached the clean generalization I think would be possible to reach.

Say every frame we update value `a` with the following expression:

`a = a + (b - a) * d`

This is a commonly used formula for linear interpolation, where `b` is a constant that can be interpreted as a target value, and `d` is another constant between 0 and 1 that represents the fraction of distance to cover.

Now as you can see in the link I shared above I have calculated that to do this independently from frame rate one has to replace the factor `d` with an expression that involves `delta_time`:

`a = a + (b - a) * (1 - d^delta_time)`

I did this by expressing this process as a recursive sequence:

```
S(0) = a
S(n) = S(n-1) + (b - S(n-1)) * d

```

Then making it non-recursive (I don't think there's a standard approach for this, just expanding the expression and looking for patterns such as series with known formulas for the sum of the first `n` elements).

Once I reached a non-recursive form, I replaced `n` with `t / delta_time`, as the number of frames elapsed is equivalent to time elapsed divided by the time between frames. Then, I introduced `delta_time` into the expression in order to cancel it out, and translated that change into a change in the `d` constant.

I am not happy with this approach however.

I am now trying to formulate the problem in some other way, seeing if it gives me some clues as to a clean generalization.

What I'm looking for is a simple rule, a way to express that:

Given an expression `S(delta_time)` which calculates how much to increase a value by each frame, an increase of `x` in `delta_time` should be equivalent to running one iteration with `delta_time = x`.

I would also be interested in a solution that would provide assurance in terms of varying time step between frames - so not just agnostic to different `delta_time` over `n` frames, but agnostic to any `delta_time` between each subsequent frame. I think this may have no importance mathematically, but I'm not sure.

Could someone help elucidate me? I feel I'm at the edge of my mathematical ability.

Thanks!

# Answer
> 1 votes
One way we can formalize this is to say we have a function \\$f\\$ that takes some input game state \\$ {\bf x}\_0 \\$ and a timestep \\$ \Delta t\\$ and transforms it into the resulting game state \\$ {\bf x}\_1 \\$ exactly that much time in the future:

$${\bf x}\_1 = f({\bf x}\_0, \Delta t)$$

As you say in the "Another Perspective" section at the bottom of your article, we want to check whether the result of evaluating this function twice is the same as evaluating it once for the combined timestep (at least for infinite-precision real numbers). That is, does it obey this identity:

$$ f\left( f({\bf x\_0}, \Delta t\_1), \Delta t\_2 \right) = f( {\bf x}\_0, \Delta t\_1 + \Delta t\_2)$$

I asked about this on the Math StackExchange, and learned that a function with this property is called a *flow*.

We can test for this property by expanding out the two sides using some algebra, and check if we get the same expression both ways. For the exponential ease-out function you showed...

$$ f(a, \Delta t) = a + (b - a)\left(1 - d^{\Delta t}\right)\\ f(a, \Delta t\_1 + \Delta t\_2) = a + (b - a)\left(1- d^{\Delta t\_1 + \Delta t\_2}\right) $$

For this case, composition over two subsequent steps expands out to...

$$\require{cancel} \begin{align} &f\left( f(a, \Delta t\_1), \Delta t\_2 \right)\\ &= f\left(a + (b - a)\left(1- d^{\Delta t\_1}\right), \Delta t\_2 \right)\\ &= \left\[a + (b - a)\left(1- d^{\Delta t\_1}\right) \right\] + \left(b - \left\[a + (b - a)\left(1- d^{\Delta t\_1}\right) \right\]\right)\left(1 - d^{\Delta t\_2}\right)\\ &= a + (b- a)(1 - d^{\Delta t\_1}) + (b-a)(1 - d^{\Delta t\_2}) - (b -a)(1 - d^{\Delta t\_1})(1 - d^{\Delta t\_2})\\ &= a + (b - a)\left(1 - d^{\Delta t\_1} + 1 - d^{\Delta t\_2} - (1 - d^{\Delta t\_1})(1 - d^{\Delta t\_2})\right)\\ &= a + (b - a)\left(1 \cancel{- d^{\Delta t\_1} + 1 - d^{\Delta t\_2}} \cancel{- 1 + d^{\Delta t\_1} + d^{\Delta t\_2}} - d^{\Delta t\_1 + \Delta t\_2}\right)\\ &= a + (b - a)(1 - d^{\Delta t\_1 + \Delta t\_2})\\ &=f(a, \Delta t\_1 + \Delta t\_2) \end{align}$$

So the composed form is equal to the single evaluation with summed time arguments, and we've proven this function has the desired "flow" property.

---

If you're looking for a relatively easy test to apply to a given function, without having to find a route to simplify the algebra to check the identity as shown above, then a **numerical simulation** is a great quick-and-dirty check:

Open up Google Sheets or the spreadsheet software of your choice. Pick a timestep, and make a column of values going up by that step. Next to them, use your step formula with that timestep and drag it down to see the sequence of values it produces. Repeat this for a different timestep (say half or double the initial choice). Then compare the values they give you, or graph the two curves. If they give diverging values at the same timestamp, the formula does not preserve framerate independence.

I show an example of that approach in this answer, to prove that some formulas being purported as "framerate independent" were not.

Because of the compounding of errors from one step to the next, the wrong formula will tend to reveal itself very quickly when you do this! And this directly tests the situation we care about in games: whether a run simulating discrete steps at 30 fps and 60 fps (for example) will see the same result.

Note that even when we use a function with this flow property, the results we get can still vary slightly at different framerates due to accumulated rounding error in the intermediate values. So when you need exact consistency for fairness or deterministic simulation, you need to fix your timestep.

# Answer
> 1 votes
You are asking the difference between a mathematical derivative and a discrete derivative:

> Given an expression S(delta\_time) which calculates how much to increase a value by each frame, an increase of x in delta\_time should be equivalent to running one iteration with delta\_time = x.

> I would also be interested in a solution that would provide assurance in terms of varying time step between frames ...

Yes, you can be assured the produced value is the best estimate possible, by virtue of the definition of a derivative: the denominator is delta t.

The error factors only include precision errors.

> agnostic to any delta\_time between each subsequent frame

No such general exact solution could exist.

Delta time has an unstable variance(outside of a RTOS).

The theoretical mathematical value is the best estimator.

## Bottom Line

It can never be exact, only close.

## Final comment

> I am wondering if there is a general approach to determining whether the expression that updates the value is "pinned" to real time, meaning that running one frame with delta time x is equivalent to running n frames with delta times adding up to x.

As close as accumulated precision will allow.

# Answer
> 1 votes
> I am wondering if there is a general approach to determining whether the expression that updates the value is "pinned" to real time, meaning that running one frame with delta time x is equivalent to running n frames with delta times adding up to x.

Yes.. If the expression's variables that are multiplied by delta-time are constant (they can not change from frame to frame) then running one frame with delta time x is equivalent to running n frames with delta time x\*n.

In your example, you provided the expression:

```
a = a + (b - a) * d

```

If `(b-a)`, the value multiplied by d, is constant (as in it can not change from frame to frame) then running it ten times for delta-time-d is the same as running it once for delta-time-10d (floating point precision ignored). This is the only case where this is true.

However, if `(b-a)` is varying from frame to frame, then EVERY different delta-time you choose to run under will produce a different outcome, because of that varying.

For example, in physics simulation, a simple first-derivative velocity approach, if velocity is changing because of acceleration, produces noticably different results based on what the actual delta-time experienced happens to be, and the method used of computing the new velocity value.

This is why typically, in a physics simulation, a 2nd order differential equation is used to compute motion, because given an acceleration, it will not only compute the current velocity given an acceleration over some given delta-time, but it will also provide an integrated average velocity (and thus motion delta) over the delta-time based on how much the velocity was changing *during* the previous delta time. This 2nd order differential equation of motion will accurately produce the same results whether it's 10x-delta-d or 1x-delta-10d - but ONLY if the acceleration over that time is constant!

If the acceleration over that time is changing, then you are back to your delta-t mattering, because of the changes to acceleration... unless the acceleration is changing with a constant 3rd derivative, and you use a 3rd order differential equation of motion.

Are you seeing a pattern?

It's turtles turtles turtles all the way down.

# Answer
> 0 votes
Your conclusion **assumes a fixed delta-time**: `u^deltatime` Which is an invalid statement if delta-time varies across steps. Almost a given on modern systems.

> There are two ways to go about this: Calculate the current value given a starting value and time elapsed (an animation curve) Update the value given the time since the last step (such as moving forward at a given speed)"

Each of your options explores/describes the same formula with different parameter options.

A true "Frame Rate Independent Lerp" fixes, makes constant, the a and b parameters at the start, as a1 and b1 and scales alpha to a normalized time period(called nt ),0 to 5 seconds becomes 0 - 1 by multiplying by 1/5, so for this example, nt = 0.2 :

```
if(sum_time < 1)
{
      sum_time += elapsed_time * nt; // this calculation may run into lower epsilon and become zero for long periods on fast computers use doubles not floats
      if(sum_time > 1)
            sum_time = 1; // eliminate overshoot, breaks linearity for the last step, due to precision errors
      current_value = a1 * (1 - sum_time) + b1 * sum_time;
}

```

By fixing the start and end values (a1,b1) the result is linear and bound to the range \[a1,b1\].

For long period lerps:

```
if(sum_time < 1)
{
      sum_time += elapsed_time;
      if(sum_time > 1)
            sum_time = 1; // eliminate overshoot, breaks linearity for the last step, due to precision errors
          st =sum_time  * nt;
// this calculation may still run into lower epsilon and become zero for long periods on fast computers for the first iterations, but will stabilize after 'sum_time  * nt' grows above epsilon.
// although the start time may be delayed(non-linear for the first steps), the outcome is the same linear movement over time.
      current_value = a1 * (1 - st) + b1 * st;

```

That is the entire article as it relates to the title.

## Ease in

Allowing `a` to vary with a fixed `b1` over iterations produces an easing effect, smooth exponential motion given a fixed(usually small) alpha value.

## Recursive analysis

You have described the differential equation of `X` as: `X(n+1) = X(n) + DX/DT`

There are three ways to treat this equation in a discrete manner Forward Euler, Backward Euler and Crank-Nicolson ie Mid-Point. Since DT, delta time is unknown in the future, Forward Euler can be eliminated, unless delayed by a step. By storing the previous calculated point Crank-Nicolson is the best stable solution.

---

> Is the geometric series/exponential curve special in this scenario? Or can other curves be made independent from frame rate?

Any and all curves including non-linear differential equations are expressed independent from frame rate by definition and could be expressed.

> Is there a way to guarantee that an iterative process will be independent of frame rate even when b and delta\_time change between iterations?

No. You are changing the parameters on the fly.

---
Tags: mathematics, timestep
---


# Question
Title: Godot 3.5: Web Build using custom GDNative C++ Library does not work due to `dlopen` error and failed linking
## The Problem

Currently I am trying to get the official GDNative C++ example for Godot 3.5, which can be found here working in the Web Export context. So far, I managed to export to X11.64 without any troubles and managed to set up the creation pipeline for the Web Assembly (see section "Web Assembly Creation Process" below), which now produces a valid output without any error messages. However, as soon as I try to run the game in any browser, it stops loading and displays the following error message:

```
Aborted(To use dlopen, you need enable dynamic linking,
see https://github.com/emscripten-core/emscripten/wiki/Linking)

```

This link only contains a link to the new documentation of `emscripten`, which is used to create the Web Assembly file, and is at the time of writing located at https://emscripten.org/docs/compiling/Dynamic-Linking.html.

## Final File Structure

```
ROOT/
  ├─godot-project-src/
  |   └─lib/
  |      ├─wasm/
  |      |   └─libsimple.wasm
  |      ├─SimpleLibrary.gdnlib
  |      └─SimpleLibrary.gdns
  └─SimpleLibrary/
      ├─godot-cpp/
      |    ├─bin/
      |    |  └─libgodot-cpp.javascript.release.wasm.a
      |    ├─include/
      |    |   ├─core/
      |    |   └─gen/
      |    └─godot-headers/
      ├─bin/
      |  └─libsimple.wasm
      └─src/
         └─init.cpp

```

## Web Assembly Creation and Export Process

### At the beginning of the project (only necessary once):

1. Initialize `SimpleLibrary` directory with `godot-cpp` and `godot-headers`.
2. Create the release JavaScript Godot Binding via
`scons platform=javascript generate_bindings=yes target=release`,
which creates the archive `SimpleLibrary/godot-cpp/bin/libgodot-cpp.javascript.release.wasm.a`.
3. Create GDNative Import Files in the Godot Project Directory.
```
 godot-project-src/lib/SimpleLibrary.gdnlib
 godot-project-src/lib/SimpleLibrary.gdns

```

### After each change:

1. Create the new Web Assembly Library
```
 cd SimpleLibrary
 emcc -o bin/libsimple.wasm -g -O3 -sSIDE_MODULE=1 src/init.cpp godot-cpp/bin/libgodot-cpp.javascript.release.wasm.a -Igodot-cpp/include -Igodot-cpp/include/core -Igodot-cpp/include/gen -Igodot-cpp/godot-headers

```
2. Copy the newly created library to the correct location in the Godot Project Folder

```
   cp bin/libsimple.wasm ../godot-project-src/lib/wasm

```
3. Update (if necessary) the GDNative Import Files in the Godot Project Directory.
```
 godot-project-src/lib/SimpleLibrary.gdnlib
 godot-project-src/lib/SimpleLibrary.gdns

```

### Web Export

Just selecting the HTML Export Template via the Godot Editor, choosing the Export Folder and let Godot do its thing.

## Questions

1. Did I miss some necessary settings during the Web Assembly creation? I already had to change some compiler flags for `emcc`and add include directories compared to the original example to get it even to compile. I also experimented with the optimization flags, the deprecated `-shared` flag, `-sDYNAMIC_EXECUTION`, `-sMAIN_MODULE`, but no changes.
2. Do I have to create a custom HTML Export Template for this to work properly? According to the GDNative Documentation, if

```
   godot-project-src/lib/SimpleLibrary.gdnlib
   godot-project-src/lib/SimpleLibrary.gdns

```

are created properly, this should not be necessary.

3. Is the GDNative C++ Web Export at all possible? During my research, I only found very vague documentation, a lot of (not really related) github issues and more questions than answers.

# Answer
> 3 votes
After some detailed checking of the `emcc` compiler flags and verifying their functionality in the documentation, I realized that the Godot Webexport does not produce the files required for the pseudo-shared library approach of `emcc`. After taking a close look at the official Godot 3.5 Documentation regarding Web Export Options, I found that I missed to set one property in the Godot HTML Export Template Settings.

The documentation states clearly that for GDNative to work in the Web Export, the `Export Type` has to be set to `GDNative`.

Now the Godot HTML Export includes the three according to the `emcc` documentation required `.wasm` files:

1. The library itself `libsimple.wasm`,
2. The side-loading library `<PROJECT EXPORT NAME>.side.wasm`,
3. The main `.wasm` containing the default Godot functionality `<PROJECT EXPORT NAME>.wasm`.

---
Tags: c++, web, export, godot-3
---


# Question
Title: Best way to implement a carrying tray in VR using Unity
I need a way to carry objects on top of other objects in VR without jitterness causing the objects to fall through a tray for example.

I've tested with rigidbodies having very high friction, this does help with the unrealistic slipping off but both the jitterness of virtual reality and also the ability to teleport creates the need for a better solution.

I'm thinking of some kind of magnet-like system where if you drop an item onto the tray, it becomes stuck until you manually take it off. This would be simple by just checking collisions, parenting the object and making it Kinematic, the issue is it still needs to follow physics where if you tip the tray the object should still be able to fall off.

Has anyone implemented anything like this before or have any ideas on the best way to solve this situation?

# Answer
> 1 votes
I have found a suitable solution using both Unity's built-in materials and a script that uses a trigger as a parent modifier.

Both the tray's and mug's collider has a material attached that raises friction.

I then have a trigger collider that is the same size as the tray but ever so slightly larger on all sides compared to the physical collider.

This is used by a script that parents this object of it is close enough.

```
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class RigidbodySurface : MonoBehaviour
{
    void OnTriggerEnter(Collider col)
    {
        if (col.GetComponent<XRGrabInteractable>() != null) {
            col.transform.parent = transform;
        }
    }

    void OnTriggerExit(Collider col)
    {
        if (col.GetComponent<XRGrabInteractable>() != null)
        {
            col.transform.parent = null;
        }
    }
}

```

I found tips by remembering this is just like having a character or object on a moving platform in a platformer game. Leaving this description for future reference in case someone is searching for a way to have a moving platform in a puzzle game where objects need to follow the platform, like the player.

# Answer
> 2 votes
It sounds like you've already figured out the solution:

> I'm thinking of some kind of magnet-like system where if you drop an item onto the tray, it becomes stuck until you manually take it off.

From reading your post, it sounds like exactly what you need. When an object is placed on the tray, make it a child of the tray, and make it kinematic, so that it still interacts with other objects, but it isn't affected by gravity.

When a user attempts to grab one of those objects on the tray, detach it and disable kinematics, so that it is a physics object again.

It should also solve your teleportation feature, as objects should remain attached on the tray.

This of course is heavily dependent on what kind of game you are going for, but from what you've described so far, this technique should work well.

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


# Question
Title: Unity Animator default values overwriten
I have created a project to reproduce the problem I'm currently facing. I'm running a simple unity animation that moves a game object and expect to be able to reset the gameobject position. This can be done by adding an empty animation, that (since it does not change anything) simply writes the default values, thus returning our gameobject to its original position.

But here is where things get complicated: if the animator gameobject is set inactive while the animation is running, new incorrect defaults values will be saved when gameobject is activated, and I am unable to reset my gameobject position.

To reproduce this issue, run the attached project: (Download from here)

1. Change the stop method to "PlayEmpty"
2. Hit Start Animation and watch the left "Hello world" text travel.
3. While it is traveling, click Disable Text GO. The left text disappears.
4. Click Enable Text GO and see the text comes back at its last location.
5. Click Start Animation and watch the left "Hello world" text travel.
6. Click Stop Animation - the text is returned to the position where it was when enabling the gameobject, rather than its original position.

Any help is welcome, suggestions on how to change the code to make the above scenario work.

Thanks, Yaniv

# Answer
## Creating an empty animation state does not write default values.

If you want a set of *default* values, you should explicitly set this default value in the state, even if this value were 0s.

Imagine if Unity were to assume everything to be their idea of a default - most animations would break. For instance, a rotating cube would jump back to world origin - we've never set its position.

If your case, simply create an empty state, assign it as your default state, and set your 'defaults' accordingly.
> 1 votes

# Answer
https://docs.unity3d.com/ScriptReference/Animator-writeDefaultValuesOnDisable.html

Setting it to "true" did it for me.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: In the Unity editor, why are the coordinates of a newly created root object not set to 0,0,0 when the object is at the origin?
My initial coordinates of a newly created object without a parent are not 0,0,0

They’re supposed to be at the origin. Instead they are some random number.

And how can I set them to zero without moving the object to some arbitrary location? I tried changing local to global in the scene, but it didnt affect those.

What caused them to be these random numbers? The floor is centered at (0,0,0)

# Answer
> 3 votes
My best guess is, you spawned the object over the top menu. This will spawn the object in the center of your current view. It would make sense from a design point of view to have the new created object close to further manipulate it - in a big scene, 0/0/0 can be quite far from the current working location.

The same happens when you right click in the hierarchy. It will still spawn at the current center.

If you right click on the scene and spawn it from there, it will be created at 0/0/0.

---
Tags: unity, transformation
---


# Question
Title: How to clean up list entries when objects are destroyed in Unity?
We are developing an economic sandbox somewhat similar to a mixture of The Guild and Kenshi.

In this game, both the player and the NPCs will often create and destroy (consume) various objects.

The trouble is that destroying an object in Unity does not remove references to destroyed objects. For example, Lists containing the object will still contain an entry for it (that compares as equal to `null`).

The best solution I came up with is to use the observer pattern, notifying all classes where the object was stored about its destruction and removing references to it from there. But this method does not look optimal; are there better options?

# Answer
> 4 votes
> The best way that I came up with is, according to the observer pattern, to notify all classes where the object was stored about its destruction and remove references to it from there.

That's what I always do.

```
[System.Serializable] public class DestroyableEvent : UnityEvent<Destroyable> {}
public class Destroyable : MonoBehaviour {
    [SerializeField] private DestroyableEvent destroyedEvent = new DestroyableEvent();
    public DestroyableEvent DestroyedEvent => destroyedEvent;

    void OnDestroy() {
        destroyedEvent.Invoke(this);
    }
}

```

Then in some other class you have something like this:

```
[SerializeField] private Destroyable prefab;
private List<Destroyable> objects = new List<Destroyable>();

public void SpawnObject() {
    var newObject = Instantiate(prefab);
    newObject.DestroyedEvent.AddListener(objects.Remove);
    objects.Add(newObject);
}

```

If objects are created and destroyed frequently, you should use a pooling system instead, but you still need events to track when an object is returned to the pool so you can remove it from any relevant lists.

Another solution you can use is to periodically scan lists for null entries and remove them, or remove them when you try to access an entry in the list and determine that it's null. I prefer to use an event-driven approach as shown above.

---
Tags: unity, c#, software-engineering
---


title: Minecraft-like simulation optimization

text:
# Question
Title: Minecraft-like simulation optimization
I am working on a voxel game similar to Minecraft. The goal would be to handle more entities but also offer a more immersive experience by the fact that the player does not need to worry about loading chunks. What is a way to handle unloaded entities? I plan to keep chunks near the player "awake" and performing a full simulation. However, I cannot do this for distant chunks, it would require too much computing power. I was thinking about discretizing some of the entity behavior, but this appears to become very complicated once there are too many possible interactions. Imagine a furnace processing ores, which in turn go into a chest, and a golem moves items from that chest into some other container. The simulation could probably be simplified the more distant from the player it is, but obviously I want to avoid anything that could lead to item duplication. Are there any elegant solutions to this problem?

# Answer
One technique you can use to optimize things like crop growth or furnace smelting in a Minecraft-like game is to, rather than have a loop that goes through all of them and updates them in accordance with the current time every frame, to just store the time they were created.

For example, for the furnace you can just store the items in the furnace, and the time at which the smelting started. And then, whenever the furnace is accessed next, calculate how many of the items should have been smelted by subtracting the stored start time from the current time. 0 (or close to 0) computation is required for all the intermittent time.

A similar technique can be applied to crop growth. Calculate their age on the fly as needed instead of manually updating them constantly.
> 2 votes

---
Tags: optimization, voxels, simulations, loading
---


# Question
Title: How do I detect a hit by a swung held object?
I have an XR Grab Interactable wrench and the grab is working fine, as is movement. I'd like to use it to smash some chains, so I figured that I could use an OnCollisionEnter on the chains, and check against the tag. Except... it doesn't seem to actually register a collision at all unless I drop the wrench. What's the best way to detect a hit on a swing? And would it be possible to require a certain amount of speed of movement to trigger the collision?

# Answer
> 0 votes
Ultimately, I wound up using a Trigger check instead of Collision. It works, although I did not bother with implementing the velocity check.

```
private void OnTriggerEnter(Collider other)
{
    GameObject obj = other.gameObject;

    if (obj.CompareTag("SmashTool"))
    {
        // Since the chains can only be smashed if both locks have been removed
        if (_locks <= 0)
        {
            gameObject.GetComponent<MeshCollider>().enabled = false;
            gameObject.GetComponent<MeshRenderer>().enabled = false;
            Destroy(gameObject, 5f); // Leaving enough time for the sound file

            _audioSource.Play();

            _doorAnimator.SetTrigger("OpenDoor");
        }
        else
        {
            // Play sound?
            // Give hint?
        }
    }
}

```

# Answer
> 1 votes
The way I would do this is to cache the position and rotation of the wrench at the end of each Update or FixedUpdate (depending on when your wrench moves). At the start of the next step, calculate the position of the end of the wrench in its previous and current orientations, then check a capsule of space encompassing those two points, to see if it intersects your chain.

This will catch a collision at the start/end of the interval, as well as any object the end "skipped over" in between, approximating the swing as a straight-line movement.

You can repeat this check for points along the handle of the wrench too, to make sure you don't miss a chain when you over-reach with the tip.

You can also break this into sub-steps to better approximate the wrench's arc, if you find players are swinging it so fast that it swings through a significant fraction of the circle in a single step.

Lastly, you can estimate the impact velocity using the point's travel divided by the timestep.

Here's some example code that does this:

```
public class SwingDetector {

   [System.Serializable]
   public struct CheckPoint {
       public Vector3 localPosition;
       public float radius;
   }

   public LayerMask whatToHit;
   public CheckPoint[] points;

   Vector3 _oldPosition;
   Quaternion _oldOrientation;

   public bool CheckHit(float deltaTime, out RaycastaHit hit, out Vector3 velocity) {
       hit = default;
       velocity = default;
       bool hitSomething = false;

       foreach(var point in points) {
           Vector3 before = _oldPosition + _oldOrientation * point.localPosition;
           Vector3 after = transform.TransformPoint(point.localPosition);

           Vector3 travel = after - before;

           float distance = travel.magnitude;

           if(Physics.SphereCast(before, point.radius, travel, out hit, distance, whatToHit)) {
               velocity = travel / deltaTime;
               hitSomething = true;
               break;
           }
       }
       transform.GetPositionAndRotation(out _oldPosition, out _oldOrientation);

       return hitSomething;
   }
}

```

---
Tags: unity, collision-detection, virtual-reality
---


# Question
Title: 2D Sprite components causing text (TextMeshPro) components to be hidden in Unity
Edit: Depending on where my game character is located in the map, some text (TextMeshPro) components get hidden/turn invisible.

I have tried to figure out what is causing this. With the help of a comment on this post I found out that the problem is located at the 2D Sprite components (background) of each chatbubble. Once I turn these 2D Sprite components off, the text is always visible.

On these screenshots you can see that the 2D Sprite components (background) get sorted in front of the text components depending on where (i assume) my camera or player is located on the map.

# Answer
Found the answer to this question:

1. Set the 'Order in Layer' of each 2D sprite component (the background of each chatbubble) to 0
2. In the inspector window of a text component, search for 'Extra Settings'
3. Set the 'Order in Layer' of each text component to 10
> 0 votes

---
Tags: unity
---


# Question
Title: How can I evaluate an entry level salary in game developer?
I want to make some informed decisions about an entry level game developer position. Specifically, how can I determine if I'm getting a fair salary. I realize that many different factors can impact pay, especially across different regions. But in general, how do more experienced developers advise new developers in determining if a salary is reasonable?

Optionally, how impactful are subspecializations? For example, for the purposes of evaluating pay, do I need to consider my experience with C++ WinRT differently than if I knew something like Unity?

# Answer
Start by looking over the most recent Developer Satisfaction Survey (DSS) from the IGDA. The 2021 survey includes salary data:

The 2021 survey doesn't subdivide pay based on experience. If you had a job offer that started at $32k USD, the data tells us that that offer is above the bottom 21% of the salaries reported. Generally speaking, most entry level positions are shifted toward the lower end of the pay scale. So that hypothetical offer is at the upper end of the of the lowest quarter.

The 2021 survey also includes other important considerations such as: regular hours of work, crunch, overtime compensation, job security, benefits and career advancement. Some of these are harder to directly compare directly between offers, but they are still important to consider - if they weren't directly disclosed, ask about them.

Some employment sites / platforms have salary information. Start with a web search for "game development careers."

The impact of (sub)specializations and experience is like most other resume traits traits: it varies. In that regard, there's nothing particularly different about the game development aspect of this question. A specialization might be mandatory for a specific role due to time or budget constraints. In other cases, a company might consider a specialization nice to have. Making an informed choice would involve researching:

* The position. How essential is the skill to that role? If you're missing a skill, do you have one or more skills that help bridge the gap?
* The job market. How likely is it that other candidates have the skill? How many other employers are seeking that skill?

Again, this isn't unique to game development and varies so much that there's no way to answer for all skills, across all locations, for all time. Again, check a few different employment sites to get information relevant to your particular situation.

It's important to recognize that that evaluating any position depends on your context. Something that's reasonable for one person might be completely unrealistic for another. Ultimately the value of a particular skill or trait is determined by both yourself and what the job market will offer.
> 2 votes

---
Tags: career
---