# Question
Title: Line strokes also adding borders to other shapes?
When you run the project, you can see that the first circles have a black border around them. When I remove the `Game.drawLines()`, the circles don't have the border around them anymore. Any help is appreciated!

# Answer
> 1 votes
> When I remove the `Game.drawLines()`, the circles don't have the border around them anymore.

Well, let's do the obvious thing and look at that function then.

```
  static drawLines() {
    ctx.strokeStyle = "#000000";
    for(let i = 0; i < 5; i++) {
      ctx.moveTo(0, i * (canvas.width / 50) + 50);
      ctx.lineTo(canvas.width, i * (canvas.width / 50) + 50);
      ctx.stroke();
    }
  }

```

Now let's contrast it against your other drawing function:

```
  static drawNotes() {
    for(let i of notes) {
      ctx.fillStyle = i.selected ? "#E95500" : "#000000";
      ctx.globalAlpha = i.opacity;
      ctx.beginPath();
      ctx.arc(i.x + i.xOffset, i.y + i.yOffset, i.radius, 0, Math.PI * 2);
      ctx.fill();
      ctx.closePath();
    }
  }

```

What's missing? In the `drawNotes` function, we `beginPath()` before drawing each disc, resetting the stored path so each one is drawn in isolation.

But in `drawLines`, we're missing this. So whatever path we drew most recently is *still stored inside the context*, just waiting to be stroked when we call `ctx.stroke()`.

It looks like you were trying to use `ctx.closePath()` to "end" the path, but that's not what this function does. It "closes" the path in the sense that it connects the endpoint back to the start point, so if you stroke it you'll see a closed loop. But the shape isn't "dropped" after you close it, it's still part of the current drawing path until you `beginPath()` again to clear it out and start a fresh path to stroke/fill/etc.

So, `beginPath()` before you draw your lines, or after you draw your notes, to ensure drawing state from one function doesn't leak over into the other.

---
Tags: javascript, html-canvas
---


# Question
Title: Rotating towards a target in top-down 2D game
I use the following code to rotate a transform towards another. And it's working fine. However, I want to lerp it over time period.

```
public void RotateToward(Transform target)
{
  Vector3 from = transform.up;
  Vector3 to = target.position - transform.position;

  float angle = Vector3.SignedAngle(from, to, transform.forward);
  transform.Rotate(0.0f, 0.0f, angle);
}

```

An example would greatly help.

# Answer
If you want to limit the speed with which your gameObject is allowed to rotate, then the Methods `Vector3.RotateTowards` or `Quaternion.RotateTowards` can help you. They can be used to turn an object towards the desired direction, but put a limit on how far the object is allowed to turn by specifying a `maxDegreeDelta` parameter.

```
Vector3 current = transform.forward;
Vector3 to = target.position - transform.position;
transform.forward = Vector3.RotateTowards(current, to, turnSpeed * Time.deltaTime)

```

The variable `turnSpeed` should be a public inspector variable. The unit is degree per second.
> 1 votes

# Answer
Usually for rotations you use slerp. https://docs.unity3d.com/ScriptReference/Vector3.Slerp.html

A basic rotation script is something along the lines:

```
    private float _timeRotation = 0f;
    private float _speed = 1f;
    private Transform _fromPos;
    private Transform _toPos;
    private bool _isRotating = false;

    void Update()
    {
        if (_isRotating)
            DoRotation();
    }

    public void Rotate(Transform from, Transform to)
    {
        _timeRotation = 0f;
        _isRotating = true;
        _fromPos = from;
        _toPos = to;
    }

    void DoRotation()
    {
        _timeRotation = _timeRotation + Time.deltaTime * _speed;
        transform.rotation = Quaternion.Slerp(_fromPos.rotation, _toPos.rotation, _timeRotation);
        if (_timeRotation >= 1f)
            _isRotating = false;
    }

```
> 0 votes

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


# Question
Title: Should recoil be an animation or script?
Should recoil for a rapid fire gun be be done through an animation or a script? I want the recoil to increase as I continuously fire, like a lot of FPS games do.

I was initially considering achieving this through a script in unity that rotates the gun slightly each time I fire, but I realized that since I plan to have most rapid fire guns be 2 handed weapons, at some point, the left hand won't be on the weapon.

However, since I also want the recoil to increase as I fire, I'm not sure how I can achieve this in an animation.

How is recoil typically done? Input on this would be very much appreciated.

# Answer
> 1 votes
This should be done via script.

How much recoil? Let's say 10 degrees at a rate of 5 m/s.

Now you level up your handling, and recoil is reduced by 10%. So now our recoil is 9 (10 * 0.9) degrees at a rate of 4.5 (5 * 0.9) m/s. This is a much easier to do and change via a script than it is via animation.

Please see Phillip's answer as well. He goes into more detail, and talks about using the animation system as well. (Although I still think doing this via scripting is the best approach.)

# Answer
> 1 votes
First of all, I would really recommend you to separate the projectiles being spawned from the gun weapon model and its animation. Attaching the spawn point to the gun model just causes unnecessary problems and unexpected behavior (like bullets flying into unexpected direction because you are shooting while still blending to the weapon switching animation). Rather attach the spawn point to the root of the character object, so you have better control over where the bullets spawn. The less surprises, the better. And now your animators are free to animate the gun and the character's hands the way they want without having to worry about the animation exactly matching the bullet spread pattern.

But that still does not mean that the recoil pattern can not be controlled through an animation. The Unity animation system is very versatile. It can do more than just control the bones of character models. It can "animate" (almost) any inspector-visible attribute of any component. So it is perfectly possible to create an "animation" for how the point of aim and random spread of a weapon changes over time while the gun is shooting. This allows you to edit the spread patterns of guns by editing curves in the Unity animation curve editor, which can be a very designer-friendly and powerful tool.

A code-based solution might be less intuitive for a designer, but more intuitive to create for a programmer. You might also be more comfortable with designing your recoil patterns as mathematical functions rather than by dragging around curves until they feel right. So that's also an option.

In software development, there is never just one solution for a problem. There is also usually not a *best* solution. Only the solution which is best *for you*.

# Answer
> 0 votes
# Both - Consider Procedural Animation

For example, you could create an animation that linearly rotates the weapon a specific angle (moving both hands and whatever else you need with it), but not "play" it in its entirety but set at which point in the animation you are via script. Say you have a max. rotation of 90 degrees, you could make the animation "take" 90 seconds and just assign myAnimation.time = kickbackInDegrees. The same can be done with a second animation for left/right kick.

This approach works well for complex and/or cumulative inputs like your cumulative recoil (multiple shots in rapid succession kick more than a single shot).

---
Tags: unity, animation, blender, workflow
---


# Question
Title: What should I do about legal considerations for an indie game?
Apologies if there's a bit too much background information here, not sure what's relevant but figured I needed to outline the financial situation to differentiate this from other questions whose answers aren't applicable here.

I'm making an indie game, to be sold online (ie, to any country that can use PayPal). My current situation is underemployed - unable to find enough work to make ends meet over the last couple of years, I'm now looking to use some of that free time to top up my income by making a little extra money from my hobby. Primarily, I look at is as art rather than a business, but with cash flow and employment prospects limited, I need to make a little money.

My question is what should I do about the legal problems that can arise out of selling a game? I've read up general advice on small businesses, so I should be fine with the usual issues like copyright, limited liability and tax - it's game development specific ones that worry me. I've also checked the licenses of any libraries used thoroughly (it's all open stuff anyhow).

Software patents are currently scaring the hell out of me - they might not be legal in my country, but if I'm going to get any sales at all with my small scale project I'm going to have to cast a broad net. As far as I understand, there are so many and so broad or poorly defined, that I can't in practical terms make a game without violating them in at least some countries. The other thing that bothers me is if there's legal issues I've never heard of and wont hear of until I get a nasty letter threatening to take everything.

I've obviously searched for related questions here and elsewhere, but had no luck - the answers always seem to say either consult a lawyer, or buy expensive legal reference materials - whilst well intentioned, given the financial situation outlined above, well this advice isn't really applicable. I have no money, and the total amount I hope to make from this game is less than one hour of legal consultation. Given the amount of researched involved in patents, and the numerous jurisdictions that my sales might come from - well, I can't think of a way that sufficient help from a lawyer will ever be within my means.

So, given those considerations, can anyone suggest a sensible course of action for such a small scale business that'll prevent me from being shut down, and from losing my creative rights to the game the moment some large company with software patents decides to sue? And further, any other steps I need to take to protect myself against legal problems specific to this industry that general advice sites wouldn't cover?

# Answer
> 22 votes
Don't steal assets or code. For the technologies you are using, make sure you're complying with their terms. Avoid emulating other games. Use an original name and logo. Follow the terms of service on whatever channels you're selling the game through. Incorporate your game company and keep its financial assets separate from your own. Comply with the corporate requirements of the state in which you incorporate. Write your own copy for all marketing materials and in-game materials.

Most importantly, provided you're doing as mentioned so far, don't be paralyzed by fear of legal harassment from a third party. Having limited financial resources is usually a disadvantage, but from a legal perspective, it takes away the incentive to sue you. Lawyers call it "judgment proof," a nicer term for broke. If you start making enough money that someone thinks it worthwhile to bring a nuisance suit, you'll have the money to pay a lawyer to defend it.

# Answer
> 0 votes
Be unique and present your ideas in a way that no one else can, use your own trademark and and make it stand out from everyone else, create and come up with ideas of what you went your assets to be and make sure, these are your assets and no one elses as this could lead to copyright claims and issues a game developer would not want.

---
Tags: legal, game-industry
---


# Question
Title: How can I make some stuff while fading the screen out and then to fade back in?
I want that when it's fading out and when the screen is black then do some stuff and then fade in back.

This is the FadeInOut script :

I have a problem with this script it does fade out and in but if I change the speed from 0.8f to 100f or to 0.01f the speed is almost the same. The fading duration is not changing.

I wanted to make that if I set the speed for example to 7f then the fade out and fade in overall will take 7 seconds. So instead speed(fadeSpeed) to use duration and change something in the script.

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

public class FadeInOut : MonoBehaviour
{
    #region FIELDS
    public GameObject fadeOutUIGameobjectImage;
    public float fadeSpeed = 0.8f;

