# Question
Title: How do game engines enforce global, engine-specific coordinate systems?
In Unreal, the 3D coordinate system is defined as a right-handed, X-forward, Y-left, Z-up frame of reference; but, the default 3D coordinate system for, say, DirectX is a left-handed, X-right, Y-up, Z-forward frame of reference.

How does an engine enforce this behavior? Or, how do engines define a global coordinate system that "just works"? When an object is asked to get its "forward direction" it doesn't do any matrix or quaternion conversions that I can tell, it just returns the I-basis (or X-component) of its transform. Its obvious something is being done to translate local transform matrices' coordinate systems into the engine-specific transform matrices' required coordinate systems. I just don't know where or when these modifications are being applied.

EDIT:

A concrete example:

My confusion is compounded by how 3D cameras work; they ultimately determine how the scene is viewed. In my own engine I don't change the default behavior that DirectX provides, so my coordinate system is a left-handed, X-right, Y-up, Z-forward. I don't like this. I *want* it to be X-forward, Y-right, Z-up globally throughout the engine. Where would I do this? During the view calculation for every camera? Would that affect intuitive translations where if I translate "right" with a vector `[+10,0,0]` the camera erroneously appears to move forward?

# Answer
A minimal renderer is written at some early stage of a graphics engine's development. At that time, some coordinate system is decided upon based on certain factors which seemed valid to the developer(s) at the time. Those could be factors could be as abritrary as "our artists produce models in Blender, and those models use this coordinate system, so we will use the same".

Conventions develop as the engine / renderer develops; orientations are often decided upon in the first few hours. These must be adhered to at every step through the pipeline, to allows things to work at all. The moment conventions are followed *inconsistently* in code, things start going wrong.

**An implementation example: Building up conventions**

Let's say I'm writing something far simpler than the sort of engines & renderers you are talking about: a Wolfenstein-style raycaster. Though it looks a little different, the same sort of process applies to its development. Let's follow through such a process.

(credit to Lucas Vieira)

Though a long time Unity user, I dislike their style of denoting the `+y` as *UP* in this case, because a raycaster works on a 2D basis but tricks the eye into thinking it's a 3D world. So in fact we are using only 2 axes primarily, `x` and `y` which represent the ground plane we are standing on.

Given math graph-drawing conventions that are burned into my brain since school, I prefer `+x` to run to my right and `+y` to be forward, which it would be if you tilted your graph paper so that the y axis, which is usually up, pointed ahead of you. I make this decision because it will make it easier for me when I am drawing out diagrams of how my engine should work and what should be happening *before* I have a renderer to test with.

