# Question
Title: There are no body properties in Cinemachine's virtual camera
Why are there no body properties in Cinemachine's virtual camera?

Unity version: 2021.3.11f1

Cinemachine Version: 2.8.9

# Answer
> 0 votes
Your inspector is currently in Debug mode, which disables custom editor drawing code that components like Cinemachine use to present a friendlier user interface, and instead shows a raw dump of the internal state.

Try clicking the three-dot icon (⋮) in the top-right of your inspector window, and change to "Normal" mode:

That should make the more familiar / documented Cinemachine interface appear.

---
Tags: unity, camera, cinemachine
---


# Question
Title: Frame graph in Vulkan: from theory to implementation
I've watched the excellent talk from Yuriy\[1\] and read a blog post\[2\] multiple times already, but I still cannot find the answers to the questions I have.

I really like the idea of defining a graph of "virtual resources", it gives a lot of flexibility, maintanability, and ease of use (think about synchronization) in the long term. First, I thought that the easier way to solve my problem (described below) is to implement this system so that the graph building and the transformation to the actual graphics API wouldn't be done every frame, only when the conditions (eg. graphics settings) change.

However, extending the "only when the conditions change" statement to include game logic-related decisions, we get to a point where the frame graph must be rebuilt almost every frame. This is also what Yuriy suggested in his talk and I agree with it.

**The main problem**

In Vulkan the whole pipeline (with the corresponding render pass) must be pre-built. So the rebuilding of the whole graph every frame can be a bottleneck as I can imagine. The pipeline cache could speed up things (in theory) but avoiding sudden frame-rate drops is top priority. However, if a pipeline (especially the shaders) have not yet been built, it could cause a hitch up. And pre-warming the cache(s) with every possible permutations defeat the purpose of the whole system.

**The question**

So I'm wondering if there is a way to keep the best from both worlds, rebuilding the whole graph every frame while avoiding sudden frame drops from pipeline creation.

If there is no such solution, what would be the closest thing to this kind of dynamic whole frame predefinition? Should I fall back to the rarely rebuild graph, and use another method to skip (sub)passes?

**References**

\[1\] FrameGraph: Extensible Rendering Architecture in Frostbite (GDC Vault)

\[2\] Render graphs and Vulkan — a deep dive (link)

# Answer
> 2 votes
Because i saw this post while wondering it myself i wanted to give an answer on how i implemented it, maybe it will be a use to someone.

As you said yourself pipeline creation every frame doesn't make sense as we are building new render passes each frame, and also just rebuilding everything each frame sound like to much wasted work. One solution is of course to use the new VK\_KHR\_dynamic\_rendering implemented in Vulkan 1.3 making it easier. Another would probably be to create render passes that are compatible with the ones we will use later in the frame so we can build pipelines out of them.

The third solution i could think of and the one i liked the most is to just build all passes and attachment details at the beginning of the application. With it we know all the passes and can build our pipelines and materials when ever we desire during the applications lifetime. It also goes well with the material system i saw here: https://technology.riotgames.com/news/better-living-through-materials. Where passes could be in this case techniques.

With it we can also cache frame buffers and image/imageviews if we want. In my case i have two of each for each frame-in-flight. Doing this we have done the setup and half of the compile phase as proposed by Yuriy.

The other half of the compile phase and the execute can still be done each frame. The idea here was to still make it necessary to activate each frame what techniques will be used. And with the activation we pass the execute function that will be called.

For example `frameGraph.Activate("Shadowpass",[=](FrameInputs& inputs){//Do stuff//});` You could like in my case also pass a pointer to an object implementing an execute interface.

And then do the second part of compiling the graph so to speak where it will check if these activations are possible given all the techniques and how they relate to each other. This makes branching possible like shown in the gdc talk.

```
if(Debug){
  frameGraph.Activate("Debug View",[=](FrameInputs& inputs){//Do stuff//});}
else{
  frameGraph.Activate("Lighting",[=](FrameInputs& inputs){//Do stuff//});}
}

```

After that just run the frame graph and it handles everything else like calling all the activated passes and passing the proper inputs to them.

---
Tags: vulkan
---


# Question
Title: How to move on vertical wall with gravity ticked for rigidbody
I am making a ball-rolling game. I want to implement an interaction where the ball can move on a specific area of a vertical wall like the game that the images show, but I don't know how to implement it.

# Answer
> 2 votes
First, we'll create invisible trigger colliders covering the volume of your map where you want the gravity to point in a new direction. Rotate those colliders so that their "forward" direction (the blue arrow on the transform gizmo in local translation mode) points in the direction you want gravity to point.

Create a physics layer called "Gravity Zone" and ensure these objects are on that layer. You can filter collisions with this layer so only objects that need to use this altered gravity detect overlaps with these objects - good for performance since you have fewer collisions to check, and it saves you some filtering code to manually ignore them in unrelated scripts.

Then we'll make a script for the rigidbody (or bodies) that should obey this altered gravity:

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

[RequireComponent(typeof(Rigidbody))]
public class VariableGravity : MonoBehaviour {

    // Reference to our attached body, for modifying our physics.
    [SerializeField, HideInInspector] Rigidbody _body;

    // Cache ID of gravity modification physics layer.
    LayerMask _gravityLayer;

    // Current gravity acceleration vector - default to normal gravity.
    Vector3 _gravity = Physics.gravity;

    // Collection of altered gravity zone trigger volumes we're touching.
    // These can overlap, so we store an ordered list of them,
    // where the last entry is always the most recent one we've entered.
    List<Collider> _zonesTouched = new List<Collider>();

    // Change our gravity to point in the provided direction.
    public void SetGravityDirection(Vector3 direction)
    {
        // We'll make our custom gravity exactly as strong as the default one.
        _gravity = Physics.gravity.magnitude * direction;
    }

    void Start() {
        _gravityLayer = LayerMask.NameToLayer("Gravity Zone");
    }

    // Apply our gravity change every physics step.
    void FixedUpdate() {
        // If _gravity == Physics.gravity, then this is a no-op
        // (ie. we apply zero additional acceleration).
        // Otherwise, it undoes the normal gravity and applies our new gravity.
        _body.AddForce(_gravity - Physics.gravity, ForceMode.Acceleration);
    }

    // When we enter a gravity zone, apply its changes to our gravity direction.
    void OnTriggerEnter(Collider other) {
        // Ignore triggers that are not gravity zones.
        if (other.gameObject.layer != _gravityLayer) {
            return;
        }

        // Add this zone to the end of our list.
        _zonesTouched.Add(other);

        // Use this zone's gravity as our current falling direction.
        SetGravityDirection(other.transform.forward);
    }

    // When we exit a gravity zone, remove its effect.
    void OnTriggerExit(Collider other) {
        // Ignore triggers that are not gravity zones.
        if (other.gameObject.layer != _gravityLayer)  {
            return;
        }

        // When we leave a zone, we want to fall back on the effects
        // of the next-most-recent zone we touched, if any.
        int zoneCount = _zonesTouched.Count;

        if (zoneCount > 1) {
            // We have another zone to fall back on.
            // If "this" zone we're leaving is the one currently in effect,
            // fall back on the next most recent zone in the stack.
            if (other == _zonesTouched[zoneCount - 1]) {
                var fallback  = _zonesTouched[zoneCount - 2];
                SetGravityDirection(fallback.transform.forward);
            }
            // ...and remove the zone from our list,
            // even if it wasn't the currently active one.
            _zonesTouched.Remove(other);
        } else {
            // No other zones in our list, revert to normal gravity.
            _zonesTouched.Clear();
            _gravity = Physics.gravity;
        }
    }

    // Automatically wire up the _body variable so we don't have to set it.
    void OnValidate()
    {
        // TryGet is a good habit for minimizing editor allocations,
        // plus it's less typing than out _body = GetComponent<Rigidbody>();
        TryGetComponent(out _body);
    }
}

```

Most of the complexity here is just in ensuring we handle entering/exiting multiple zones in any order - so if you have a funny-shaped volume to navigate, you can build it out of multiple colliders and this script will handle the transitions between them sensibly.

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


# Question
Title: Interaction between interfaces with C# Unity
I'm making a Mindustry-type prototype. Some block (such as miners) can output resource (with the `IOutput` interface), some block (such as containers) can input those resource (with `IInput`) and some can do both.

All of them will have the `IStorage` interface (for storage) with `AddToStorage` and `RemoveFromStorage` methods.

```
namespace Conveyor
{
    [System.Serializable]
    public class bulkItem
    {
        public int itemCount;
        public int id;

        public bulkItem(int iC, int i)
        {
            itemCount = iC; id = i;
        }
    }

    interface IBlockStorage
    {
        public int maxCapacity {get;}
        public List<bulkItem> items {get; set;}

        public void InitializeStorage();
        public void AddToStorage(bulkItem item);
        public void RemoveFromStorage(bulkItem item);
    }
}