    private Image fadeOutUIImage;

    public enum FadeDirection
    {
        In, //Alpha = 1
        Out // Alpha = 0
    }
    #endregion

    #region FADE
    public IEnumerator Fade(FadeDirection fadeDirection)
    {
        fadeOutUIGameobjectImage.SetActive(true);

        float alpha = (fadeDirection == FadeDirection.Out) ? 1 : 0;
        float fadeEndValue = (fadeDirection == FadeDirection.Out) ? 0 : 1;
        if (fadeDirection == FadeDirection.Out)
        {
            while (alpha >= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
            fadeOutUIGameobjectImage.SetActive(false);
        }
        else
        {
            fadeOutUIGameobjectImage.SetActive(true);
            while (alpha <= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
        }
    }
    #endregion

    private void SetColorImage(ref float alpha, FadeDirection fadeDirection)
    {
        if (fadeOutUIImage == null)
        {
            fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
        }

        fadeOutUIImage.color = new Color(fadeOutUIImage.color.r, fadeOutUIImage.color.g, fadeOutUIImage.color.b, alpha);
        alpha += Time.deltaTime * (1.0f / fadeSpeed) * ((fadeDirection == FadeDirection.Out) ? -1 : 1);
    }
}

```

The second script is how I'm using the fading now :

The problem in this script is that I want to make some stuff when the fade out is black when it's getting black make some stuff then fade in back. stuff I mean the part of code between the fade out and fade in :

```
StartCoroutine(fadeInOut.Fade(FadeInOut.FadeDirection.Out));

            navi.transform.parent = naviParent.transform;
            navi.transform.localPosition = new Vector3(0, 0, 0);//GameObject.Find("Navi Parent").transform.localPosition;
            navi.transform.localRotation = Quaternion.identity;
            navi.transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);

            if (ikControl.target != null)
                ikControl.target.distance = 0;

            player.transform.LookAt(freeLookCam2.transform);

            freeLookCam2.enabled = true;

            StartCoroutine(fadeInOut.Fade(FadeInOut.FadeDirection.In));

```

And the full part :

```
private void Update()
    {
        ChangeChild();
    }

    public void ChangeChild()
    {
        var dist = Vector3.Distance(transform.position, navi1.transform.position);
        if (dist < 0.1f && childChangedNaviIsHandChild == false)
        {
            childChangedNaviIsHandChild = true;
            ikControl.startMovingNAVI = false;

            StartCoroutine(fadeInOut.Fade(FadeInOut.FadeDirection.Out));

            navi.transform.parent = naviParent.transform;
            navi.transform.localPosition = new Vector3(0, 0, 0);//GameObject.Find("Navi Parent").transform.localPosition;
            navi.transform.localRotation = Quaternion.identity;
            navi.transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);

            if (ikControl.target != null)
                ikControl.target.distance = 0;

            player.transform.LookAt(freeLookCam2.transform);

            freeLookCam2.enabled = true;

            StartCoroutine(fadeInOut.Fade(FadeInOut.FadeDirection.In));
        }

        if(dist < 0.3f && fadeOnce == false)
        {

            fadeOnce = true;
        }

        if (ikControl.startMovingNAVI)
        {
            transform.position = Vector3.MoveTowards(transform.position, navi1.transform.position, 0.5f * Time.deltaTime);
        }
    }

```

# Answer
You are starting one coroutine, then you are doing a bunch of stuff and then you are starting another coroutine - all within the same Update. So all of that will happen immediately. The changes will happen immediately and then two coroutines will run simultaneously - one fading in and one fading out. When you want a 3 step process executed in sequence:

1. Fade to black
2. Do stuff
3. Fade back in

then all these things need to happen within one coroutine. This is how I would write this coroutine:

```
public IEnumerator Fade(float duration)
{
    // 1. fade to black
    fadeOutUIImage.gameObject.SetActive(true);
    for(float timePassed = 0f; timePassed < duration; timePassed += Time.deltaTime) {
        SetImageAlpha(timePassed / duration);
        yield return null;
    }

    // 2. do the stuff
    navi.transform.parent = naviParent.transform;
    navi.transform.localPosition = new Vector3(0, 0, 0);//GameObject.Find("Navi Parent").transform.localPosition;
    navi.transform.localRotation = Quaternion.identity;
    navi.transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);
    if (ikControl.target != null)
        ikControl.target.distance = 0;
    player.transform.LookAt(freeLookCam2.transform);
    freeLookCam2.enabled = true;

    // 3. fade back in
    for(float timePassed = 0f; timePassed < duration; timePassed += Time.deltaTime) {
        SetImageAlpha(1.0f - timePassed / duration);
        yield return null;
    }
    fadeOutUIImage.gameObject.SetActive(false);
}

private void SetImageAlpha(float alpha) {
    fadeOutUIImage.color = new Color(
        fadeOutUIImage.color.r,
        fadeOutUIImage.color.g,
        fadeOutUIImage.color.b,
        alpha
    );
}

```
> 2 votes

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


# Question
Title: How would I optimize that piece of code using Unity?
I'm doing filtering on a depth image and I would like to convert that piece of code into job system of unity, because it's so slow. The image update is called each frame

```
 public unsafe  void DRSFilter( byte *  src, byte * dst, uint data_delta, uint history_scan_depth)
     {
         if (history_scan_depth > history_capacity)
         {
             history_scan_depth = history_capacity;
         }

         for (int i = 0; i < layer_size; i++)
         {
             byte b = src[i];
             bool is_color_pixel = false;
             uint avrg = 0;
             for (int k = 0; k < history_scan_depth; k++)
             {
                 avrg += history[k * layer_size + i];
                 if (history[k * layer_size + i] > 0)
                 {
                     is_color_pixel = true;
                    // break;
                 }
             }
             average[i] = (byte)(avrg / history_scan_depth);

            //if (b > 0 || b == 0 && !is_color_pixel) {
             if (Abs(b - average[i]) < data_delta)
             {
                 dst[i] = b;
             }
            // }

             history[layer * layer_size + i] = b;
         }

         layer++;
         if (layer == history_scan_depth)
         {
             layer = 0;
         }
     }

  private unsafe void ImageUpdated(Camera cam,  ref Mat cvMatDepth)
     {

         long addrsrc = cvMatDepth.dataAddr();
         long addrDst = dstResult.dataAddr();
         DRSFilter((byte*)addrsrc, (byte*)addrDst, a, b);

         Utils.matToTexture2D(dstResult, texture);
         canvas.GetComponent<RawImage>().texture = texture;

     }

```

Update Sketch:

```
 [BurstCompile] // <-- For this you need to add the Burst package using the Unity package manager, this attribute is completely optional but it improves performance by a lot (like 10 times faster)
    public struct ConvertJobParallel : IJobParallelFor
    {
        public NativeArray<byte> input;
        public NativeArray<byte> output;
        public NativeArray<byte> history;
        public NativeArray<byte> average;
        public int _history_scan_depth;
        public int _history_capacity;
        public int _layer_size;
        public int _data_delta;
        public int _layer;

        // This gets called by the job system. index ranges between 0 and the 'arrayLength' specified in the first parameter of Schedule()
        public void Execute(int index)
        {
            if (_history_scan_depth > _history_capacity)
            {
                _history_scan_depth = _history_capacity;
            }

            byte b = input[index];
            uint avrg = 0;
            for (int k = 0; k < _history_scan_depth; k++)
            {
                avrg += history[k * _layer_size + index];

            }
            average[index] = (byte)(avrg / _history_scan_depth);

            if (Math.Abs(b - average[index]) < _data_delta)
            {
                output[index] = b;
            }

            history[_layer * _layer_size + index] = b;

            _layer++;
            if (_layer == _history_scan_depth)
            {
                _layer = 0;
            }
        }

    }
   [SerializeField] private Texture2D _inputTexture; // Texture that we are reading, should have read/write enabled set to true and Compression set to None
    [SerializeField] private Texture2D rawImage;
    private Texture2D _outputTexture;

    private NativeArray<byte> inputArray;
    private NativeArray<byte> outputArray;

    private NativeArray<byte> historyArray;
    private NativeArray<byte> averageArray;

    private int _history_scan_depth;
    private int _history_capacity;
    private int _data_delta;
    private int _layer;
    private void Awake()
    {
        historyArray = new NativeArray<byte>(history_capacity * layer_size, Allocator.Persistent);
        averageArray = new NativeArray<byte>(layer_size, Allocator.Persistent);
        outputArray = new NativeArray<byte>(layer_size, Allocator.Persistent);

    }

    private void OnDestroy()
    {
        historyArray.Dispose(); // We need to manually dispose our NativeArrays. The arrays retrieved from the Textures are disposed by the textures so we don't care here
        averageArray.Dispose();
        outputArray.Dispose();

    }

    private void ImageUpdated(ref Texture2D zedTextureDepth)
    {

        inputArray = zedTextureDepth.GetRawTextureData<byte>(); // Could use GetPixelData instead when working with mipmaps

        var job = new ConvertJobParallel()
        {
            input = inputArray,
            output = outputArray,
            history = historyArray,
            average = averageArray,
            _history_scan_depth = history_scan_depth,
            _history_capacity = history_capacity,
            _layer_size = layer_size,
            _data_delta = data_delta,
            _layer = layer
        };

        JobHandle handle1 = job.Schedule(inputArray.Length, 100); // The 100 here is a magic number, it is basically a number that says how many items (Color32 in our example) are handled in one 'batch' where each batch can run async on any thread
        JobHandle.ScheduleBatchedJobs(); // Start running (all) our previously scheduled jobs
        handle1.Complete(); // Wait on the main thread fot this job to complete

        _outputTexture.LoadRawTextureData(outputArray);
        _outputTexture.Apply(); // Copy changes to gpu

        canvas.GetComponent<RawImage>().texture = rawImage;

    }