(`z` is left free for future height / flying calculations, but we don't care about this right now.)

This means I can write vectors in the `(x, y)` format (two contiguous letters of the alphabet) rather than always having to remember to skip a letter `(x, z)` when working on the horizontal plane that forms the basis of my raycaster. To *me* this is important; to another developer, it may not be. But barring a change of heart, the convention has now been established.

(If I change my mind later, there will be quite a few things I'll need to go back and painstakingly change to suit, step by step. This is another reason that once such conventions are decided upon, they usually remain unchanged in a given renderer / engine. Choose wisely at the start.)

My raycaster casts rays through e.g. a heightmap grid (2D array), and tells us when we've hit something tall, or else the raymarch continues to the edge of the grid. How is the above `(x,y)` vs `(x,z)` choice implemented when marching the grid? Well, all `for` loops that iterate over the 2D array `grid` use `x` and `y` (in that order, e.g. accessing `grid[x, y]`) as their iteration variables, because we know that's exactly what we mean when we're walking over that grid - `z` is irrelevant when crossing the grid. If I access `grid` as `grid[x, y]` here, I must do so everywhere else that I read or write `grid`. So here again, the convention has been reinforced.

(If I had chosen to always write and read `grid` as `[y, x]` that would be fine too - but then *all* reads and writes must follow that convention - this is somewhat arbitrary because you can use memory any way you want to. However, because I have my vectors ordered as `x, y` I would prefer that my `grid` array access looks the same, to avoid any typos.)

Based on these decisions, I now introduce player camera movement to use similar conventions: I know, assuming the player is is standing at the origin `(0,0)`, and has a rotation or heading of `0` degrees or radians to the positive `y` axis, that I would like `+y` to be their forward movement direction in world `grid` space, and `+x` to move them to the right. *Consequently*, I know that if their rotation is 180 degrees or Pi radians, that they *must* move in the opposite directions when pressing the `up` (forward) or `right` (right) arrow keys. Once again, the convention has been reinforced simply by writing this code to agree with both this plan, and with what we wrote before.

Lastly, we need to render this abstract world we have created as an array in memory. Decisions now become more arbitrary, because a user of the engine won't usually see the code we've written, but they will see a 3D world whose perspective and motion either seems to work, or doesn't.

Let's say that in my head and on paper, with the player standing at `(x=0,y=0)` with a heading of `0` radians, I know that I am going to cast the leftmost screen column as a ray first, then the second left most, etc., all the way over to the right of the screen and the rightmost of the rays on my piece of paper, pushing each into an array of results sequentially, e.g. `rayResults[0]`, `rayResults[1]` etc. to `rayResults[n-1]`, so ordered from left to right in the array. At least, that's the plan.

**Q & A: What happens when conventions are broken**

* What if I now mapped the above `rayResults` to screen columns in reverse order, by mistake? In other words if I mapped `rayResults[0]` to the rightmost column first, and so on over to the left? When I press the right key I will appear onscreen to move left; and when I press the left key, I will appear to move right, (Backward and forward would be unaffected.) working like a mirror. Is this wrong? No, not necessarily. It is simply one interpretation of the abstract data we have created. A player's mind would understand it, but they wouldn't necessarily enjoy using it. Had we produced the `rayResults` from right to left and rendered from right to left (double negation), camera movement would have worked correctly according to your playtesters. Again, if we had produced `rayResults` from right to left, then we could render them from right to left as screen columns. But because we chose to produce these left to right, we must do things the same way when rendering them. *That, right there, is a convention.*
* What if I imported the Stanford Bunny model from a package that treats `+y` as up, and the `z` axis as right / left? Well then, assuming there is no re-interpretation in the model importer, the bunny's ears will point over to the right, since `+y` is right in our raycaster renderer.

**Hardware and API specifics**

Besides some of the more arbitrary factors I mention above, different APIs and hardware can offer different features that are immutable. These factors can influence the way the engine is built, right out of the gate, for reasons that are either immutable or unwise to change due to potential performance impacts.

* Row/column majority in matrices in DirectX, OpenGL and other graphics APIs.
* Projection matrices in fixed function pipelines
* Vertex array formats in fixed function pipelines

**Conclusion**

This is broadly how the process works in *any* engine's development. There is a step-by-step process of building up and reinforcing conventions, until you end up with the final engine.

Conventions begin to be set up from the first hour of development, and further conventions are set up on these first assumptions, as we move ahead with development. If at any stage the combination of those conventions are ignored, problems arise. The conventions decided upon often seem arbitrary to the outsider, but if you speak to the developers, they could often tell you good reasons why each decision decision was made.

As seen in the last section, conventions we create in writing code can be subtle; sometimes we don't even know we've set a convention until something goes wrong and we realise that's because A doesn't conform to be B in code we wrote last week (last month, or last year).

I hope this gives you some insight into the sort of process (a) developer uses to make these decisions, and how following the presumed conventions at every stage, including in user code, is essential to make things work intelligibly.
> 2 votes

---
Tags: c++, architecture, unreal-4, coordinates
---


title: How to use C# 8.0 with Godot 3.3.2?

text:
# Question
Title: How to use C# 8.0 with Godot 3.3.2?
I am trying to use the `System.Range` and `System.Index` classes with new C# v8.0 construct, see (here). But, I cannot make it work. I have tried under Windows with .NET 5.0 and under Ubuntu with Mono 6 but I got the same result:

First I have changed the `.csproj` file like that:

```
<Project Sdk="Godot.NET.Sdk/3.3.0">
  <PropertyGroup>
    <TargetFramework>net472</TargetFramework>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>
</Project>

```

Note the `<LangVersion>` set at 8.0. With that parameter, I can now build the project with this kind of snippet:

```
int[] nb = {1, 2, 3};
GD.Print(nb[1..2]);

```

But at runtime, I got this error: `Predefined type 'System.Range' is not defined or imported`

---

EDIT: To answer the comments.

I had to add `using System.Runtime` to make the project able to build.

I had tried to change target framework to `.net5.0` (that was only possible on Windows). The project was still able to build but the error at runtime was different:

```
E 0:00:01.563   debug_send_unhandled_exception_error: System.TypeLoadException: Could not resolve type with token 01000010 from typeref (expected class 'System.Range' in assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
  <C++ Error>   Unhandled exception
  <C++ Source>  modules/mono/mono_gd/gd_mono_utils.cpp:423 @ debug_send_unhandled_exception_error()

```

But this answer made me think that the Mono assemblies used at runtime needs `net472`.

Another hint is that an important Godot project that claims to use C# v8.0, the beautiful Thrive, sets `net472` and `8.0` in their config file (see here)

# Answer
> 8 votes
The issue was coming from TargetFramework!

If the option `.net5.0` is not supported by Godot, there is another option to have full System.Runtime feature of C# v8 `netstandard2.1`:

```
<Project Sdk="Godot.NET.Sdk/3.3.0">
  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>
</Project>

```

The answer was given by a user called `31` on Github and Discord (see the closed issue here).

---
Tags: c#, godot
---


title: Dynamic bridge via joints

text:
# Question
Title: Dynamic bridge via joints
When a new object is added to the bridge, the bridge shakes violently, and when objects are added even faster, it breaks.

I've tried changing mass and changing time step, but that doesn't solve the problem.

Code for adding a new object:

```
[SerializeField]
Rigidbody _last;

[SerializeField]
GameObject _prefab;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        var go = Instantiate(_prefab);
        var fj = go.GetComponent<FixedJoint>();
        fj.autoConfigureConnectedAnchor = false;
        fj.connectedAnchor = new Vector3(0f, 0f, -2f);
        fj.connectedBody = _last;
        _last = go.GetComponent<Rigidbody>();
    }
}

```

The first cube is kinematic. prefab:

How can you solve this? Thanks for help

# Answer
> 0 votes
```
[SerializeField]
Rigidbody _last;

[SerializeField]
GameObject _prefab;

void Update()
{
    if (Input.GetMouseButtonDown(1))
    {
        var go = Instantiate(_prefab);
        var fj = go.GetComponent<FixedJoint>();
        go.transform.position = new Vector3(_last.position.x, _last.position.y, _last.position.z + 1f);
        fj.connectedBody = _last;
        fj.autoConfigureConnectedAnchor = false;
        fj.connectedAnchor = new Vector3(0f, 0f, 1f);
        _last = go.GetComponent<Rigidbody>();
    }
}

```

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


# Question
Title: How do I remove the shinyness from the terrain when using an orthographic camera?
I am having an issue with terrain having a sheen around edges when I set the game camera to orthographic. Changing it to perspective, the shinyness goes away:

I have tested with textures from the Unity terrain tools sample pack, as well as purchased textures, and they all have the same problem. The textures have diffuse, normal, and mask maps assigned. Metallic and smoothness sliders for the textures are both set to zero.

I have read up on channel packing for the mask map, but even setting the metallic and smoothness channels to black makes no difference, it seems entirely dependent on camera mode.

It's important that I keep the orthographic view for my game, is there any way to fix this?

# Answer
Thanks to @DMGregory for setting me on the right path. It appears you can't change the terrain shader, but you can change the terrain material.

I solved this by changing the material from "Default-Terrain-Standard" to "Default-Terrain-Diffuse", which also had the side-effect of making the texture color appear closer to the color of the diffuse map, but also somewhat less realistic... but I can tinker with it.
> 1 votes

---
Tags: unity, graphics, terrain
---


# Question
Title: I need help converting Unity .shader to Shader Graph: Bumpy Glass
I've been tasked with converting an older Unity shader which does Bumpy Glass with some alpha modification, to URP. I'm assuming that means using Shader Graph. I'm a bit new to shaders in general, but managed to find various clues here and there and have come to the conclusion that creating a Custom Function is probably the easiest way (I could be wrong). Did I mention, this is targeted for WebGL?

Here is the original shader:

```
Shader "Custom/Glass-Seethrough Alpha" {
Properties{
    _Color("Main Color", Color) = (1,1,1,1)
    _SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
    _Shininess("Shininess", Range(0.03, 1)) = 0.3
    _MainTex("Base (RGB)", 2D) = "white" {}
    _BumpMap("Normalmap", 2D) = "bump" {}
    _AlphaMap("Alphamap", 2D) = "black" {}
    _DistAmt("Distortion", range(0,256)) = 100
}
    SubShader{
        GrabPass { }

        Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Opaque" }
        LOD 200

        CGPROGRAM
        #pragma target 3.0
        #pragma exclude_renderers gles
        #pragma vertex vert
        #pragma surface surf BlinnPhong alpha
        #include "UnityCG.cginc"

        float4 _Color;
        float _Shininess;
        sampler2D _MainTex;
        sampler2D _BumpMap;
        sampler2D _AlphaMap;
        sampler2D _GrabTexture;
        float _DistAmt;
        float4 _GrabTexture_TexelSize;

        struct Input {
            float2 uv_MainTex;
            float2 uv_BumpMap;
            float2 uv_AlphaMap;
            float4 proj : TEXCOORD;
        };

        void vert(inout appdata_full v, out Input o) {
            UNITY_INITIALIZE_OUTPUT(Input, o);
            float4 oPos = UnityObjectToClipPos(v.vertex);
            #if UNITY_UV_STARTS_AT_TOP
                float scale = -1.0;
            #else
                float scale = 1.0;
            #endif
            o.proj.xy = (float2(oPos.x, oPos.y * scale) + oPos.w) * 0.5;
            o.proj.zw = oPos.zw;
        }

        void surf(Input IN, inout SurfaceOutput o) {
            half3 tint = tex2D(_MainTex, IN.uv_MainTex);
            half3 nor = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
            half3 alpha = tex2D(_AlphaMap, IN.uv_AlphaMap);

            float2 offset = nor * _DistAmt * _GrabTexture_TexelSize.xy;
            IN.proj.xy = offset * IN.proj.z + IN.proj.xy;
            half4 col = tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(IN.proj));
            half3 tinted = col * tint * _Color;

            o.Albedo = lerp(col, tinted, alpha);//tex.rgb * _Color.rgb * col.rgb;
            o.Normal = nor.rgb;
            o.Specular = _Shininess;
            o.Gloss = col.a;
            o.Alpha = alpha.r;
        }
        ENDCG
    }
    FallBack "Diffuse"

```

}

The idea is to have the bump map animate on, say, uv.v, to simulate water flow through a pipe, and animate the alpha map to 'reveal' the pipe. Here's what it should look like:

I found this article which helped (I THINK!) with the 'vert' part of the shader. Where I'm getting stuck is in the 'surf' part. I've set up a bunch of inputs, and maybe I've gone down the wrong rabbit hole, but I'm getting an error saying that uv\_MainTex does not exist:

Here's a shot of the work in progress:

And the full text (admittedly incomplete):

```
half3 tint = SAMPLE_TEXTURE2D(MainTex, SS, uv_MainTex);
half3 nor = UnpackNormal(tex2D(BumpMap, uv_BumpMap));
half3 alpha = tex2D(AlphaMap, uv_AlphaMap);

float2 offset = BumpMap * DistAmt; * GrabTexture_TexelSize.xy;
proj.xy = offset * proj.z + proj.xy;
half4 col = tex2Dproj(GrabTexture, proj);
half3 tinted = col * tint * color;

Albedo = lerp(col, tinted, alpha);

```

But I'm getting this error that uv\_MainTex does not exist.

Am I even on the right track? Am I using the wrong macros? Do I need additional SamplerStates? Or hey, has someone already made such a shader I can get and call it a day? Thanks

# Answer
This should give you something fairly close to what you had. The `proj` data coming from the vertex shader wasn't doing anything geometrically meaningful, so I skipped that for simplicity. You can get a similar effect by tuning your `Distortion` parameter instead.
> 1 votes

---
Tags: unity, unity-shader-graph
---


# Question
Title: If and why is randomness a bad thing in competitive games?
AFAIK it is a consensus within esports that randomness should be reduced? *League of Legends* has little RNG, *Dota* has more but both games employ rng smoothing algorithms (details for Dota, LoL).

The rationale is that if there is randomness then random chance can easily determine the outcome of a match (instead of player skill) which is unacceptable for pro play and tournaments. Quoting the articles I linked to above:

> In general Randomness is rejected from competitive gaming since it can decide over loss and defeat without reflecting the actual skill level.

> In League, a single action can determine the outcome of a lane, or even the game. For this reason, randomness in the game is a tricky topic. While landing a huge critical strike (crit) on your opponent can be satisfying, being the victim of a “lucky” crit can be frustrating, or worse: a random event could cause a skilled player to lose to a less-skilled player, even though the skilled player made a better play. In a casual game, the decision to include randomness might be a no-brainer, if it makes the game more fun. However, the decision to include randomness in Esports has the potential to make or break a pro player’s career or determine the outcome of a tournament. As a result, many game developers take measures to reduce the influence of randomness in their games.

Seems reasonable, but... I dont understand, there just seem to be too many counterexamples! Pokemon is insanely random, yet Pokemon is being played competitively as far as Im aware. More traditionally, Poker and Bridge seem to be ones of the most obvious counterexamples. These games would seem to demonstrate that it is not the case that pro play demands little to no randomness?

If and why does it make sense to reduce randomness in games intended to be played competitively?

For the sake of completeness, I feel I need to include two more opinions on the subject I heard/read.

Firstly: On Discord, someone told me that Poker is not really comparable to LoL as it is less popular (I was astonished to learn that LoL tournaments have tens of million watchers while Poker only has hundreds of thousands) and Poker is a gambling game, which is why randomness works for Poker - randomness in games makes them gambling games which presents a problem on its own.

Secondly: Extra Credits made a video on the subject, where they said randomness can work for competitve games (and IIUC implied that the claim that competitive games must have little to no randomness is incorrect) but tournament format needs to be adjusted - instead of single elimination they should make the tournaments in round robin. But doesn't this introduce new problems, since - correct me if I'm wrong - don't most people, both players and spectators, find round robin excessively boring?

# Answer
I feel thinking about randomness as a single, monolithic thing isn't super useful in a game design context. A distinction should be made between *input* and *output randomness*.

**Output randomness**

1. Player(s) make decision(s)
2. Random event determines the outcome.

Explanation

This is the type of randomness we're most familiar with. In the board game Risk, players place their pieces, decide who to attack/defend, and THEN a dice roll determines the outcome of their decisions.

**Input randomness**

1. Random event occurs
2. Player(s) respond.

Example

In League of Legends, there are 4 types of dragons that can spawn, each which give different buffs and have different attack characteristics. The dragon-type may determine how many resources a team wants to invest in the objective, or whether they want to contest at all. In LoL, you're given ~4m heads up telling you the next type of dragon that will spawn. This is crucial, as it means teams are given the chance *respond* and shift strategies depending on the random event.

**Conclusion**

In general, Input randomness is fine. It can lead to interesting decisions as it gets players to react dynamically to new scenarios which forces players to understand the systems of a game instead of memorizing a set of actions which have been solved by a meta. On the other hand, in a competitive context, Output randomness is bad. It adds chaos, meaning that more games will have to be played to determine the skill of each player/team. If the purpose of a competitive game is to determine skill (knowledge of a games' systems, knowledge checks, and mechanical proficiency), then output randomness is always undesirable as it increases the sample size you need to do so.

**In Practice**

Now of course in reality things are not as clear. A blurry spectrum exists between platonic *input* and *output randomness*. Critical strikes in LoL in the context of a single auto attack are purely output randomness. The summoner decides to auto, and **then** a virtual dice roll determines the output damage. However in the context of an entire prolonged fight, crit-chance skews towards input randomness. Players get to **respond** to these unexpected variations in crits and shift their play accordingly by retreating, chasing, or holding abilities in response to shifting luck.

Here's the article which founded these terms if you're interested in a much more eloquent and comprehensive explanation
> 3 votes

# Answer
First things first, to be BIG in competitive games, you need spectators. If nobody is watching, then nobody is to there to be made money of. So obviously whatever randomness is in a game is more or less important to the viewer count.

The viewers like to watch a game, if it is interesting to watch. Its fascinating, intriguing and not foreseeable who will win. And in most cases, the viewer know more than the actual players. E.g. in Poker, the viewers often can see, what the players hands look like, even the percentage of winning with their hands compared to the other hands etc.

Now imagine a completely deterministic game with the difference from game to game is the decision a player makes. There also is something like the optimal way. Like chess, but the starting player has a way of always winning. Like a series of certain moves the opposing player cant stop. Noone would watch it. And pro players in any game will certainly reach this optimum.

Now lets just add a bit of randomness and it is open who will win. Does the Pokemon attack hit and one-shot the enemy Pokemon or will it miss? Even the selection of Pokemon is 'random' as the enemy does not know beforehand, what Pokemon his opponent will have. That is where Meta will kick in. And it just became a lot better to watch.

In Pokemon, one unlucky move can cost you alot. One paralyze, missed moved etc. It can determine a game in one round of around 10. In opposition to that, in League just one lucky crit does nothing (most of the time). In this kind of game, the players skill is more important than one crit. If a game like this would be influenced more by a lucky roll than skill, then spectators would get disappointed that the better team would still loose.

And then there is Poker. Poker is not purely luck-based. Its more what a player does with his dealt cards. Does he fold, raise, bluff or roll high on his insight on his opponents bluff? This again is skill-based with a lot of randomness. Good players know how to reduce the amount of luck they need and just go the way of higher success in relation to their assumption of the oppnents cards.

All in all, it seems that there is a sweet spot that determines if a game is enjoyable to watch or not. No randomness will make the game to deterministic and obvious who will win. To much randomness and the team you are rooting for looses every game, although they are clearly the best team (seriously).
> 1 votes

# Answer
You have to take into consideration the *frequency* and *significance* of randomness.

Let's take a MOBA as an example. Say that we are auto-attacking 20 times per minute, and each attack has a flat 5% chance of being a double-damage critical hit. This means we can usually expect one critical hit per minute, and our damage output is going to be about the same. Sometimes we might get very lucky and get in four crits in 20 attacks, giving us a 15% damage boost for that period (we do 120% damage instead of our typical 105%), which is noteworthy but not usually game-breaking.

With smoothing we can make the randomness even less random; for example, we can code the game to always award exactly 1 critical hit per 20 attacks, simply making it random which one of those 20 attacks is a critical hit. This will ensure our damage rate doesn't suddenly spike due to particularly good luck.

Now, consider a different scenario where there are no critical hits, but the damage of each attack varies by +-5%. On paper this doesn't seem like a big deal. If we had perfect luck, we'd be doing 5% extra damage all of the time (or -5% if we had perfectly bad luck). In practice, we might have streaks of good or bad luck, but it should average out to 0% over extended periods of time.

However, imagine that our base damage is 100, which makes our randomized damage 95 - 105, and *there is an enemy unit with exactly 100 HP*. This means we can expect about 50% of our attacks to kill the enemy in one hit, and 50% to leave it with a sliver of health left. That's a huge problem, and bursts of particularly good or bad luck can significantly change the outcome of the game.

Now imagine we have +- 5% randomness on an AoE ultimate attack that does 800 base damage. If the ultimate hits multiple targets, that +- 5% could add up to hundreds of points of extra or reduced damage, which again can significantly alter the outcome of the game.

Too much randomness can also lead to a surge in player complaints which can generate negative publicity and put extra stress on customer service reps.

**When is randomness a good thing?**

Randomness can still have an important place in "gambling"-style moves or characters. For example, you might give one hero an ultimate that does +- *50%* damage, or has a 50% chance to hurt allies instead of enemies. Because this is a single, highly notable ability only possessed by one character, its randomness may be more widely accepted and players will likely develop strategies around utilizing or avoiding the move. It can also lead to hallmark moments in competitive play where a player decides to make a big gamble with a highly random ability and it pays off or fails in spectacular fashion, making the match a fan favorite that is destined to be rewatched and debated endlessly for years to come.

For gambling-style abilities to fit into the game well, their nature should be obvious to the player (everyone knows this move is heavy on random), and the player should have total control over when the ability is activated (so they can choose when to take a gamble, as opposed to having it thrust on them continuously or at random times).
> 1 votes

---
Tags: game-design, random, competition
---


# Question
Title: How to find if a Ray intersects a Triangle Clockwise or Counter Clockwise
I have a Triangle with an intersecting Ray.

How can I find out if the triangle's vertices are in a clockwise or counter clockwise rotation order with respect to the Ray?

# Answer
Assume the triangle's vertices are wound in the order A, B, C

Form a normal to the triangle N = (B - A) x (C - A)

Now you can detect whether your triangle is clockwise or counter-clockwise by the sign of the dot product between this normal and the ray direction

In a left-handed coordinate system:

* Negative = Clockwise from ray's point of view
* Positive = Counter-clockwise from ray's point of view

In a right-handed coordinate system, it's the opposite:

* Negative = Counter-clockwise from ray's point of view
* Positive = Clockwise from ray's point of view
> 2 votes

---
Tags: raycasting, trigonometry, ray
---


# Question
Title: Instantiated entities don't collide with each other
I've started to learn DOTS some day ago, and decided to create a simple project. When I added some simple physics to the game I faced the problem. I added one object on the scene and another instantiated from a resource as a prefab (prefab contains physics shape and physics body), but they didn't collide and just go through. When I tried to place both objects in the scene they work perfectly. Then I tried to instantiate them both and got nothing, I mean they didn't collide... Maybe I miss something? I couldn't find any explanation for this in the Unity Physics doc.

Tried in Unity 2021.1 and 2020.3

Box on the scene configuration:

Sphere prefab configuration:

Spawn object code:

```
        var world = World.DefaultGameObjectInjectionWorld;
        var entityManager = world.EntityManager;

        var settings = GameObjectConversionSettings.FromWorld(world, null);
        _entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(_playerPrefab, settings);

        Entity player = entityManager.Instantiate(_entityPrefab);
        entityManager.AddComponent<PlayerMovementComponent>(player);
        entityManager.SetComponentData(player, new PlayerMovementComponent()
        {
            Speed = 10f
        });
        entityManager.SetComponentData(player, new Translation()
        {
            Value = new float3(.5f,0f,.5f)
        });

```

# Answer
Found the solution at the Unity's forums old thread, here's the link. Long story short I passed null as the second parameter when called GameObjectConversionSettings.FromWorld function. But you MUST pass any blob store, you can create a new one or you can get it from the world, by calling this script:

```
var conversionSystem = world.GetExistingSystem<GameObjectConversionSystem>();

```

So final spawn method should look like that:

```
    var world = World.DefaultGameObjectInjectionWorld;
    var entityManager = world.EntityManager;
    var blobStore = new BlobAssetStore();
    var settings = GameObjectConversionSettings.FromWorld(world, blobStore );
    _entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(_playerPrefab, settings);
    Entity player = entityManager.Instantiate(_entityPrefab);

```

or like that if you want to use blobStore from the world:

```
    var world = World.DefaultGameObjectInjectionWorld;
    var entityManager = world.EntityManager;
    var conversionSystem = world.GetExistingSystem<GameObjectConversionSystem>();
    var settings = GameObjectConversionSettings.FromWorld(world, conversionSystem.BlobAssetStore);
    _entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(_playerPrefab, settings);
    Entity player = entityManager.Instantiate(_entityPrefab);

```
> 2 votes

---
Tags: unity, collision-detection, physics, entity-component-system, unity-dots
---


# Question
Title: Box selection with Physics2D.BoxCastAll is mirrored when selecting in the bottom half of the screen
Using Physics2D.BoxCastAll based on the rectangle is working fine when a drawing is started on the top part of the screen, but when a drawing is started on the bottom you can see this strange mirroring effect.

Code:

```
void OnGUI()
{
    // LMB clicked
    if (Input.GetMouseButtonDown(0))
    {
        boxStartPosition = new Vector2(
            Input.mousePosition.x,
            Screen.height - Input.mousePosition.y
         );
    }

    // LMB drag
    if (Input.GetMouseButton(0))
    {
        boxEndPosition = new Vector2(
            Input.mousePosition.x,
            Screen.height - Input.mousePosition.y
        );

        rectangle = new Rect(
            boxStartPosition.x,
            boxStartPosition.y,
            boxEndPosition.x - boxStartPosition.x,
            boxEndPosition.y - boxStartPosition.y
        );

        GUI.DrawTexture(rectangle, RectangleTexture);

        float pixelsToWorld = Camera.main.orthographicSize / (Screen.height / 2f);

        Vector2 boxCenter = Camera.main.ScreenToWorldPoint(rectangle.center);

        boxCenter.y = Mathf.Abs(boxCenter.y);

        float boxWidth = Mathf.Abs(rectangle.size.x) * pixelsToWorld;
        float boxHeight = Mathf.Abs(rectangle.size.y) * pixelsToWorld;
        Vector2 boxSize = new Vector2(boxWidth, boxHeight);

        BoxCastDebug.DrawBoxCast2D(boxCenter, boxSize, 0f, Vector2.zero, 0f, Color.black);
        hits = Physics2D.BoxCastAll(boxCenter, boxSize, 0f, Vector2.zero, 0f);
    }
}

```

Can anyone help me to solve these issues? Is it directly connected with the setup of my scene, camera, or scripts?

# Answer
I'll start off by mentioning that I'm not an expert with Unity, but looking at the image provided and your code, here what I think the issue is.

The behaviour we see is this: when you click/drag from top left of the rectangle, you get a rectangle "outline" and a "filled" paler rectangle following the mouse positions, when you click/drag from the bottom right of the rectangle, you get the "filled" paler rectangle following the mouse position, while the "outline" is mirrored vertically.

The code you supply suggests that you draw two rectangles:

* `GUI.DrawTexture(rectangle, RectangleTexture);`
* `BoxCastDebug.DrawBoxCast2D(boxCenter, boxSize, 0f, Vector2.zero, 0f, Color.black);`

The main difference here is that essentially, you don't supply the same parameters for drawing both rectangles because you change the absolute value of the "box center" (`boxCenter.y = Mathf.Abs(boxCenter.y);`).

Assuming the `Camera.main.ScreenToWorldPoint()` has its center in the center of the screen, then `boxCenter.y` will always end up being in the top part of of the screen, thus making your call to `BoxCastDebug.DrawBoxCast2D()` always draw its rectangle in the upper half part of the screen.

How to fix this? Well it depends on what was your intention with making the `y` position positive only, but perhaps not doing so would fix the issue.
> 1 votes

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


# Question
Title: What could effectively affect the falling speed of a b2Body?
I tried to set up a test demo to see if Box2D physics are working. It works, but I have one small problem: I cannot seem to get the dynamic `b2Body` to fall faster.

I tried modifying and setting the `gravity` and its `gravityScale`, its `fixture`, the `density`. I also tried `applyForce` and `setLinearVelocity` in a constant loop. I tried passing different values for the `b2World.Step()` function, by giving it different `dt`, `velocityIterations` and `positionIterations`. I know it has nothing to do with it, but I also tried modifying the `mass` of the body. By changing the `gravity`, I only managed to decrease its falling speed.

I managed to find a way to increase the falling speed of the dynamic body, but only because I performed a `b2World.Step()` function multiple times per loop. I do not want to use that method to increase the falling speed.

Do you have any suggestions what I could use to increase the falling speed of the dynamic body?

Edit: I now include the source code for anyone who is interested.

# Answer
> 5 votes
This Stack Overflow question titled "Too slow movement despite enormous gravity in box2d" contains a link to this Box2D tutorial which says:

> There is a maximum movement limit of 2.0 units per time step give in the file b2Settings.h in the source code.

(It however seems that the movement limit is now defined in the file `b2_common.h`, if you want to verify this yourself)

This means that if you are using pixels are units for your object sizes, you will have a maximum movement speed limit of 2 pixels per time step. This is why you only get a speed up by executing multiple timesteps, and the other parameters have no visible effect, since the speed limit is reached extremely quickly.

You will want to use smaller coordinates and sizes in your physics simulation, and multiply with an appropriate scalar to convert world coordinates into view space.

There is a mention about the units in Box2D in it's documentation's FAQ portion:

> What units does Box2D use?
>
> Box2D is tuned for meters-kilograms-seconds (MKS). Your moving objects should be between 0.1 - 10 meters. Do not use pixels as units! You will get a jittery simulation.

> How do I convert pixels to meters?
>
> Suppose you have a sprite for a character that is 100x100 pixels. You decide to use a scaling factor that is 0.01. This will make the character physics box 1m x 1m. So go make a physics box that is 1x1. Now suppose the character starts out at pixel coordinate (345,679). So position the physics box at (3.45,6.79). Now simulate the physics world. Suppose the character physics box moves to (2.31,4.98), so move your character sprite to pixel coordinates (231,498). Now the only tricky part is choosing a scaling factor. This really depends on your game. You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot.

---
Tags: box2d
---


title: Optimized linear to sRGB GLSL

text:
# Question
Title: Optimized linear to sRGB GLSL
I'm currently using a simple implementation of linear to sRGB transform:

```
float sRGB(float x) {
    if (x <= 0.00031308)
        return 12.92 * x;
    else
        return 1.055*pow(x,(1.0 / 2.4) ) - 0.055;
}
vec3 sRGB_v3(vec3 c) {
    return vec3(sRGB(c.x),sRGB(c.y),sRGB(c.z));
}

```

Possibly, that the correction for small values `(x <= 0.00031308)` will not matter in practice.

I considered to just let ´pow(x, 1.0 / 2.4) but I'm not sure how much impact it will have.

Is there any way to optimize it? Can be vectorization help? Can some polynomal fitting be better?

# Answer
> 6 votes
Adjusted version of Tynach's answer that leaves the alpha channel alone, since it's already linear.

```
// Converts a color from linear light gamma to sRGB gamma
vec4 fromLinear(vec4 linearRGB)
{
    bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308));
    vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055);
    vec3 lower = linearRGB.rgb * vec3(12.92);

    return vec4(mix(higher, lower, cutoff), linearRGB.a);
}

// Converts a color from sRGB gamma to linear light gamma
vec4 toLinear(vec4 sRGB)
{
    bvec3 cutoff = lessThan(sRGB.rgb, vec3(0.04045));
    vec3 higher = pow((sRGB.rgb + vec3(0.055))/vec3(1.055), vec3(2.4));
    vec3 lower = sRGB.rgb/vec3(12.92);

    return vec4(mix(higher, lower, cutoff), sRGB.a);
}

```

# Answer
> 5 votes
A few days ago, I ran into this when messing around on Shadertoy. I was curious and some solutions to the various problems I faced, so I may as well post what I've made here for you.

Note, however, that I have never benchmarked this and I don't know *how* fast it works. But I've heard that different drivers/hardware/etc. implement sRGB conversion differently, so I wanted to make my own, correct implementation... And as far as I can tell, I succeeded. It does not use `if`s and operates on entire color vectors at a time.

The trick with `bvec`s was learned from here. He says it won't work on most GLSL ES versions, but it seems to work well in the browsers I've tested (including Chrome on my Pixel). Still something to consider, especially since my uses are pretty limited (just making test images for my desktop, though I did test on my phone too).

I'm sure somebody could make a more optimal version that's just as accurate, especially as I'm *very* new to GLSL in general. However, since nobody was really giving you actual code (except to suggest x1/2.2 and the like), and my own code seemed to follow the general advice of avoiding branches, I figured I may as well post it.

```
// Converts a color from linear light gamma to sRGB gamma
vec4 fromLinear(vec4 linearRGB)
{
    bvec4 cutoff = lessThan(linearRGB, vec4(0.0031308));
    vec4 higher = vec4(1.055)*pow(linearRGB, vec4(1.0/2.4)) - vec4(0.055);
    vec4 lower = linearRGB * vec4(12.92);

    return mix(higher, lower, cutoff);
}

// Converts a color from sRGB gamma to linear light gamma
vec4 toLinear(vec4 sRGB)
{
    bvec4 cutoff = lessThan(sRGB, vec4(0.04045));
    vec4 higher = pow((sRGB + vec4(0.055))/vec4(1.055), vec4(2.4));
    vec4 lower = sRGB/vec4(12.92);

    return mix(higher, lower, cutoff);
}

```

# Answer
> 2 votes
* Balance between speed and accuracy: `pow(x, 2.2)` for textures and `pow(x, 1.0/2.2)` for output
* More speed, less accuracy: `x*x` for textures and `sqrt(x)` for output

# Answer
> 1 votes
If you're worried about optimization then use vectors more, the optimizer may or may not do that for you.
Avoid conditionals, all branches of them will be executed.
But the major bottleneck on modern GPUs is from samplers, pow and log are pretty negligible.

If possible then just use sRGB internalformat in your framebuffer, most gpus will do the conversion in hardware.

---
Tags: glsl, srgb
---


# Question
Title: Difference between ComputeBuffer and GraphicsBuffer in Unity?
At first I thought that `ComputeBuffer`'s could only be used in compute shaders and that `GraphicsBuffer`'s could only be used in materials. But Unity provides overloads for setting `ComputeBuffer` and `GraphicsBuffer` to both compute shaders and materials. So how do they differ?

# Answer
It seems that they differ in the type of data that they can hold. A GraphicsBuffer can be used for vertex and index buffers, while a ComputeBuffer can be used for any arbitrary data, which is mostly needed for compute shaders.
> 0 votes

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


# Question
Title: Unity intersection of mesh renderers on Android
I’m currently developing a game with Unity and ran into a problem while building for Android.

The player and obstacles are mesh renderers (for example cubes & boxes). On iOS and the Unity editor, when a cube collides with a box, they intersect, they go "inside each other", which is what I want to happen.

On Android, however, one is drawn on top of the other, there is no intersection. When the cube moves through more than half of the box, the box is drawn on top of the cube.

What is the cause of this? Why does it only happen on Android?

These are my camera settings:

I would really appreciate any responses, especially suggestions on how I could fix this. Unity version is 2017.3.1f1. Thank you!

# Answer
> 0 votes
Setting the rendering path to "Deferred" solved the issue.

---
Tags: unity, android, 3d-meshes
---


# Question
Title: Overriding template variables for Gradle generation
I'm using Unity 2020 to build for Android. Unity provides a `mainTemplate.gradle` file, looks a bit like this.

As per Unity docs, there are certain template variables that Unity will fill in when it generates the actual `build.gradle` file.

What the docs don't mention at all is what the logic is behind how these are filled in. The specific issue I have is that it defaults to a version of the build tools that's too old for a particular entry in my manifest. As such, I'm trying to override `BUILDTOOLS`, but I've not been able to find anything online about either manually overriding an arbitrary template variable, or explicitly setting the Build Tools version.

All the docs say is `SDK Build tools used (for example, 25.0.1).`, completely unhelpfully.

Any advice welcome.

# Answer
After mucking around with Unity a bit more, I think what happens is that it picks the highest version of the Build Tools component that is installed.

What I didn't realize is that I needed to restart Unity for that to happen. I also deleted `Temp/gradleOut` for good measure. So, between these two actions, it eventually started working.

I still haven't got a clue whether it's possible to give those template variables custom values.
> 1 votes

---
Tags: unity, android, gradle
---


# Question
Title: How can you create a side-scrolling beat-em-up perspective in Unreal Engine?
How can I achieve Streets of Rage type of perspective in UE4? By that, I mean having a 2D character that walks "into" the screen, but the character doesn't get smaller or angled in any way.

Is there a camera setting that allows that? Or some kind of character setting?

Also, how would I set up the background? I'm pretty sure that it's just a static image that is put behind on a plane, but maybe there's a better way to do that?

I already created a game that attempted this with a friend during a game jam, but the camera view doesn't look the way we want.

# Answer
> I mean having a 2D character that walks "inside" the screen, but the character doesn't get smaller or angled in any way. Is there a camera setting that allows that?

You want an orthographic projection mode.

> Also, how would I set up the background? I'm pretty sure that it's just a static image that is put behind on a plane, but maybe there's a better way to do that?

There are two ways I can think of:

* Easy: You can have the background be a plane behind, simple. It is basically using the 3D engine as a 2D engine, letting the depth only apply for occlusion (depth-test/z-order). See SHOVEL KNIGHT IS A 3D GAME?! Its Own Developer Explains - Boundary Break
* Hard: you can use billboard sprites for the characters (that way the angle of the camera does not affect how they look※), make the scenario 3D, and angle the camera. Similar to making isometric games in 3D, except not in that angle, but something that suits better the game. See Can I use a 3d plane for a 2d game?

※: Alternatively you can use 3D models and apply a transformation on them corrects for the angle of the camera. See Zelda: A Link Between Worlds From a Brand New Angle - Boundary Break.
> 3 votes

# Answer
I'm currently making a 2D brawler myself. I found UE4 does NOT have a mechanic for this specifically, but instead, and it's an easy fix,

1. limit the camera: the camera must be fixed on certain areas. So when you complete the area, code the camera to pan to the next one. Keyword Pan
2. it has to be 3D: the only thing in the game that needs to be 3D is the floor. You can position the sprites diagonally to accommodate the look you're going for. But with a 3D platform, the sprite will be able to walk up and down it. Make sure to put guard rails on your platform so your character doesn't fall off or jump off.
3. jump and fall animation: when jumping you can't go straight up and down, but you need to use the axis while jumping. So it appears they're jumping, but in reality they're just moving sideways on the 3D platform.
> 0 votes

---
Tags: unreal-4, perspective, 2.5d
---


# Question
Title: Is there an equivalent of Unity's OnCollisionEnter() in UE4?
I've been looking for how to figure out when two objects are colliding all day.

If anyone knows how to do it I would be grateful. What I really want is a similar function to Unity's OnCollisionEnter() and a way to get a pointer to the object that I'm colliding with.

# Answer
> 6 votes
I'm not familiar with unreal-4, but perhaps you are looking for OnActorBeginOverlap?

Relevant documenation: https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/GameFramework/AActor/OnActorBeginOverlap/index.html

The remarks say:

```
Called when another actor begins to overlap this actor, for example a player walking into a trigger. For events when objects have a blocking collision, for example a player hitting a wall, see 'Hit' events.

Components on both this and the other Actor must have bGenerateOverlapEvents set to true to generate overlap events.

```

Or perhaps you DO need Hit events:

https://docs.unrealengine.com/latest/INT/Engine/Blueprints/UserGuide/Events/index.html#eventhit

```
This event will execute as long as the collision settings on one of the Actors involved have Simulation Generates Hit Events set to true.

```

Maybe posting your question on an unreal-4 forum would yield more specific answers. Sorry I can't be more helpful.

# Answer
> 1 votes
I don't want to replicate Steven's answer, but I want to include images.

The correct answer is to use OnActorBeginOverlap, as you were marked to. If you are not receiving the correct triggering dispatch, it's almost sure that you don't have the correct layering configuration.

You can do that using the Collision subpanel in the Details panel of your object as is shown in the image from below. This also applies if you are trying to configurate the collision of an element inside a blueprint.

If you want to handle the event in Blueprints, you can do this, as described in the documentation

If what you need is to handle the collision from C++ and configure the layering, then you can refer to this page in the documentation, where you can find a good example.

EXAMPLE OF COLLISION MANAGMENT IN C++ FOR UE4

# Answer
> 0 votes
OnComponentHit is equivalent unity OnCollisionEnter

---
Tags: c++, collision-detection, unreal-4
---


# Question
Title: How to use Texture2DArray with Normal map and Normal Unpack node in Shader Graph
I am extracting `Normal Map` from `Texture2DArray` in shader graph and then converting it to normal using `Normal Unpack` node. But results I get are different, compared to usual `Texure2D` `Normal Map`.

`Texture2DArray` Normal doesn't work correctly at all, except it just makes terrain look darker.

`Texture2DArray` is generated using `TextureFormat.RGBA32` as well.

I've tried setting import settings of normal as "Normal Map" and as "Default". Normals are a bit different in both cases(When generating with import setting of "Normal Map", it becomes Red, when generating with setting of "Default", its colors are more correct), but overall results are the same - dark terrain without correct lighting in both cases.

Thanks for any help!

# Answer
> 1 votes
Problem was, Normal Unpacking only works with non-SRGB textures.

In order to generate non-SRGB `Texture2DArray` you'd need to provide last parameter(Set texture to be linear):

`Texture2DArray(int width, int height, int depth, TextureFormat textureFormat, bool mipChain, bool linear = true)`

But since my Texture array includes both normal maps and albedo maps, all other textures look flatter and uglier(Since they're linear now).

There are 2 ways of solving this issue:

1. Use 2 texture arrays, one for normal maps(non-srgb) and another for albedo maps(srgb)
2. Use non-srgb texture array, but convert albedo maps to srgb inside the shader. Either using cheap approximation: `pow(col.rgb, 2.0)` or built-in `GammaToLinearSpace(col.rgb)`

---
Tags: unity, shaders, textures, normal-mapping, unity-shader-graph
---


# Question
Title: OpenGL translation based on “scaled” pixels? (Not physical pixels)
My (2D!) game runs in a “scaling mode” so to speak, and I’ve yet to find anyone asking this question anywhere. Basically, I want to achieve a sort of “scaling algorithm” whether graphics are translated based on some “virtual pixel” multiplier.

Essentially, if the game is running natively at 624x240, then everything is translated exactly 1 physical pixel. But, if the game has been scaled 2 or 3 times, then I need the graphics to be translated by 2 or 3 pixels, respectively, because the graphics are scaled. Basically, each pixel should move 1 pixel multiplied by the scaling factor. In other words, a 64x64 pixel Sprite would move 3 pixels to the right when scaled 3 times. If this sprite starts at 100x50, then it’s new position would be 103x50, not 101x50. This is the issue I cannot overcome. I have tried something like this: `model = glam::mat4(<identity>, glm::vec3(pos.x + scale, pos.y + scale, 0.f));` -\> everything still moves 1 physical pixel.

I asked on the gamedev subreddit, but no one was able to help me out, primarily because either I probably misunderstood what they were saying, or they were quite vague in what they were saying. One person was talking about scaling the vertex positions in the vertex shader, then mentioned using GL\_SHORT when calling `glVertexAttribPointer` but I was trying for over an hour and couldn’t make GL\_SHORT work to save my life.

I tried using glViewport, but everything is still translated by physical pixels. Anyone have any ideas? Any insights? I also tried framebuffers but they ended up being a huge pain for what I want to do, that they didn’t seem worth it to me.

# Answer
Ways to do this, in roughly descending order of complexity.

**Modify all vertex positions by hand in code**

This is going to be nasty, messy, bug-prone and you:re all but guaranteed to find edge cases where it doesn't do exactly what you want. I would avoid this if at all possible.

**Use a framebuffer object**

Draw to the sized-down framebuffer, then draw that to the screen. You mention you tried it and rejected it for reasons of complexity. I wouldn't consider it hugely complex but much simpler solutions do exist.

**Use glCopyTexImage**

With this method you draw to a sized-down viewport, copy it to a texture, then draw that to screen. It's like a poor man's version of framebuffer objects, but can work well enough.

**Modify your ortho matrix**

Probably the simplest way, just change your ortho matrix to the virtual size you want to draw at, and you can then draw everything as if the screen were that size.
> 0 votes

---
Tags: opengl, shaders, transformation, viewport, vertex-shader
---


# Question
Title: 2D vs 3D mobile power consumption in Unity
For an optimised and playable game written for mobile with Unity, how much of a difference is there in power consumption between 2D and 3D?

Assuming:

* Unity game engine
* The game requires constant screen updates such as FPS or arcade, not turn-based
* As much as possible is about equal - optimisation, complexity, user experience

My initial feelings are that 2D should use less power than 3D, but I have not seen anything other than opinion to support this view. The only reasoned argument that I have seen so far actually favours 2D (over low poly 3D) in this answer: https://gamedev.stackexchange.com/a/101344/153665

I don't want to explore whether I should optimise or when to optimise. That has been covered many times elsewhere.

# Answer
> -1 votes
The answer to this question will not be a fair one: it really depends on the game design and gameplay. In a pure comparison 2D will win the argument but this should not be the case when you are going to chose how your game will be. Most mobile phone these days can run games with stable frame rates, take a look at the ranking that list most common GPUs out there in the market.

Always use Unity Profiler during development as it will help you a lot in optimizing your game.

---
Tags: unity, 2d, 3d, performance, mobile
---


title: Why do games run slow on CPU

text:
# Question
Title: Why do games run slow on CPU
Maybe my question sounds naive because I'm not a game developer but I dont see objective reasons for this. An average cpu is in times more powerful than an average gpu like a few graphics cards in one.

The most repeated reasons in internet:

> the GPU isn't as busy as the CPU

If the gpu renders the screen how it can not be busy The modern cpus are powerful enough. They are not busy most of time. For example my cpu's usage is 3%.

> many GPU's are designed to process graphics commands in parallel, CPU single threads them

What bothers the games to run a few parallel processes even on one cpu core? In my opinion its not correct to tell that the gpu is better if games never use 100% of the cpu's capacity. To be specific they dont use even 50%.

---

To clarify my question based on responses in the comments:

> Did you mean to ask "Why do games render more slowly on the CPU?"

Yes I mean why the cpu cant do the whole work for games when it is underloaded and especially if it does the largest part of work in any case.

> You can not compare GPUs and CPUs directly, because they do different things.

What bothers them to do the same things?

> The CPU isn't as well suited to performing rendering calculations

I dont understand what "suited" means. And why the cpu is not suitable for primitive tasks aka paint roller.

> adding additional parallel processes doesn't improve performance

Then why do you produce multicore graphics cards and multicore central processing units? Just give various parts of one task to a few processes if one process is slow and 100% of the capacity is not used. What bothers to emulate the gpu?

Its also unclear for me why when you play without a separate graphics module the games see only one cpu core when you play with the gpu they see and use all the cpu cores. May be some magic.

# Answer
> 3 votes
You can not compare GPUs and CPUs directly, because they do different things. You can't say that one is a "more powerful" computing device than the other because they are specialized in different things.

GPUs are specialized in performing short and linear programs on large datasets. These programs are called "shaders" which is a term you might have heard of before. Most of them are just a handful lines of code. For example, a pixel shader might take a million of pixels and for each one sample the RGB color value of a texture, calculate the proximity to the nearest light source and multiply it with that.

CPUs are specialized in performing large and complex programs with very large amount of code full of complex instructions and lots of diverging paths. And they usually run that code on data which is a lot more heterogeneous.

While the GPU's shader operates on a million pixels, the CPU performs on the same frame all this:

* Query the state of physical devices like mouse and keyboards
* Parse a 3d model file streamed from the filesystem and transform it into a format the GPU can work with
* Route finding for 20 enemies
* Calculate Sizes and positions of 23 UI elements
* Execute the AI behaviors for 54 enemies
* Calculate the trajectories of 162 projectiles
* Check for collisions, which means to perform calculations with hundreds of mobile and thousands of immobile geometric shapes to find out if any of them intersect.
* Check the health of 232 entities in the game
* Notice that one of them has below 0 health, remove it from the game, update various data structures indexing entities, check if there are any events which need to be executed on the destruction of that entity and execute those events
* And lots and lots and lots and LOTS of other things.

All of that stuff can require tens of thousands of lines of code which need to be executed every single frame, and another hundreds of thousands which *might* get executed.

As you can see, they are very different computing device optimized for very different tasks. Some games require more work from the GPU, which means the CPU will have some idle time while you play. Other games might have less computationally intense graphics and more computationally intense gameplay, so they will be CPU bound, which means that the GPU won't run at full capacity while the CPU gets to its limit (or at least one of its cores - the limits of CPU multithreading are a different and also very complex topic).

Or to use an analogy: Think of the GPU as a paint roller and the CPU as a paint brush. The roller lets you get a lot of paint on the wall quickly, but it lacks finesse. You can only use it for large, even surfaces. A paint brush gets you fewer paint on the surface at the same time, but it is a much more flexible tool. It is far better at taking care of small details, uneven surfaces and hard to reach places. They are both tools for painting, just like GPU and CPU are tools for computing. But while they both seem to do the same thing, one tool is not superior to the other. They are tools with different strengths and weaknesses which compliment each other. And if you want to be an efficient painter / game developer, you need both of them. Depending on the project ahead of you and the unique challenges it poses, one tool might see a lot more use than the other. But you better have both of them in your toolbox and know how to use them and when to use them.

# Answer
> 1 votes
Generally speaking, a game doesn't execute on a GPU, it executes on the CPU & the rendering executes on the GPU. The GPU is specialized to execute graphics related calculations whereas the CPU is designed for more general purpose calculation. For games that use a GPU instead of the CPU for rendering, the CPU is still necessary for executing everything else. When you run have a game that renders using the CPU instead of the GPU, you have two main disadvantages:

1. The CPU is doing more work than it would if the rendering calculations were being handed off to the GPU.
2. The CPU isn't as well suited to performing rendering calculations as a GPU (of equivalent vintage anyway; a modern CPU might be able emulate a significantly older GPU in some cases without any trouble).

Regarding parallel processes, some games do use parallelization to improve performance. But the gains aren't linear, meaning past some point, adding additional parallel processes doesn't improve performance. But it increases complexity, making the code harder to design, maintain & fix. Parallelization is a tool that is used when it makes sense, but it's not a silver bullet solution for improving performance.

# Answer
> 1 votes
**Design differences**

> The CPU isn't as well suited to performing rendering calculations
>
> I dont understand what "suited" means.

Think about a CPU like a 4x4 - it can go anywhere, but it isn't necessarily the fastest or most fuel efficient thing in the world. A CPU can do anything, go anywhere. But it's not a racing car.

Think about a GPU like a drag racing car - it can go very fast, but it can't change direction quickly. And it can't go offroad, nor can it climb a steep hill.

These two cars are designed for completely different purposes. Why shouldn't this be the same for any other machine? DISCLAIMER: Sure, this is not a perfect analogy, but it makes the point.

Here's one of the most important differences. When there is a conditional branch (`if` or `switch`) in code, a CPU is designed to handle that in the most efficient way possible. A GPU works differently. It expects to be able to pipeline information similarly across all of its cores.

So let's say you have an `if` statement in a shader. This means that if one core / thread fails to return `true`, the others are all held up, because GPU threads work in lockstep, unlike on the CPU. (Actually, one `if` statement is often okay, but the deeper you go, the more this fragments the workload so that the GPU is unable to create an efficient dataflow.) For something like your `paint roller` which doesn't require a lot of `if` statements, but just to paint the whole screen quickly, this works very well.

Now let's consider giving a CPU the same task. Every CPU core is *hugely* more complex in it's design (both in itself and within the context of its parent CPU's design) than a typical GPU thread. Guess what the downside is? OVERHEAD. There is overhead for branch prediction, there is an overhead dependent on cache regime complexity, there is an overhead for SSE/AVX/MMX, etc. etc. etc. There are probably hundreds of features. Every time you assign a thread to a CPU core, there is a startup and shutdown cost that can be many CPU cycles (which are lost for processing *your* code). On the GPU, any overhead to startup or shutdown is mitigated (amortised) by the fact that when you start one thread, you are starting several hundred others, as well, so cost becomes negligible.

In STEM, hybrid solutions often come out better than "pure" solutions - for effectiveness, cost and/or efficiency.

**Cost of manufacture**

It *is* true that a CPU could do anything, if it had enough cores. (You could say a GPU is not so capable, mainly because of a lack of branch prediction.) Cost per CPU core has traditionally been on the order of 10s-100x more costly than GPU cores. The reason is that these cores are fare more full-featured. They typically have multiple levels of cache, branch prediction, vectorisation, and many other features. Per se, a CPU has traditionally been massively more complex than a GPU. A GPU consists of a lot more *repitition* than of the *systemic complexity* than a CPU.

So if you could buy 1 car engine vs. 10 motorcycle engines that apply twice the power for half the cost and weight, which would you buy? It would depend on many factors, such as power vs torque rating, engine wear and maintainability, acceleration curve, weight etc. Similar principles apply here.

In the real world, money talks. If Option A manufacturing setup costs me 10x, 5x, or even 2x to get the same quality product as Option B, why would I choose option A? At the end of the day, that cost has to go the consumer, which means to do the same tasks we do today on CPU + GPU, in the world you have proposed, we would have been paying maybe 5x-20x more for a CPU that can literally do everything, for the last 20 years. Would that have been worth it?

**Efficiency of code**

> Its also unclear for me why when you play without a separate graphics module the games see only one cpu core when you play with the gpu they see and use all the cpu cores. May be some magic.

Sure, some people and companies write inefficient code. Alternatively, you're comparing a game from 20 years ago, with one made today. Some technical developers can produce very high quality optimised code, usually due to (1) a deep understanding of complex CPU architecture, and (2) a *lot* of time spent in low-level optimisation.

The industry has sped up since the early 2000s, CPUs and GPUs have become a lot more powerful and thus able to carry a bigger load, and consequently many developers no longer give as much attention to deep optimisation as they may once have done. It often just isn't economically viable in today's fast-paced and highly competitive world, to optimise so much. Whereas before year 2000, you had no choice if you wanted to write a game that could run reasonably well.

# Answer
> -1 votes
Most CPUs have a lower-end GPU Unit with a fewer number of computing units and less memory and bandwidth. Modern video games come with complex shaders, higher numbers of primitives and volumetrics, and so on. Rendering such perplexed programs and other things would be a headache for CPU, even today.

On the other hand, CPU cores aren't designed for rendering geometries. They are able to, but numerous times slower than a GPU can. In addition, information from the G-buffer (as most of the modern AAA titles are using 4K and 8K textures), which including base color, normals, roughness and AO, combine to make a massive load of data to load into the VRAM.

More often there are obvious visual artifacts that occur which more like low draw distance and object disappearance if the video game running on a CPU rather than a dedicated GPU. Rendering merely with a CPU is impracticable. If you are familiar with SwiftShader how performing well on low-end PC's, swift shader which meant to render games based on Software wisely to cope with CPU

---
Tags: rendering
---


# Question
Title: How do I create a perfectly set up FBX file by script?
I have a huge FBX file which contains make animations. I want to split these into different takes by using a C# script file.

It worked, but it happened often that I messed up the FBX file because my script was just not perfect yet.

What I did in such a case was to restore a backup manually.

However, after having to do that over 30 times already, I thought that I could simply copy the original FBX and its meta data and work with the copy.

This way I would not have to backup / restore the original fbx each time.

I would create the copy at the start of my script.

And then I would call my usual code like this:

```
ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sCopyOfFBXFile);

if (nModelImporter == null)
{
    Debug.LogError("Doh!!!!");
}

```

To my surprise, the ModelImporter of the newly created copy is "Null".

The next thing that came to my mind was that perhaps Unity misses the ".fbx.meta" file, so I copied the .meta file, too.

The problem would still persist: The ModelImporter was still Null.

The next thing I tried to call

```
AssetDatabase.SaveAssets();

```

Still didn't help.

The solution was to stop the script after the creation of the Unity.

In other words: Unity needed some time on its own without the script still running.

Then Unity would work hard and show a progress bar which indicates that it's now processing the newly created .fbx file.

Then I could run another script which would then do the ModelImporter work on the new copy.

However, I don't want to wait that long until Unity has processed the copy, and I don't want to use 2 steps for a process of which I feel could be done in a single script.

I wanted to provide Unity a perfect copy of which it would automatically know that it doesn't have to do any more work on. I thought that providing the .meta file would do this job.

Does anybody know why that is not the case and what I would have to do in order to work without interrupting my script intentionally?

Thank you!

ps: Here is my current file for completeness:

```
using UnityEngine;
using UnityEditor;
using UnityEditor.VersionControl;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;

public class NewBehaviourScript : AssetPostprocessor
{
    private static void pCreateNewCopy(string uOrig, string uDest)
    {
        if (File.Exists(uDest))
        {
            File.Delete(uDest);
        }
        File.Copy(uOrig, uDest);
    }

    public static bool pathsFromObject(UnityEngine.Object uAny, out string uAssetFile, out string uAbsolute)
    {
        uAssetFile = "";
        uAbsolute = "";

        try
        {
            string sPathOfFBXInAssetDir = AssetDatabase.GetAssetPath(uAny);
            string sRealPathFromAsset = Application.dataPath + sPathOfFBXInAssetDir.Substring(6);//Remove first 6 chars because they are "Assets" (same as the end of the Application.dataPath)

            uAssetFile = sPathOfFBXInAssetDir;
            uAbsolute = sRealPathFromAsset;

            return true;
        }
        catch (Exception x)
        {
            return false;
        }
    }

    [MenuItem("Tools/FBX/Split")]
    private static void SplitFBX()
    {
        var nSelectedFBXFile = Selection.activeObject;

        string sRelativePath = "";
        string sAbsolutePath = "";

        bool b = pathsFromObject(nSelectedFBXFile, out sRelativePath, out sAbsolutePath);

        string sAbsolutePathCopy = sAbsolutePath.Replace(".fbx", "_split.fbx");
        pCreateNewCopy(sAbsolutePath, sAbsolutePathCopy);

        string sRelativePathCopy = sRelativePath.Replace(".fbx", "_split.fbx");
        AssetDatabase.ImportAsset(sRelativePathCopy, ImportAssetOptions.ForceSynchronousImport);
        //AssetDatabase.SaveAssets(); //not necessary
        ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sRelativePathCopy);
        if (nModelImporter == null)
        {
            Debug.LogError("Doh!!!");
        }
        else
        {
            Debug.Log("All is good!");
        }
    }
}

```

# Answer
I found the solution.

The following is wrong:

```
ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sAbsolutePath);

```

The following is correct:

```
ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sRelativePath);

```

As one can see, AssetImporter.GetPath expects a relative path.

Also, as DMGregory pointed out, the following call is necessary to make Unity aware of a newly created file:

```
AssetDatabase.ImportAsset(sRelativePathCopy, ImportAssetOptions.ForceSynchronousImport);

```
> 1 votes

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


title: How big can/should wall colliders be?

text:
# Question
Title: How big can/should wall colliders be?
Following my previous question, I now have my wall collider building tool and built many of them:

Bird-view, about 17 walls selected, on the right, one is selected:

Here, wall and barriers form a collider so the car will hit the barrier:

Here you can climb on that little slope:

**Question:**

Having either a single, large collider or tons of small ones doesn't sound good to me.

What's a good metric in deciding how many (and how big) colliders should there be?

Also, should they be as simple as possible, e.g. less points for straight lines?

# Answer
> 0 votes
Not only how tall and big walls should be, how thick is also very important as I started seeing this:

> \[Physics.PhysX\] cleaning the mesh failed

**Wall model is the following:**

* a wall is made of points, at least two, in the end only `p0` is needed for a wall segment
* `p1` is next segment, `p2` and `p3` are simply `p0 + Vector3.up`

**How were thick walls in gray built in a easy way?**

~~Generate a mesh then a collider out of it.~~ That was long, painful and not even right!

Again, by leveraging Unity's stuff:

* compute wall segment center out of `p0/p1/p2/p3`
* compute normal from plane of `p0/p1/p2`, re-orient to world up
* compute forward from `p1 - p0`

At this point we have all we need to create/scale/orient child colliders!

**The code is as simple as that:**

```
private void RebuildColliders()
{
    // start clean, destroy child box colliders

    while (transform.childCount > 0)
        DestroyImmediate(transform.GetChild(0).gameObject);

    // if we don't want colliders then return now

    if (!RebuildCollidersEnabled)
        return;

    // create child box colliders

    var vertices = GetComponent<MeshFilter>().sharedMesh.vertices;

    var quads = vertices.Length / 4;

    for (var i = 0; i < quads; i++)
    {
        var p0 = vertices[i * 4 + 0];
        var p1 = vertices[i * 4 + 1];
        var p2 = vertices[i * 4 + 2];
        var p3 = vertices[i * 4 + 3];

        var pf = Flipped ? (p1 - p0) : (p0 - p1); // Z-axis

        var pg = GameObject.CreatePrimitive(PrimitiveType.Cube);
        pg.name = $"CUBE {i}";
        GameObjectUtility.SetParentAndAlign(pg, gameObject);

        // NOTE all the following changes do adjust the collider automatically

        var pt = pg.transform; // re-position and re-orient the collider

        pt.position = (p0 + p1 + p2 + p3) / 4.0f; // they're all on same plane so this is fine

        pt.rotation = Quaternion.LookRotation(pf.normalized, new Plane(p0, p1, p2).normal) *
                      Quaternion.AngleAxis(90.0f, Vector3.forward); // normal was X-axis, make it Y-axis

        var ww = WallWidth * WallScale;
        var wh = WallHeight * WallScale;
        var wl = pf.magnitude * WallScale;

        pt.localScale = new Vector3(ww, wh, wl); // size the collider to fit wall

        pt.Translate(-ww * 0.5f, 0.0f, 0.0f, Space.Self); // collider is centered, should be on edge instead
    }
}

```

**Conclusion:**

Of a line segment, I've been able to generate thick walls quite easily, this is really cool.

Walls should definitely be thick somehow else PhysX might choke in generating colliders for them and as @DMGregory suggested, it's a good insurance for the collisions.

For their length, I suppose they're fine for now, I've sliced them to what made sense to me though I may have to edit them for some reason I don't yet know.

---
Tags: unity, level-design, collider
---


# Question
Title: Several questions about Unity license and revenue from games
So, what I know is if I'm using Unity Personal Edition and start earning more than $100,000 I need to upgrade to Plus or Pro, but I have some questions:

1. If revenue from the game reached more than $100,000, but after a few months it dropped and now it's much less than $100,000, can I "downgrade" (go back) to the Personal Edition?
2. Does revenue from ads count?
3. Does revenue from microtransactions count (buying in-game items)?
4. If revenue from in-game ads counts, what's with ads on the web page where you download the game? Do these also count as my revenue from the game?
5. Does revenue from merch, soundtrack and things like that count?
6. If I "downgraded" from Plus or Pro to the Personal Edition, do I have to remove games made with Plus or Pro from e.g. Steam, Epic, GameJolt? If not, do I have to update the game with Personal Edition (so the game has Unity logo again)?
7. If my revenue is more than $100,000, but I stopped using Unity, do I have to still pay?

# Answer
> 1 votes
> If revenue from the game reached more than $100,000, but after a few months it dropped and now it's much less than $100,000, can I "downgrade" (go back) to the Personal Edition?

You can downgrade once you have reached the end of your plan. This is covered here: How long does one have to pay the $125 per month subscription fee for Unity pro?.

> Does revenue from ads count?

It is *all revenue* (from the Unity Personal page: "Eligibility: Unity Personal is for individuals, hobbyists, and small organizations with less than $100K of revenue or funds raised in the last 12 months."). This means that if your aunt gave you 50k to start your company, and the government gave you 49k to start your company, and you made 1k in revenue from ads on your web site, you need to upgrade.

> Does revenue from microtransactions count (buying in-game items)?

Yes.

> If revenue from in-game ads counts, what's with ads on the web page where you download the game? Do these also count as my revenue from the game?

It's all revenue, not only from a single game.

> Does revenue from merch, soundtrack and things like that count?

Yes.

> If I "downgraded" from Plus or Pro to the Personal Edition, do I have to remove games made with Plus or Pro from e.g. Steam, Epic, GameJolt? If not, do I have to update the game with Personal Edition (so the game has Unity logo again)?

No, you don't have to remove them, and you do not have to "downgrade" them.

> If my revenue is more than $100,000, but I stopped using Unity, do I have to still pay?

You still need to pay until the end of your plan. This is also covered by the question linked above.

---
Tags: unity, licensing, monetization, revenue, microtransactions
---


# Question
Title: How to change multiple materials attached to one GameObject
I am working on a script that changes the material of a selected object when hovered over. The object(s) in question have multiple materials attached. The problem is that only the first material is being changed and the others are staying the same. When a ray hits an applicable object it changes colour, when the ray is no longer on the object it changes back to the default colour. I am using SNAPS prototype assets from the asset store and cannot edit them to use one material, I cannot figure out how to make them use one material either, if there is a simpler way to do this please let me know.

Below is the code that I have attempted:

```
void Update()
    {
        if (_selection != null)
        {

            var selectionRenderer = _selection.GetComponent<Renderer>();
            Material[] materials = selectionRenderer.materials;
            foreach (Material mat in materials)
            {
                selectionRenderer.material = defaultMaterial;
            }

            _selection = null;
        }
        camera = Camera.main;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            var selection = hit.transform;
            if (selection.CompareTag(selectableTag))
            {

                var selectionRenderer = selection.GetComponent<Renderer>();
                Material[] materials = selection.GetComponent<Renderer>().materials;
                if (selectionRenderer != null)
                {
                    foreach (Material mat in materials)
                    {
                        selectionRenderer.material = highlightMaterial;
                    }
                    _selection = selection;
                }

            }
        }
    }

```

# Answer
> 1 votes
What you are doing right is that you are using `GetComponent<Renderer>().materials` to get all the materials. But what you are doing wrong is that you are then set the material with `selectionRenderer.material = highlightMaterial`. This line uses the `material` property of the renderer, which always refers to the *first* material only.

In order to change every material on the object, you need to replace the whole `.materials` array.

However, there is likely a better way to do what you are trying to do. Accessing the materials of a renderer through those properties is discouraged, because whenever you do that, you are creating a completely new material in memory. That new material won't be shared with anything, so you will force the GPU to make a lot more draw calls.

A better way to temporarily change the way an object is being rendered is by using material property blocks. These allow you to override individual settings of one or more materials without switching the materials actually being used by the renderer. For example, when you want to change the emission color of all materials on a bunch of renderers to yellow:

```
foreach(var renderer in GetComponentsInChildren<Renderer>) {
    var propertyBlock = renderer.GetPropertyBlock();
    propertyBlock.SetColor("Emission", Color.yellow);
    renderer.SetPropertyBlock(propertyBlock);
}

```

Note: property names are stringly typed. What names are available and what they do depends on the shader. It is very well possible that the emission property of your particular shader is not called "Emission" but something else.

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


# Question
Title: 2D - How to make a gun muzzle aim at the mouse when the rotation pivot isn't on the muzzle?
I'm making a simple 2D shooter game in pygame and I've come across an issue when making the character aim its gun at the mouse.

To make the gun aim up and down, I've set it so that the gun uses the angle between the x axis and the mouse to rotate itself on its handle. It works just fine but the issue is that since the muzzle of the gun is above the pivot, the muzzle never aims directly at the mouse but slightly higher.

My question is, is there a way to compensate for the offset of the muzzle while keeping the rotation pivot on the handle of the gun?

# Answer
> 1 votes
In real life, weapons have their sights (whether metallic, reddot, optical scope, etc.) slightly above the barrel axis.
To compensate for this, the sights axis is usually set to point slightly down such that the sight axis and the barrel axis cross at a distance X, for example 100 m. It means that if you aim at a target 100 m away from you, the bullet will hit precisely where you aim. If you're target is closer, the bullet will hit a little below and if the target is further, the bullet will hit a little above the point you're aiming.
This setting can be altered to any desired distance X, this is called **zero a rifle**.
Precision weapons can be zeroed thanks to screws on the scope, but most other weapons have the zero preset and cannot be easily changed on the field.

To translate this into your game, you can either:

* Mimic real life, have a fixed angle between the aiming sights and the barrel,
* Automatically adjust the zero distance to match where your cursor is. For example, if your character is aiming at a wall, knowing the distance between him and the wall allows you to compute the angle and compensate such that the bullet will hit where the cursor is.

# Answer
> 0 votes
There is probably a more mathematically elegant solution, but you could just offset where you are aiming based on the rotation of the gun.

Say your barrel of your gun is 20px higher than your pivot point, you would calculate your angle to point the barrel based on 20px below your mouse curser to compensate. If you're aiming completely up, you would calculate your rotation on a point 20px to the right, if you're aiming down below, it would be 20px to left, and if you're aiming backwards (and you don't flip your character) it would be 20px lower.

You could use an if statement to check if you're within one of these angle ranges and lerp between them.

I'm not a python programmer and as familiar with pygame, but you could do something like the following in javascript (assuming the 0 degrees is up, and y gets bigger the higher you are on the screen).

```
    if (angle < 90) lerp({x: 20, y: 0}, {x: 0, y: -20}, angle/90)
    else if (angle < 180) lerp({x: 0, y: -20}, {x: -20, y: 0}, (angle-90)/90)
    else if (angle < 270) lerp({x: -20, y: 0}, {x: 0, y: 20}, (angle-180)/90)
    else lerp({x: 0, y: 20}, {x: 20, y: 0}, (angle-270)/90)

```

---
Tags: 2d, rotation, mouse, shooter, aiming
---


# Question
Title: What single word could be used to describe city adventures?
I am developing an urban racing simulator in a very "underground" stylized setting. It's name is **The Underground King** and you have the ability to either:

* A) Race in a 2d side view.
* B) Do something in the city.

Doing either of A or B will pass the day since it's assumed it takes all day to perform that action. My issue is that while racing levels are caled Racing, the city action/adventure is called Event which is both too generic, and conflicts with my game engine's internal event systems.

I have tried to find a relevant replacement that is descriptive enough on what it is, whithout relying to medieval fantasy type tropes such as "Adventure" or cyberpunk's very own "Run".

What I could think of / narrow down are: **Buisness** or **Biz**, **Happening**, **Venture**, **Risk**, **Encounter**. Here are some examples of the kind of things you can find:

* You accidentally bump into a drunk thug who wants to start a fight.
* A dog has something shiny and valuble looking in its bouth and wants to run away to bury it.
* A suspicious-looking woman dropped a package in a trash can.
* You get a tip about an abandoned but heavily locked garrage.
* A rich businessman wants to put a bet on your next race but wants a guarantee.
* While driving with your crew, you smell something burning (with random consequences):
    + Somebody is playing with matches.
    + The engine is burning.
    + Somebody tried to sabotage your car for the next race but it shortcircuited.
    + A rusted part finally started spinning again. The car has higher stats now.

I am looking for a single word term that can apply to any sort of event as written above which is generic enough to encompass anything you can potentially gain from, but specific enough to represent its something you can pursue or happen to you while you are present in the city.

Thanks!

# Answer
Here are some options:

* Wander
* Buzz
* Rumble
* Slack(ing)
* Errands
> 1 votes

# Answer
* Life Event
* Daily Life
* Daily Experience
* Daily Happening (Last 2 have been mentioned, just added Daily to them)
* City Life
* City Event
> 1 votes

---
Tags: game-design, ui-design
---


title: Is there no UI culling for unity?

text:
# Question
Title: Is there no UI culling for unity?
I don't understand, am I missing something?

I have hundreds of moving images on screen that only need to render and do their logic/physics when they are in the canvas.

Otherwise they can just deactivate to save on performance and there is a very big fps difference when they are deactivated vs activated outside the canvas.

RectMask2D on the canvas does barely anything.

Checking the bounds for hundreds of UI elements seems like madness.

So what are you supposed to do?

# Answer
Have you profiled to see what's actually causing your FPS drop? It might be the physics, not the rendering, that is choking your framerate. You do not need to use colliders to determine if two labels overlap; you can also do so manually with things like `rect.Overlaps()` or `RectTransformUtility.RectangleContainsScreenPoint()`.

It shouldn't be very difficult to check if objects are outside the screen bounds and disable them if so. This is a bit oversimplified, but it conveys the idea:

```
void Update() {
    foreach (var image in images) {
        //edges might be grabbed from a RectTransform, the screen bounds, or defined manually
        Vector3 position = image.transform.localPosition;
        image.enabled = (position.x > leftEdge && position.y < rightEdge
           && position.y > bottomEdge && position.y < topEdge);
    }
}

```

If looping all the images each frame is hurting your framerate (unlikely on a PC), you could perform that loop once every few frames.

You might take it a step further and use a pooling system, with a pool of reusable UI objects that you can display as needed.

Or, if you are committed to using colliders, you can add trigger colliders around the screen bounds that will automatically disable your images/labels/whatever on `OnTriggerEnter()`.
> 1 votes

# Answer
Disable Pixel Perfect on Canvas.

Unfortunately, when you disable Pixel Perfect and have many groups with layouts and content size fitter (to have some order and divisions) and dynamically add an object, it wont fit it. So my idea is that Pixel Perfect refreshes the UI all the time, checks items dimentions and proportions, but slows the performance.
> 0 votes

---
Tags: unity, gui, culling, frustum-culling
---


# Question
Title: How could I intercept a save scene action being run in Unity?
How could I intercept a save scene action being run in Unity?

There is some code I would like to run in editor whenever a scene is saved. Is it possible for me to detect somehow when a scene is saved?

# Answer
> 4 votes
Unity already has a built-in event for doing exactly what you want: `EditorSceneManager.sceneSaving`

Usage:

```
EditorSceneManager.sceneSaving += OnSavingScene;

private void OnSavingScene(UnityEngine.SceneManagement.Scene scene, string path) {
    //do some stuff here
}

```

---
Tags: unity, events, savegame, scene
---


# Question
Title: how to make a damage curve not end abrubtly
I want this because I am making a game where you control a bunch of units, and each of them have different health and weapons. I want to make a weapon that deals damage to everybody on the enemy team, but to prevent spamming that unit it deals a specific damage type and each unit can only take a certain amount of damage from that unit every second.

Some things I have considered is having it be linear up until the cap, but that feels like the sudden stoppage of damage these units would do would be too abrupt. I have also considered doing something logarithmic with a hard cap.

My question is what other options are there that would make sense in this scenario?

# Answer
Use a sigmoid curve, like these computationally cheap examples.

If you want a smooth approach to zero with no upper limit, use tangent.
> 6 votes

---
Tags: game-design, combat
---


# Question
Title: Making a dialog that expands to fit its text
I'm trying to make an OK/Cancel-style dialog which will expand to fit its text in Unity 5.6. I've been trying to pull this off using Unity's built-in UI layout components, but so far I haven't been able to get it exactly right.

The dialog has a background, a title, a body, and two buttons. The goal is for the dialog to resize itself vertically to fit the length of the text. Here is an example with placeholder graphics:

I have this almost working properly, but I created it by abusing the built-in layout components and it doesn't always behave properly. Here's how it's currently set up:

* **Background** is an `Image`
    + `Vertical Layout Group`:
        - Control Child Size: Width
    + `Content Size Fitter`:
        - Horizontal Fit: Unconstrained
        - Vertical Fit: Min Size

Background has the following children:

* **Title** is a `Text`
* **Body** is a `Text`
    + `Content Size Fitter`
        - Horizontal Fit: Unconstrained
        - Vertical Fit: Preferred Size
* **Buttons** is a GameObject
    + `Horizontal Layout Group`
        - Child Force Expand: Width and Height

This setup works about 90% of the time, with the dialog properly resizing according to the text. However, at certain (seemingly arbitrary) body lengths, an extra blank line will be added to the Body text, which disrupts the vertical spacing and gives the dialog a strange look:

This isn't too surprising, because you're not supposed to put a Content Size Fitter on a child of a Layout Group; however, I couldn't figure out any other way to get the dialog to vertically expand to fit more text. Is there a better way to handle this?

# Answer
> 2 votes
You can use the text object's `preferredWidth` and `prefferedHeight` values to do this.

I've done something similar in a project here:

https://github.com/Draco18s/IdleArtificer/blob/master/Assets/draco18s/artificer/game/GuiManager.cs#L66

My code includes a value for creating a ratio in the end result's width and height, but if you are only expanding the height, all you need to do is call `SetSizeWithCurrentAnchors` vertically and it should expand to the necessary height.

Some of the operations I perform, however, are due to scene setup and the background image I use. Be aware of such things when it looks arbitrary.

# Answer
> 0 votes
Perhaps you could set the "body" component to have the text verically aligned to the center. Therefore, even if there's a blank line, the text appears on the center anyway.

# Answer
> 0 votes
Step 1: There is a component called Layout element, set the needed adjustment in that and add one more component ContentSizeFitter and set the horizontal and vertical as preferred size. This will modify the width and height of the text rectttransform .

Step 2: Add a script in the image (message box) which will modify the size

```
    TextMeshProUGUI textVal;

    RectTransform rectTransform;

    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        textVal = GetComponentInChildren<TextMeshProUGUI>();
        StartCoroutine(ModifySize());
    }

    IEnumerator ModifySize()
    {
        //skipping one frame so that UI size modifications will happen properly
        yield return new WaitForEndOfFrame();

        //setting the textbox size and adding some offset so that it looks little spacious
        Vector2 sizeDelta = textVal.rectTransform.sizeDelta + new Vector2(Screen.width * 0.2f, Screen.height * 0.1f);
        rectTransform.sizeDelta = sizeDelta;
    }

```

---
Tags: unity, gui
---


# Question
Title: What is the Library folder and why is it needed?
What and why does the Library folder in Unity projects do and why all recommend adding it to .gitignore when working with VCS (version control system)?

Only it can be somehow simpler, and not like in the article that I read, where Library is called "local cache for imported Assets". Yeah, it's clear that nothing is clear.

Why do you need this Library folder if everything works without it? It is removed and it is re-generated when the project starts. What kind of creature is this Library and why does it exist?

# Answer
> 15 votes
As you have correctly read, it is a cache.

This means that it is not needed, in the sense that if it is missing it can be generated anew. And it *is* needed in the sense that if it is present, it avoids the need to generate it anew each time. It does what caches do - make "things" happen faster.

The simplest way to think about it is that project assets have 2 versions, one easy for you to use and another that's easy for Unity to use. So Unity takes the assets you put in your project and prepares them to be easy for runtime use inside the Library folder. This way you don't have to wait for that to be done each time you run the game.

# Answer
> 1 votes
Library folder is storing your imported assets as document says. If you delete it Unity can create and install dependencies on it. When you add it your .gitignore file vcs like git doesn't track this files and when you push your project to repository, you will send less files to server. It will takes less time and less space.

---
Tags: unity
---