```

The issue is, where should the script for **transportation** (for example, transporting building material) be attached?

Should the output blocks **actively** searches for input blocks, then use `RemoveFromStorage` on **itself**, and `AddToStorage` on the input blocks it found? Or vice-versa?

Or should there be an universal `InputOutputManager` script somewhere and **remotely** use `AddToStorage` and `RemoveFromStorage` to those input/output blocks?

What would be the most code-efficient method of doing this?

# Answer
Unity is a game engine that's designed around the principle of composition over inheritance.

That means the idiomatic way to design this would be something like this:

* GameObjects that represent items in the game world with:
    + A `ResourceItem` component which state what kind of resource it is.
    + A `FollowConveyorMovement` component which controls its movement over a conveyor belt.
* GameObjects that represent producers, crafters and consumers which have a combination of these components:
    + A MonoBehaviour `ResourceStorage` which maintains the item counts.
    + A `ResourceInput` which checks for items in the world, and if so removes them from the world and increments the counter on the `ResourceStorage` component on the same object.
    + A `ResourceConverter` behavior which interacts with the `ResourceStorage` by checking if the resources for its crafting receipt are available, removing the ingredients from the storage and adding its product to the storage.
    + A `ResourceOutput` behavior which decrements the counts of the `ResourceStorage` behavior on the same GameObject (if available) and spawns new items into the world.

This pattern is applicable to both classic MonoBehaviours and to the Data-Oriented Tech Stack with its new Entity-Component-System architecture. The ECS architecture is still in an "experimental" state, but really useful for a game like the one you want to make where you deal with a very large number of relatively simple objects. (And besides, the ECS pattern also solves the question of which component of which entity is responsible for an entity-entity interaction. Neither is. It's the responsibity of a system interacting with both components on both entities).

But Unity is a flexible tool. You don't *have* to follow this pattern. If you feel more comfortable with classic object-oriented patterns like inheritance and interfaces, feel free to use them.
> 2 votes

# Answer
I'm not a proffesional, so you should take this with a grain of salt.

I think you should create a separate MonoBehaviour script which takes the `Item` class and executes the logic you need in it. The best example that would fit your situation is this video, the Area Damage part to be exact.

In your case, it will be an animation or a visual effect.
> 1 votes

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


# Question
Title: Why can't I write to depth buffer if I specify the render target to something different than the default camera frame buffer?
Using Unity's URP I've been trying to setup a scriptable render feature which will add a pass which draws objects on a certain layer to multiple render targets. Unfortunately, I am not able to get it to draw to the camera's depth buffer no matter what I do. According to the docs there is a way to specify a depth attachment along with color attachments. Looking at the source code, it seems that Unity will default to using `BuiltinRenderTextureType.CameraTarget` if no depth attachment is specified. Unfortunately, I think the actual usage is closed source so I don't know how Unity handles it.

One thing I noticed is that it seems it will only draw to the proper depth buffer if I set the render target to cameraColorTarget:

```
var rt = new RenderTargetIdentifier(renderingData.cameraData.renderer.cameraColorTarget, 0, CubemapFace.Unknown, -1);

ConfigureTarget(rt, m_CameraDepthTarget);
// Or also works:
ConfigureTarget(rt);

```

and setting it to anything else doesn't work. I'm drawing in the `Exceute` method using `context.DrawRenderers`.

What I'm wondering is if there is some way I can draw color to a different render target than camera's framebuffer, but still draw/test depth using default depth buffer? Without much resources and documentation on URP side of things I'm a bit lost on if/how it can be done at the point. Is it something that can be done in general? Or are depth buffers somehow tied to a render texture under the hood or something so it is not possible? But if that is the case, then it should still be possible using multiple render targets (MRT) since I can render to cameraColorTarget as well as my custom render target in a single pass (but unfortunately I've tried and doesn't seem to work for whatever reason).

# Answer
For some reason it works if you enable depth texture in the scriptable renderer asset.

I could not find an explanation for why it behaves like that though.

I don't intend to use the depth texture, and so it seems a bit wasteful and not the perfect solution as it adds a CopyDepth pass; but it is the only solution I know of at the moment.
> 0 votes

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


# Question
Title: Unity App working on one phone but crashes on another with the same API level
I built a Unity AR app which worked on my phone. However, on sharing the APK to another phone with the same Android version, it crashes on startup. I've tried increasing the target API level to max, and using Developer Mode for the other phone, but it still crashes. All the versions work on my phone. What is the problem here?

# Answer
> 1 votes
So, I fixed this by going to Build Settings \>\> Player \>\> Other Settings \>\> Scripting Backend and changing it to IL2CPP as well as including ARMx64 in the target architecture. The basic problem was that ARMx64 architecture wasn't included, which is needed for some phones.

---
Tags: unity, android, augmented-reality
---


# Question
Title: 1v1 bartering brain game – see any problems?
While in line at Disneyland, my friends and I came up with a 1v1 bartering game. Here's how it works:

1. Two players are negotiating the price of a good. One player is the buyer, one is the seller.
2. Pseudo-RNG: Each player thinks of two numbers from 0-99. Each says only one of the numbers aloud. Then each adds the other player's spoken number to their secret one and mods by 100 to obtain their final secret number, e.g. 45 and 82 become 27. If the players don't trust each other not to cheat, they can each write their secret number down.
3. Negotiation: For the buyer, the secret number is the maximum they'll pay for the good. For the seller, it's the minimum they'll sell it for. They negotiate until a deal is reached at a certain price, which could include some role-playing for fun.
4. Scoring: When the deal is made, each adds the absolute difference between the price and their secret number to their tallied score, in layperson's terms, how much personal profit each made. If no deal is reached, both score 0 if there was no possible deal (buyer's max was lower than seller's min), or both score -99 if a deal was possible (which only matters in a tourney with other players).
5. Resetting: The buyer becomes the seller and vice versa for the next round.

My question is, are there any holes in this, or other downsides? At first I didn't want the RNG step, but I couldn't figure out a scoring mechanism that couldn't be abused, e.g. the buyer always picking 99. I'm pretty confident in the RNG's security since neither player can reliably guess what number the other will say. The -99 for failing to reach a deal is kind arbitrary, so I don't know about it.

# Answer
> **Note to readers:** just because this answer sorts to the top at the moment does *not* mean it's the best. This is still a young question, so check out the other answers and vote on them too, or consider posting your own analysis.

First: that's a clever way of generating two numbers that neither player can unilaterally control. A lot like Diffie-Hellman key exchange! As long as at least one player is choosing numbers uniformly at random, then the result is also uniformly random, so each player is incentivised to choose randomly to minimize the control their opponent has.

The downside is that this means the chance that the buyer's number is at least as high as the seller's is only 50.5% - so very nearly half the time, no deal is possible, and there's no chance to change your lead vs your opponent. In fact, since neither player should accept a deal that would score them 0 points, **there's only a *mutually-agreeable* deal 48.51% of the time**. (47.53% if I insist on only accepting deals where I might have an *edge*)

I'd expect this would tend to frustrate players. Compare this to a game like Solitaire, which has a solvability rate somewhere in the 80-90% range.

You may want to investigate whether you can find a way to **ensure the buyer more often gets the greater of the two numbers** \- such as drawing chips with discernable orientation from a bag, held so each player only sees one face of the chip.

However, I think *some* possibility of an impossible deal is helpful, because it gives players plausible deniability: maybe I'm not being unreasonably stubborn/greedy, maybe my number's just on the wrong side of yours. That increases each player's uncertainty about their opponent's number and emphasizes the bluffing aspect of the game. So you might not want to *eliminate* impossible deals, just make them a less expected outcome. Especially if you explore kaya3's excellent answer suggesting a reward for being the first to correctly identify the deal as impossible.

The next problem is that, without any constraints on the negotiations, **each player is incentivized to be as annoying a negotiation partner as possible**.

ie. They should each start at the most extreme bid possible - $0 for the buyer, $99 for the seller - regardless of their secret price, to avoid revealing any information to their opponent. So the optimal first move is decided for you, and you're not really making a choice.

For the next move, well, the situation is the same, just with the domain of possible guesses reduced by one. That makes for a very tedious count-down, gradually narrowing the range of guesses toward the acceptable range.

The game can get more interesting once you've narrowed the range above your minimum sale price or below your maximum buying price, as you try to estimate how much farther you can push. But since the penalty for a failed deal is always the same for both players, **your incentive to avoid a deal that's even slightly more favourable to your opponent than to yourself is stronger than your incentive to avoid no deal at all**. That means you should reject any deal that gives you less than about a quarter of your maximum theoretical profit, resulting in successful negotiations that move the game along only about one time in eight.

In practice, human players usually won't play in the way described above (it's mind-numbingly slow and robotic). But the incentives push them to get as close as they or their partner will tolerate. It's not a good thing when the optimal strategy is to exhaust the players' patience.

You should **look for ways to break this symmetry** and punish a player who forces no-deal by being too greedy or drags out the negotiation well past their threshold of profit, so there's an incentive to take a deal over nothing, and an opportunity to bluff/play chicken with that penalty / opponent's reward. Again, other answers have great suggestions for specific mechanisms to do this, so I'll defer to them.

---

Despite all of the above, you probably find that the games you've played with your friends - at least the runs you've enjoyed most - deviate significantly from this behaviour. **It's likely you've invented unspoken "house rules" about what kinds of bids are "sporting" play**. If someone started negotiating in the manner described above, the group would likely protest that this person isn't playing "right". Those tacit norms can give hints into how to shape play in a way that's more fun.

Take some time to record a number of rounds that you and your friends have found enjoyable, and look for patterns in behaviour to try to suss out what these tacit rules of "good play" might be, and see if you can **formalize them into the game's explicit rules** in a way that keeps players from being too robotic, while still giving freedom of choice to find personal strategies within that range.

Some examples might be having a limited number of bids or ranges the bids can be placed within, so players have to gamble with larger steps and incomplete information, or even making those bids a resource that can be earned or banked so sometimes accepting a less favourable deal is worthwhile if it puts you in a better bargaining position for the next negotiation.
> 27 votes

# Answer
I can see an exploit for a 1v1 game (i.e. outside of a tournament). As soon as one player is in the lead, their optimal strategy is to completely refuse to make a deal after that. Both players get the same penalty for not making a deal, so the player with the lead will keep that lead for all subsequent rounds.

One additional thing I noticed is that part of the process of playing the game would be trying to guess what the other player has picked as their secret number. It's normally possible to make better-than-random guesses because people are terrible at picking good random numbers. For example, if someone's previous random number was 10, I'd be surprised if their next random number was in the 0-19 range (i.e. I'd expect that to happen less often than the expected 20% chance from a good random number generator).
> 16 votes

# Answer
Neat idea for a game; it's something you can play with a friend while you're waiting in a queue at Disneyland, without needing any equipment or having to remember much game state.

The main problem I can see is that there is nothing forcing a deal to be reached, and in many cases (even when a mutually "profitable" deal *is* possible) the incentives of the scoring system mean that the players will often not to want to make any deal at all. To keep the game moving and prevent stalemates, I propose the following extra rules:

* Players take turns.
* The buyer's bids must be increasing, and the seller's bids must be decreasing.

This forces the game to progress, but it doesn't address the problem that the players will just bid in $1 increments starting from the extremes, and there is still no incentive to accept a bid when you can just wait for a better one. So let's add another rule:

* Once both players have bid at least once, instead of bidding, a player may make a challenge, ending the round. The challenge is successful if the other player would have made a "profit" by accepting the previous bid, relative to their secret number. So for example, if I'm the seller and I bid $35, and the buyer's secret number is $50 but they rejected my bid, then I would win a challenge because the buyer could have profited $15 by accepting it instead. The winner of the challenge scores the full difference between the two secret numbers.

This gives players an incentive to accept bids that are profitable to them, because if they don't, their opponent might challenge them and win. It also incentivises players to make bids at greater than $1 increments, because they want to make bids that are at least slightly profitable for the opponent, to have the opportunity to win a challenge.

There is still the issue of when the buyer's secret number is less than the seller's secret number, in which case no mutually-profitable trades are possible. So we can add one more rule:

* On any of their turns, instead of bidding a player may guess that there is no mutually-profitable trade possible, ending the round. If they are correct, then they score the difference between the two secret numbers; otherwise the opponent scores the difference.

This gives players an "out" when they would otherwise be forced to bid an unprofitable price, though there might still be an incentive to make a slightly-unprofitable bid rather than risk guessing wrong, or giving your opponent an opportunity to guess right.
> 9 votes

# Answer
I think in practice this game will end in a stale mate 100% of the time, as there is no incentive to buy for more than 0$ or sell for less than 99$.

One change I would make would be to make the game cooperative. A good way to do this would be to allow a set number of rounds in which each player needs to reach a specific amount of points.

In my opinion this would make the game more fun and more true to life: negotiations should not be a zero sum game imo.

This increases the need to reach a deal as both players benefit from making a sale. This also mirrors real life where both parties generally gain from a sale and how much you gain compared to the other party is of less interest.

It also allows scaling the difficulty by increasing/decreasing the goal, so that it might be enjoyed by more people.
> 3 votes

# Answer
Thanks for all the feedback. It's made me think more clearly about the game, and I think I've realized how to fix it. (Not gonna accept my own answer, just collecting stuff here.)

1. Same as before. One buyer, one seller, 1v1.
2. RNG: Same but each player thinks of numbers in \[0, 59\] and mods by 60. The buyer adds 40. So seller's cost S is in \[0, 59\], and buyer's demand B is in \[40, 99\]. This makes impossible deals less likely. Could easily tweak this to eliminate impossible deals altogether by doing mod 50 offset 50.
3. Same negotiation step, but either player can instantly kill the deal if desired. And as an optional rule to spice it up, I like katya3's idea of letting either player profit from guessing that the deal is impossible.
4. Profit scoring is the same. Penalties for killing a possible deal are reworked. For the buyer, it's 100 - B. For the seller, it's just S. So the penalty is within \[0, 59\] for each. Both are penalized regardless of who kills the deal.
5. Same, you take turns being buyer vs seller.

#4 is the crucial part. The uniform -99 was broken, as answers pointed out. In 1v1, you only care about the difference in profits or penalties, cause it's zero-sum. A seller with higher-than-average S or a buyer with lower-than-average B has a positive *expected* (not known) value from killing the deal, but they can do even better by pushing the advantage, or the other player can scare them by bluffing. It's a little like heads-up Hold'Em.

It's also been pointed out that this doesn't mimic real haggling. Normally the buyer and seller are mutually benefiting rather than trying to harm each other. But it still works in a cutthroat way. Consider a 4-player Catan game where only two players have a real chance of winning; should one titan ever trade with the other? Maybe you think that the trade benefits you more than the other player realizes, and the other player thinks the same. I guess the IRL examples are grim, like predatory economic systems or enemy armies agreeing on a battle location.
> 1 votes

---
Tags: game-design, random, strategy, game-theory
---


# Question
Title: How to analyze 2D Animation configuration?
I am modding a 2D game that heavily depending on Animation Event to drive game logic.

How can I analyze an animation event during runtime and by using unpack tools?

* During runtime, I would want to know which animation fires the event, and the time point of the event in the animation.
* By using unpack tools, I would like to view investigate the complete sequence.
In UABE, I could see m\_Events in AnimationClip, but:
    + Is "float time" in seconds?
    + How to locate SpriteRenderer, etc. from a AnimationClip? (I mean, for SpriteRenderer, Animator etc. do they always sit between 0-1 depth away, or they search each other deeper? Unity component dependencies are extremely puzzling and undocumented)
    + Where is Animation Event's receiver object stored?

# Answer
**In future, please ask one question per post. As you can see in the links below, many of these questions are answered by the documentation already,**

> Is "float time" in seconds?

The documentation says it is. Seconds as unit of time is the norm in Unity.

When a time is represented relative to the length of a clip, they'll call it `normalizedTime` instead, to distinguish this.

> Where is Animation Event's receiver object stored?

According to the documentation, animation events call functions on "any script attached to the GameObject" that hosts the `Animator` or `Animation` component playing the animation. "Similar to SendMessage" as the scripting API docs say.

> During runtime, I would want to know which animation fires the event, and the time point of the event in the animation.

If you have a function that's being called by an animation event, you can get a reference to the `Animation` or `Animator` component on that same object, inquire about its currently-played clip(s), and find the matching event in them.

That could look something like this - I haven't tested this code extensively, but it should give the general idea of the strategy:

```
(AnimationClip, float) FindAnimationEventSource(string functionName)
{
    // If fired by an Animation component,
    // we just have to check all cross-fading animation states.
    if (TryGetComponent(out Animation animation))
    {
        foreach (AnimationState state in animation)
        {
            foreach (AnimationEvent e in state.clip.events)
            {
                if (e.functionName != functionName) continue;

                // A clip might call the same event function more than once,
                // so let's make sure this instance matches the playback time.
                if (e.time <= state.time
                    && e.time >= state.time - Time.deltaTime * state.speed)
                {

                    return (state.clip, e.time);
                }
            }
        }
    }
    // For an Animator, things get more complicated, since we
    // have to check the current and next transition states in each layer.
    else if (TryGetComponent(out Animator animator))
    {
        for (int i = 0; i < animator.layerCount; i++) {
            var state = animator.GetCurrentAnimatorStateInfo(i);

            foreach (var clipInfo in animator.GetCurrentAnimatorClipInfo(i)) {
                foreach (var e in clipInfo.clip.events) {
                    if (e.functionName != functionName) continue;

                    float time = state.normalizedTime * clipInfo.clip.length;

                    if (e.time <= time
                        && e.time >= time - Time.deltaTime * state.speed)
                    {

                        return (clipInfo.clip, e.time);
                    }
                }
            }

            state = animator.GetNextAnimatorStateInfo(i);

            foreach (var clipInfo in animator.GetNextAnimatorClipInfo(i))
            {
                foreach (var e in clipInfo.clip.events)
                {
                    if (e.functionName != functionName) continue;

                    float time = state.normalizedTime * clipInfo.clip.length;

                    if (e.time <= time
                        && e.time >= time - Time.deltaTime * state.speed)
                    {

                        return (clipInfo.clip, e.time);
                    }
                }
            }
        }
    }

    return (null, float.NaN); // No match found.
}