```

# Answer
Here is a vertex-fragment shader that imitates the action of your job:

```
Shader "Unlit/DepthFilter"
{
    Properties
    {
        _MainTex  ("Texture", 2D)   = "white" {}
        _HistoryA ("History A", 2D) = "white" {}
        _HistoryB ("History B", 2D) = "white" {}
        _HistoryC ("History C", 2D) = "white" {}
        _dataDelta ("Data Delta", range(0, 256)) = 256
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            sampler2D _HistoryA;
            sampler2D _HistoryB;
            sampler2D _HistoryC;
            float     _dataDelta;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed source = tex2D(_MainTex, i.uv).r;

                // Accumulate the history into a total.
                float average = tex2D(_HistoryA, i.uv).r;
                average      += tex2D(_HistoryB, i.uv).r;
                average      += tex2D(_HistoryC, i.uv).r;

                // Divide by our sample count to get an average.
                average /= 3.0f;

                // Write into the output texture if and only if
                // abs(source - average) < _dataDelta.
                clip(_dataDelta/256.0f - abs(source - average));
                return source;
            }
            ENDCG
        }
    }
}

```

Assign this shader to a material and you'll see three slots to assign textures: one representing your new "source" data, and three others representing your history buffer. You'll also have a slider property where you can assign your data delta.

We can ask the GPU to perform this filter on a given source and destination buffer like so:

```
public class DepthFilter : MonoBehaviour
{
    const int HISTORY_CAPACITY = 3;

    readonly static int _dataDeltaID = Shader.PropertyToID("_dataDelta");
    readonly static int[] _historyIDs = new int[] {
        Shader.PropertyToID("_HistoryA"),
        Shader.PropertyToID("_HistoryB"),
        Shader.PropertyToID("_HistoryC"),
    };

    public Material filterMaterialAsset;
    Material _filterMaterialInstance;
    RenderTexture[] _historyPages;
    int _oldestPage = 0;

    public void Filter(ref RenderTexture source, RenderTexture destination, uint dataDelta) {

        // If we haven't initialized our history buffer, do so.
        // Match the size/format of whatever render target
        // we were passed as a source.
        if (_historyPages == null) {
            _filterMaterialInstance = Instantiate(filterMaterialAsset);
            _historyPages = new RenderTexture[HISTORY_CAPACITY];
            for(int i = 0; i < HISTORY_CAPACITY; i++) {
                _historyPages[i] = new RenderTexture(source);
                _filterMaterialInstance.SetTexture(_historyIDs[i], _historyPages[i]);
            }
        }

        _filterMaterialInstance.SetFloat(_dataDeltaID, dataDelta);

        // Apply the shader filter to the source and current history,
        // and write the result into destination.
        Graphics.Blit(source, destination, _filterMaterialInstance);

        // Our source becomes the newest sample in our history.
        // (Or, if it's supposed to be your destination, use that instead).
        // The oldest history page takes its place as a new writable source texture.
        var newPage = source;
        source = _historyPages[_oldestPage];
        _historyPages[_oldestPage] = newPage;
        _filterMaterialInstance.SetTexture(_historyIDs[_oldestPage], newPage);
        _oldestPage = (_oldestPage + 1) % HISTORY_CAPACITY;
    }
}

```

Call `Filter()` to write the filtered result into your destination texture, and update the history buffer with the latest source data, returning you the oldest history page to overwrite with your new source data next frame.

This approach keeps all of this data GPU-side at all times. We never download that data back to the CPU to process it and upload it back to the GPU afterward, we just tell the GPU what to do with the data it already has in its memory.
> 2 votes

# Answer
Although a GPU solution is probably better and faster in your case, I don't have enough knowledge about this so I'll leave it to someone else to write that answer :)

Here I'll show you an example of how to edit textures using Unity's job system. This example is not tailored to your needs, but I think it should be enough of an example to help you along implement your functionality yourself should you choose not to use a GPU solution for any reason.

In the below example I made a Parallel job that swaps the red and green channels, this can however be altered to do whetever you want ofcourse.

```
public class Example : MonoBehaviour
{
    [SerializeField] private Texture2D _inputTexture; // Texture that we are reading, should have read/write enabled set to true and Compression set to None
    [SerializeField] private RawImage rawImage;
    private Texture2D _outputTexture;

    private NativeArray<Color32> inputArray;
    private NativeArray<Color32> outputArray;

    private NativeArray<byte> yourCustomArray; // Can be any (struct)type So byte, int, Color32, etc. all work

    private void Awake()
    {
        // Copy original texture to a new Texture2D for testing
        _outputTexture = new Texture2D(_inputTexture.width, _inputTexture.height, _inputTexture.format, _inputTexture.mipmapCount > 1);
        Graphics.CopyTexture(_inputTexture, _outputTexture);

        // Get the underlying NativeArrays which can be used by the jobs system
        inputArray = _inputTexture.GetRawTextureData<Color32>(); // Could use GetPixelData instead when working with mipmaps
        outputArray = _outputTexture.GetRawTextureData<Color32>();

        // Assign outputtexture to a rawimage
        rawImage.texture = _outputTexture;

        yourCustomArray = new NativeArray<byte>(inputArray.Length, Allocator.Persistent);
    }

    private void OnDestroy()
    {
        yourCustomArray.Dispose(); // We need to manually dispose our NativeArrays. The arrays retrieved from the Textures are disposed by the textures so we don't care here
    }

    private void Update()
    {
        var job = new ConvertJobParallel()
        {
            input = inputArray,
            output = outputArray,
            yourData = yourCustomArray
        };

        JobHandle handle1 = job.Schedule(inputArray.Length, 100); // The 100 here is a magic number, it is basically a number that says how many items (Color32 in our example) are handled in one 'batch' where each batch can run async on any thread
        JobHandle.ScheduleBatchedJobs(); // Start running (all) our previously scheduled jobs
        handle1.Complete(); // Wait on the main thread fot this job to complete
        _outputTexture.Apply(); // Copy changes to gpu
    }

    [BurstCompile] // <-- For this you need to add the Burst package using the Unity package manager, this attribute is completely optional but it improves performance by a lot (like 10 times faster)
    public struct ConvertJobParallel : IJobParallelFor
    {
        [ReadOnly] public NativeArray<Color32> input;
        public NativeArray<Color32> output;
        public NativeArray<byte> yourData;

        // This gets called by the job system. index ranges between 0 and the 'arrayLength' specified in the first parameter of Schedule()
        public void Execute(int index)
        {
            // This is simply a demo test, it swaps the red and green channels, here you put your logic
            Color32 inputColor = input[index];
            output[index] = new Color32(inputColor.g, inputColor.r, inputColor.b, inputColor.a);
        }
    }
}

```

So in your case you can change the `yourCustomArray` and `yourData` to whatever you want, you can add more NativeArrays if you want to in a similar way, you can also add variables to your job that contain only one value (like `public uint data_delta;` for example). Note however that you should consider any variable that is not a NativeArray as readonly in your job.

**EDIT** Forgot to mention this, in this test I immediatly call Complete() after scheduling the job. If possible you should always make sure that you do other things in between scheduling and awaiting for the job to complete to fully utilize multithreading. So for instance, schedule at the start of the frame and complete at the end of the frame or in a later frame depending on your needs.

**Edit2** Based on comments and the updated code you posted. The `Execute(int index)` method of the `ConvertJobParallel` will be run multithreaded by Unity. When you call `job.Schedule(inputArray.Length, 100);` you are telling Unity you want to call Execute inputArray.Length times in batches of 100. Unity will then handle that these batches of 100 are distributed among different threads. This also means that altering the variables of ConvertJobParallel inside the Execute job is problematic. The only thing which you can write to and persists after the job are the contents of the NativeArray's you pass along. That `layer++` you do won't work as you expect it, as it won't increment the actual layer outside the job. So these parts should be moved outside the job (Actually, anything inside your original code outside this loop `for (int i = 0; i < layer_size; i++)` should be moved outside the job

You should also try to cache the NativeArrays of the Textures you are using if possible. These NativeArrays contain the actual bytes of this Texture on CPU side. Meaning if you change any value of that nativeArray, you change the value of the Texture itself **and vice-versa**. But it won't be copied to the GPU untill you call texture.Apply(). Note that the url you posted of how you retrieve the texture, it uses a cached texture if possible, so if it returns a cached texture whose NativeArray you retrieved in the past, you don't need to update your cached NativeArray, your NativeArray should contain the correct bytes already.

So my change to you current posted code would be something like this: The Job itself:

```
[BurstCompile] // <-- For this you need to add the Burst package using the Unity package manager, this attribute is completely optional but it improves performance by a lot (like 10 times faster)
public struct ConvertJobParallel : IJobParallelFor
{
    [ReadOnly] public NativeArray<byte> input;
    public NativeArray<byte> output;
    [NativeDisableParallelForRestriction] public NativeArray<byte> history;
    public NativeArray<byte> average;

    // These should always be considered read only, as writing to them is problematic. Execute gets called async on many threads.
    // So editing these values inside execute does not yield the wanted results
    public int _history_scan_depth;
    public int _layer_size;
    public int _data_delta;
    public int _layer;

    // This gets called by the job system. index ranges between 0 and the 'arrayLength' specified in the first parameter of Schedule()
    public void Execute(int index)
    {
        byte b = input[index];
        uint avrg = 0;
        for (int k = 0; k < _history_scan_depth; k++)
        {
            avrg += history[k * _layer_size + index];
        }
        average[index] = (byte)(avrg / _history_scan_depth);

        if (math.abs(b - average[index]) < _data_delta)
        {
            output[index] = b;
        }

        history[_layer * _layer_size + index] = b;
    }
}

```

Scheduling the job:

```
if (history_scan_depth > history_capacity)
    history_scan_depth = history_capacity;

var job = new ConvertJobParallel()
{
    input = inputArray,
    output = outputArray,
    history = historyArray,
    average = averageArray,
    _history_scan_depth = history_scan_depth,
    _layer_size = layer_size,
    _data_delta = data_delta,
    _layer = layer
};

layer++;
if (layer >= history_scan_depth)
    layer = 0;

JobHandle handle1 = job.Schedule(inputArray.Length, 100); // The 100 here is a magic number, it is basically a number that says how many items (Color32 in our example) are handled in one 'batch' where each batch can run async on any thread
JobHandle.ScheduleBatchedJobs(); // Start running (all) our previously scheduled jobs
handle1.Complete(); // Wait on the main thread fot this job to complete

_outputTexture.Apply(); // Copy changes to gpu

