# Question
Title: creating assembly files for third party libraries
I basically have a huge project and we just came to know about assembly definitions could speed up our compile time. I've got a lot of libraries hooked in, and when I tried to simply add an `assembly definition` file to my project directory for the plugins all sorts of error started to popup.

One of the error was this which was from the megafiers asset: from the asset store `Assets/MegaFiers/Scripts/MegaFiers/Modifiers/MegaDisplace.cs(60,4): error CS0246: The type or namespace name 'BurstCompileAttribute' could not be found (are you missing a using directive or an assembly reference?)`

The place I put the assembly definition was like this:

```
---Assets
  |-plugin 1
  |-plugin 2
  |-Megafiers
  |  \-Burst
  |  \-Editor
  |  \-MegaControllers
  |  \-Utils
  |-AssemblyDefinition

```

So, I'm kind of just suspecting that since all the assets are jabbed into AssemblyDefinition maybe the assembly definition didn't contain non-code files such as materials, prefabs etc? I'm just guessing though, I have minimal knowledge on the subject. Please give me some insight on solving this issue. Thanks in advance.

EDIT: Also, some of these libraries seem to have code in the `Editor` folder. From the docs, these code get compiled into the default assembly file(assembly-csharp). But, doesn't that file change each time we make code changes? So, what's the point of a library creating `asmdef`s to a place that always changes?

EDIT2: For the clarification on my question edit. And, taking instance of the Megafiers library above, The editor folder seems to get compiled into the `assembly-csharp-editor` dll and other files, inside this library, don't seem to be associated with a dll file other than `assembly-csharp` which happens to get recompiled when we make a change. Since these code also don't change at all, it would make sense to build a dll for them as well(?). But, when I add an assembly definition to the `Megafiers` folder, it gives errors like mentioned above in the question. And the reason was that code in the library was being referenced(e.g. class was being used) in some part of the project. In this case, how do we create a dll for the `Megafiers` library?

# Answer
> 1 votes
just found your question while checking if someone had built asmdefs for Megafiers. Since it was the top hit, I'll put mine here and have a stab at answering your question (although you've probably moved on give its age)!

# General asmdefs background = The goal

We want code that doesn't change often not to be compiled every time we change our code.

## Asmdefs

All code in the same or sub-directories as an asmdef gets included in that asmdef's DLL.

So, easy, we put all asssets (which don't change often) in their own asmdef(s) and *our code* (that does change often) in its own asmdef(s).

### Hitch 1

asmdefs separate code so you can't access the asset's methods! Well, in come references. When our code wishes to reference things in those other asmdefs, we edit our asmdef to add references to the assets'.

## Editor code

Without asmdefs, any code under a directory named "Editor" gets added to the "`Assembly-CSharp-Editor`" assembly and anything outside it goes in "`Assembly-CSharp`" (caveat see Plugins below).

## Plugins

Anything under an "`Editor`" directory under "`Plugins`" goes in "`Assembly-CSharp-Editor-firstpass`" and under "`Plugins`" but not "`Editor`" is "`Assembly-CSharp-firstpass`". Before asmdefs, this was how we achieved compilation time speedups -- move everything under here!

### Hitch 2

When we add an asmdef, *all* code under it goes in the asmdef's DLL. That includes all the "Editor" code which won't have reference to Editor methods and will then get included in the build which won't work and cause everything to fail! nooo.

So, every "`Editor`" directory needs its own asmdef. This says the code next-to-and-under is Editor-only. Obviously that Editor code will need to reference the top-level asset asmdef! For some assets, there's a single "`Editor`" directory so it's 1 extra asmdef. For some, it's ... well, let's say quite a few. I've ended up moving things around to reduce numbers since, while compile time is large when lots of source files are compiled in one go, if you get lots of DLLs needing linking, that can cause time to shoot up too!

# Megafiers! (finally)

Megafiers 2 (which I'm using) uses Burst. I've included all the files needed below. (I don't have Megafierrs 1 (pre-Burst) but I'd hazard you just omit "`Unity.Burst`", "`Unity.Collections`", "`Unity.Jobs`" and "`Unity.Mathematics`".)

One non-Editor asmdef at top level `Assets/MegaFiers/Scripts/Megafiers.asmdef`:

```
{
  "name": "Megafiers",
  "references": [
    "Unity.Burst",
    "Unity.Collections",
    "Unity.Jobs",
    "Unity.Mathematics",
    "Unity.ProBuilder",
    "Unity.TextMeshPro"
  ]
}

```

One in the first "`Editor`" directory `Assets/MegaFiers/Scripts/MegaFiers/Editor/Megafiers.Editor.asmdef`:

```
{
  "name": "Megafiers.Editor",
  "references": [
    "Megafiers",
    "Unity.ProBuilder",
    "Unity.TextMeshPro"
  ],
  "includePlatforms": ["Editor"]
}

```

And lastly another in the "`MegaShapes`" sub-directory `Assets/MegaFiers/Scripts/MegaShape/Editor/Megafiers.MegaShapes.Editor.asmdef`:

```
{
  "name": "Megafiers.MegaShapes.Editor",
  "references": [
    "Megafiers",
    "Megafiers.Editor",
    "Unity.ProBuilder",
    "Unity.TextMeshPro"
  ],
  "includePlatforms": ["Editor"]
}

```

Lastly, in your main project's asmdef, you'll need to reference "`Megafiers`" and now you should be set to go! (at least for Megafiers ;) ). HTH & GL

---
Tags: unity, assembly
---


# Question
Title: How can I check which of an object's colliders was touched during a collision?
I my game, I am trying to create a door/loading zone system, in which a GameObject has several loading zones as children, each with triggers as components. Also attached to each of the loading zones is a script that gives details for where it leads. What is supposed to happen is, when the player touches any of the loading zones, a script on the parent GameObject checks to see which of the loading zones was entered, in order to figure out to which other loading zone the player should be taken to. However, I am having trouble figuring out how to detect which of the loading zones was touched. This is my code so far:

```
private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.name == "Player")
        {
            EnteredDoor = Collision2D.otherCollider;

            Debug.Log("enter door");

            Player.controls.Disable();
            FadeBlack();

            StartCoroutine(EnterDoor());
        }
    }

```

Most everything seems to be working, except that, when writing Collision2D.otherCollider, an error appears, saying that "CS0120: An object reference is required for the nonstatic field, method, or property 'Collision2D.otherCollider'". Does anyone know how I might go about clearing this error, or potentially an alternative way to figure out which of the object's colliders was touched during the collision?

# Answer
> 0 votes
```
EnteredDoor = Collision2D.otherCollider;

```

`Collision2D` is a class name, when you access its member variables directly using the class name, you are trying to access a **static** member of that class.

See: Static Classes and Static Class Members (C# Programming Guide)

Maybe this is what you want:

```
EnteredDoor = collider.otherCollider;

```

This will cause a new error because otherCollider is a member of Collision2D ,not Collider2D.

So you should use it like this:

```
private void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.name == "Player")
    {
        EnteredDoor = collider;

        Debug.Log("enter door");

        Player.controls.Disable();
        FadeBlack();

        StartCoroutine(EnterDoor());
    }
}

```

Or

```
private void OnCollisionEnter2D(Collision2D col)
{
    var collider = col.otherCollider;
    if (collider.name == "Player")
    {
        EnteredDoor = collider;

        Debug.Log("enter door");

        Player.controls.Disable();
        FadeBlack();

        StartCoroutine(EnterDoor());
    }
}

```

---
Tags: unity, c#, 2d, collision-detection
---


# Question
Title: Circle collider disappears after OnTriggerEnter
I have a 2D circle collider with "Is Trigger" set to true. Currently, all I have it do is play an animation (on just the sprite) and set a bool when the trigger is hit:

```
void OnTriggerEnter2D(Collider2D other) {
    animator.SetBool("Touched", true);
    timerRunning = true;
}

```

This is the animation that plays when "Touched" is set to true in the animator:

After the animation plays, the collider component seems to disappear from the game object. I want to keep it to do other stuff. Is this expected behavior? If it is, how do I keep the collider around? Thanks!

# Answer
Never mind! I found the culprit. The bee (the game object the user controls) had a leftover deprecated script that destroys other colliders and I must have missed it because it had so many other components on it :D
> 0 votes

---
Tags: unity, 2d, collision-detection
---


title: Why isn't my code running?

text:
# Question
Title: Why isn't my code running?
I have other code that uses this same kind of format but for some reason this one is not working. Is there a specific reason why? It is connected to a game object and if I were to not use the if statement then it would work but I don't see why the if statement would be an issue.

The code is being used to close and open a Raw Image element that is nested within Canvas.

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

public class Invetory : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown("Q"))
            this.gameObject.active = true;
    }
}

```

# Answer
As DMGregory said:

> when you use the string version of `GetKeyDown`, the letter keys are identified by lower-case letters ("q" not "Q") — see the list of supported identifiers here.
>
> A better policy is to use `KeyCode.Q` — it saves you from common errors and processing overhead of "stringly typed" code.
> 3 votes

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


# Question
Title: How do I handle lists/arrays in Unity DOTS/ECS?
I'm new to ECS and am having issues finding the right data structure to use.

For context, I have a galaxy with solar systems that produce resources at a given rate (`ResourceProducer` component). Resources are tallied in a stockpile (`ResourceStockpile`) and the individual types are defined in a `Resources` enum.

```
public struct ResourceProducer : IComponentData {
    public Resources resourceType;
    public float quantity;
    public float interval;
}

```

(`ResourceStockpile` is the same but no `interval`)

I had originally intended to have multiple producers and stockpiles per location, one per resource type, but Unity objects to having multiple of the same component on a single entity (and I've seen some Stack Overflow posts supporting this philosophy).

So I then created a

```
public struct ResourceQuantity {
    public Resources resourceType;
    public float quantity;
}

```

and changed my stockpile to use

```
public ResourceQuantity[] resources;

```

(Planning to worry about production rate later as I can't represent it here. Also, I'd prefer a list, but an array seemed more appropriate given the error below)

But now I get an issue in my baker....

```
public class ResourceStockpileBaker : Baker<ResourceStockpileAuthoring> {
    public override void Bake(ResourceStockpileAuthoring authoring) {
        Entity entity = this.GetEntity(new TransformUsageFlags());
        AddComponent(entity, new ResourceStockpile {
            resources = authoring.resources
        }) ;
    }
}