```

> How to locate SpriteRenderer, etc. from a AnimationClip? (I mean, for SpriteRenderer, Animator etc. do they always sit between 0-1 depth away, or they search each other deeper? Unity component dependencies are extremely puzzling and undocumented)

It's not that the relationships of the components are undocumented, it's that those relationships are up to the developer. I can have an `Animation` on one object modify properties on another object arbitrarily distant in its child hierarchy, if that's what I choose to do as the creator of the game. Paths to these components are specified explicitly when authoring the clip, they are not found by searching.

Here's an excerpt of the YAML of a sample `AnimationClip` I just made, changing the sprite of a `SpriteRenderer` component located on an object named "Grandchild" which is nested under an object called "FirstChild" which is in turn nested under the root object with the `Animation` component.

```
  m_PPtrCurves:
  - curve:
    - time: 0
      value: {fileID: 21300000, guid: 7bc5fd6fd95fa87488b4b5405bfccdb7, type: 3}
    - time: 0.21666667
      value: {fileID: 21300000, guid: e2b76bfe1164e774291c9a49d5cea5f0, type: 3}
    - time: 0.38333333
      value: {fileID: 21300000, guid: 7bc5fd6fd95fa87488b4b5405bfccdb7, type: 3}
    attribute: m_Sprite
    path: FirstChild/Grandchild
    classID: 212