```

In this example, I'm not sure what \_data\_delta should be, in your comment to the original post I read 500, but since you are comparing it to a byte which max value is 250 I tested this at 50. `_outputTexture.LoadRawTextureData(outputArray);` You shouldn't really call this, as you just want to be Editing the NativeArray of that texture directly, rather then copying another one to it every frame, I do this in my original post by creating a new Texture2D with correct width, height and format and then use GetRawTextureData to get the outputArray that is directly mapped to the Texture2D.
> 2 votes

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


# Question
Title: How should I store loaded world chunks in RAM (For my game similar to Minecraft)?
I am trying to replicate a chunk loading system, in C, for my own minecraft like game, though I don't know how. Once chunks are loaded, are they placed in an array, or are there a bunch of variables for each loaded chunk?
In my game, once I load chunks using `fread`, what should I use to store them? My problem for a two dimensional array for storing chunks, is that the loaded chunks might be separate and not start at zero. Are there any suggestions for storing loaded chunks?

I have a code fragment, solely so you guys will not yell at me for not including code:

```
    char ChunkFilePath[strlen(CurrentWorld)+32];
    sprintf(ChunkFilePath, "%s/ChunkData/%ld %ld", CurrentWorld, X, Z);
    FILE *ChunkFile;
    if ((ChunkFile = fopen(ChunkFilePath, "r"))) {
        //chunk file exists, Read Chunk file to ???
    }
    if ((ChunkFile = fopen(ChunkFilePath, "w")) == NULL) {
        fputs("Error Loading Chunk (File Not Found)", stderr);
        return;
    }
        /*Chunk does not exist, but any other errors would have been caught
        at this point, so Generate chunk, write generated results to ???*/

```

Note: The game I am trying to make is purely for my personal use, not for any commercial use.

> Edit:

The problem is just an array will not work. Suppose there is a player at 1000000 and another one at -1000000 They would only render 6 chunks around them, but if they shared an array, all the 2000000 blocks worth of chunks that aren't loaded would be taking up memory. I would refer to chunks like LoadedChunk\[1000\]. How can I handle that?

# Answer
If you don't want a 2d array of chunks indexed by world position because the player might get very far away from the world origin or you might have negative indexes, then it might be worth to look at other data structures.

* A hash table with the coordinates as keys
* A 2-d tree which you auto-balance so that the root is always at the player (can also be useful for render order determination, collision detection and many other purposes)
* A 2d array of **pointers** to chunks, where the indices are not relative to the world origin but relative to the player position. If the player moves to a different chunk, you need to shift that array so that the center point of the array is again the chunk the player is in (which doesn't mean that you rebuild the chunks, just that you move the pointers to chunks in the 2d array).
* A graph where each chunk has pointers to its four neighbors (as suggested by PSquall in the comments).
> 6 votes

# Answer
I'd bridge to C++ and use a `std::map()` and abstract away the process of accessing these voxels, so they can be called by C
> 0 votes

---
Tags: voxels, c
---


# Question
Title: Workflow for accountable file transfers between freelancer and developer
I'm an indie game developer and I often hire freelancers for artwork. We sign an agreement to basically state that I'd get ownership of the resources they produce.

I'm a fairly picky person when it comes to formalities in these agreements, and I can't find a good system to document file transfers between freelancer and client. What I'm looking for is:

A way to track a relationship between their email account and mine, and document file exchanges, like a "timeline":

* Freelancer uploaded X file at 16:50 UTC+03:00, \[download button\]
* Freelancer uploaded Y file at 17:43 UTC+03:00, \[download button\]
* Client uploaded Z file at 18:35 UTC+03:00, \[download button\]

And files are permanently kept in the timeline for documentation purposes - it should be impossible to delete an entry (unless both parties agree to delete it). The point of such structure is to "vouch" that this person transferred a file at some point and neither party can deny it.

---

Technically, e-mail attachments do exactly this. However, if it is a relatively large file, Gmail will ask them to upload to Google Drive. The problem with this is that Drive lets them keep ownership of the file (so if they delete it, I cannot get it back unless I had downloaded it); we would lose the whole "record" thing as there will be no guarantee that the file that I have is in fact the file that they uploaded.

How we've worked with a few freelancers in the past is that they will transfer a bulk of files (zip) to us using whatever convenient method, and then, in written, state that they have produced and transferred a zip with some MD5 hash. So if it is ever necessary to prove that such a file was given to me by a freelancer, we'd just compute its hash. However that's understandably inconvenient.

# Answer
Version control software designed for large binary files would solve this problem.

For example, git lfs provides efficient versioned storage for any type of file with infinite history (provided infinite storage space). It supports commit signing to prevent resource corruption.

Perforce is another example common the game dev industry (source).

The key factor is that you want version control designed for binary data rather than source code/text data. Most version control works by using diffs between subsequent versions of a file - while this works great for text, it performs poorly on the compressed data found in most image & audio formats.
> 7 votes

---
Tags: legal, workflow
---


# Question
Title: How do I move an object towards a moving object?
I am trying to make an AI that tries to move towards the player but I don't know how. I tried using `Vector2.MoveTowards()` but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot :D) but i couldn't make it move towards and touch the player! Help please :D.

Also my original code:

```
#pragma strict
var speed : float = 100;
var targetX : Transform;
var targetY : Transform;
var mex : Transform;
var meY : Transdorm;
function Update ()
{
var targetX = transform.position.x;
var targetY = transform.position.y;
var meX = transform.position.x;
var meY = transform.position.y;
Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed);
}

```

# Answer
Hey there are couple of things which you are missing out.

1) Even thought the motion is in 2d plane but the gameobject dimension is 3D, so use Vector3 instead of Vector2

2) When you calculate Vector3 Movetowards it returns a value which is calculated upon current position , target position and speed.

This needs to be assigned to the transform of the AI. Link:- http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

Here is the code: This script needs to be put on AI object , and assign the player variable through inspector.

```
 var player : GameObject;
 var speed : float;

function Start ()
{
    speed = 10;
}

function Update ()
{
    gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, player.transform.position  , Time.deltaTime*speed);
}

```
> 2 votes

# Answer
Your `targetX` and `targetY` are being set as your current script's `transform.position`, rather than your target's position.

Also, `targetX` and `targetY` are `Transform`s, when really it sounds like they should be `floats`, or perhaps even just simplified as a single `var target : Transform;`. You could also just have `var me : Transform;` as well.

Your `MoveTowards` should also multiply `speed` by `Time.deltaTime` to make the movement be framerate-independent.

```
#pragma strict
var speed : float = 100;
var target : Transform;
var me : Transform;

function Update ()
{
    Vector2.MoveTowards(me.position, target.position, speed * Time.deltaTime);
}

```

Note that you will need to define both `target` and `me` either in the Inspector or within a script.
> 0 votes

# Answer
```
public GameObject player;
public float speed;

void Start()
{
    player = GameObject.Find ("player");
}

void Update()
{
    float z = Mathf.Atan2((player.transform.position.y - transform.position.y), (player.transform.position.x -
                                                                                transform.position.x))*
        Mathf.Rad2Deg - 90;

    transform.eulerAngles = new Vector3( 0, 0, z);

    GetComponent<Rigidbody2D>().AddForce (gameObject.transform.up * speed);

}

```

}
> -2 votes

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

public class MoveEnemy : MonoBehaviour{
 //link the player//
 public GameObject player;
//fix the speed//
public float speed;

void Update ()
{
    gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, player.transform.position  , Time.deltaTime*speed);
}
}

```
> -2 votes

---
Tags: unity, 2d, ai, unityscript
---


title: can't make my unity character move

text:
# Question
Title: can't make my unity character move
so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https://docs.unity3d.com/Manual/ScriptingRootMotion.html

If you ask I'll give you my project .

EDIT :

ok so I made some advances :

```
 void OnAnimatorMove()
{
        m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude * 10000);
        m_Rigidbody.MoveRotation(m_Rotation);
        Debug.Log("m_Animator.deltaPosition.magnitude: " + m_Animator.deltaPosition.magnitude);

}

```

m\_Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ?

# Answer
> 3 votes
I have the same problem, I started solving it by removing the last part:

`m_Animator.deltaPosition.magnitude` to some other float that i want and called it speed meaning my OnAnimatorMove is looking like this

//move the position

```
m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * 0.05f);

```

you can either change the last float to a public variable for you'r convenient

Another sulotion that i found relevant to my case that in my animation setting of the walk animation i activated the ***bake into pos*** option for the x,z,y transforms once i disabled it that worked just fine with the same code but i neede to add a speed variable and multiply by it because it was too slow

# Answer
> 3 votes
> **Animator.deltaPosition** Gets the avatar delta position for the last evaluated frame.
>
> Animator.applyRootMotion must be enabled for deltaPosition to be calculated.
>
> https://docs.unity3d.com/ScriptReference/Animator-deltaPosition.html

You have to enable your animator's `applyRootMotion`. if you don't enable this option or your avatar doesn't have a delta position (not changing position), then Animator.deltaPosition returns 0.

More about applyRootMotion: https://docs.unity3d.com/ScriptReference/Animator-applyRootMotion.html

# Answer
> 1 votes
I think I found a solution.

I ran into the same problem, but I solved it in the following way

1. animation correction I used my own models and animations, but I wasn't moving them forward despite the walking animation. (It was stamping feet on the spot.) This has been modified to move forward.
2. select the root node Armature/Hips were assigned to the Inspector/Rig/Root node of the model. Initially I was simply going to Armature, but then I realized that the root of the animation was Hips.

After fixing the above two points, the problem was solved.

I hope this helps those who still refer to this thread.

Sorry for the poor English, thank you.

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


# Question
Title: Authoritative game server and database storage
In an authoritative game server working with websockets, should you store every action to the database before sending the response to the client? The risk is the slow response time.

Or should the result be calculated with variables we cached earlier and cache the result to update the cache to the database once in a while? But with a risk that data can be lost if the server crashes before it's stored into the database.

For a game server handling up to 500 players at the same time and up to 16 request by seconds with no heavy calculations, what should be decided?

# Answer
> 2 votes
Sending the data to the client before you are sure that it was successfully stored in the database, you run the risk that the client will display information to the user that the server ultimately will disagree with eventually. You should consider on a case-by-case basis if the consequence of a user potentially seeing this "incorrect" information, is greater than the consequence of the user having to wait slightly longer.