```

`AddComponent` fails to compile with

> The type 'ResourceStockpile' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent(Entity, in T)'

It feels like I may be dealing with an XY problem... I'm going down a rabbit hole without knowing it's the right one.

What's the correct way to represent an entity that produces multiple resources at different rates, to be accumulated in a stockpile for later usage?

# Answer
If you want a component that doesn't have a 1:1 relationship with entities but a n:1 relationship, as in "an entity can have multiple instances of that component", then you need a Dynamic Buffer Component.

A dynamic buffer component is basically a component that is not a single structure but an array of structures.

I actually created a ECS prototype of a game that seems very similar to yours. That was about a year ago, so considering the speed with which DOTS evolves it probably no longer follows the idiomatic style of the week. But this is how I solved this back then.

This is my ResourceStorage structure. Each entity with an inventory has one per resource.

```
public enum ResourceType : short {
    METAL = 0,
    FOOD = 1
    // Remember to update the InternalBufferCapacity of the ResourceStorage buffer component below when adding more resources
}

[InternalBufferCapacity(2)]
public struct ResourceStorage : IBufferElementData {
    public ResourceType type;
    public float max;
    public float current;
}

```

This is the code that adds an inventory to an entity:

```
public void SetResourceStorageData(IEnumerable<ResourceStorage> values, Entity entity) {
    EntityManager manager = World.DefaultGameObjectInjectionWorld.EntityManager;
    DynamicBuffer<ResourceStorage> buffer;
    buffer = manager.AddBuffer<ResourceStorage>(entity);

    foreach (ResourceStorage entry in values) {
        buffer.Add(entry);
    }
}

```

This is the resource production system that increases it:

```
public partial class ResourceProductionSystem : SystemBase
{
    protected override void OnUpdate()
    {

        float deltaTime = SystemAPI.Time.DeltaTime;

        Entities.ForEach((DynamicBuffer<model.ResourceStorage> storages) => {
            for (var i = 0; i < storages.Length; i++) {
                var storage = storages[i];
                storage.current += deltaTime;
                storage.current = math.clamp(storage.current, 0.0f, storage.max);
                storages[i] = storage;
            }
        }).ScheduleParallel();
    }
}

```
> 3 votes

---
Tags: unity, c#, entity-component-system, unity-dots
---


# Question
Title: Hybrid perspective / orthographic projection
I'm trying to figure out how to setup camera projections such that they fulfill following requirements:

* main scene is rendered with perspective projection
* camera / viewport controls allow only zoom (scale) and pan (translate)
* when zooming and panning, the image "does not change", as if we were scaling/panning orthorgraphic projection
* the image does not loose quality when zoomed in

So a naive solution would be to render the main scene to FBO, then use that as a texture for a quad, that translates and scales depending on zoom/pan interaction. This however results in low-quality, as I have to pre-set resolution for that FBO texture. That's not what I want.

What else can I try?

# Answer
> 1 votes
So the solution at the end is trivial. Simply premultiplying the perspective projection matrix, with a translation matrix, moves the rendered image around.

* for panning, premultiply the perspective projection matrix with a translation matrix
* for zooming, apply zoom factor while calculating effective FOV and sides of the perspective projection matrix

With THREE.js this is simply:

class HybridCameraImpl extends THREE.PerspectiveCamera {

  controlMatrix: THREE.Matrix4;

  constructor(fov?: number, aspect?: number, near?: number, far?: number) {
    super(fov, aspect, near, far);
    this.controlMatrix = new THREE.Matrix4();
  }

  updateProjectionMatrix() {
    super.updateProjectionMatrix();
    if (this.controlMatrix) {
      this.projectionMatrix.premultiply(this.controlMatrix);
      this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
    }
  }
}

// Using it
cameraRef.current.zoom = s;
cameraRef.current.controlMatrix.makeTranslation(-tx, -ty * aspect, 0);
cameraRef.current.updateProjectionMatrix();
```

# Answer
> 1 votes
To change the zoom without changing the image, modify your field of view angle. This effectively scales the image up or down, without changing the geometric relationships in the image plane — if two lines cross at a particular point, they'll continue crossing at that same point, with no parallax effects that move the apparent intersection relative to other image features.

To translate side to side or up and down (truck and boom/jib movements — perpendicular to the view direction), you can use an oblique camera frustum. This effectively shifts the image after the projection has been applied, so again you'll see no parallax. The effect can be strange though, if you use a large shift: you'll see an image projected from a viewpoint distant from the location in the center of the image, and you'll see more dramatic perspective distortion the farther you go from the camera's axis.

Taking the classic OpenGL projection matrix:

$$\left\[\begin{array}{cccc} { \dfrac{2n}{ r-l } } & 0 & { \dfrac{r + l} { r-l } + x\_{shift}} & 0 \\ 0 & { \dfrac{2n}{ t-b } } & { \dfrac{t + b}{ t-b } + y\_{shift}} & 0 \\ 0 & 0 & -{\dfrac{f+n}{f-n}} & -{\dfrac{2fn}{f-n}}\\ 0 & 0 & -1& 0\\ \end{array}\right\]$$

The \\$x\_{shift}\\$ and \\$y\_{shift}\\$ variables there control the oblique frustum. When they're zero, you get the usual projection, with the camera axis passing through the center of the image. As you adjust these values, you'll slide the image side to side without altering the perspective.

---
Tags: opengl, camera, projection
---


# Question
Title: Randomization algorithm that trades between more variance and higher total value
I need to generate discrete integer variables that each have meaning, so does their sum. I am essentially looking to partition a normal distribution into n bins. You can think of them as stats. The total obviously matters, but if we always equally distribute them, an item with higher total stats would be strictly better than one with lower total. We can't have that. Therefore, I had the idea to "reward" the player with bigger variation if the generated sum is low. I just do not know how to achieve this.

Generating a total value from a normal distribution is easy. However, I don't know how to distribute them in the way I described. Below are methods I have tried:

1. Start with an equal partition, for a random number of steps, increase a random stat by 1 and decrease another by 1. Problem: the values always seem to be stuck near the beginning.
2. Start with an equal partition that is higher than the desired average. For a random number of steps, increase a random stat by 1 an decrease all others by 1. Problem: this seems to just universally lower all the stats without producing the variation I wanted. The sum total is also not normally distributed.
3. Randomly generate the first (n-1) variables from normal distributions, and fix the last one. Problem: this produces very predictable results. Each sample looks more or less the same.

Is there an algorithm that achieves this except just to generate many samples until it has the desired distribution?

# Answer
## Differently sized dice

Disclaimer: this is only a partial answer since it does **not guarantee** high variance outcomes for low sums and also does **not guarantee** the same chance for all results with the same variance. However it might still be suitable for the described problem.

## Basic principle

if we look into the results of random numbers generated through dice, using multiple 4d6 - 4 results in values between 0 and 20 with much smaller variance than using a single d20 (which would be 1 to 20 but close enough for demonstration)

## how to use this for your problem

If your generated sum is high, use "small dice" to determine how much to add to a bucket in each step, if the sum is low, use "bigger dice" for each step, until your desired total is reached.

## pseudo code

input:
`targetSum` `diceSize`

code:

```
while(targetSum > sum(buckets)){
   buckets[random] += randomBetween(1,diceSize)
}

```

For items with a high generated `targetSum` choose a small `diceSize` (1 or 2) and scale the dice size with decreasing `targetSum` (for example up to 40). For the exact formular to convert `targetSum` into `diceSize` you will need to try out what works best for you.
> 0 votes

# Answer
## reverse preprocessing

In preprocessing for machine learning it is usual to scale values so they have a deviation of 1 and a mean of 0. We can reverse these steps to achive a solution to your problem.

Step 1:
decide on a total target sum: `targetSum` and a `targetDeviation` that you want to achive. You can decide for yourself how these two values exaclty correlate but from your questions high `targetSum`s should come with low `targetDeviation` and vice versa. As a derived value also calculate your `targetMean` = `targetSum / numberOfBuckets`

Step 2:
generate a floating point number between 0 and 1 for each bucket individually.

Step 3:
calculate the mean and substract it from each bucket

Step 4:
calculate the deviation and divide each bucket by it

Step 5:
multiply each bucket by your `targetDeviation`

Step 6: add `targetMean` to each bucket

Now you have all buckets filled in a way that their sum is equal to your generated total value and their deviation is equal to the input deviation. (of course there will be rounding errors but if your stats have a sufficient range like 0-100 these will be marginal)
> 0 votes

---
Tags: mathematics, game-design, random
---


# Question
Title: How "Dodge" characteristic is calculated on enemy troops
I was torn about whether to post this as a game problem or as a maths problem. My maths is a little shaky, so thought maybe best to post here. The game, for anyone who is familiar with it, is War and Order a mobile RPG / MMMORPG (I was never quite sure on the definitions).

In the game, cavalry troops can learn a skill named "Dodge". When maxed, the skill is:

> Cavalry have a 16% chance to dodge enemy attacks.

My question is how that 16% might be applied. Obviously the actual mechanics are under the hood so this is all guesswork.

I dont think a great deal of detail around troop formations here is necessary. But each battle formation can hold up to 10 troop types, and subsequently, 10 "pods" of troops.

A common troop formation is like below. The troops walk towards the enemy and when they get in range they start attacking. Troops attack at the same rate, so its reasonable to assume that in most cases, each troop pod will have an equal number of attacks.

(troops facing down)

```
  1
  2
  3

```

Say over 10 seconds, this formation produces 30 attacks, all focused on enemy cavalry with 16% "Dodge". Probability suggests you would expect 4.8 of those attacks to be dodged. Because it's chance based, if you were to rerun the fight a a few times. Maybe sometimes it was 3 attacks dodged, and maybe sometimes it is 7, but overtime it should average to 4.8, or 1.6 per pdo

Now is the time to point out, that while Dodge treats all attacks as equal (or so we assume), I, as the attacker, care more about the attack coming from troop pod 1 (which has higher attack) than troop pod 3 ( which has lower attack but higher health and defense).

Now take this new formation. I have included two new troop pods. Their numbers are small and they exist only to attempt to trick "Dodge".