```
* The `attribute` line indicates the name of the field being modified.
* The `path` line gives the path to the object with this component.
* The `classID` line identifies the `SpriteRenderer` component.
> 1 votes

---
Tags: unity, animation, modding
---


# Question
Title: Diagramming quests with multiple paths when those paths can fail
I'm having a planning issue with writing quests for my game. Let me give an example:

During one of the steps of a quest, the player is sent to a nightclub to ask some questions. There are several ways the player can approach this:

1. The player can enter the club by waiting in line and then talk to the bartender and ask the questions. These questions can be asked by lying to the bartender or by intimidating him.
2. The player can enter the club through violence and automatically intimidate the bartender.
3. The player can sneak through a backdoor and find the items in the employee room.

This is simple enough to model as a tree:

What I'm having issues is when it comes to failure and consequences.

For instance, if the player fails the strenght check when trying to enter the club through violence, they are sent to the back of the line but still have access to all the other paths. If they try to intimidate the bartender and fail, they are forbidden from entering the club through the front-door. And finally the player might fail all of their skill checks, which will lead to a safety net to keep the quest going.

Is there a way to represent this kind of flow graphically? Ideally I'd like to represent every possible path and consequence, hopefully making it easier to visualize if I've really thought about every possible scenario.

# Answer
Sounds like a job for an Activity Diagram (UML) or some similar Flowchart adjacent diagram. For example, I made this with Mermaid:
> 0 votes

---
Tags: game-design, planning, visualization, quests
---


# Question
Title: How can I implement semi-transparent/semi-opaque voxels in a voxel game?
I am creating a voxel game with OpenGL, and I would like to implement water. My voxel world is divided into chunks of 16x256x16 cubes (or voxels). Each chunk has its own VAO with two VBOs, the first one containing a cube, and the second one being used to store the model matrices and the texture coordinates of the visible cubes. I use the Instancing method from OpenGL to render every cube (or voxels) in a chunk with a single draw call.

Recently I've wanted to implement water. For the sake of simplicity, water in my game is simply a cube with a blueish translucent texture. However, the fact that the texture is not completely opaque nor completely transparent causes issues with the depth buffer. With completely transparent cubes, I can use the `discard;` method in the fragment shader. However here, I can't, or my water texture would be completely transparent.

I've looked for solutions to my problem on Internet, and one way I found to achieve proper semi-transparency would be to render the cubes from back to front. But rebuilding the second VBO every frame would absolutely destroy my game's performance. Another solution I found was to first render all the opaque cubes in the world, then render all the translucent cubes. While this solution sounds good on paper, it means I would have to create a second VAO containing only the translucent cubes for every chunk, which again, would be terrible for the performance.

So, what would be the best way to implement water in my voxel game ?

# Answer
> 1 votes
I've been able to implement water (or semi-transparent voxels) by creating a second VAO containing water voxels for every chunk. There was no impact on the FPS, and little impact on the memory usage either, although creating a second VAO for every chunks is a little costly (a few MB). When rendering, I first render all the solid voxels from the first VAO, then I render water voxels from the second VAO. I also made sure to render chunks from nearest to furthest to avoid transparency overlap when rendering water. Thanks to @Basic for the help!

---
Tags: opengl, voxels, transparency
---


# Question
Title: Create and configure new Niagara Emitters from C++
I’m trying to create a magic system that lets the player add spells and modifiers to a spell stack and combine them following a set of rules, creating new spells in the process (that maybe can be combined even further)

To do that with Niagara I need to be able to create new emitters from C++ using the merged settings of both emitters, then load the new emitter into a UNiagaraSystem. I’m guessing that I have to follow this path since I want to be able to merge multiple effects together and not just chain them (maybe one spell has a vortex modifier and the other burst meshes in an area, so the child could burst them in an area and the direction is altered by the parent vortex)

The compilation times for the UNiagaraSystem are fast enough to compile them on runtime (at least in my machine with test systems) so it doesn’t worry me a lot, and I see functions to ask the system to recompile from C++.

My main concern is being able to deduct the current properties and create a new UNiagaraScript to populate the different FNiagaraEmitterScriptProperties so I can create a new emitter into the new derived system (I’m guessing).

Is this even possible with current versions? The editor does it (although with scratchpad…), do I have to fondle with UnrealEditor code? Maybe using an empty system and adding lots of simulation stages? Are the provided modules even accessible from code?

As I am unable to find ANY working example creating emitters from c++, can you please post an example if you now how to?

I’m working with UE5 early access 2

Thanks a lot in advance to everyone!

# Answer
> 0 votes
It's probably possible; but not straightforward. You'd need to trace through what the editor does when you modify a Niagara script. Somewhere in there, it's parsing the script, turning it into HLSL, and shoving it into the render graph pipeline (assuming you're using GPU sims); but replicating that would require engine modifications to that entire path.

But... it seems like you could accomplish the same thing with User Parameters on your Niagara system. You can include emitters for all the various permutations of the effect, and enable/disable them at runtime.

That's the approach I'd take, anyway...

# Answer
> 0 votes
Don't force users to compile new systems at runtime - you don't have access to the shader compiler in a cooked build and adding that much overhead is unnecessary.

Either expose user variables that will get tweaked by gameplay interactions. If that does not give you enough control you can always write your own data interface that can be fed with data from the game thread and set the particle attributes directly.

---
Tags: unreal-4, unreal
---


# Question
Title: Stop an object from rotating past a certain rotation value in Unity
Learning how to program in Unity, so bare with me. I'm making a game called Flappy Bird and I'm having issues with my z-rotation boundaries. Let's say I have some gameObject (call it Bird) that goes up and falls down from the y-axis. However, I want this bird, when it goes down, the z-axis rotates clockwise (so negative rotation). Once it starts falling down, the z-values in the rotation ramps from 0 to -90 in float values. Now, my bird should not keep spinning but stay fixed to the limit until I start flying again. When I make my fly action, the bird should reset the z-rotation back to 0 in a gradual manner, not -45 to 0 immediately.

From what I have achieved, there was no luck for me to stop the spin on the bird. It is just continuously spinning without stopping from the range I want. My range is from 0 to -45 z-axis rotation.

I have tried to play around with the transformation of my z values to get an idea, but nada. From what I have gathered and tried, I was playing around with the `eulerAngles` values, Rigidbody.freezeRotation(), `transform.Rotate()` method, and even the `Quanterion.Euler()` method.

here is the code function example I'm making:

```
public float zTest;
public Vector3 movementDirection;

private void FallSpeed()
{
    movementDirection.y +=  my_gravity * Time.deltaTime; //my_gravity is set to -9.81f
    transform.position += movementDirection * Time.deltaTime;
    zTest += 1 * movemenntDirection.y;
    transform.rotation = Quaternion.Euler(0, 0, zTest);
    if ((transform.rotation.z >= -45.0f && transform.rotation.z <= 0.0f))
    {
        transform.Rotate(0, 0, zTest); //I have a feeling this is completely bad, but I was trying to reset my rotation values.
        // transform.rotation = Quaternion.Euler(0, 0, zTest); //Another way I was trying it
        // currentEuler = new Vector3(transform.rotation.x, transform.rotation.y, -69); //Another way I was trying it
    }
}

```

To be honest, a lot of reading documentation made me more confused in how this interaction is happening and I'm not fully thinking straight at this point. Anyone has suggestions in tackling this problem or pointing me to the right direction? If anything, I will make more edits if needed for clarification and documentation for myself and others.

# Answer
> 0 votes
`transform.rotation` is a unit quaternion, not a triplet of angles in degrees. That means all its components are in the range -1...1. So checking to see if `transform.rotation.z >= -45` is meaningless.

Try something like this:

```
// "movementDirection" is not just a direction, it also has a varying magnitude,
// so use the conventional name for that: velocity.
public Vector3 velocity;
float _angle;

public float minAngle = -45f;
public float maxAngle = 0f;

private void FallSpeed()
{
    velocity.y +=  my_gravity * Time.deltaTime;
    // I assume this is intended to apply both y AND x movement?
    transform.position += velocity * Time.deltaTime;

    // Convert velocity to an angle. (If velocity.x is 0, use 1 instead)
    float newAngle = Mathf.Atan2(velocity.y, velocity.x);

    // Convert to degrees, and clamp between your desired range.
    newAngle = Mathf.Clamp(newAngle * Mathf.Rad2Deg, minAngle, maxAngle);

    // Blend from your old angle toward the new angle, smoothly.
    _angle = Mathf.Lerp(_angle, newAngle, Time.deltaTime);

    // Set your rotation to this angle.
    transform.localEulerAngles = new Vector3(0, 0, _angle);
}

```

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


# Question
Title: Implementation of Vector3.RotateTowards from Unity
I'm using vector3 as direction of object movement and i want to smoothly rotate it to another direction vector. I found SLERP but it rotate by percent. Looks like Vector3.RotateTowards is what i need, but i can't find the source code of this method and my project is **not** on Unity.

So, can you help me realize rotation like SLERP but by **fixed angle**? Thanks

# Answer
> 2 votes
Here's an example implementation:

```
Vector3 fromDirection = fromVector.normalized;
Vector3 toDirection = toVector.normalized;

float angleRadians = Mathf.Acos(Vector3.Dot(fromDirection, toDirection));

float angleDegrees = Mathf.Min(angleRadians * Mathf.Rad2Deg, maxAngleDegrees);

Vector3 axis = Vector3.Cross(fromDirection, toDirection);

Quaternion rotationIncrement = Quaternion.AngleAxis(angleDegrees, axis);

outputVector = rotationIncrement * fromVector;

```

---
Tags: unity, rotation, vector
---


# Question
Title: If I create a prefab out of an object on scene will my game take more memory in Unity?
If I create a prefab out of an object on scene will my game take more memory in Unity?

I have 30 enemies on my scene. I created a prefab for every one of them. I am going to use each of the created prefabs to respawn enemies in the same places where I put each one of them, with the same configurations.

Now, my question is if it is ok to create a lot of prefabs? Will Unity know how to prevent them taking a lot of space? Or will I have troubles with memory when I will create more levels (read here scenes) with even greater amount of enemies, given that each enemy will have its own prefab?

# Answer
> 2 votes
.PREFAB files are just text files taking very little space. Prefabs are just saved information of how the game object should be configured or what components should be attached at the time of instantiation into the scene. So, creating lots of prefabs can consume very little memory or disk space only in the editor mode. But in the final build, there is no effect of creating lots of prefabs.

# Answer
> 2 votes
It depends on how you use them, but generally prefabs will take memory in the game (not just in the editor), even if you do not instantiate them.

More concretely, any prefab that is referenced by a loaded scene will be loaded to memory as well. You can avoid this by not referencing your prefab directly, and instead put it in the `Resources` folder and instantiating it by calling Resources.Load. This way, the memory will be used only when you need the prefab, and not when the scene loads, which might have a huge impact if you use lots of prefabs (or large prefabs).

---
Tags: unity, memory-efficiency, memory, prefabs
---


# Question
Title: Compute Shader generating data for use on CPU
I'm trying to create a compute shader that will generate and manage the movement of a point cloud.

The shader needs several thousand points to work on and I want to pull back the first dozen or so.

Currently I'm trying to crate a minimal working example, where the compute shader populates a buffer of ~8k values and I read the first 10 back.

Compute Shader:

```
RWStructuredBuffer<float3> starLocationBuffer;
[numthreads(64, 1, 1)]
void BuildStars(uint id : SV_GroupIndex) {
    starLocationBuffer[id] = float3(id, 1, 1);
}

```

Calling class:

```
    private ComputeBuffer starLocations;
    private int numStars = 8192;
    private int numLocations = 10;

    private void Build() {
        starLocations = new ComputeBuffer(
            numStars,
            Marshal.SizeOf(typeof(Vector3)),
            ComputeBufferType.Default,
            ComputeBufferMode.Dynamic);

        mapComputeShader.SetBuffer(Kernel("BuildStars"), "starLocationBuffer", starLocations);

        int y = (int)(Mathf.Ceil(numStars / 64f));
        Debug.LogFormat("Building star map [64, {0}, 1] for a total of {1:#,0}", y, y * 64);
        mapComputeShader.Dispatch(Kernel("BuildStars"), 64, y, 1);

    }

    private void Read() {
        var locs = new Vector3[numLocations];
        starLocations.GetData(locs, 0, 0, numLocations);
        Debug.Log(String.Join(", ", locs.Select(x => x.ToString())));
    }