Typically for transactional kinds of information, e.g. spending resources, sending a message or saving progress, it is a lot more important for the user to be assured that the information is *actually true* than it is to know the information 100 milliseconds sooner.

For fast-updating information that is quickly invalidated by something new, e.g. the position of a player that is moving around a world, the slower you get that information to the user, the less valuable it is (due to how frequently it changes). Also, the individual importance of each update is likely much smaller, and thus the consequence of it being incorrect is much lower. In some critical cases, every moment of unnecessary delay will make your client application feel less responsive and degrade the user experience.

See also: https://en.wikipedia.org/wiki/Client-side\_prediction

---
Tags: client-server, server, databases, node.js, websocket
---


# Question
Title: Composite collider 2D mysteriously adds x velocity to player rigidbody
As you can in the gif above there is an x velocity being set in the players rigidbody upon contact with the tilemap surface (Tilemap collider using composite). It was fine when I was using standalone colliders but now this happens.

Is this a bug or am I missing something. Help is much appreciated.

Unity ver. 2019.4.8f1

# Answer
> 0 votes
I solved this by setting offset distance of the composite collider to zero. I don't really know why it solved but it works for now.

---
Tags: unity, platformer, rigidbody
---


# Question
Title: Problem modifying GameObject in list of GameObjects Unity
So I've been working on a little project that involves Valve's "Portal" style portals, the type where you can seamlessly see what's on the other side and walk through. I've run into a problem when it comes to teleporting an object to it's new location upon hitting the portal. I have a `List<GameObject>` that contains all the objects that are in close enough range to feasibly travel through the portal, but when I try to modify the `transform.position` of one of these GameObjects, nothing happens, no error messages.

So I've been going through my script line by line and writing little dummy functions to test different parts of it to see where the problem lies, and everything seems to work up until I index the list and try to modify a value, nothing happens. So was thinking that perhaps the List doesn't actually contain a reference to the GameObject in the scene, but simply a copy of the GameObject's data at the time it was passed into the list. So I checked this by making the list public so that I see it in the inspector, and when I click on an item in the list it highlights that same GameObject in the hierarchy, which suggests it is actually a reference. See bellow...

I am at a loss as to what's happening here and would really appreciate if anyone could offer a suggestion, Here is the dummy function where I try to arbitrarily modify the GameObject data from the List...

```
        if (Input.GetKeyDown("k"))
        {
            for (int i = 0; i < trackedTravelersObjects.Count; i++)
            {
                trackedTravelersObjects[i].transform.position += new Vector3(0, 30, 0);
                Debug.Log("K");
            }
        }

```

You'll notice a `Debug.Log("k")`, this is just to check that the code is actually being called, which it is.

Thanks.

# Answer
Your problem is not the list, it's the `CharacterController` component.

(Testing this code inside and outside of the list, or with different objects would let you isolate this)

The character controller caches the last position it moved to, and performs its next move from there - no matter where the transform has travelled in between.

Using the advice in this thread, we can adapt your code to...

```
if (trackedTravelersObjects[i].TryGetComponent(out CharacterController character)
&& character.enabled) {
    character.enabled = false; // Put the character to sleep for a moment.
    trackedTravelersObjects[i].position += new Vector3(0, 30, 0);
    character.enabled = true; // "Wake up" the character in its new place.
} else {
    trackedTravelersObjects[i].position += new Vector3(0, 30, 0);
}

```
> 0 votes

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


# Question
Title: How do I get my sprite to do a regular jump instead of jolt up?
I have been getting into game development and I have made some progress. I have come across an obstacle which is jumping I managed to get the Jumping to semi work but it doesn't look like a jump but instead it Jolts up or teleports up. This is how it looks:

It's a bit slower thanks to the gif but as you can see it just jolts up. I tried implementing multiple ways to jump and I tried to stay with the velocity and acceleration method.

This is what I have right now:

```
sf::Vector2f velocity = sf::Vector2f(0,0);
float accelaration = 1.f;
void Player::updatePhysics(int deltaTime) {
    if (playerCount == 1) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            velocity.x -= accelaration * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            velocity.x += accelaration * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W) && !isJump) {
            isJump = true;
            jumpDownEnd = false;
            velocity.y -= 30 * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S) & velocity.y > 800) {
            velocity.y += accelaration * deltaTime;
        }
    }

    if (velocity.y > 800) {
        velocity.y = 800 - player.getGlobalBounds().height / 2;
    }
    else {
        velocity.y += gravity ;
    }
    player.setPosition(velocity.x, velocity.y);
}

```

***Notes***
I have tried a couple of other things like storing player position and adding velocity and multiplying by deltaTime and it worked but I got rid of it because I got a few bugs.

Also I tried to change the `velocity.y -= 30* deltaTime` to `velocity.y = 30* deltaTime` and all it did was reduce height by a bit.

Also the reason I am not multiplying velocity by delta time when setting position is because it starts to twitch when it gets further away from the original position.

I have tried searching for answers but they didn't help me find any solutions.

***Also deltaTime is as milliseconds instead of seconds. I constantly get a deltaTime of 15 or 16 if that helps.***

***Update***

I have made the code to add velocity to player position but now the jump is just super fast and still jolts up.

```
void Player::updatePhysics(int deltaTime) {
    velocity.x = 0;
    if (playerCount == 1) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            velocity.x -= accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            velocity.x += accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W) && !isJump) {
            isJump = true;
            jumpDownEnd = false;
            velocity.y = -300;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S) & velocity.y > 800) {
            velocity.y += accelaration;
        }
    }
    velocity.y += gravity * deltaTime;

    playerPos.x += velocity.x * deltaTime;
    playerPos.y += velocity.y * deltaTime;

    if (playerPos.y > 800) {
        playerPos.y = 800 - player.getGlobalBounds().height / 2;
        velocity.y = 0;
    }

    player.setPosition(playerPos);
}

```

# Answer
> 1 votes
So I figured out my issue. Thanks to @Ocelot for telling me my deltaTime in milliseconds was too high. So I just divided my deltaTime by 100 and that fixed my issue.

```
void Player::updatePhysics(int deltaTime) {
    velocity.x = 0;
    if (playerCount == 1) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            velocity.x -= accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            velocity.x += accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W) && !isJump) {
            isJump = true;
            jumpDownEnd = false;
            velocity.y = -300;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S) & velocity.y > 800) {
            velocity.y += accelaration;
        }
    }
    velocity.y += gravity * deltaTime/100;

    playerPos.x += velocity.x * deltaTime/100;
    playerPos.y += velocity.y * deltaTime/100;

    if (playerPos.y > 800) {
        playerPos.y = 800 - player.getGlobalBounds().height / 2;
        velocity.y = 0;
    }

    player.setPosition(playerPos);
}

```

---
Tags: c++, 2d, physics, sfml, jumping
---


# Question
Title: How to rotate vector A around another vector B?
Lets say I know what is directly above a turret. I also know where the turrets gun is currently pointing. I would like to know where will the turret's gun will point if I rotate it.

I suppose I could multiply \\$A \cdot B\\$, project \\$A\\$ on the plane \\$B\\$ is a normal of and then do the rotation in 2D and add back \\$A \cdot B\\$ but I am sure the math should be simpler than that?

# Answer
You want to reflect \\$\vec A\\$ across \\$\vec B\\$. This has a simple formula, if \\$\vec B\\$ has length 1:

$$-\vec A + 2( \vec A \cdot \vec B)\vec B$$

What we've done here is to reverse \\$\vec A\\$ first, which means we negated both the component of \\$\vec A\\$ that's parallel to \\$\vec B\\$ and the component of \\$\vec A\\$ perpendicular to \\$\vec B\\$. Then we added twice the parallel component, \\$-1 + 2 = +1\\$, bringing it back to its previous value. So the net effect is that the part of \\$\vec A\\$ that was parallel to \\$\vec B\\$ remains unchanged, and only the perpendicular part gets reflected.
> 1 votes

# Answer
You simply want to apply the rotation matrix.

Assuming you use a cartesian metric for your game, and your gun is pointing in direction \\$ \vec{A} = (x,y,z) \\$, and you rotate around the vertical axis \\$ \vec{B} = (0, 0, 1) \\$. Then the rotation \\$ R\_z \\$ by and angle \\$ \theta \\$ is defined as $$ R\_z(\theta) = \left(\begin{array}{ccc}\cos \theta, & -\sin \theta,& 0\\\sin\theta, &\cos \theta,& 0\\0,&0,&0 \end{array}\right) $$

Thus the rotated vector \\$\vec{A}^\prime = \vec{A} \cdot R\_z = (x\cos\theta-y\sin\theta, x\sin\theta + y\cos\theta, 0)\\$

For a more elaborate treatise around general axis, consult a book on algebra or have a look on the wikipedia article on rotation:

> The matrix of a proper rotation \\$R\\$ by angle \\$\theta\\$ around the axis \\$\vec u =(u\_{x},u\_{y},u\_{z})\\$, a unit vector with \\$u\_{x}^{2}+u\_{y}^{2}+u\_{z}^{2}=1\\$, is given by:\[3\]
>
> $$\small {R = \begin{bmatrix}\cos \theta +u\_{x}^{2}\left(1-\cos \theta \right)&u\_{x}u\_{y}\left(1-\cos \theta \right)-u\_{z}\sin \theta &u\_{x}u\_{z}\left(1-\cos \theta \right)+u\_{y}\sin \theta \\u\_{y}u\_{x}\left(1-\cos \theta \right)+u\_{z}\sin \theta &\cos \theta +u\_{y}^{2}\left(1-\cos \theta \right)&u\_{y}u\_{z}\left(1-\cos \theta \right)-u\_{x}\sin \theta \\u\_{z}u\_{x}\left(1-\cos \theta \right)-u\_{y}\sin \theta &u\_{z}u\_{y}\left(1-\cos \theta \right)+u\_{x}\sin \theta &\cos \theta +u\_{z}^{2}\left(1-\cos \theta \right)\end{bmatrix}}$$
> 1 votes

---
Tags: mathematics, vector
---


title: Simplified aerodynamics for 3D airplane

text:
# Question
Title: Simplified aerodynamics for 3D airplane
I'm looking how to implement simple movement for an airplane in 3D in godot, i couldn't find any tutorial or any hints on how to do this, mostly theoric information on a more real flight movement.