Comparing to the first scenario, we are now producing 5 attacks at a time, so over that same 10 second time period, 50 attacks are produced.

The basic maths, to me, suggest that now averaged out over time, 8 attacks will be missed. Which comes to the same 1.6 per pod.

(troops facing down)

```
4  1  5
   2
   3

```

*Remembering that we care most about the attack from pod 1 **not** being dodged, because it does the most damage*

**My theory / question**

Is there maths to suggest that formation 2 would perform better than formation 1? Or to state more concretely, in formation 2, given a

At first glance, I would have expected 16% to mean 16% and move on. However:

* Scenario 1: the attacks we care about make up 33% of the total attacks
* Scenario 2: the attacks we care about make up 20% of the total attacks

Given that these fights only last a certain amount of time. Because 16% of all attacks are dodged, and in Scenario 2, the attacks we care about (pod 1) make up a smaller percentage of the total attacks is there a greater chance that fewer attacks from pod 1 are dodged?

I've dragged myself into a hole of poisson and binomial distributions, but my maths basics is not strong enough to come up with a working theory on my own.

# Answer
> 3 votes
No, there is not a greater chance that the attacks from pod 1 will be dodged as each dodge is an independent check (unless there is some feature you haven't described). Pod 1 still gets 10 attacks, and an average 16% of the attacks from each pod will be dodged, completely independently of each other and the other pods. Same for pod 2,3,4, etc.

# Answer
> 1 votes
## No

unless `dodge` is implemented in a very weird and sophisticated way (see the evasion system in path of exile) **AND** you know how that implementaion works, there is no way to "game the system".

If it is actually just a random chance applying to each attack individually, then there is literally nothing you can do to "game the system".

---
Tags: mathematics, game-mechanics, probability
---


# Question
Title: Preload multiple scenes at the same time and activate them on demand in Unity. [Unity, async, simultaneous]
Preload scene in unity \- this question tells us about how we can pre-load a scene in Unity and load it on demand. What it doesn't tell us - how do we pre-load multiple scenes at the same time and also keep the other scenes in memory waiting to be activated when we load another scene?

Use case: pre-loading multiple scenes at the start of the application, so they are ready when required. Example:

1. You have a `[Scene] Intro` which takes `20s` to complete where you start pre-reloading `[Scene] Main Menu` that takes `10s` to load. When `[Scene] Main Menu` has finished pre-loading, you still have `10s` to spare, those could be used to pre-load `[Scene] Main Game`.
2. You have a `[Scene] Main Menu`. Depending on user choice you load `[Scene] Main Game` or `[Scene] Sandbox`. You pre-load both scenes while user is still in `[Scene] Main Menu`. When user makes their choice, chosen pre-loaded scene is loaded.

# Answer
## Short answer

Currently we can't do that in certain cases.

## Long asnwer

AsyncOperation.allowSceneActivation tells us:

> When `allowSceneActivation` is set to false then progress is stopped at `0.9`. The `isDone` is then maintained at `false`. When `allowSceneActivation` is set to true `isDone` can complete. While `isDone` is false, the `AsyncOperation` queue is stalled. For example, if a `LoadSceneAsync.allowSceneActivation` is set to `false`, and another `AsyncOperation` (e.g. `SceneManager.UnloadSceneAsync` ) is initialized, the last operation will not be called before the first `allowSceneActivation` is set to `true`.

Which means that there is an order to load pre-loaded scenes. If we pre-load scenes `[Scene] Main Game` and `[Scene] Sandbox` in this order, we can't activate `[Scene] Sandbox` until we activate `[Scene] Main Game`. If we first activate `[Scene] Main Game` it will activate without a problem if it was pre-loaded first, and following we can activate `[Scene] Sandbox` because the queue is empty.

In conclusion, right now we can only load scenes in specific order.

***More:*** \[ISSUE\] Activating multiple scene at the same time via AsyncOperation.allowSceneActivation .

## Solutions

1. Use Addressables and make scenes as prefabs. Load/Unload instances of this prefab in a manner like you would load/unload scenes.

## Code

**Git:** Preload multiple scenes at the same time and activate them on demand in Unity. \[Unity, async, simultaneous\]

I have tested this with both `SceneManager` and `Addressables`.

`PreloadSceneManager.cs`

```
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;

public class PreloadSceneManager : MonoBehaviour
{
    private Dictionary<string, AsyncOperation> _sceneName_sceneLoadAsyncOperation = new Dictionary<string, AsyncOperation>();

    public AsyncOperation PreloadSceneAsync(string sceneName, LoadSceneMode loadSceneMode)
    {
        if (this._sceneName_sceneLoadAsyncOperation.TryGetValue(key: sceneName, value: out AsyncOperation loadSceneAsyncOperation))
            return loadSceneAsyncOperation;

        loadSceneAsyncOperation = SceneManager.LoadSceneAsync(
            sceneName: sceneName,
            mode: loadSceneMode
        );

        loadSceneAsyncOperation.allowSceneActivation = false;

        this._sceneName_sceneLoadAsyncOperation.Add(
            key: sceneName,
            value: loadSceneAsyncOperation
        );

        return loadSceneAsyncOperation;
    }

    public AsyncOperation LoadSceneAsync(string sceneName, LoadSceneMode loadSceneMode)
    {
        if (this._sceneName_sceneLoadAsyncOperation.TryGetValue(key: sceneName, value: out AsyncOperation loadSceneAsyncOperation))
        {
            loadSceneAsyncOperation.allowSceneActivation = true;

            return loadSceneAsyncOperation;
        }

        loadSceneAsyncOperation = SceneManager.LoadSceneAsync(
            sceneName: sceneName,
            mode: loadSceneMode
        );

        return loadSceneAsyncOperation;
    }

    private Dictionary<string, AsyncOperationHandle<SceneInstance>> _sceneName_sceneLoadAsyncOperationHandle = new Dictionary<string, AsyncOperationHandle<SceneInstance>>();

    public AsyncOperationHandle<SceneInstance> AddressablesPreloadSceneAsync(string key, LoadSceneMode loadSceneMode)
    {
        if (this._sceneName_sceneLoadAsyncOperationHandle.TryGetValue(key: key, value: out AsyncOperationHandle<SceneInstance> loadSceneAsyncOperationHandle))
            return loadSceneAsyncOperationHandle;

        loadSceneAsyncOperationHandle = Addressables.LoadSceneAsync(
            key: key,
            loadMode: loadSceneMode,
            activateOnLoad: false
        );

        this._sceneName_sceneLoadAsyncOperationHandle.Add(
            key: key,
            value: loadSceneAsyncOperationHandle
        );

        return loadSceneAsyncOperationHandle;
    }

    public AsyncOperationHandle<SceneInstance> AddressablesLoadSceneAsync(string key, LoadSceneMode loadSceneMode)
    {
        if (this._sceneName_sceneLoadAsyncOperationHandle.TryGetValue(key: key, value: out AsyncOperationHandle<SceneInstance> loadSceneAsyncOperationHandle))
        {
            loadSceneAsyncOperationHandle.Result.ActivateAsync();

            return loadSceneAsyncOperationHandle;
        }

        loadSceneAsyncOperationHandle = Addressables.LoadSceneAsync(
            key: key,
            loadMode: loadSceneMode,
            activateOnLoad: true
        );

        return loadSceneAsyncOperationHandle;
    }

    private void Awake()
    {
        Object.DontDestroyOnLoad(target: this.gameObject);
    }
}

```

`SceneLoader.cs`

```
using System.Collections;
using UnityEngine;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    private IEnumerator LoadSceneAsyncProcess(string sceneName, AsyncOperation asyncOperation)
    {
        while (!asyncOperation.isDone)
        {
            Debug.Log($"[scene]:{sceneName} [percent complete]: {asyncOperation.progress}");

            yield return null;
        }
    }

    private IEnumerator LoadSceneAsyncProcess(string sceneName, AsyncOperationHandle<SceneInstance> asyncOperationHandle)
    {
        while (!asyncOperationHandle.IsDone)
        {
            Debug.Log($"[scene]:{sceneName} [percent complete]: {asyncOperationHandle.PercentComplete}");

            yield return null;
        }
    }

    [SerializeField] private PreloadSceneManager _preloadSceneManager;
    public PreloadSceneManager _PreloadSceneManager => this._preloadSceneManager;

    [SerializeField] private string _sceneNameOrKey = "[Scene] Preload Scene 1";
    public string _SceneNameOrKey => this._sceneNameOrKey;

    [SerializeField] private KeyCode _loadSceneKeyCode = KeyCode.Alpha1;
    public KeyCode _LoadSceneKeyCode => this._loadSceneKeyCode;

    [SerializeField] private LoadSceneMode _loadSceneMode = LoadSceneMode.Additive;
    public LoadSceneMode _LoadSceneMode => this._loadSceneMode;

    private void Update()
    {
        //if (Input.GetKeyDown(key: KeyCode.Return))
        //{
        //  // Start scene preloading.

        //  Debug.Log($"Preload [scene]: {this._sceneName}");

        //  AsyncOperation asyncOperation = this._preloadSceneManager.PreloadSceneAsync(
        //      sceneName: this._sceneName,
        //      loadSceneMode: LoadSceneMode.Additive
        //  );

        //  this.StartCoroutine(
        //      routine: this.LoadSceneAsyncProcess(
        //          sceneName: this._sceneName,
        //          asyncOperation: asyncOperation
        //      )
        //  );
        //}

        //if (Input.GetKeyDown(key: this._loadSceneKeyCode))
        //{
        //  Debug.Log($"Load [scene]: {this._sceneName}");

        //  AsyncOperation asyncOperation = this._preloadSceneManager.LoadSceneAsync(
        //      sceneName: this._sceneName,
        //      loadSceneMode: LoadSceneMode.Additive
        //  );
        //}

        if (Input.GetKeyDown(key: KeyCode.Return))
        {
            // Start scene preloading.

            Debug.Log($"Preload [scene]: {this._sceneNameOrKey}");

            AsyncOperationHandle<SceneInstance> asyncOperationHandle = this._preloadSceneManager.AddressablesPreloadSceneAsync(
                key: this._sceneNameOrKey,
                loadSceneMode: this._loadSceneMode
            );

            this.StartCoroutine(
                routine: this.LoadSceneAsyncProcess(
                    sceneName: this._sceneNameOrKey,
                    asyncOperationHandle: asyncOperationHandle
                )
            );
        }

        if (Input.GetKeyDown(key: this._loadSceneKeyCode))
        {
            Debug.Log($"Load [scene]: {this._sceneNameOrKey}");

            this._preloadSceneManager.AddressablesLoadSceneAsync(
                key: this._sceneNameOrKey,
                loadSceneMode: this._loadSceneMode
            );
        }
    }

    private void Awake()
    {
        Object.DontDestroyOnLoad(target: this.gameObject);
    }
}

```
> 2 votes

# Answer
I've found that you can preload multiple scenes if they all use `LoadSceneMode.Additive`. If any one of them uses `LoadSceneMode.Single` then it will block the Async queue.
> 0 votes

---
Tags: unity, scene, preload, async
---


# Question
Title: Why are my avatar hands not closed when performing clap animation downloaded from mixamo
I am using finalIk to rig my avatar in my project. Looks okay. I also have a few animations downloaded from mixamo that I am using with it. However, there is a particular animation (clapping) that when used on my avatar, the two hands do not meet with each other. for some avatars, the hands go into each other, the clapping are not proper like it is shown in mixamo.

Edit: I have noticed that I can solve this with the **Character Arm-Space** variable (see attached image) in mixamo's animation options. How can I control this variable at run time.

# Answer
Problems like that are pretty common when trying to retarget animations from one character to another. The reason why it occurs is probably that the positions and lengths of the arm bones of your character don't exactly match those of the character the animation was designed for. So when the same bone rotations are applied, the hand-bone ends up in a slightly different position.

One possible solution can be to use inverse cinematics. When you set the IK position for both hands to the same position, then you can "glue" the hands to a specific point in 3d space.

Now if you enable IK permanently, then the hands will of course not clap but stick together. That's probably not what you want in this case. You only want them to meet during a certain point of the clapping animation. This can be achieved by also animating their IK weights. So you can only give the hands an IK weight when close to the contact phase of the clapping animation, and let the animation control the hands during the rest of the animation.
> 1 votes

---
Tags: unity, animation, rigging, avatar
---


# Question
Title: How to implement NPC that reads player input and counters it?
input reading = NPC reads the input of the player and instantly reacts to counter everything the player does.

So, is it like :

```
if player in range and key is being pressed :

Npc reaction

```

Is that right? What would happen if there more players? is it as easy as getting the input of the closest player?

What ways are there to predict the input of players? Like say some players are spamming dodge and parry like DarkSouls is their middle name, how do I make the enemy NPC adapt to player patterns?

# Answer
You can have the NPC read input, yes. However, that is unlikely to be enough to counter the player, as - chances are - positioning is important.

For example, having the NPC to shoot a projectile leading the player requires to look into the player character speed, the distance to it, and the speed of the projectile to compute the optimal direction to shoot. *There are question on the topic on this site, try searching.*

In that case the speed of the character, and its position, are part of its state. We can easily turn input into state with the approach that Engineer comments: if player is performing an action (e.g. because of user input) set a `bool` flag, or change a `state` variable.

Then, for the case where there are multiple player characters, the NPC can use a "sight" area where it detects player characters, keep track of them, and pick the closest one. Having a reference to the player character, it can read its state.

*Furthermore, changing the input scheme would not require to update the NPC code.*

---

Adapting to player patterns require to first identify the patterns. And then have some strategy to counter them. Presumably you would have a finite number of strategies programmed (barring machine learning), thus I suggest to think about the problem the other way around: for each strategy the NPC can use, what are the conditions for it to work, and then figure out how to check for those conditions. *You would, of course, use feedback from player testing to improve it.*

Checking if an strategy might work could - again - require to check positioning (e.g. distance to the player character), and might involve line of sight (i.e. raycast) or dedicated detection areas, in addition of checking the state of the player character (e.g. check if it is invulnerable to some attack).

In fact, you might not limit yourself to a single player character! That is, instead of checking which strategy can be applied to the closest player character, you might check on which player character each strategy can be applied. *You might have it pick an strategy at random until it finds one that works, or go down the list in a predefined order, but be careful to not harm performance by doing too many checks in one frame.*

About prediction, you need to think how the states of the player character will change. For example, you might know that a typical jump of the player has it landing in 1.5 seconds (again, as an example), using that the NPC can use an attack that - approximately - will hit the player when it lands. *Something similar can be applied to temporary buffs or player abilities that have timeouts.*

---

*I will ultimately depend on your game mechanics, but I hope this give some idea of how to go about it.*
> 1 votes

---
Tags: ai, logic, combat, npc, patterns
---


# Question
Title: How do you declare a custom structure to retain field values after a scene reload?
I have the following code :

```
public class SomeClass : MonoBehaviour
{
    public Vector3 Vector3;
    public Foo Foo;

    void Start()
    {
        Vector3 = new Vector3(1.0f, 1.0f, 1.0f);
        Foo = new Foo(1);
    }
}

```

After scene is reloaded, the value of the field inside `Foo` is lost (reset to the default value which in this case is zero), while fields inside `Vector3` (which is a built-in type in Unity) are kept.

Foo is defined this way:

```
public struct Foo
{
     public int x;

     public Foo(int x)
     {
         this.x = x;
     }
}

```

How to modify that structure to make it behave like `Vector3` after scene is reloaded ? (the value inside fields are kept).

# Answer
> 1 votes
Declare your struct to be serializable:

```
[System.Serializable]
public struct Foo {
   // ...
}

```

This tells Unity to record the values of its fields marked `public` or `[SerializeField]` into scene or prefab asset files that contain this structure. If the type does not have this attribute, the C# compiler doesn't generate the helpers needed to serialize and deserialize it to/from a data stream this way.

This will not, on its own, save and restore values that changed while playing in a scene. Reloading the scene will restore the values saved in the `.unity` scene file, ie. the last values it had at edit time. If you want to store values somewhere that won't get unloaded/reloaded on scene changes, you can use a `static` variable to hold data not attached to any single instance.

---
Tags: unity, scene, struct
---


# Question
Title: How to efficiently detect targets for AI?
A creator named NovemberDev made this game without having performance in mind, yet his enemy AI, while being relatively simple, is still extremely fast: his game can have hundreds of enemies all moving and colliding around without too much performance issues.

The only sources of lag in his game are literally the enemy sounds; if you delete all the sound nodes and make the game mute, it runs incredibly smoothly with a large amount of enemies.

like here's the enemy.gd: https://github.com/NovemberDev/novemberdev\_soulslike\_darksouls\_godot/blob/main/Scripts/Enemy.gd

I'd like to replicate his methods, only one problem....he doesn't use areas to detect the player the player position, he uses the tree node.

Autoloads : `get_node("/root").add_child(player)`

Enemy.gd : `distance_to_player = Globals.current_player.global_transform.origin.distance_to(global_transform.origin)`

I tried using the same player detection, it was actually my very first method of doing it.

The problem is that the Godot documentation suggests that to save and load the game, one must delete all saved nodes before loading as to avoid the nodes being duplicated every time you save and load.

Straight from Godot docs:

```
var save_nodes = get_tree().get_nodes_in_group("Persist")
for i in save_nodes:
    i.queue_free()

```

so whenever you save and load the game, since the enemies are keeping track of a specific node, the game will crash because the node that the enemies where keeping track was deleted and replaced... it doesn't matter that it is literally the same node, a complete clone... godot doesn't recognize it and the game crashes.

So for now, I tried using multiple area nodes, each one with a collision attached to it. That was a bad idea. I also tried to maybe not use area nodes but just create an area in code and use it to define distance... and that wasn't such a big improvement, not at all actually. Rays just make the enemy agent feel like it is blind, and to mimic the effects of areas you have to add dozens on dozens of rays in all directions, otherwise the player can easily hide behind a blade of grass and become invisible to the enemy.

So what other ways are there to detect players/prey/physical things that AI is supposed to detect?

# Answer
> so whenever you save and load the game, since the enemies are keeping track of a specific node, the game will crash because the node that the enemies where keeping track was deleted and replaced... it doesn't matter that it is literally the same node, a complete clone... godot doesn't recognize it and the game crashes.

You can check with `is_instance_valid`:

```
var current_player := Globals.current_player
if is_instance_valid(current_player):
    distance_to_player = current_player.global_transform.origin.distance_to(global_transform.origin)
    # ...

```

You would, of course, update `Globals.current_player` to the new `Node` when it becomes available. *You might also consider using a signal to notify about it.*

*See also `is_inside_tree`, `is_queued_for_deletion` and `NOTIFICATION_PREDELETE`.*

---

> So for now I tried using multiple area nodes, each one with a collision attached to it and that was a bad idea

You would be checking distance all the time. Which might be OK for a single or for few targets.

On the other hand, using areas gives you the flexibility to define a shape (e.g. have the enemies be able to detect the player further away if they are on the direction they are looking to). And would be easier to handle for certain types of games (e.g. stealth).

---

> also tried to maybe not use area nodes but just create an area in code and use it to define distance...

Look into using `intersect_shape` instead.
> 2 votes

---
Tags: ai, performance, godot
---


# Question
Title: How do I keep a node centered while animating scale in Godot?
When scale is modulated, the item scales from the top-left corner. I tried changing anchors preset to "center" but it still scaled from the top-left corner. How do I make it scale from center?

# Answer
> 2 votes
Assuming you are scaling with `scale`, what you need to do is set the `pivot_offset` to the center of the `Control`, i.e. to half of `size` (which is the size of the `Control` before scaling).

In general the `Control` will scale *and rotate* keeping the point specified by `pivot_offset` in place. So when the `pivot_offset` is `Vector2(0, 0)` (which is the default) `scale` *and `rotation`* will keep the top left corner in place.

Thus - to reiterate - change `pivot_offset` to the center *or whatever position you want to keep fixed during scaling and rotation*.

---
Tags: animation, gui, transformation, godot
---


# Question
Title: Inertia Tensor Relative to Center of Mass vs Inertia Tensor in Body Coordinates
If I have the inertia tensor relative to the center of mass, is that the same as the inertia tensor in body coordinates? If no, can you please explain the difference and how do I numerically calculate the inertia tensor in body coordinates using the inertia tensor relative to the center of mass?

# Answer
Yes, they are the same, just as long as the point mass vectors are calculated using the offset from the center of mass and there is rotation or no scaling applied.

The inertia tensor is fixed in body (local) space. It only needs to be calculated once and stored.
> 0 votes

---
Tags: rotation, matrix
---


title: Easiest to balance formula for damage?

text:
# Question
Title: Easiest to balance formula for damage?
The problem with:

```
Damage dealt = damage - defense

```

is that you get a situation where no one will ever choose attack speed vs damage because high attack speed players risk doing hundreds of 0 damage hits per minute and critical hits become the meta.

For now,

```
damage dealt = damage / defences

```

seems the fairest and in fact most games use this formula, but I was wondering if there are better options, especially since this only equalizes offensive stats but not defensive ones.

When damage is divided by defense, health points become mathematically useless. League of Legends deals with this problem by making all defensive stats have a hard cap with incredible diminishing returns while making health potentially infinite with no diminishing returns.

Other games ignore the problem completely.

# Answer
> 0 votes
This is a situation where limited randomness needs to be introduced.

Add a constrained random variable to each factor in all equations.

The randomness will limit the determinism beyond fixed values.

The randomness will tilt the balance one way or the other.

---
Tags: balance, combat
---


# Question
Title: How can I make sprites and tile-sets interact with y-sort correctly in Godot?
Y-sort is not working how I would expect in Godot. I have a player sprite, their feet are at the origin. I have a y-sorted tile layer. The mushroom base is at the bottom of the tile, it doesn't start in the middle or anything.

When I stand in front of a mushroom title, it displays in front when it should be behind. If I step down just a bit, it finally pops behind. It seems like Godot thinks that the y-position of my player is near their center. I don't know why.

What other steps need to be taken to make y-sort work as expected?

# Answer
> 0 votes
This is a terrible solution, but changing y-offset for the character sprite to some random position mostly fixed the issue:

---
Tags: godot, depth
---


# Question
Title: How to use "Debanding" option to prevent color banding in a gradient TextureRect?
I want to have a Godot 4.0 `TextureRect` background with a linear gradient from `#18181b` to `#27272a`. This causes some noticeable color banding issues:

I tried to research and solve this issue. I found a GitHub issue asking for dithering which ultimately points to another issue on a "debanding" option which would fix this.

I've found the setting in Godot and enabled it:

But the screen remains completely unchanged. Both when I actually *run* the project, and inside the editor:

The tooltip does say:

> 2D rendering is not affected by debanding unless the Environment.background\_mode is Environment.BG\_CANVAS.

So I also added a `WorldEnvironment` Node as a child to the `Panel` root node, created a new environment, and set the Background/Mode property to "Canvas" from the dropdown. This didn't change anything either.

What am I missing?

PS. As a workaround I've created a gradient in Figma and exported it as a PNG. This works, but is a bit cumbersome (I want to change the "to" and "from" colors of the gradient frequently). Here's a screenshot for reference:

# Answer
> 1 votes
I was struggling with this one myself, turns out your issue is that your gradient texture is too small, only 64x64. The documentation states that the height and width represent the sample count over the gradient in each dimension. It doesn't matter how much debanding you apply to a tiny gradient texture, it's still going to have visible steps between samples. I confirmed that debanding does in fact work using the method you used by blowing out the contrast on my own too-small gradient texture.

You can see the deband dither visible on top of the texture, along with the bands still there. Just boost the appropriate dimension until it looks good. One caveat: the deband filter doesn't seem that good for really subtle gradients over a large area regardless, so this may only work up to a point. I have a large sprite applied over a huge area and I can see slight banding even with a huge texture size.

Edit: I built a subtle noise shader that does a better job of debanding gradients than the built-in debander. It doesn't do any advanced Bayer filter dithering or anything so it's not perfect, but it significantly reduces the issue on really subtle color shifts. I'm sure somebody could do better.

The full code can be found here.

---
Tags: 2d, rendering, godot
---


# Question
Title: Does "critical chance" have any reason to exist?
How do you make critical attacks not useless in video games?

In most games, critical attacks are just a random chance to deal extra damage—but why would players choose random chance rather than extra damage if the end result is the same?

Whether you increase your raw power or your critical chance, the result is always more damage, so players will always pick either what sounds cooler or what is mathematically more efficient in the game.

# Answer
Critical hits are a form of **variable ratio reward**.

* "**ratio**" means the player has to do an action some number of times to get the reward (it doesn't just arrive on a timer - you have to attack to get a critical hit)
* "**variable**" means that the player can't predict *how many* times they need to do the action before the next reward comes. Any attack *could* be the one to land a critical, but you don't know until you try.

Behavioural psychology experiments have found that this type of reward is one of the stickiest and most habit-forming, which is why they're so commonly used in games, like random loot drops. They're so effective that we've fielded questions here before wondering why games would even bother with any *other* reward schedule. (This is also reason to use them with *caution* and professional responsibility, as this can easily cross the line from giving the player a compelling and enjoyable experience to a compulsive/addictive one)

In the case of critical hits, the reward is a spike of **excitement** when something goes better than expected, and added **anticipation** leading up to the attack hitting. (Brain scanning experiments with slot machine players find the thrill ramps up while the wheels are still spinning - the unknown dials up the mental engagement even for the attempts that *don't* pay off)

This is especially true in JRPG-style games where you select an attack from a menu and then the characters animate to act it out. If the damage was already pre-determined, this is just dead time - the player already knows the outcome of the attack from the moment they select the move, and the animation is just an enforced delay to sit through. But if the attack can miss or hit better or worse, then the player stays engaged throughout to see the outcome of their move and adjust tactics for their next play accordingly.

This can give the player **stories to tell** \- events that make one encounter with a generic monster different from the next. "Oh, you should've seen it, I landed three crits in a row and basically melted the enemy into goo before it could act!" Whether or not these rise to the level of salience you actually tell someone about, they add texture that reduces the repetitive grind.

The possibility of more-than-expected damage also gives you something else important: **hope**. In a game with no randomness, the player can already predict the outcome several steps ahead. And if they're losing, this is deeply demoralizing. Let's say you know the enemy has 50 HP left and your sword only does 30 damage per hit. That means it's going to take 2 more attacks to kill it. If it's readying a one-hit kill or a nasty status effect, there's no way you'll kill it before it gets the move off. You see your defeat coming and the mechanics drag you through the mud waiting for it to unfold. But if there's some *possibility* you could score a critical and end the monster before it gets its attack off, now you have hope. Now you're still engaged in the fight and striving for a good outcome, and if it pans out, you'll have a story to tell about snatching victory from the jaws of defeat - something you just can't get with deterministic damage.

See the Prototype that was Banned from Halfbrick for more on the psychological impacts of fully-deterministic combat versus systems with some non-deterministic relief valves built-in.

Critical hits also form a new **building block** from which designers can build more complex **dynamics**. As other answers note, critical hits can proc other special effects, bypass defenses or debuffs, or even influence loot drops.

One example I want to add is in Team Fortress 2, the critical hit chance ramps up from 2% to 12% (ranged) or 15% to 60% (melee) depending on the amount of damage the player has done in the last 20 seconds. This creates a **positive feedback loop** where getting crits leads to getting more crits, contributing to an exhilarating rush and feeling of being "on a roll". It also encourages aggressive play and pressing the advantage rather than slow and methodical defensive play. That's not to say that this style of play is always "better", but in this case the choice to include critical hits and ramp their chance like this helps support the style of play and emotional experiences Valve's designers wanted TF2 to deliver.
> 31 votes

# Answer
# (Almost) no mechanic is bad

It's very difficult for a single *mechanic* to be bad. Unless it causes harm to a player's health or well-being, pretty much every mechanic could potentially be part of a good game.

There are two big objections to crit chance stats which I often see from players: "Crit is just another flavor of damage" and "Random crits diminish the effect of skill." I'll address both.

## Crit as a calculation

I've sometimes heard crit jokingly called "Yellow attack power" (in a multiplayer game where crits show up in yellow text and normal attacks show up in red). This is because of the perception from players that because only the long-term expected value of damage matters (which was true for that game), crit and attack power could be thought of us just two different flavors of the same stat.

Such jokes aside, I'd contend that having yellow attack power isn't a bad thing.

### Simple calculations aren't bad

If you have a game with attack power and crit chance, and the expected value of damage over time is a simple multiplication of the two, and the player can freely assign points between the two, and there is a trivial calculation that the player can do. Even if all of those things are true, that's still not worse than only having an attack power stat that grows quadratically.

Some players enjoy calculations. Calculating the *most optimal* stat build engages players' senses of accomplishment and mastery, even if the puzzle is easy enough to be solved by elementary schoolers. In fact, if you're making an RPG that's designed to appeal to elementary schoolers, you might consider including a lot of simple calculations like that so that they can have optimization puzzles to solve that are on their own level.

### Most calculations aren't simple

In modern games, you very rarely have a binary choice between x points of "attack power" and the same points of "crit chance." The most common way is that players pick items as complete packages. Players can't pick and choose individual points - they can take the gloves with +60 crit and +20 damage to pair with the chestplate of +100 damage and +40 crit. Finding the exact combination of items which gets them closest to the *optimal* ratio of crit to damage is an NP Complete problem \- though often presented at a small enough scale that players can solve it (or look up the answer in a guide).

### Sometimes, it's not a calculation at all

Sometimes, the difference between a sword that gives more crit and a sword that gives more damage is so complicated that it can't fully be *solved*, even by the best players or modern AIs.

Consider a roguelite game, where players are frequently resetting their build from scratch, but where they must replay the early levels of their build in order to do so.

Suppose that the player starts with has 20 damage and no crit chance, and crits deal double damage. Early on, they are presented with a choice of either +20 damage or +25 crit chance. This might seem like a no-brainer - a choice between either +100% DPS or +25% DPS - but if damage grows by +10/level while critical chance has no automatic scaling, then the two choices become incomparable.

The +damage option would serve weaker players who are struggling with the early stages of the game, while the +crit option would serve more experienced players who are confident that they can reach the stage of the game where the crit will pay off.

This sort of trade-off can increase both the replayability and the approachability of the game overall (*both important considerations for a roguelite!*): beginners who choose the +damage option will progress further into the game than if only the +crit option were offered, which makes the game seem more approachable to them, while players who choose the +crit option will be effectively playing the early levels of the game on a higher difficulty level, commensurate with their greater skill and make it take longer for them to get bored of it.

## The role of randomness

Critical hits being a random element that inhibits skill is another common objection. After all, in a good game, the best player should win every time, right?

### No, the best player shouldn't necessarily win every time, actually

For a competitive game to succeed, it needs to be fun to lose as well as to win. Games which are only fun if you're already winning, it will have a hard time retaining new players, who lack the skill to win consistently.

One of the easiest ways to make losing fun is to make losing feel like winning: If games are played best-3-of-5, with enough randomness in the game that a rookie can hope to win at least one round, then the impact of their overall defeat is blunted because they got to experience victory while losing.

This is (I think) why Magic: the Gathering requires that players build 60-card decks even though in most games, they will only see about 20 cards from them - but also treats best-of-three as its premier competitive format. They could make the game more consistent by allowing 40-card decks (outside of limited) and then not need as many games to decide winners, but doing so would make losing less fun.

### If it averages out, chunkiness is exciting

Even if the game is best-of-one and competitive, there's still sometimes some merit to including some RNG in combat.

A critical hit is a moment in the game, which can be emphasized in the game's sensation - such as by screen shake, popping out larger damage text, playing a more impactful sound for that attack, and sometimes even having a more dramatic attack animation entirely. These sorts of things can create break up the monotony and make combat feel more engaging, well in excess of the actual mechanical impact of critical hits on the numbers.

## Crits aren't for every game

There are situations where the cons outweigh the benefits and neither of the arguments above apply. For a highly competitive game where fights are often determined by thin margins and where the predictability of the game is an important part of its skill (like fighting games), crits would do more harm than good. A competitive game with long match-times which are played best-of-one might suffer from including them. Even if crits average out enough that over the course of a long match, the winner is still almost always the player who played better, crits can make the match *feel* less legitimate.

Also, not every game needs or wants the effects that crits have on combat pacing. Games where skill already creates variance even in the resolution of an attack (like headshots in first-person shooters), wouldn't benefit from adding crits. Games where individual attacks are so common that emphasizing crits would be meaningless noise to the player (like Starcraft and other RTS games) can't use them to create pacing. Indie game which can't afford the level of sensory polish needed to take advantage of crits would not benefit from including them.

In the end, crits, and crit chance/"yellow attack power" is just another tool in the designer's kit for building different experiences. Sometimes it will be the right tool, and sometimes it won't.
> 10 votes

# Answer
Critical hits are much more than just flat additional damage. If the game supports different careers, some of them might offer additional traits that interact with critical hits (e.g. your critical hits now add burn damage, you heal X% on dealing critical damage, ...), opening the door to all new kinds of strategies.
Some games also have an opponent type, that is simply immune to critical hits. So you could be a crit monster obliterating everything, but still struggle against those opponents, which encourages you not to put all your skill points on one lane.
> 6 votes

# Answer
Some game design goals you can fulfill by adding critical chances are:

* Breaking situation where the game stalls. You might have a situation where two combatants fight each other who both have high defense and low damage. So they can't cause serious damage to each other. Such a combat can take forever. But a "Critical hit" mechanic might allow those combatants to occasionally overcome each others defense, allowing such a combat to resolve before the player becomes bored.
* Using the skinner box effect to generate positive emotions in the player when their character causes critical hits. Psychological research has shown that a randomly occuring positive event has a stronger reward effect than a reliably occuring one. A rarely occurring critical hit generates an "ooh, nice!" emotional response in the player that increases the enjoyment of the game.
* Generating interesting situations when the enemies land critical hits. A random critical hit might turn an otherwise boring combat encounter into an exciting one. When the combat system is relatively predictable, then the player will in most cases know whether they will win or lose a combat encounter. That isn't a lot of fun. But a random critical hit by an enemy might suddenly put the player into a situation that is far more perilous than they expected from that encounter and generate a moment of excitement. But this is a double-edged sword, because when you apply this mechanic carelessly, then it can just as well turn a combat encounter that is already challenging into an unfair or even impossible one. Which can be a really frustrating experience for the player ("I just lost because the random number god hates me!").
> 3 votes

# Answer
I wanted to offer some things critical hits may not do inherently, but games can and do use critical hits as a vehicle to do, which they are inherently fairly well-suited for. Crits may not be the only ways to do these, but they work (and have precedent, I guess).

# Case Study 1: Pokemon

In pokemon, a crit does 1.5x damage--but it also ignores debuffs to your own attack and buffs to the enemy's defence.
The general idea here is likely to reduce the benefits of stall tactics.
If you super-debuff your enemies' attack, and super-buff your own defence, you haven't won yet, because there's still a risk they will get crits, which can chip away at and potentially kill you. You've only half-won, and you still need a good offensive plan to pair with this, which I think is what Nintendo wants to be the case.
(There are also moves that are guaranteed or more likely to crit, which thereby serve as counters to defensive buffing.)
This mechanic doesn't *have* to be implemented as a random chance, but implementing it as a random chance has some nice features:

* The alternative would be nerfing defensive buffs directly, which might be tricky or disadvantageous to do, or might feel bad, or might hurt non-stall-based defensive tactics.
* The randomness means that e.g. a combination of defensive buffs and healing will not be fully reliable--both the enemy pokemon getting a crit on the same turn might 100-\>0 one of your pokemon. This lack of reliability reduces the viability of stall as a go-to strategy--you can choose a tactic that *benefits* from defensive buffs, but not something that *relies* on them.

# Case Study 2: League of Legends

In League of Legends, there are a bunch of stats, and you can buy items to buff those stats.
Let's compare an AD (attack damage) caster, and an autoattacker. We'll assume an item increases your damage by 100%, and you have 4 item slots.
(This is all massively oversimplified, and the math is fudged.)

* AD caster: buys 4 +AD items, does +4\*100% damage = 5x damage.
* Autoattacker: Buys a +AD item, a +attack speed item, a +crit chance item, and a +crit damage item. Does 2x damage * 2x speed * 2x crit chance * 2x crit damage = 16x damage.

(Basically, critical-based damage increases provide more things that boost attack that multiply with each other, which can be useful as a balancing lever. It's not easy to describe "oh, this item increases your attack damage by 100%, which is multiplicative with other percent-attack-damage-boosting items, as long as you have four or fewer total.")
(Side note: also, the multiplicative effect goes both ways--+crit chance and +crit damage are much less useful alone then together. Choosing to go for a crit-based build (a) locks you into this path, and (b) makes you weaker earlier and stronger later. In LoL, I think this is intended, and is part of what term "AD carry" is generally understood to imply as a role.)
> 3 votes

# Answer
It's only useless if you design it that way.

A critical strike mechanic gives you (the developer) additional knobs to use to tune the combat experience. Lets say you have two characters with different gear/builds. One focuses on crits and the other on base damage. Even when their overall stats generate the same average damage per second, you can give those two players very different gameplay experiences. Throw in an enemy type that is resistant or immune to crits, and the base damage build has an advantage. Or, use an enemy type whose armor reduces incoming damage by a flat amount (not a percent) to give the crit damage build an advantage. Game mechanics that reflect damage can turn crit-heavy builds into a high risk/high reward playstyle option. You sometimes end fights so fast that you don't take any damage at all, but sometimes those crits get reflected back at you and leave you in an extremely vulnerable position. When *enemies* can crit, players get those same knobs as well. Choosing the wrong armor or defensive abilities for an encounter becomes a lot more punishing.

Depending on the type of game you're making, critical hits can be (at least partially) a reward for skill or strategy. Perhaps a critical hit can only occur when striking an enemy's vulnerable spot, when attacking with the right timing, when successfully executing combos, etc. New players would get more benefit from a more-forgiving flat damage build, and experienced players would be better able to take advantage of critical hits. You can even limit critical hits to certain weapon type + monster type combinations, giving the player an advantage only if they bring the right gear to an encounter. Another option is to use critical hits to encourage teamwork by making them the result of two players using complementary abilities.

At a higher level, saying that increased crit chance is the same as increased base damage is only true in the statistical sense. That is, the overall damage per second numbers would be the same if you averaged them out over a long period of time. In most games, battles don't last anywhere near long enough for the two trend lines to converge like that. Defeating an enemy in 4 turns with a crit vs. 6 turns without a crit makes the battle feel completely different and far less predictable. Fighting against a group exaggerates this difference even more. Let's say I'm fighting against two enemies. The base damage build takes 5 turns to kill each enemy, and the crit build takes one enemy down in 2 turns with a crit but then takes 8 to whittle down the other one. Both builds took 10 turns to do the same amount of damage. The base damage build was attacked 15 times in the process, while the crit build was attacked only 12 times (or possibly 18 times, depending on which enemy was killed first). Those are all the same *on average*, but the fights are short enough that they don't feel remotely the same. The base damage build is more predictable, provided I can withstand the additional attacks. The crit damage build enables me to quickly take out enemies that are beyond what I could normally survive, but I have to be prepared to flee if the dice aren't falling in my favor. Two completely different experiences and playstyles, even though the high-level math looks the same.
> 3 votes

# Answer
This answer is in addition to the psychology (crits feel good) and meta-game (crit as a stat is an additional lever to play with when determining the optimal build) aspects that are covered by other answers.

When a game includes the ability to heal, in addition to just dealing damage, the timing of when damage arrives, along with the size of that damage, has an impact on how survivable the damage is.

Generally, big spikes of damage are harder to heal through, so even if over time the damage is mathematically equivalent, having X DPS and Y crit chance will make it easier to kill the opponent than simply having X * (1 + Y) DPS and no crit chance.

As an extreme example, consider an attacker who deals exactly 10 damage with every attack, attacking once per second, and a defender who has 20 health and is able to heal 10 health every second. The attacker will never make any progress, and the defender will never die. Now, consider an attacker who deals 9 damage with every attack, but has a 10% chance to do 18 damage, attacking the same defender. While the defender will slowly heal back up after a crit, getting hit with a second crit within 8 seconds (which isn't particularly unlikely) would leave the defender dead.

When the game incorporates other mechanics related to timing like healing abilities with different cast times, this can add additional layers beyond just allowing crit strings to affect/determine who wins. For example, if the healer's target gets hit with a big crit while the healer is in the process of using a heal with a long cast time, the healer needs to decide whether to continue with the existing cast, or abandon it to cast a heal that will take effect sooner instead. This can have a positive impact on healing-centric game play, by making healing a more dynamic experience where choices matter. A similar situation arises for a single player who, after losing a big chunk of health to a crit must decide between continuing to attack, or switching to healing.
> 2 votes

# Answer
The nature of critical hits as an occasional multiplier on damage has been covered by other answers.

But critical hits do not need to be that, or *just* that. You can add additional mechanics to them, such as "crits set enemy on fire", or perhaps different weapons having different critical strike rates or multipliers for each body part.

In this generalised form, form they are often called "lucky hits" or something to that effect, and on games with lots of opportunities for build combinations, they can become cornerstones of builds that count on indirect effects to succeed.
> 2 votes

# Answer
> but why would players choose random chance rather than extra damage if the end result is the same?

Let me demonstrate the answer to you with Math. Imagine you have 40m of fence, and you want to maximize the area it surrounds. It must be a rectangle btw.

```
side lengths | area
1,1,19,19    | 1m * 19m = 19m²
3,3,17,17    | 3m * 17m = 51m²
5,5,15,15    | 5m * 15m = 75m²
8,8,12,12    | 8m * 12m = 96m²
10,10,10,10  | 10m * 10m = 100m²

```

So the quadratic multiplication yields the best result. If you have 'n' factors that influence the outcome, it's always best to increase all of them, but in a way where there is some kind of exponential equilibrium.

In games where you have 'n' stats that increase damage (attack speed, critical strike chance, outright bonus damage), it's best to increase all of them (taking weighting into regard). Critical strike is just *one* of multiple factors that need to be increased for optimization.

So players are basically *forced* to go for critical strike, simply because it's one factor of many.

> How do you make critical attacks not useless in video games?

This is an excellent question, because in many games critical strikes are just another fancy way of increasing the damage/heal output of players (as you said). If the critical strike chance is 10%, and the damage multiplier is 200%, it means you make 10% more overall damage. Some games add some special effect, like gaining some buff if dealing a critical strike. Said games often have a high ratio of attack rates and critical strike chances though, meaning its occurrence is part of the basic attack rotation. Some games give you even 80%+ critical strike chance at some point, rendering its concept into absurdity.

So what would be a good way to implement critical strikes:

1. Make them not chance based, but situation based. Both parties should affect its occurrence. An easy example is flanking - aka striking an enemy from behind or the side. Or in shooter games, hitting the head or the back.
2. Stealth attacks, and maybe skills that manually cause a critical strike. Or as Fallout 4 did, having critical strikes being manually triggered, whereas the "critical meter" fills up by just attacking.
3. If it's supposed to be a random chance, it should occur rarely enough, so that it is significant. That means maybe 1 occurrence every ~20-40 seconds. I made a formula in which "critical strike" is an attribute that influences both, the chance and modifier at once. First it raises the chance quickly from 0% to 5%, then it smoothly converges to 10%, while the modifier is first increased very little, and then more rapidly. This ends up in the total extra output being linear, meaning 10% of critical gives 10% bonus damage, 50% gives 50% bonus damage. And it will make critical strikes more impactful as that stat increases. Otherwise you have the problem that it's up to the player to do the x\*y Math (that's the case for most games).
4. Make critical strikes occur rarely, but it causes bonus flat damage, meaning the attack is independent, and the occurrence can be based on time (like procs per minute).

By the very nature of what critical strikes are supposed to be, they should be rare and something a player would notice when it occurs.
> 0 votes

---
Tags: game-design
---


# Question
Title: Why objects are falling equally in Unity
I have different game objects with rigid bodies, each having its own mass and drag. However, when these objects fall, they appear to fall at equal speeds. This raises the question of why they do not reach the ground at different times. You can watch a video explanation of this phenomenon here.

# Answer
> 9 votes
Check out the implementation of linearDamping in PhysX here (what Unity calls Linear Drag in the `Rigidbody` built on top of PhysX). It's equivalent to:

```
velocity = velocity * (1f - linearDamping * Time.deltaTime);

```

This is not a physically accurate model of air resistance - it's just a cheap calculation to let excess velocity decay away, damping down jitters in the physics system.

You'll notice that it doesn't include mass. Neither does acceleration due to gravity (a heavy object feels a greater force of gravitational attraction, but also requires more force to accelerate, and these two effects exactly cancel each other out).

So that means in your example, the only difference between these three objects is that one has a damping of 0.3 and the others have a damping of 0.1.

As I show in this spreadsheet sim, that's only enough to delay the impact of the first object by 0.04 seconds over a 5 meter drop - that's only a little more than a single frame at 30 fps - so it's not surprising that there's no perceptible difference here.

Real air resistance is a force proportional to cross sectional area and speed (or proportional to the *square* of speed at high speeds), and heavy objects accelerate less for the same force, so that's where the intuitive idea that the heavy object should fall faster comes from. But this is much more expensive to calculate, even approximately, and different games will have different needs in terms of speed/realism trade-offs, or different types of fluid interactions they need to model. So for efficiency, physics engines don't make any attempt to model this messy phenomenon by default — they just give you a cheap way to make things slow down and stop jittering.

But that doesn't stop you from writing your own air resistance calculation - to whatever degree of accuracy is appropriate for your game's needs - and injecting that into the physics tick using `FixedUpdate`, something like this:

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

    public float dragCoefficient;

    // You could calculate this automatically from the colliders / bounds,
    // or even recompute it for each direction of travel.
    // Tumbling bodies are left as an exercise for the reader.
    public float crossSectionalArea;

    [SerializeField, HideInInspector]
    Rigidbody _body;

    void OnValidate() {
        if (_body == null) TryGetComponent(out _body);
    }

    void FixedUpdate() {
        Vector3 vel = _body.velocity;
        float speed = vel.magnitude;

        // Assume high speed flow, drag proportional to square of speed.
        Vector3 drag = -vel * speed * dragCoefficient * crossSectionalArea;

        // How much force would be required to stop the object entirely?
        float limit = _body.mass * speed / Time.deltaTime;

        // Ensure we never accelerate more than that (no reversing direction).
        drag = Vector3.ClampMagnitude(drag, limit);

        // Apply the clamped drag.
        _body.AddForce(drag);
    }
}

```

---
Tags: unity, physics, rigidbody, gravity
---


# Question
Title: How do you handle edges on textures that join adjacent textures?
This question explains how to use borders to avoid texture bleeding. The following image is taken from the excellent answer to that question.

But the problem I don't understand is, imagine you have an 800x800 texture, and to alleviate the colour bleeding you use a one pixel border to the right. Now when the sampler samples from the last pixel it can blend between the second last pixel and the last pixel (the padding border you put).

However now imagine at a lower mip level. Now picture the image (or atlas, or whatever you want to imagine), instead of being 800 pixels across, is only 4 pixels across. Now the last pixel is located at U value is located at the centre of the fourth pixel, 0.5 + 0.125 + (0.125 /2). Anyway, U value after that (the centre of the fourth pixel) is going to want to be blended with an equally large pixel to the right. That one or two pixel border you put or however big really to the right isn't going to do anything because it was only 2 pixels in an 800 pixel image, and meanwhile in the 4x4 mipmap each pixel covers the equivalent of 200 pixels in the original image.

Please explain.

# Answer
> 6 votes
You've accurately identified the reason why it's better to store textures like this in a texture array / array texture, where supported, rather than a texture atlas.

In a texture array, each image wraps and mips independently, so samples near the border of one never end up pulling in data from a different image, and you don't need any borders or padding at all.

When you don't have texture arrays available, or you need to pack images of different dimensions, then about the best you can do is add more padding. Take the deepest mip level you want to be able to address, subtract one, raise two to the resulting power, and that's how much padding you need to ensure that even at the deepest mip, your samples never blend between two distinct images.

That can get excessive, so you can also accept some bleeding at deep mips, on the assumption that these objects must be very far or viewed very obliquely for that mip to even be sampled, and so the bleeding will likely be less noticeable.

---
Tags: textures, texture-atlas, filtering
---


# Question
Title: How do I render a pixel art game in a modern (scalable, smooth, crisp, hdpi friendly) way with Godot?
In modern pixel art games, one will usually find the following features:

* dpi agnostic: Having an HDPI screen does not mean the game is tiny.
* "large" pixels: Game-pixels are big, made up of multiple screen-pixels.
* "crisp" pixels: Game-pixels don't smoosh. They are always the same size on the screen.
* smooth camera movement: The camera still moves in smooth screen-pixel increments. It doesn't chunk up the way game-pixels do

---

**Here's whate I've tried so far:**

If I make the *viewport to match game-pixels*, it can be scaled up (https://www.youtube.com/watch?v=Nsj5SGEUZhU) using advanced settings. Specifically `Display > Window > window height/width override` and `Rendering > 2D > Snap`. The issue with this is that camera/screen movement will also snap to the game-pixel size, which looks relatively jerky compared to modern pixel games. It's not smooth.

Alternatively, if I make *viewport match target window size*, I can use `Display > Window > Stretch > Scale` to make the game look right. But then Margin Containers end up targeting a screen thats scaled too large.

On top of this, I'm on an HDPI screen and everything is tiny by default. To make it work on my end, I have viewport settings at 2160 x 1440, but this is a ludicrous default for at pixel art game. Ideally, I could target a general screen size in mm, and have it figure out how to scale game-pixels to screen-pixels (2x2, 3x3, 4x4, etc) such that the window is roughly in that size range.

I recognize that this is a lot of different questions in one, but none of these things seem to be solvable in a vacuum. The results are only correct if everything works together.

# Answer
I believe this tutorial covers most of what you want: How to make a silky smooth camera for pixelart games in Godot.

The idea is to have a (Sub)Viewport where you render your game world. And this Viewport will actually be larger by one world pixel margin, so you can move the image via code to have a smooth camera.

The Viewport would be in a `ViewportContainer` so you can scale however you want (using a `ViewportTexture` on a `TextureRect` might give more flexibility if the `ViewportContainer` is not quite right)

And as a bonus - optionally - you can have UI outside of the Viewport, so fonts can render with full quality.

---

*No, it cannot target a screen size defined in millimeters. Godot does not have such feature.*
> 2 votes

---
Tags: godot, viewport, pixel-art
---


title: How to use gather offsets

text:
# Question
Title: How to use gather offsets
I have this situation where I have parts of the same scene in each 4 half squares of a rendertarget rendered with the same view projection matrices. In my deferred pipeline I would like to sample with gatherRed the four pixels representing the same screen space location for each quarter. So there is this offset possibility but it is int2 not float2 so I don't get how to use these offsets. Is it pixel decal or something else? Obviously doing (screen = W1920-H1080):

```
 GatherRed(sPoint, input.tex.xy, int2(0,0), int2(960,0), int2(0,540), int2(960,540));

```

does not give me the expected result. Is it limited to closest pixels?

currently I'm doing 4 sampling that work : SampleLevel(sPoint, input.tex.xy + float(dx,dy)) where dx,dy are 0 or 0.5 or both.

# Answer
> 0 votes
This seems to be covered in the documentation for Gather.

The offset uses only the low 6 bits as a signed integer where 1 = 1 texel width, so it has a range of -32 to +31 texels on Shader Model 5+ (-8 to +7 on older models).

These functions are not appropriate for what you are trying to do with them. You should use four conventional texture samples, or if you only need one channel per view, stack all four into the same texture area on different colour channels.

---
Tags: textures, directx11, hlsl
---


title: Game numbers and meaning

text:
# Question
Title: Game numbers and meaning
Each game has it's own "maximum number". One question that comes into mind every time I play a(nother) game is ***how are these maximums determined*** and ***how do these affect gameplay***? To explain, here's some rough references from games and anime.

# Numbers on Levels

One instance is the "level cap". In some games, it's 100 - which I can easily understand to be like percentage. But other games have weird level caps. I remember Fallout (3?) having a level cap of 30. The anime Log Horizon has a level cap of 90 (and increased to 100 after "the apocalypse"). Ragnarok Online once had 99, then increased (to 120?) for Renewal servers.

# Numbers on Attributes

Another instance is attributes (Strength, Agility, Intelligence etc.). Ragnarok Online starts you at 5 a piece and level up in small increments. Skyrim starts you at ~15-25 depending on race. In the anime Sword Art Online, they have this scale of 1000.

# Numbers on Damage

Then there's attack power. In Yu-Gi-Oh card game, the attack power comes in the thousands. MTG on the other hand is as small as 0-10, with the 1-6 range as very common numbers. DotA damage starts \<100 and reach as high as 2000 on critical strikes.

# Exceeding caps

Then there's this Skyrim mod that makes you level up in excess of the cap. Why would they make something like that? Is there something beyond the level cap that the regular game doesn't address? Is the system not enough?

In summary, here's my questions:

* How are these scales and maximums determined? Is there some magical formula or a generic guideline (like from a game)?
* How does these number affect overall gameplay? I mean I can have a 100-scale that does the same thing as 1000-scale or 10000-scale. But why do they opt for these numbers? Why go for smaller ones or the insanely huge ones?
* Why is there a level cap? And what does it mean when the level cap is broken or increased?

# Answer
> 3 votes
I'm going through your questions one by one.

> How are these scales and maximums determined? Is there some magical formula or a generic guideline (like from a game)?

No, there is no magic formula whatsoever. The only rule of thumb is that people usually like round numbers. That is why there are so many games with max lvl 100 (or 99) and not max lvl 639. Beyond that, how the maximum is decided depends on several gameplay elements, such as how the character power progresses, the half life of your players, playtesting sessions, etc.

To elaborate a little bit, usually you plan how long you expect players to play to reach cap level. It shouldn't be the same say for a casual 1 player RPG than for a hardcore MMORPG, so the caps and how hard it is to reach it has to be adjusted accordingly.

> How does these number affect overall gameplay? I mean I can have a 100-scale that does the same thing as 1000-scale or 10000-scale. But why do they opt for these numbers? Why go for smaller ones or the insanely huge ones?

It affects the progression of the game. You can multiply damage by 100 and enemy life by 100 and get the same power ratio, but the progression would be different.

It is not the same if you start a game dealing 10 damage and at endgame you deal 100, than if you deal 100.000. On the second case your progression is much more dramatic than in the first. Again, this depends on what kind of experience you want to provide with your game. You want advance players to wipe the floor with newbies assess or to have a smaller, more reasonable gap? Do you want players feel like going from crap to god or a more flat progression?

> Why is there a level cap? And what does it mean when the level cap is broken or increased?

Probably the first reason in computer games is because there is a limit on what you can represent in a computer. This is particularly poignant in early RPGs where some stats were represented as bytes, and thus their maximum value was 255 (never though this maximum value was odd?). But there are also gameplay implications. For one, many people like progression towards a goal. That is why reaching a level cap is satisfying. The second, more obvious, is because you want to limit player power. You don't want players to get infinitely powerful in an online game to promote competition, and even in single player games, you want player to be confronted with challenging enemy encounters (and dynamic enemy leveling not always cut it).

**Final notes**

Actually your question is a little bit skewed because it assumes that leveling systems with caps is the most common practice. However there are lots of alternatives, including limitless leveling system, or progression systems that don't rely on levels at all. For a more informed reading, I would recommend the Wikipedia article on Experience points.

# Answer
> 2 votes
> How are these scales and maximums determined?

Mostly through painstaking developer & QA team iteration, also known as Blood, Sweat & Tears. Game balance grows geometrically more complex with each additional gameplay factor. See Combinatorial Game Theory. Custom formulae may also be used to ease the problem, but ultimately we rely on an iterative approach.

> How does these number affect overall gameplay? I mean I can have a 100-scale that does the same thing as 1000-scale or 10000-scale. But why do they opt for these numbers? Why go for smaller ones or the insanely huge ones?

Because there needs to be a small, finite scale on which your (finite) team of devs / QAs can balance the game. Precisely balancing 1000 discrete levels is over 10 times more difficult than precisely balancing 100 discrete levels. All of this adds up to... blood, sweat & tears.

> Why is there a level cap?

Cost-benefit analysis: Because if there weren't a cap, developers could sit there bleeding, sweating and crying indefinitely just in order to balance levels, which is hardly cost effective since most games are paid for upfront, one-off (if that, in view of piracy)... unless the developers have promised and are being paid for X new balanced levels per month. Balancing takes time.

> And what does it mean when the level cap is broken or increased?

It is like voiding the warranty on your phone by jailbreaking it. Yes you still have that brand of phone, but you can no longer rely on the "safety" that the developers provided in the original, unmodified product. Hence, beyond the level limit, strange, unbalanced things will happen. See Fate, by the designer of Torchlight, where the character level cap is extremely high (199) and the dungeon levels are practically unbounded. Balance quickly goes out the window after the usual dungeon range (about 1-30 or so, within a range of 2^31-1 or 2 billion levels).

**The Crux of the Matter**

Producing game balance procedurally, i.e. without human QA, is a very difficult problem indeed, since gameplay itself is human-subjective... though I have no doubt that some innovators out there are at least attempting to develop such a system. So for now we do it manually, which takes time.

# Answer
> 1 votes
The amount of levels is often designed to meet the amount of creatures, areas , techniques / powers and other types of game content. Levels are a way to classify content and reward the player. You may need more when you have more content to offer; levels reflect the time the player spent in the game and are used to classify content as appropriate to players with a certain amount of experience (not xp) in that game.

If you have a very large amount of content, you would likely want to offer more levels. If you are following a certain RPG rule-book like D&D then it may not be so. Levels are also used to reward the player and keep them excited about the game. A lot of players enjoy leveling up and powering up their characters so if your target audience requires this stimuli, adding a lot of levels may seem like a good idea.

All and all, it's about the ux. Going to either extreme would interfere with the gameplay experience. Having only 2 levels, would make the players feel like they have achieved nothing for too long awhile and having 1000 levels, would make content too specific possibly, and also constantly disrupt the play when the character's attributes and powers need to be upgraded.

In general I advise not to think about levels but focus on content, character powers and such. Later on classifying the content and powers as appropriate for certain levels.

# Answer
> 1 votes
Levels can be summed up as a rate of progress.

To find your level cap or whatever break your game into 3 parts, the beginning, middle and end.

Find out how much attributes and skills you want in total at the end. Then balance out the middle so that everything works fine and then look at the numbers of encounters and their challenge to find the rate of progress. You also want the first few levels to be rewarding at the start so tweak until it works.

Damage and health numbers are completely arbitrary. It is only a question of precision. Games with very small numbers have bigger impact because of the scale of the damage. For example in a game with 34HP, 12 damage is immense but its the same as 3441HP and 1249 Damage the only thing you get is more number precision that doesn't go into rounding problems.

Ultimately it is about relationships between things and scale then anything else.

# Answer
> 0 votes
The other answers are quite good, but I'd like to add some additional thoughts.

> Why is there a level cap? And what does it mean when the level cap is broken or increased?

## UI

These numbers are presented somewhere in the UI and you have to make space for them. If they can get indefinelty large, they will break your UI at some point. Where a two digit 99 fits nicely, a 100 might go out of border. Ofcourse you could design the UI with three digits in mind but again at lvl 1000 there would be one digit to much.

## Skillpoints

In a lot of games with levels (and level caps) you get one form or another of "skillpoints" when you level up. Points you can spend to increase stats, gains skills, etc. For example the perks in Skyrim When designing a game you can only create so much skills. Lets say you create 1000 distinct skills to spend points on. When comparing different characters, at first you will see them getting more distinct and unique with every level as everyone will spend their point on different skills (with good balance). However at some point all characters would become again very same. If your 1000 skills contain 200 that are interesting for "melee" characters, at level 200 EVERY melee character has the same skills chosen with very little variance. and at level 1000 literally every character would have the same skills, losing all uniqueness.

Of course there is no exact formular for this but as upper edge you could make some characters for each archetype at your max level and see if you are able to make them sufficently distinct. If you feel like you have to choose always the same "best-in-slot" skills and don't have any left for "interesting-but-not-strong" skills, consider raising the level cap. If you feel like there is nothing much else left to pick, consider lowering it.

---
Tags: game-design, levels
---