```

I'd expect that to return an array of Vector3 with values `(0,0,0)`, `(1,0,0)`, `(2,0,0)`, etc...

What I actually get back varies. Initially, I was getting mostly-zero values with some unusual values thrown in (NaN and large numbers). Now, I get consistent zeros.

I'd assume this was an issue with the array being uninitialised, however, the compute shader is supposed to write every value before I go and look at the data.

My next thought is that there may be a race condition... Perhaps the compute shader hadn't had time to write those values before I went looking, however, this post by a Unity engineer indicates it enforces sequential execution.

What am I missing?

# Answer
Turns out it was an issue with the way I was setting up the compute buffer.

Specifically, it was `ComputeBufferMode.Dynamic` that was incorrect.

https://forum.unity.com/threads/clarification-on-computebuffermode-immutable.1150250/

> Immutable buffers should be used. It's a doc and naming bug. Immutable buffer is actually the most mutable of them all. Dynamic buffers are meant only for meshes etc, as they're CPU visible. Users shouldn't need to change the buffer mode at all. The default one works on C# side. We're delaying the doc fix for now.

Switching to `ComputeBufferMode.Immutable` \[which isn't actually *immutable*\] solved the problem.
> 3 votes

# Answer
I believe the problem is the arguments you are passing to `Dispatch`. The value that you are calling `y` is actually the number of threadGroups in the X dimension (the total number of objects to operate on, divided by how many threads are in each group). So, the line should be

```
mapComputeShader.Dispatch(Kernel("BuildStars"), y, 1, 1);

```

Also, I think you are using the wrong `id` in the shader. You are getting the id of the thread group, but what you actually want is the id of each individual thread. You can get that like this:

```
void BuildStars(uint3 id : SV_DispatchThread) {
    starLocationBuffer[id.x] = float3(id.x, 1, 1);
}

```
> 3 votes

---
Tags: unity, shaders, compute-shader
---


# Question
Title: RuntimeNavMeshBuilder: Source mesh does not allow read access
My code generates a level by looping through a list of empty game objects and choosing a random object from another list of objects, then instantiating that object at the empty object's position. Then I call `BuildNavMesh` on my navmesh surface and it gives me this error:

> RuntimeNavMeshBuilder: Source mesh Buildings does not allow read access. This will work in playmode in the editor but not in player
>
> * UnityEngine.AI.NavMeshBuilder:BuildNavMeshData (UnityEngine.AI.NavMeshBuildSettings,System.Collections.Generic.List\`1\<UnityEngine.AI.NavMeshBuildSource\>,UnityEngine.Bounds,UnityEngine.Vector3,UnityEngine.Quaternion)
> * Unity.AI.Navigation.NavMeshSurface:BuildNavMesh () (at Library/PackageCache/com.unity.ai.navigation@1.0.0-exp.4/Runtime/NavMeshSurface.cs:251)
> * CityGenerator:Start () (at Assets/CityGenerator.cs:19)

This is the code:

```
public List<GameObject> cityChunks;
int cityChunk;
public List<GameObject> grid;
public NavMeshSurface surface;
void Start()
{
    foreach (GameObject empty in grid)
    {
        cityChunk = Random.Range(0, cityChunks.Count);
        Instantiate(cityChunks[cityChunk], empty.transform.position, Quaternion.identity);
    }
    surface.BuildNavMesh();
}

```

# Answer
This error message is telling you exactly what is wrong: the model you're trying to build a navmesh for has not been marked as readable, so in a built game the CPU will not be able to read its geometry information to build that navmesh.

So: select the models you want to spawn dynamically this way, and tick the "Read/Write Enabled" box in their import settings:

This is covered in the documentation:

> **Read/Write Enabled** When you enable this option, Unity uploads the Mesh data to GPU-addressable memory, but also keeps it in CPU-addressable memory. This means that Unity can access the Mesh data at run time, and you can access it from your scripts. For example, you might want to do this if you’re generating a Mesh procedurally, or if you want to copy some data from a Mesh.
>
> When this option is disabled, Unity uploads the Mesh data to GPU-addressable memory, and then removes it from CPU-addressable memory.
>
> By default, this option is disabled. In most cases, to save runtime memory usage, leave this option disabled. For information on when to enable Read/Write Enabled, see Mesh.isReadable.

That last link there says:

> You should only enable it under the following circumstances:
> ...
>
> * When you use the Mesh to bake a NavMesh using the NavMesh building components at run time.

Just typing "unity mesh read access" into a search engine turns up a link to this documentation as one of the top results, as well as several past troubleshooting threads explaining how to resolve your error. So please get in the habit of looking at the key words in your error message and searching for them, rather than jumping to the conclusion that the error is just "weird" and posting a new question about it. You'll find your answers faster by doing this basic level of research first.
> 1 votes

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


# Question
Title: Will putting Screen.orientation in Update affect the performance?
If I put `Screen.orientation` in Update to detect whether the device is in landscape orientation, will it affect the game's performance?

```
if(Screen.orientation == ScreenOrientation.LandscapeLeft ||
Screen.orientation == ScreenOrientation.LandscapeRight)
{
}

```

# Answer
As Philipp says in a comment above, the best answer to *every* question of the form "how does X affect performance?" is:

**Profile your game and find out**.

Unity has some great profiling tools you can use to inspect the performance of your game in detail. You could set up artificial tests, accessing `Screen.orientation` from dozens or hundreds of script instances, just to exaggerate the impact in the profiler to see if you get a noticeable blip. Or you can just test your planned use inside your actual game scene, to test whether it makes any difference there. Even an expensive function can be fine if you only call it a bit, or if your game's stuck waiting for something else (like rendering or an asynchronous load) anyway.

---

Since I don't have access to your game to profile it - that's *your* job - the best reassurance I can give you is to peek at the code. We can find (most of) the implementation of `Screen.orientation` in Unity's publicly-released C# source code reference.

Specifically, in the Screen class:

```
public static ScreenOrientation orientation
{
    get => ShimManager.screenShim.orientation;
    set => ShimManager.screenShim.orientation = value;
}

```

That calls into the ShimManager class:

```
private static List<ScreenShimBase> s_ActiveScreenShim = new List<ScreenShimBase>(
                                                          new [] { new ScreenShimBase() }
                                                         );
internal static ScreenShimBase screenShim => s_ActiveScreenShim.Last();

```

And this ScreenShimBase has different implementations for different cases (editor views, device simulator, and presumably, actual device screens). We don't have access to the code used in built executables, but we can peek at how it's simulated in ScreenSimulation:

```
public override ScreenOrientation orientation
{
    get => m_RenderedOrientation;
    set
    {
        if (value == ScreenOrientation.AutoRotation)
        {
            m_AutoRotation = true;
            ApplyAutoRotation();
        }
        else if (m_SupportedOrientations.ContainsKey(value))
        {
            m_AutoRotation = false;
            RequestOrientation(value);
        }
    }
}

```

So, there's some overhead in calling a pair of static getters (the runtime inserts a check that the static members have been initialized) and in pointer-chasing (follow a pointer to the `Screen` class then follow a pointer to the `ShimManager` class then follow a pointer list of shims, then jump to the last item in that list, then follow a pointer to the active shim). But after that, it's just returning the value of a cached variable.

While the static access and pointer-chasing aren't free, they're not anything worse than you get when you write:

```
int itemCount = GameManager.ActivePlayers[i].Inventory.carriedItemCount;

```

So if you're not being picky about that kind of code, you probably shouldn't worry about `Screen.orientation` either - at least not until you see it showing up on your profiler.

It's possible that Unity compiles the built version of your game against a platform-specific version of the `Screen` class that bypasses these shims entirely and just returns a cached value for the screen orientation directly, making it even cheaper than the code above would suggest. I'd find it *very surprising* if this getter did any expensive computation like an OS call or hooking into a hardware driver every time you read this value.

But of course, the only way to be sure is not to take the word of some Internet rando like me, but to **profile your game**.
> 2 votes

---
Tags: unity, c#, performance, mobile, aspect-ratio
---


# Question
Title: How do I get Alpha/Transparency working with TGA files in Unreal?
I've got a file that needs to be TGA for technical reasons. In that file, I've got two boxes in the lower half, just right of center, that need transparency. One is for glass (upper, fully transparent) and one is for a "smoke" sun visor (lower, gray/transparent).

The texture already has an alpha layer. If I click "Remove Alpha Channel" then the transparent square goes white and the smoke square goes gray.

I export this to TGA, can open the TGA, it shows as transparent.

When I import the texture to Unreal, the "Has Alpha Channel" is `True`, but the transparent block now shows as blue for some reason, and the smoke block turns solid black.

I can't seem to figure out why this is happening. The best I've been able to find online is to use a PNG instead, but again I can't do that for reasons beyond the scope of this question.

I've also seen advice to tick an "alpha channel" option on export, but I have no such option when I export the file. All I get are the options for compression or no compression, and where the origin of the file is.

If this isn't possible then I can try to work around it, but I'd really like some help understanding what I'm doing wrong. I'm hoping someone here has seen this issue before.

# Answer
> 0 votes
**:EDIT: - Here's the real cause of the issue!**

The "transparent" color was solid blue, \[0,255,0\], with opacity set to 0. I noticed my "clear" material still had a tinge of blue, so I went back to the color and realized what's up. I'm assuming the color is showing as blue in the texture preview because Unreal isn't rendering the alpha channel in the preview.

-Original answer-

As @DMGregory hinted in the comment above, looking at the material that's using the texture made a big difference. I want the texture to be transparent, but it's showing up as blue/black when I view the texture AND when I view the material:

Changing the Blend Mode to Translucent seems to have correctly applied the transparencies, though. I still don't know why the TGA transparent values are showing up as blue, but if they're meant to be transparent then you need to have a translucent material.

Another problem I was having is that I've applied the same texture to two different materials, one that's supposed to be opaque and one that's supposed to be translucent. I would check the texture preview, see the blue, click the opaque material, also see the blue. It wasn't until I checked the translucent material that I saw it was showing transparency correctly.

---
Tags: textures, unreal-4, alpha-blending
---


# Question
Title: Vertex displacement shader graph shows unexpected creases at the beginning and end of a gradient texture
I'm trying to perform a basic vertex displacement by means of a horizontal gradient:

I'm using an on-the-fly created plane mesh. Most of this process is clear to me. I'm not understanding where the weird folds at the beginning and the end are coming from and when it should be a smooth transition from beginning to end.

Settings of the texture:

# Answer
Ok, with the help of some Redditor i solved it. The problem is that one cant disable repeat on the texture itself, but has to do a round trip via an input param on which the repeat can be disabled:

Then the gradient texture can be set as a value for the input param on the object which received the shader as material. Also the type has to be set to color - not data
> 0 votes

---
Tags: godot, vertex, displacement-mapping
---


# Question
Title: Godot: how to get rid of color border in linear gradient texture 2d
Im trying to use a linear gradient to displace a plane mesh via vertex displacement in the visual shader editor. However the linear gradient always seems to drop back to the start color at just before the end, which throws of my vertex displacement:

How do i get rid of that? The documentation mentions some "ramp" but i couldnt find it anymwhere in the UI

# Answer
The actual problem was that the gradient repeat cannot be disabled on the gradient itself, which caused the issues I experienced. See this answer for more information.
> 0 votes

---
Tags: godot, vertex
---


# Question
Title: How can I update my kinematic object's rotation based on how much it has moved per frame?
I'm moving a kinematic circle (and its child sprite) horizontally back and forth after a delay using `transform.Translate()`. I'm wondering how I can find a suitable rotation value for my circle based on the amount it has moved per frame, almost like what one would expect if he or she was rolling a coin across a desk.

I've tried using a pre-selected `rotationSpeed` value, but this conflicts with the variable velocity produced by using acceleration; and updating `transform.eulerAngles.z` with the current velocity causes the circle to rotate way too much every frame (multiplying the velocity by `Time.deltaTime` causes it to move far too little).

I suspect there is a mathematical way to derive what I'm looking for based on the amount moved and the size of the circle, but do not know where to begin with this.

```
using UnityEngine;