Any ideas on how to implement this?

*I'm not looking for realistic physics, just a more arcade type of movement*

# Answer
Since you're looking for an arcade type of movement, I will make simplifications that will suit your use case. I will assume that you're familiar with the second law of Newton, as well as integration to compute speed and position based on acceleration.

An airplane in the air have 6 degrees of freedom: \[X,Y,Z\] are the coordinates in space (position) and the pitch, roll and yaw are the orientation around the plane's center of gravity. (Notice the axis orientation, in particular the Z axis pointing down, they are standard in aeronautics)

Planes in the air are subject to 4 forces: lift, weight, thrust and friction (airdrag). The resultant of these forces determines the moment and overall force that will accelerate and turn the airplane.
<sub>(source: cap-ny153.org)</sub>

**Weight**
The well-known formula \\$W = m.g\\$

**Thrust**
In your simplify model, it could be a constant multiplied by a user input.

**Drag**
In reality: \\$\frac{1}{2}.\rho.S.V^2.C\_x\\$ With

* \\$\rho\\$ the air density
* \\$S\\$ the equivalent surface of your plane (more wing surface -\> more drag and lift)
* \\$V\\$ the plane airspeed (speed relative to the air: a plane at 100 kts with a front wind of 20 kts has an airspeed of 120 kts)
* \\$C\_x\\$ the drag coefficient depending on the plane geometry and the angle of incidence

In your simplified model: \\$A.V^2\\$ with A a well-tuned constant and V the airspeed of your plane.

**Lift**
In reality: \\$\frac{1}{2}.\rho.S.V^2.C\_y\\$
In your simplified model : \\$A.V^2\\$ with A a well-tuned constant and V the airspeed of your plane. Note that drag and lift are very similar. The coefficients \\$C\_x\\$ and \\$C\_y\\$ are related and depend on the airplane geometry as well as the angle of incidence, but your simple model does not need that.

It's enough to compute easily the trajectory of the plane, but what about orientation? You've got to know the point of application of these forces relative to the center of gravity of your plane.
However, in arcade physics, the angular acceleration could be as simple as a constant multiplied by a user input. Integrated twice over time, that would give the angular position. Your job will be to tune the constants to achieve a desired behavior.
> 3 votes

---
Tags: physics, godot
---


title: Why is the player suspended in the air?

text:
# Question
Title: Why is the player suspended in the air?
I'm making a 2D platformer with Unity. I used this video to write the code but with some little changes. I want to support both keyboard and gamepad, so I use the new Input System. I defined three variables called `GroundedRememeber`, `JumpPressedRemember` and `JumpPressedRememberTime` and basically they work like timers and check if the player leaves the ground and if so, then the player can jump when he is near the ground without the need to touch it. These timers were not working, so I added a new method called `TryJump` and deleted some lines and now, the player is suspended in the air and moving upwards.

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

public class PlayerController : MonoBehaviour, PlayerInputActions.IPlayerActions
 {
   private PlayerInputActions controls;
   [SerializeField] LayerMask groundLayers;
   private Rigidbody2D rb;
   private Animator anim;
   private bool facingRight = true;
   private Vector2 moveInput;
  [SerializeField] private float jumpForce;
    float JumpPressedRemember = 0;

   [SerializeField] float JumpPressedRememberTime = 0.2f;
    float GroundedRemember = 0;

   [SerializeField]  float GroundedRememberTime = 0.25f;
   [SerializeField]  float HorizontalAcceleration = 1;
   [SerializeField] [Range(0, 1)] float HorizontalDampingBasic = 0.5f;
   [SerializeField] [Range(0, 1)] float HorizontalDampingWhenStopping = 0.5f;
   [SerializeField] [Range(0, 1)] float HorizontalDampingWhenTurning = 0.5f;
   [SerializeField] [Range(0, 1)] float JumpHeight = 0.5f;

   private void Awake()
   {
      controls = new PlayerInputActions();

      controls.Player.SetCallbacks(this);
    }
     void Start()
    {
      rb = GetComponent<Rigidbody2D>();
      anim = GetComponent<Animator>();
}
   void PlayerInputActions.IPlayerActions.OnMove(InputAction.CallbackContext context)
   {
      moveInput = context.ReadValue<Vector2>();

   }
     bool TryJump() {
    if (GroundedRemember > 0) {
        Jump();
        return true;
    } else {
        JumpPressedRemember = JumpPressedRememberTime;
        return false;
    }
}
     void PlayerInputActions.IPlayerActions.OnJump(InputAction.CallbackContext context)
   {
       jumpForce = context.ReadValue<float>();
       switch (context.phase) {
            case InputActionPhase.Performed:
               TryJump();
               break;
       }
   }
    void Jump() {
     rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Force);
     GroundedRemember = 0;
     JumpPressedRemember = 0;
   }

  void FixedUpdate()
  {

   if(facingRight == false && moveInput.x > 0){

    Flip();

   }else if (facingRight == true && moveInput.x < 0){

    Flip();

   }
 }
    void Flip(){

    facingRight = !facingRight;
    Vector3 Scaler = transform.localScale;
    Scaler.x *= -1;
    transform.localScale = Scaler;

 }
 void OnEnable()
 {
     controls.Enable();
 }

 void OnDisable()
{
    controls.Disable();
}
 void Update()
  {

   Vector2 GroundedBoxCheckPosition = (Vector2)transform.position + new Vector2(0, -0.01f);
   Vector2  GroundedBoxCheckScale = (Vector2)transform.localScale + new Vector2(-0.02f, 0);
   bool Grounded = Physics2D.OverlapBox(GroundedBoxCheckPosition, transform.localScale, 0, groundLayers);

    GroundedRemember -= Time.deltaTime;
    if (Grounded)
    {
      GroundedRemember = GroundedRememberTime;
    }

    JumpPressedRemember -= Time.deltaTime;

    if ((JumpPressedRemember > 0)) {
      TryJump();
    }

    rb.velocity = new Vector2(rb.velocity.x, jumpForce);

     float HorizontalVelocity = rb.velocity.x;
      HorizontalVelocity += moveInput.x;

        if (Mathf.Abs(moveInput.x) < 0.01f)
            HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingWhenStopping, Time.deltaTime * 10f);
           else if (Mathf.Sign(moveInput.x) != Mathf.Sign(HorizontalVelocity))
           HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingWhenTurning, Time.deltaTime * 10f);
        else
            HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingBasic, Time.deltaTime * 10f);

        rb.velocity = new Vector2(HorizontalVelocity, rb.velocity.y);
  }
}

```

# Answer
> 2 votes
As Zibelas points out in the comments, these lines...

```
void PlayerInputActions.IPlayerActions.OnJump(InputAction.CallbackContext context) {
    jumpForce = context.ReadValue<float>();
    switch (context.phase) {
        case InputActionPhase.Performed:
            this.Jump();
            break;
    }
}

public void Jump() {
    rb.AddForce(Vector2.up * this.jumpForce, ForceMode2D.Force);
}

```

...allow the input system to 100% skip your ground checks and timers, and just add a force to the player anytime the button is pressed. There's not a single line of code here that knows what ground is.

You can fix this by adding a new method:
(You can make this public if you want to call it from on-screen controls or such)

```
// Request a jump - but if we can't honour it right away, remember it for later.
bool TryJump() {
    if (GroundedRemember > 0) {
        Jump();
        return true;
    } else {
        JumpPressedRemember = JumpPressedRememberTime;
        return false;
    }
}

```

Then modify those lines at the top to call this `TryJump` method instead. You should also clear out the GroundedRemember value in your Jump function so you don't allow double-jumping in a tiny window just after you leave the ground.

```
void PlayerInputActions.IPlayerActions.OnJump(InputAction.CallbackContext context) {
    jumpForce = context.ReadValue<float>();
    switch (context.phase) {
        case InputActionPhase.Performed:
            TryJump();     // <-- Jump if grounded, otherwise remember the press.
            break;
    }
}

void Jump() {              // <-- Doesn't need to be public
    rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Force);
    GroundedRemember    = 0; // <-- We just jumped.
    JumpPressedRemember = 0; //     Nothing more to remember.
}

```

Then down in your update loop you can delete your `if (controls.Player.Jump.triggered)` clauses, and modify this one:

```
    /* Delete this. Your interface code will already do this work when the action is performed.
    if (controls.Player.Jump.triggered) {
        JumpPressedRemember = JumpPressedRememberTime;
    }
    if (controls.Player.Jump.triggered) {
        if (rb.velocity.y > 0) {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * JumpHeight);
        }
    }
    */

    if (JumpPressedRemember > 0)) {
        TryJump(); // <-- Don't repeat yourself, keep your jumping logic in one place.
    }

```

As an aside, I don't recommend jumping with forces. Use velocities or impulses instead. A force represents a gradual push over time, not a sharp change in motion like a platformer bounce. Using the right physics type will make it easier to tune this feature, and avoid inconsistency if your mass or timestep changes.

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


title: Implementing Seperating Axis Theorem

text:
# Question
Title: Implementing Seperating Axis Theorem
I'm trying to implement the Seperating Axis Theorem by following this article I found on MDN. Unfortunately, I'm not too geometry savvy and I wasn't able to find any good, simple implementation examples around the internet. I've tried to search for the specific concepts that the article mentions, but I'm not sure that I'm on the right track and I've got several doubts about this.

Here's what I did so far:

```
export class Point {

    constructor(x, y) {

        this.x = x;
        this.y = y;
    }

    rotate(pivot, angle) {

        let s = Math.sin(angle);
        let c = Math.cos(angle);

        let p = new Point(this.x - pivot.x, this.y - pivot.y);

        return new Point((p.x * c - p.y * s) + pivot.x, (p.x * s + p.y * c) + pivot.y);
    }

    compare(point) {

        // todo
    }
}

import { Point } from "./Point.js";

export class Line {

    constructor(p1, p2) {

        this.p1 = p1;
        this.p2 = p2;
    }

    getSlope() {

        return (this.p2.y - this.p1.y) / (this.p2.x - this.p1.x);
    }

    getNormal() {

        let dx = this.p2.x - this.p1.x;
        let dy = this.p2.y - this.p1.y;

        return new Line(new Point(-dy, dx), new Point(dy, -dx));
    }