public class RotatingCircle2D : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 9f;
    [SerializeField]
    private float acceleration = 25f;
    [SerializeField]
    private float reverseTime = 3f;

    private float velocityX = 0;
    private float directionX = 1;

    private float timer = 0;

    private void Update()
    {
        MoveAndRotate();
    }

    private void MoveAndRotate()
    {
        if (timer >= reverseTime)
        {
            directionX *= -1;
            timer = 0;
        }

        // Move
        velocityX = Mathf.MoveTowards(velocityX, moveSpeed * directionX, acceleration * Time.deltaTime);
        transform.Translate(Vector2.right * velocityX * Time.deltaTime, Space.World);

        // Rotate
        float targetRotationZ = transform.eulerAngles.z + velocityX * Time.deltaTime; // This isn't right...
        Quaternion targetRotation = Quaternion.Euler(0, 0, targetRotationZ);
        transform.rotation = targetRotation;

        timer += Time.deltaTime;
    }
}

```

# Answer
> 1 votes
**TLDR: A circle will rotate 360 degrees every time it travels a distance equal to its circumference.**

I stumbled upon the Coin Rotation Paradox, which helped me to better understand this problem.

A circle with radius `r = 1` has a circumference `2 * Pi * 1 = 6.28`. Rolling this circle around another circle with radius `r = 3` and circumference `2 * Pi * 3 = 18.84` causes the circle to complete **four 360 degree rotations**, which seems counter intuitive because the circumference of the circle around which it is rotating is only three times as large. But the path of motion around the larger circle is also a circle with radius `r = 1 + 3`, the distance of both the original circles' radii added together. The initial circle will thus move a total distance of **four times its circumference**, or `2 * Pi * (3 + 1) = 25.12`. This path is shown below in blue:

This means that a circle will rotate 360 degrees every time it travels a distance equal to its circumference. Indeed, the cited Wikipedia article shows that rolling the original circle over the straight line made from the unraveled circumference of the second circle with radius `r = 3` causes that circle to only rotate three times, as the total distance traveled is just 3 times its circumference.

So, to rotate a circle as it moves around the game:

1. Find the circumference of the circle
2. Get the amount moved this frame
3. Divide this amount by the circumference to get the ratio of movement : circumference
4. Add to or subtract from the circle's z rotation this ratio multiplied by 360

```
using UnityEngine;

[RequireComponent(typeof(CircleCollider2D))]
public class RotatingCircle : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 9f;
    [SerializeField]
    private float acceleration = 25f;
    [SerializeField]
    private float reverseTime = 3f;

    private CircleCollider2D circleCollider;
    private float circumference;

    private float velocityX = 0;
    private float directionX = 1;

    private float timer = 0;

    private void Awake()
    {
        circleCollider = GetComponent<CircleCollider2D>();
        circumference = 2 * Mathf.PI * (circleCollider.radius * transform.localScale.x);
    }

    private void Update()
    {
        MoveAndRotate();
    }

    private void MoveAndRotate()
    {
        if (timer >= reverseTime)
        {
            directionX *= -1;
            timer = 0;
        }

        // Move
        velocityX = Mathf.MoveTowards(velocityX, moveSpeed * directionX, acceleration * Time.deltaTime);
        transform.Translate(Vector2.right * velocityX * Time.deltaTime, Space.World);

        // Rotate
        float movementToCircumferenceRatio = Mathf.Abs(velocityX * Time.deltaTime) / circumference;
        float rotationAmount = 360 * movementToCircumferenceRatio;

        float targetRotationZ = transform.eulerAngles.z - rotationAmount * Mathf.Sign(velocityX);
        Quaternion targetRotation = Quaternion.Euler(0, 0, targetRotationZ);
        transform.rotation = targetRotation;

        timer += Time.deltaTime;
    }
}

```

---
Tags: unity, 2d, rotation
---


# Question
Title: Changing falling behavior of my object after collision to go gradually down and not instantly
# Context

I'm here today to figure out how can I have an object to fall down after colliding to another object. In my case, I'm remaking Flappy Bird and trying to reapply some of the physics in place from the original to mine as a fun and learning project.

Yesterday, I came to here and a friendly user helped me out with my problem (post about rotating an object on specific angle while falling). It did wonders and wanted to reapply the same concept again with the methods used previously. Obviously, not the exact same ones, but grab and test out what works the best.

Now, this is what I have at this moment and what I'm trying to replicate

## (Mine. I'm doing frame by frame to point out)

## (Original concept)

# Problem

As you saw, what I'm trying to replicate is the falling bird from my `current height` to `0` y-axis in constant speed (keyword "speed"). Currently what I have, is that I Clamp my current y-pos right before I collide and go to 0 (min: 0.0f, max: 0.001f). Which, in my opinion, it is a temporary solution I got, but not suitable for the actual task. I have read more into Lerp and SmoothStep, but I think it will not be *constant speed* for what I'm achieving. So, instead, I am putting an eye into `MoveToward()` method from my Bird vector to the floor. `MoveToward()` moves your object a to move towards to another object b. In my case, it is bird to floor. I tried to use it, but it does not do the trick I was hoping to do it or not using it well enough. (source in how I got into this point)

For now, let's stick from what I have currently from the GIF example I have provided and share the code

# Code

```
private bool gameOver = false;
private Vector3 velocity;
private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Grass_floor") || collision.gameObject.CompareTag("Pipe"))
    {
        HitAndDie();
        gameover = true;
    }
}

private void HitAndDie()
{
    // velocity = Vector3.down;
   // velocity.y +=  my_gravity * Time.deltaTime; //I need my Time.deltaTime() in here, but not quite sure if I'm using it correctly.
  float fallPosition = Mathf.Clamp(transform.position.y, 0.0f, 0.001f);
  transform.localPosition = new Vector3(transform.position.x, fallPosition, transform.position.z); //Here I'm just basically want to give a new position to my object from the given clamp.
}

```

# Explanation

With this code, basically my object bird collides to a another object and it results to go to the floor thanks to the Clamping. Now, once the bird hits, the `gameover` switches to true and therefore, the gameloop `Update()` is done. I feel like before triggering my gameover to true, I need to make the bird to fall first to the floor and let gameover turn to true.

To get it down as a falling object before the gameover turn `true` is what I'm trying to achieve here. So that is why I was looking into `MoveTowards()` method, which is what I'm picturing to give me results.

If you have questions or something to point out, let me know so I can clarify and potentially edit the post a bit more.

# Answer
> 1 votes
I solved my issue! I was overthinking in my solution that I forgot to have a condition to check when my object collides to `0` pos y-axis. So all of my approaches were just me overthinking in complicated solutions; but that is fine because I have an understanding of how things are working out.

So, what I have change is to add a limit of a certain vector position and have a velocity that includes gravity speed. This is all being checked in my `Update()` because it is where I'm checking if it is `gameOver` or not, and a flag whenever I hit the collision.

# Code

```
private bool gameOver = false;
private Vector3 velocity;
public Transform target; //I give the floor object to my main bird
public bool hit = false;

void Update()
{
    StartSpawn(); //Not related to the problem, but here I start with a Time.timeScale to 0
    if (!gameOver)
    {
        FallSpeedAngle(); //Not related to the problem
        PlayersAction(); //Not related to the problem
        if (transform.position.y > upperBound)
            transform.position = new Vector3(transform.position.x, upperBound, transform.position.z);
    }
    else //HERE is where the problem gets solved
    {
        if (transform.position.y >= target.position.y)
        {
            velocity.y +=  my_gravity * Time.deltaTime;
            transform.position += velocity * Time.deltaTime;
        }
        GameOver();
    }
}
private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Grass_floor") || collision.gameObject.CompareTag("Pipe"))
    {
        HitAndDie();
        GameOver();
    }
}

private void HitAndDie()
{
    if (hit == false)
    {
        hit = true;
        sound_hit.Play();
        sound_die.Play();
    }
    Time.timeScale = 1;
}
private void GameOver()
{
    gameOver = true;
    Debug.Log("Game Over!");
}