    getYIntercept() {

        return this.p1.y - this.getSlope() * this.p1.x;
    }

    getPointProjection(point) {

        let slope = this.getSlope();
        let yIntercept = this.getYIntercept();

        let slope2 = -1 / slope;
        let yIntercept2 = point.y - slope2 * point.x;

        let nx = (yIntercept2 - yIntercept) / (slope - slope2);

        return new Point(nx, (slope2 * nx) + yIntercept);
    }
}

import { Point } from "./Point.js";
import { Line } from "./Line.js";

export class Polygon {

    constructor(...points) {

        this.points = points;
    }

    overlaps(polygon) {

        let side = new Line(this.points[0], this.points[1]);

        let axis = side.getNormal();

        function findMinAndMaxProjectedPoints(polygon) {

            polygon.points.forEach(point => {

                let projection = axis.getPointProjection(point);

            });
        }

    }
}

```
1. Did I implement the various formulas correctly?
2. How should I "keep track of the highest and lowest values" for each polygon? How am I supposed to determine which projected points are the lowest and which are the highest?
3. How do I check for gaps between the highest and lowest projected point of the two polygons?

# Answer
> 1 votes
> 1. Did I implement the various formulas correctly?

No.

* A normal should be a single direction vector with one x value and one y value, not a line segment joining two points.
* Point projection where you divide by slope will behave badly for horizontal lines where the slope goes to zero.
* Your overlap test checks only one side of one polygon.

> 2. How should I "keep track of the highest and lowest values" for each polygon? How am I supposed to determine which projected points are the lowest and which are the highest?

Use a vector dot product. Given a vector along your candidate axis `axis = (axis.x, axis.y)`, the projection of a `point` along that vector is proportional to:

```
Dot(point, axis) = point.x * axis.x + point.y * axis.y

```

Technically this gives us a true distance only when the axis is a "unit vector" with length 1 (ie. `Dot(axis, axis) = 1`), and will give us an exaggerated/scaled result if the axis has a different length. But to check for overlaps this scale factor doesn't matter, so you can save yourself the work of normalizing the vector and just tolerate it.

The result of a dot product is a scalar (a number, not a vector). So we can find the greatest/least with a min/max function.

```
let least = inf
let greatest = -inf

polygon.points.forEach(point => {
    let projection = Dot(point, normal)
    least = min(least,  projection)
    greatest = max(greatest, projection)
});

```

> 3. How do I check for gaps between the highest and lowest projected point of the two polygons?

After you've computed your least and greatest values as above for each polygon along the same separation vector, you just compare the numbers. If there's a gap, then it means the least value from one polygon is still greater than the greatest value from the other polygon.

```
if (polygon1.least > polygon2.greatest or polygon1.greatest < polygon2.least)

```

---
Tags: collision-detection, javascript, separating-axis-theorem
---


title: Rendering voxel data efficiently

text:
# Question
Title: Rendering voxel data efficiently
With Metal, I need to pass in an array of primitives to the GPU to be rendered. I'm making a terrain-based voxel game like Minecraft, but I have a problem.

`for`ing through all of the visible voxels, and in each processing the list of block IDs and Metadata into a list of primitives for rendering is asinine, because I imagine obtaining primitives from raw block data being an expensive process. Surely there's a better way.

Given that you cannot duplicate or cull vertices and planes on the fly on the GPU, doing this in the vertex shader is out of the question. My problem is when or how translate raw block data into a list of primitives ready for the GPU to apply 3D projections to it.

It would definitely be a good idea to maintain the already-processed primitive lists, and only update them when a block updates. However, maintaining these is tricky. Maintaining them one block at a time is very messy, but one voxel at a time would require stitching them together prior to rendering.

This is the foundation of a block sandbox game like Minecraft. Without it I can't progress to gameplay mechanics. My game manages voxel data with a C++ style map, of 3 dimensional arrays of 16 by 16 by 16 4-byte blocks. I simply need to know where, when, and how the process of obtaining primitives from raw block data should take place. How do most games do it?

It's also worth noting that I'm using Metal, a game framework, rather than a game engine, so if game engines generally abstract away this process and therefore this question seems nonsensical, I'm not using a game engine, I'm using a game framework.

# Answer
> I simply need to know where... and how the process of obtaining primitives from raw block data should take place. How do most games do it?

1. Check whether any voxels have changed
2. If so, reconstruct voxel surface geometry accordingly (this comes down to surface calculation using your boolean grid of air/voxel - a surface appears where we change from air to solid or solid to air)
3. Submit this buffer to the GPU for rendering, each frame.

> when

On each frame, whether that is on vsync or on game loop iteration. This will happen after all your game logic, such as changing of voxels, has been done, i.e. render is the last stage in the frame. So each frame consists of something like

1. input
2. game logic
3. render

> It's also worth noting that I'm using Metal, a game framework

Metal is not a (high level) game framework. It is a low-level, modern graphics API. There is a very great difference between those two ideas.

I get the impression you have a lot more work to do before you can be writing Metal code, comfortably, as well as developing a complex game with it. Just a suggestion that you may want to get to grips with software rendering using a simpler setup than Metal, at first.
> 1 votes

---
Tags: performance, voxels, metal
---


# Question
Title: Unity FPS Drop on Android Low end devices
I have stumbled upon an issue that is now taking a lot more time than I assumed. I have a game that has a lagging issue and I have tried almost all techniques that I could remember to fix that but now I am in desperate need of advice. I am on **Unity 2019.4.14f1 (URP)**

I have done the following:

1. Turned off everything including UI and still CPU around 40ms and 25fps on **Samsung Galaxy S6**
2. Optimized Memory though textures compression of RGBA Crunched ETC2 or RGB Crunched ETC as needed.
3. Added target framerate = 60 as without this Semaphore.WaitForSignal took a lot more CPU ms and was resulting in even worst FPS even in an empty scene.
4. Turned off vSync
5. Turned off all sort of lights in the game
6. Tried turning off scriptable render features just to be sure they are not culprits.

Here are the setting screenshots:

Here are profiling screenshots of gameplay without turning off everything.

Here are the screenshots when everything including Ui, 3D Env/Char, and lights are turned off.

# Answer
> 1 votes
So after a lot of digging finally achieved 60 FPS on Samsung Galaxy S6 with the following steps:

1. Included Graphics APIs OpenGLES2
2. Texture streaming and generated mipmaps and mipmap streaming
3. Incremental GC
4. C++ Compiler set to Master (was previously set to Debug)
5. Depth Texture off in URP

---
Tags: unity, android, lag
---


# Question
Title: When to carry on with a buggy game state versus terminate the process?
Imagine a situation where a level/game designer has missed assigning a prefab in one of the game objects' inspector configurations. (I am coming from Unity, but what I basically mean a reference to some object prototype).

In this case we are getting a `NullReferenceException` which could crash the game.

If we know that this could happen, we can prevent this exception and print something useful to the console.

How should we choose between these two methods?

* throw an exception and crash the process
* or just print something useful to the console for the developer to know.

The problem is when player would be playing the game, in case of an exception they would be thrown out of the game and it would stop working showing them what has gone wrong and to send info to the developer, but in case of console log they would be able to continue playing the incomplete version of the game.

It may seem like this question requires an opinionated answer, but to me it seems like there is a best practice for these situations and there are vivid pros and cons to each one.

**My thoughts:**

If player continues to play an incomplete game this will result in an incomplete experience which may lead to bad reviews or something like that. But when game is terminated at some point - player may be even angrier that game is not working at all.

My own conclusion is that you would rather continue with the game, but in case of any error logs you would display player that something has gone wrong in the UI.

**Unity specific:**

Unity usually runs fine after unhandled exception has been thrown, so there could be no point to this.

But the problem is that I have a choice between:

```
Debug.LogError("Something useful for the designer.");
return new ADummyObjectThatWillPreventFutherExceptions();

```

or

```
throw new NullReferenceException("Something useful for the designer.");