```

# Result

I will share this code to my gist if you want to check it out with more details.

Thanks to Sebastian and DMGregory for pointing me out on the right direction (and my peer!)

# Answer
> 0 votes
In your code i see 1 posibly issue im not 100% sure that is for this that your code isn´t working but could be a posibility.You are makin the .Clamp to a float that make reference to the worldposition (transform.position) but then you are modifying the local position that isn´t the same.

Basicaly i create a new position that it´s in the same position in x and z but in the y axis u put Time.deltatime (this is basicly the time between frames that is runing on your pc, when u are making movement in your code u always want to use this instead of your 0.001f constant (time.deltatime is like a very small float). More here https://docs.unity3d.com/ScriptReference/Time-deltaTime.html

This is other posibility to solve the problem but in this case im using transform.postion insted of transform.localPosition. The diference is basicly that transform.position make reference to the global position and not just the parent object. And again instead of using a constant like 0.01f use time.deltatime that is better when u whant to make movement codes.

---

With the .clamp metod it´s hard to reach the exact 0 y position ,you probaly will reach like 0,000000001 but never 0. So to trigger your game over i like most the first metod because you can triger like this:

Hope it was usefull.

---
Tags: unity, c#, physics, movement, collision-resolution
---


# Question
Title: How to have point of view independent Screen Space Reflection deepness
With regular raymarching algorithm we can fade the reflected pixel based on the number of iterations used when looping. I can’t use an iteration number when doing both hierarchical z (HiZ) and raymarching loop for refinement as the two loops did not work the same. Using a global iteration value produces incoherent fading.

To obtain a fading aspect that works for both I’m using this : SSRcolor = float4(Color,1-abs(SSray.z-D)\*500);

Where color is the color of the scene (multilayer), SSray.z is the depth when the ray hits something in one layer, D is the initial depth from where the ray started. 500 accounts for the depth difference compared to 1. 500 gives good results for my needs but it can be more for more fading or less for less fading.

A problem I have when using an iteration or depth-based fading is that the fading ratio is POV dependent as shown in picture. For iterations I guess you are doing more loop rounds when closer and for Depth-based fading the closer you are the bigger SSray.z-D must be.

Is it possible to make the fading POV independent? Taking the constant 500 as a starting point can we design a formula for it taking into account the distance to POV or something like that.

# Answer
> 0 votes
As stated in the comments using the length of the ray from start to the hit point was better working but not fully satisfying. What works the best for me is to make this length relative to the maximum expected length. Something like:

```
 float3 RayStart = float3(Input.TexCoord.xy, Depth); //I'm doing SSR in screen space
 float3 RayEnd = RayStart + RayDir*MaxDistance
 float MaxLength = length(RayEnd-RayStart);

 float3 RayHit = RayStart;
 do SSR stuff until RayHit find something

 float FadeAlpha = length(RayHit-RayStart)/MaxLength;
 float4 HitColor = float4(texture(sampler, RayHit.xy).rgb, FadeAlpha);

```

In addition I had observed that far objects gets this "sliced" look as a well known SSR artifact if I use a constant RayStep, e.g. 0.02, to modulate the ray direction. This was solved by making the RayStep dependent on the position z of the starting point, like:

```
  get PosV as the starting position of the ray (in view space for me at this stage).
  RayStep = 3/PosV.z; //modulate the constant 3 depending on finer/coarser step you want.

```

---
Tags: movement, reflection-rendering
---


title: Looping walk animation doesn't work

text:
# Question
Title: Looping walk animation doesn't work
I have a walk cycle, and even though I have ticked, `loop walk` and `loop pose`, the looping fails, I think it's because of the red indicator which probably says something about loop mismatch. The animation is from mixamo, and it should be a loopable animation, but it's not an `in-place` animation, so maybe that's what that means? Please let me know what this means and how should I fix it?:

EDIT:  As per the documentation linked in the comments, it seems all 4 dots don't have to turn green, but, the animation doesn't loop.

# Answer
I pretty much didn't think there was an apply button there, just wasted 2 hours:
> 1 votes

# Answer
Well if you have downloaded the animation from mixamo you need to usse Ctrl+D to make a duplicate and than edit it because the orignal wont edit, even thought it give the option of edit
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Text disappearing when partially covered by SpriteRenderer
I have two SpriteRenderers in a Canvas with a Text object in front. They work as expected, with the Text being on top and the two SpriteRenderers showing through from behind it, except for some occasions when the Text is updated from a script, in which case the Text is no longer visible

From playing around it seems that the Text is visible as long as it's covered less than 50% by one of the SpriteRenderers behind, even when the Text's Z-index is set to be far closer to the Camera than the SpriteRenderers

Any help, suggestions, or even just keywords to google should be super helpful, thanks!

# Answer
> 0 votes
Big thanks to DMGregory, my issue was using a SpriteRenderer rather than a UI image and that was causing my Text to be hidden

Switching out to an image solved that problem for me. Thanks again!

---
Tags: unity
---


# Question
Title: Raycasting : computing x position of sprite on the screen
I am trying to create a raycasting engine using C and CSFML, I already have the walls and textures rendering done and right now I would like to be able to render sprites into the scene. The difficulty I'm facing currently is finding the x position of the sprite on the screen. I have already looked up a number of tutorials and it somewhat works but not completely. When I move the player left and right, the sprite position gets calculated right, but when I look on the left and right by changing the player camera angle, the sprites moves on the left or right. I can't figure out what's wrong.

Here's the code I'm using to find the sprite position on the screen, it is from Liam Wynn tutorial :

```
void draw_entity3d(core_t *c, entity_t *entity)
{
    sfVector2f h;
    sfVector2f sprite_screen;
    sfVector2f scale;

    h.x = entity->pos.x - c->player->pos.x;
    h.y = entity->pos.y - c->player->pos.y;
    float p = rad_to_deg(atan2(-h.y, h.x));
    if (p > 360)
        p -= 360;
    if (p < 0)
        p += 360;
    float q = ((rad_to_deg(c->player->angle) + (c->render3d.fov / 2))) - p;
    scale.x = 1000 / (dist_from(entity->pos, c->player->pos));
    scale.y = 1000 / (dist_from(entity->pos, c->player->pos));
    sprite_screen.x = q * (c->render.w_size.x / c->render3d.fov);
    sprite_screen.y = (c->render.w_size.y / 2);
    sfSprite_setPosition(entity->sprite, (sfVector2f){sprite_screen.x,
    sprite_screen.y});
    sfSprite_setOrigin(entity->sprite, get_sprite_center(entity->sprite));
    sfSprite_setScale(entity->sprite, (sfVector2f){scale.x, scale.y});
    sfRenderWindow_drawSprite(c->render.window, entity->sprite, NULL);
}

```

# Answer
> 0 votes
I think in this line

```
float q = ((rad_to_deg(c->player->angle) + (c->render3d.fov / 2))) - p;

```

q should be between 0 and 1. From your code it seems q is between 0..360 (degrees). You should divide it by c-\>render3d.fov:

```
float q = (((rad_to_deg(c->player->angle) + (c->render3d.fov / 2))) - p) / c->render3d.fov;

```

In this way it is the linear scaling factor you need later:

```
sprite_screen.x = q * (c->render.w_size.x / c->render3d.fov);

```

Here you see that q==c-\>render3d.fov leads to sprite\_screen.x = c-\>render.w\_size.x

---
Tags: sprites, raycasting, sfml, c
---


# Question
Title: Multithreading in extra large MMO worlds
How is a gameworld of super large size handled? I was always wondering how games handle large MMO worlds. Until now I thought that separation of areas was the key for games like World of Warcraft. In WoW there are continents, that are handled by different threads. And each continent can be multiphased and each phase would be handled by different thread. But recently I started playing a game called Dual Universe. This game features a single shard space of size more than 100 000km x 100 000km x 100 000km. There is no loading when moving around and you can be anywhere with your 2m tall character and build anything of even smaller size. So, how is this possible? Do they just have one core to process this whole game world? (of course use different threads for networking, user input validation, database, etc) Or did they come up with some way how to split game world into zones and handle each one by different thread and then do some syncing and handovers when something happens near the zone edges? I always thought that this is impossible, because all MMOs do some kind of world splitting like continents/planets/solar systems/realms.

# Answer
> 0 votes
There is little reason for things to interact with something a kilometer away. So there is no reason for the entire world being a single shard.

This means that if you segregate the world into chunks each in their own thread/process, there is only the boundaries where those things need to interact across shards. And where players traveling through need to get migrated from one shard to another.

There are a few ways to design those areas to encourage players to stay away from them:

If those boundaries are non-pvp-combat zones then it's less critical that sudden interactions need to happen instantly.

Remove the farmable critters in those boundary areas and you naturally create a zone where players just travel through quickly.

Other options to design a boundary is long corridors with sight blockers at either end (not uncommon in MMOs to create an entrance to a building). As the player runs through you migrate them from one shard to another.

As an aside: there is no reason that a shard only needs a single thread. There are plenty of strategies of dealing with multiple players and entities interacting with the world and each other and resolving that spread over all the cores in a server.

---
Tags: mmo, multithreading, open-world
---


# Question
Title: How can I get the window associated with a SDL_Renderer?
As the title says, is there a member or function to get this?

For example `renderer->window`? Or `renderer.window`? Or so?

# Answer
As of SDL 2.0.22 there is a function to do this, `SDL_RenderGetWindow`:

```
/**
 * Get the window associated with a renderer.
 *
 * \param renderer the renderer to query
 * \returns the window on success or NULL on failure; call SDL_GetError() for more information.
 *
 * \since This function is available since SDL 2.0.22.
 */
extern DECLSPEC SDL_Window * SDLCALL SDL_RenderGetWindow(SDL_Renderer *renderer);

```
> 3 votes

# Answer
No. Not easily.

You can get the renderer from the window, but it doesn't seem like you can go the other way around. This is interesting since if you examine the (internal) definition of the `SDL_Renderer` structure in `SDL_sysrender.h` you can see that it does contain an `SDL_Window *` member referring to the window (named `window`) several bytes in (after a bunch of function pointers).

However, the definition of `SDL_Renderer` is not provided to you in the public headers, so you can't read this member and there does not appear to be an API for exposing it to you.

If you were *particularly* desperate you could copy-paste the definition from the source code to your own source code, cast the `SDL_Renderer *` you have to it, and read the window that way... but that's probably a bad idea as it's quite brittle.

A more practical solution is likely to use `std::map` or `std::unordered_map` to maintain your own association between SDL renderers and the window you use to create the renderer.
> 1 votes

---
Tags: sdl2
---


# Question
Title: How to convert a 4x4 matrix transformation to another coordinate system?
Is there a general method to convert a matrix transformation from one coordinate system to another, so that the resulting transformation looks the same on screen?

For example: There are some transformations in a coordinate system with X right, Y up, and Z toward the viewer. And they need to be converted to a coordinate system with X right, Y away from the viewer, and Z up.

What would be the operation that needs to be performed for each matrix so that the transformations look the same in the other coordinate system? And is there a general way to construct this operation given the source and destination basis vectors?

# Answer
> 5 votes
This is as easy as writing your old coordinates in terms of the new ones.

* We want +x to map to +x (1, 0, 0)
* We want +y to map to +z (0, 0, 1)
* We want +z to map to -y (0, -1, 0)
* We want the fourth, homogenous coordinate to survive unchanged (0, 0, 0, 1)

So you make those vectors the columns of a coordinate conversion matrix:

$$\Bbb C = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & -1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$

If you left-multiply this matrix by any homogeneous vector in your old coordinate system, it converts it to the corresponding vector in the new coordinate system:

$$\vec v\_{\text{new}} = \Bbb C \times \vec v\_{\text{old}}$$

And the same goes for any vector transformed by a transformation matrix \\$\Bbb M\\$ expressed in your old space:

$$ \vec v\_{\text{new}} = \Bbb C \times \vec v\_{\text{transformed}} = \Bbb C \times (\Bbb M \times \vec v\_{\text{untransformed}})\\ \vec v\_{\text{new}} = (\Bbb C \Bbb M) \times \vec v\_{\text{untransformed}}$$

So you can multiply any transformation matrix by this coordinate transformation matrix to get a single matrix that does both the original transformation and the coordinate conversion.

If you use the opposite multiplication convention - vector on the left, matrix on the right - then take the transpose of \\$\Bbb C\\$ (so your destination vectors are the rows instead of the columns) and multiply it on the right instead of the left.

---

You can use this same logic to work with untransformed vectors already in the new coordinate system: just convert them back to the old coordinate system (using the inverse of matrix \\$\Bbb C\\$ above, \\$\Bbb C^{-1}\\$), use the transformation matrix from the old system (\\$\Bbb M\\$), and then convert back:

$$\begin{align} \vec v\_\text{transformed-new} &= \Bbb C \times \vec v\_\text{transformed-old} \\ &= \Bbb C \times (\Bbb M \times \vec v\_\text{untransformed-old}) \\ &= (\Bbb C \Bbb M) \times (\Bbb C^{-1} \times \vec v\_\text{untransformed-new}) \\ &= (\Bbb C \Bbb M \Bbb C^{-1}) \times \vec v\_\text{untransformed-new} \\ \end{align}$$

So, your matrix that does the same job as \\$\Bbb M\\$ but in the new coordinate system is just \\$\Bbb M\_\text{new} = \Bbb C \Bbb M \Bbb C^{-1}\\$.

Since your coordinate transformation is pure rotation/reflection - no scaling/shearing - the inverse of \\$\Bbb C\\$ is just its transpose (making its rows into columns and vice versa):

$$\Bbb C^{-1} = \Bbb C^T = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & -1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$

# Answer
> 1 votes
**Final solution with code and optimization:**

Here is the code that is doing the conversion in one go. It includes:

* **Conversion** to destination system as described in the answer by DMGregory
* **Uniform scaling** from meters to millimeters
* **Transpose**, because the matrix layout of the destination software is different

All of these steps combined in one efficient method look like this:

```
public static Transform MatrixToXForm(ref Matrix m, float s = 1000)
{
    var rs = 1.0f / s;
    var t = new Transform();

    t.M00 =  m.M11;      t.M01 = -m.M31;      t.M02 =  m.M21;      t.M03 =  m.M41 * s;
    t.M10 = -m.M13;      t.M11 =  m.M33;      t.M12 = -m.M23;      t.M13 = -m.M43 * s;
    t.M20 =  m.M12;      t.M21 = -m.M32;      t.M22 =  m.M22;      t.M23 =  m.M42 * s;
    t.M30 =  m.M14 * rs; t.M31 = -m.M34 * rs; t.M32 =  m.M24 * rs; t.M33 =  m.M44;

    return t;
}

```

The interesting point here is that the "matrix sandwich" \\$\Bbb M\_\text{new} = \Bbb C \Bbb M \Bbb C^{-1}\\$ cannot be expressed as one matrix multiplication, but it can be written as code that shuffles the elements and signs.

If the two coordinate systems only differ in swapped axes and uniform scaling (here from the software vvvv to Rhino3d), you can derive the code for an efficient direct method like this:

* Construct the conversion matrix \\$\Bbb C \\$ using the basis vectors. In this case:

$$\Bbb C = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & -1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$

* Use an example transformation for \\$\Bbb M \\$. I've just used the row/col index of the elements:

$$\Bbb M = \begin{bmatrix} 11 & 12 & 13 & 14 \\ 21 & 22 & 23 & 24 \\ 31 & 32 & 33 & 34 \\ 41 & 42 & 43 & 44 \end{bmatrix}$$

Then do the \\$\Bbb M\_\text{new} = \Bbb C \Bbb M \Bbb C^{-1}\\$ operation and see where the elements land and what sign they have:

By reading the index numbers, this can be directly converted into code. The full chain of operations including uniform scaling and transpose looks like this and results in the code above:

---
Tags: mathematics, matrix, transformation, coordinates
---


title: Decoupling Components

text:
# Question
Title: Decoupling Components
I am working on my first Tower Defense game and I got stuck with architecture. I found some past Q&A "Should the entity handle his own movement?", read about Entity Component approach, and decided to stick with it.

I want to have different scripts that are responsible for different behaviors. For example:

* if a unit contains an `IEnemy` script then it will follow predefined path through the level.
* If it has an `IDamageable` script it can receive damage.
* If it has a `Health` script then the damage will affect health.

In order to create friendly unit all I have to do is throw away the `IEnemy` script and add the `IFriendlyUnit` script.

In order to do that, I decided to have some storage and a manager of that storage. The manager will have methods like `Heal(healthPoints)`, `RemoveArmorPoints(armorPoints)`, `AddArmorPoints(armorPoints)`, `DecreaseHealthBy(damage)`.

But the problem is that If I want to have a `Damageable` script which has only one method `ReceiveDamage()` then it needs to have a reference to the `StateManager` in order to inflict damage and it breaks the design because it forces me to add the `StateManager` script to the `GameObject` in order to remove some health points and I cannot easily add an independent `Damageable` script to the object.

I want to decouple my code as much as possible and stick to SOLID principles, but seems like I am either over engineering or choosing the wrong way.

# Answer
One great tool for decoupling components in Unity are events.

The high-level idea of events is that one component says "Something happened with me" and other components can choose to subscribe to such events and then react on them. The component which posted the event does not need to know who listens to the event it invokes (or if anyone listens at all). And the components reacting to them do not need to know which component invoked the event. That means you have components which communicate with each other without even knowing about their existence.

Unity actually has several event architectures. I will present two here, the classic message broadcast events and the much newer UnityEvents.

## Messages

One is the classic method `SendMessage("OnDamage", damageAmount)`. It's part of the class `Component`, so you can call it from any script. This method looks at all components of the same gameObject for any methods called "OnDamage" and calls those methods passing arbitrary data as an argument. The advantage of this technique is that it is very easy to implement. But it has two major drawbacks:

1. It is limited to components on the same gameObject, so you can't use it for communication between different objects. OK, there are also BroadcastMessage that calls the methods on the object or any children, and SendMessageUpward that calls it on its parents. But both require knowledge of your object hierarchy. That's not really loose coupling. And you can't use it to send events to objects on another branch of the scene graph at all.
2. The method names are "stringly typed". When you misspell the method name (for example "onDamage" instead of "OnDamage"), then nothing is going to tell you. The code just runs and nothing happens. Which is a symptom that can be caused by all kinds of causes. Which can be really frustrating to debug.

## UnityEvents

A far better event technique, though, are Unity Events. For example, when you have a component which should be allowed to post damage events, then you simply add a new field of type UnityEvent to the class. Here is an example of such a script. This object continuously loses HP and invokes events which allows others to listen to that:

```
public class Damageable : MonoBehaviour
{
    public float hp;
    public float maxHp = 10;

    public UnityEvent<float, float> damagedEvent;

    void Start()
    {
        hp = maxHp;
    }

    void Update()
    {
        hp -= Time.deltaTime;
        if (hp <= 0f) Destroy(gameObject);
        damagedEvent.Invoke(hp, maxHp);
    }
}

```

When you now look at the inspector of a gameObject with that component, then you will see that you have a new widget as you might know it from buttons in the input system:

You can now add any methods from any components of any gameObject to it (as long as the signature matches). For example, here is a component that controls a health bar:

```
public class HealthBar : MonoBehaviour
{
    private Image myImage;
    void Start()
    {
        myImage = GetComponent<Image>();
    }

    public void UpdateBar(float current, float max) {
        myImage.fillAmount = current / max;
    }
}

```

Note that it does not reference the Damageable script. But it has a method "UpdateBar" which takes two floats, just like the UnityEvent. That means we can use the inspector to bind this method to the event of the damageable object. Just go to the inspector of the event, click the "+" icon, assign the health bar to the "Object" field and select the function "HealthBar-\>UpdateBar" in the function dropdown. It should now look like this:

Now when the damageable invokes the damagedEvent, the health bar gets updated. Without the health bar knowing that the Damageable exists, or the Damageable knowing about the health bar. That's loose coupling!

You can also set up such event subscriptions at runtime. For example, when you have a different component on the same gameObject which should always react to the damageEvent of the Damageable component, you would do this:

```
void Start() {
    GetComponent<Damageable>().damagedEvent.AddListener(OnDamage)
}

private void OnDamage(float current, float max) {
    Console.Log($"Ouch, I am down to {current} hp!");
}

```
> 3 votes

---
Tags: unity, architecture, component-based
---


# Question
Title: Unresolved external symbol linker errors when including stb_image.h
I get the following errors:

> * LNK2019 unresolved external symbol `_stbi_load` referenced in function `_main`
> * LNK2019 unresolved external symbol `_stbi_image_free` referenced in function `_main` LNK 1120 2 unresolved externals

Initially, I gave the path of the `stb_image.h` & `stb_image.c` file location C/C++ include directories, as adding the header file directly to the project was not working.

# Answer
Add:
`#define STB_IMAGE_IMEPLEMENTATION`

And after that add:
`#include stb_image.h`

I had also faced same issue but this define solved it.
> 1 votes

---
Tags: opengl, c++, glfw
---