```

The second one seems more appealing since it's really hard or impossible to predict most situations when this could happen.

# Answer
There are a few considerations here:

1. **Can you *ensure it doesn't happen* at runtime, by construction?** (yes ➡ do that instead)

This isn't always possible, but in the cases where it is I'd argue it's better than either a hard crash or a soft fail. Not only does an error that *cannot* happen no longer have power to harm your game experience, it also frees you from spending time or energy checking for it.

In Unity, you can use the `[RequireComponent(typeof(Dependency))]` attribute to guarantee your objects are created with the components they're dependent on attached. You can also use the `OnValidate()` message to ensure an object is configured in a sensible way at design time, and fix it automatically or error before the game is even run.

If you're working with C# 8.0, you may even be able to enable Nullable reference types, designating certain variables to never be allowed to be null, and warning in many cases where nulls may be handled unsafely, minimizing the surface area for null reference errors to arise at runtime.

Unit testing covering all the edge and corner cases of your systems can be another great way to catch many potential errors of this type in isolation, before they become hard-to-reproduce bugs in your gameplay.

See if you can incorporate this into your build/check-in pipeline. In the continuous integration system we use at the studio where I work, every new submission has to pass a battery of validation steps before it can be submitted, and before the submitted data is accepted into the next build. This catches common errors like invalid references in designer-made assets, so a whole class of data setup error is nipped in the bud.
2. **Can this system do *anything useful* in this error state?** (no ➡ hard fail)

If you have a camera follow script, it doesn't make any sense without a target to follow. A character select screen can't let you continue with a null character selected.

If the game isn't going to be playable past here anyway, you might as well throw a hard fail to make the exact site the error was detected as easy as possible to spot and fix.

Something that arose in the comments: even if the camera example seems harmless/obvious enough to skip the hard fail, crashing here can be useful in particular if you have any automated testing in your game. Say I have a script that boots the game into each level/sector/mission beat to make sure it loads, and runs around randomly to see if it falls through an unloaded floor. Because this script is playing "blind," it's not going to notice if it manages to run right out of view because the camera follow script glitched, so it might report "loaded and played fine!" when a human player would find it anything *but* fine. Upgrading this to a crash makes it something even a very naive testing script can't miss, and it saves you from repeating the check in every test case if you trap it at its source.
3. **Can this system do anything *harmful* in this error state?** (yes ➡ hard fail)

I'm currently wiring up some networking logic for a client-server game in a personal project. This involves a lot of coordinated state transitions and handshaking to be sure everyone stays in sync. If I manage to somehow find myself in a game state that I should not have been able to reach from where I was, this could be a *Bad Thing*™ - potentially causing cascades of additional errors that spill out into the server or impact other players, maybe even corrupting saved game progress.

In this type of situation, a hard fail is a bulkhead to contain the error before it causes more damage. This type of error can also be a bit subtle and hard to track down if it runs away on you: the first observable symptom could be multiple game state transitions down the road from the first place you went off the rails, so `Assert`ing at each transition that you've come from a valid state into another valid state can catch the culprit before you completely lose your map of the territory.

Anything dealing with file access - and especially transactions or interaction with players' entitlements - is prone to this kind of consideration.
4. **Is the error mostly cosmetic, at least for now?** (yes ➡ soft fail / log)

Small glitches will happen. We know this. Crashing/excepting on *every* undotted i or uncrossed t is going to slow down everyone's workflows and breed frustration. Especially if you're just prototyping a section that might not go in the released game anyway - you want to be able to be a bit loose so you can test the important stuff and not sweat the details.

Timing matters here. What's just a cosmetic error early in development can become a compliance failure by the end, so expect to upgrade this class of bug later - maybe add a pre-processor directive or log level parameter that will let you escalate this from a warning to an error/crash when it comes time for polish.

I'm currently working on a large open world game, and one of the most common errors I see is exceeding asset budgets for the number of props or vegetation objects in the current loaded chunks. This isn't really that much of a problem on our dev machines, which are built well above the game's minimum target spec. And if the framerate starts to chug a little bit, but folks can still do their work and test, then that's better than crashing and rendering a section of the map unplayable until the artists have time to fix it. (And also better than culling props past the budget limit - props that might be required for mission completion). So we just log warnings "Too many Asset type Xs loaded. The collection will expand in dev mode, but this will not work in release."

Now, when we come closer to shipping and our game needs to hit our target framerate on the fixed hardware of a console, then we do a more stringent pass to prune whatever's over-budget, or outright fail validation of chunks that cross the limit.

This phased approach lets us dial in the gameplay experience and look first, then get more strict about ironing out the technical details once that foundation is secured.
5. **None of the above? Use your judgement.**

There's not a hard & fast rule for everything. At some point you will need to make a judgement call, or lean on a "house rule" policy or convention about how your team typically handles this type of scenario. Being consistent with how it's handled elsewhere in your project minimizes surprises and the risk of missing an important error/fix.
> 48 votes

# Answer
Let me get philosophy out of the way. If you think that the goal of game development is to deliver an experience to the players. Then that's it. Remove or hide anything that would break that experience.

Instead, think of giving a good experience to developers, designers, testers and players.

---

Now, I can be a bit more pragmatic. *DMGregory answer is even more pragmatic.*

I present to you the concept of environments:

* Development environment
* Testing environment
* Release environment

*These might map to phases, or they might be custom builds.*

On your development environment, you want to fail fast. The sooner the developer is aware of a mistake, the faster you can fix it, and the cheaper it will be. *The cost of fixing bugs grows with time.*

On the testing environment, the focus should be on getting the most information. If you can get stack traces, screen shots, a list of recent input, and so on, then do that. That would make it easier to track down those bug that did not happen often enough.

On the release environment, you still want to get as much information as possible. But you should not inconvenience the player. Furthermore, privacy and law comes into play when collecting information. That is something you should address in an EULA.

Thus, I'm saying that the way you deal with an exception, should depend on the environment.

---

You should also consider the type of exception.

We have exception from which you can't or it makes no sense to recover (such as a `OutOfMemoryException`).

Then there are exception that you should prevent instead of handle. These are exceptions for developers and should not reach Release (such as `NullReferenceException`). It could be that the developer missed them and they got into a testing environment. Code review, static analysts, and tests will help you find them.

On a test environment, you want to gather as much information of how they happened. So that the developer can figure out how to prevent them.

And finally there are exception that you should not prevent, but handle. These are exception about I/O (such as `FileNotFoundException`). For these, get a log, and try to recover and keep the game running. *Note that even if you check if the file is there, the OS could preempt the thread after the check and when you use it. That gives a chance to another process to delete it.*

Exceptions ere, of course, exceptions. Some systems will hide them, leading to a different exception down the road, one that should not be. *It is exceptional*. For example, the system loading a corrupted file should throw. Yet, they could have made it return null instead. That will lead to a hard to debug `NullReferenceException`, which could make its way to Release.

*Oh, and null in Unity is a special case, because it isn't actually null.*

This reduces the question to: how to handle an exception that should not reach Release, but did anyway? Well, I have one more concept for you…

---

Defensive programming and Offensive programming. Defensive programming is about checks and validations to prevent errors. While offensive programming is about letting errors happen and either crashing or recovering.

In Release. If you are dealing with external systems, be Offensive (e.g. do not try to prevent I/O exceptions, recover from them). If you are dealing with internal systems, be Defensive.

For example, a saved game is something you did not release with your game, and thus treat as external. Thus, when loading it, the guideline is to use offensive programming. No checks. On a corrupted save file, the system should throw. If it loads well enough to run, and if there is something missing because it failed to load, let it crash.

But a stage is something you did release with your game, and thus you may treat as internal. Thus, when loading it, the guideline is to be defensive. Check that it loads, if it didn't, have a fallback, or disable the content. For example, dialog fails to load, have some default dialog. Nobody should notce.

Note: You do not want the fallback content in the testing environment. Instead, you want testers to catch the problem giving you a chance to fix it.
> 8 votes

# Answer
You should always **handle exceptions if you know what they are about, and crash if you don't**.

Players overwhelmingly prefer a crash to a corrupted save.

If you want just one single rule that handles any and all unhandled exceptions, the only feasible one is to crash. Sure, it's far better if there is more graceful handling in case of minor/cosmetic bugs - but to do that you need to figure out which ones are minor/cosmetic.

You can handle minor/cosmetic bugs by writing to the log and or implementing a "temporary" workaround. But to decide if a bug is minor/cosmetic you have to first know what the bug is.

---

> it's really hard or impossible to predict most situations when this could happen.

If there are lots of unhandled exceptions that are impossible to predict, there are major flaws in the software that must be addressed. If there are just a few unhandled exceptions, you find them with Unit Testing, then internal testing, then alpha and beta testing.
> 3 votes

# Answer
# Pain is useful

Check this explanation of the 4 types of exceptions: https://ericlippert.com/2008/09/10/vexing-exceptions/
Out of these, it seems that you are talking about the second type; **boneheaded exceptions**.

> are your own darn fault, you could have prevented them and therefore they are bugs in your code. You should not catch them; doing so is hiding a bug in your code. Rather, you should write your code so that the exception cannot possibly happen in the first place, and therefore does not need to be caught.

It sounds extreme, but exceptions are like pain. If you hold your hand into an open flame, you don't want to just be thinking *"Hu, that feels funny. Anyway..."*.

# Development vs. Release

Like you say yourself, *"Unity usually runs fine after unhandled exception has been thrown"*, so during development, catching boneheaded exceptions doesn't give you a considerable advantage. Even worse, it does add more work to do. However, your text seems to be talking about a released game. Contrary to intuition, it's even *worse* there!

You set the example of a missing prefab. Let's say it's the graphics for your armor in a 2D platformer. Now that armor isn't being displayed, but you can still play. So we catch the exception, write a log message that the armor prefab is missing and accept it as a glitch.

Now the player proceeds and they update their armor. They proceed to play and it seems fine. Then they are done for the day and save it. The next day they try to load the save and it's corrupted.

So now we get a bug report about a corrupted save game. There's a certain, more or less specific sequence of actions that lead to this. Because of our attitude towards exceptions, a couple of other exceptions have been thrown in between - the one about the armor seems like the least likely candidate.
And now you may try and remotely debug this issue, via a third party that is probably a non-developer player, starting with a description of *"Loading saved game doesn't work"*.

# In all seriousness

The question is of course how "serious" you are about your game - are you even planning to support your game after release? If you're making something similar to Flappy Bird, or those 2000s flash games, the extra effort of fixing exceptions is probably not worth it.
> 2 votes

# Answer
The short answer from me is: You shouldn't ever carry on with a buggy game state. Anything you do carry on with needs to be considered "acceptable" at minimum. While @Theraot was on point with the discussion of environments, in my opinion it's a little bit more simple. Instead of what *environment* you're running, consider this:

Who is seeing the error?

* **A Developer**: Fail fast, and fail hard. Any unfixed bugs that make it past the developer will only become a bigger headache for people who know nothing about the code. I won't touch on runtime assertions here, but in my opinion it fails under the "fail-fast" mentality (Per @DMGregory: If the error can't happen, you never need to worry about it!).
* **A Tester**: Similar to developers, but provide more information than typically necessary, to save time in hunting down the details of a bug once reported. This would be akin to printing stack information, variable inputs, etc.
* **A User**: Again, fail fast. In this case, however, the end-user is *very unlikely* to be able to make use of the information that would be presented to a tester or developer. They need a new class of feedback.

In terms of responding to a user about crashing feedback, let's go off into a real world example, Minecraft's older error reporting system: Hopper.

On a game crash, a user would be presented with a plethora of information that was seemingly useless to anyone code-illiterate (read: many young children playing the game):

To alliviate this, Mojang added *Hopper*, which would receive a report from the client of the unique type of crash (e.g. you could hash the stack trace). The service can then have a landing page for those errors, which would provide more specific, user-level feedback about the crash, and how to fix it.

The main point I'm trying to drive home here is that lots of information can be good and helpful. However, in a production environment, sometimes more information can actually just mislead and confuse people, versus a simpler explanation from someone who understands the context of the issue. This also allows you to explain real-world crashes that aren't fixable by developers (e.g. not having graphics drivers installed), and provide remedies for those issues to your end-users.

You should not accept a buggy game state, as simply letting a bug continue onward in your game can leave as bad of an impression on users as your game crashing. But game crashes are much more obvious and likely to be fixed than silent bugs, motivating your developers to not push a buggy/crashing build to begin with.
> 0 votes

---
Tags: exceptions, error-management
---