# Question
Title: How can I access a ScriptableObject from C# class?
I adjust my level settings in a Scriptable Object and I want to access that Scriptable Object from a non-Monobehaviour C# class. When I use ScriptableObject.CreateInstance\<\> method, I get default values of fields in ScriptableObject; but I want to access the values that I adjusted in the inspector. How can I do that ?

My scriptable object class

```
[CreateAssetMenu(fileName = "NewLevelSetting", menuName = "Level/New Level Setting")]
public class ScriptableLevelSettings : ScriptableObject
{
    // Only for initial level settings

    [SerializeField] private int _forwardPlatformCount = 30;
    public int ForwardPlatformCount { get => _forwardPlatformCount; }

    [SerializeField] private int _bendPlatformCount = 0;
    public int BendPlatformCount { get => _bendPlatformCount; }

    [SerializeField] private int _forwardPlatformIncreaseAmount = 2;
    public int ForwardPlatformIncreaseAmount { get => _forwardPlatformIncreaseAmount; }

    [SerializeField] private int _bendPlatformIncreaseAmount = 1;
    public int BendPlatformIncreaseAmount { get => _bendPlatformIncreaseAmount; }
}

```

LevelSettings class should access the scriptableobject to set its initial values and adjust those values with the given "level".

```
public class LevelSettings
{
    private ScriptableLevelSettings _initialSettings;

    private int _forwardPlatformCount = 30;
    public int ForwardPlatformCount { get => _forwardPlatformCount; private set => _forwardPlatformCount = value; }

    private int _bendPlatformCount = 0;
    public int BendPlatformCount { get => _bendPlatformCount; private set => _bendPlatformCount = value; }

    private int _forwardPlatformIncreaseAmount = 2;

    private int _bendPlatformIncreaseAmount = 1;

    private int _maxBendPlatformCount = 3;

    public LevelSettings(int level)
    {
        InitializeSettings();
        SetSettings(level);
    }

    private void InitializeSettings()
    {
        _initialSettings = ScriptableObject.CreateInstance<ScriptableLevelSettings>();
        if (_initialSettings != null)
        {
            _forwardPlatformCount = _initialSettings.ForwardPlatformCount;
            _bendPlatformCount = _initialSettings.BendPlatformCount;
            _forwardPlatformIncreaseAmount = _initialSettings.ForwardPlatformIncreaseAmount;
            _bendPlatformIncreaseAmount = _initialSettings.BendPlatformIncreaseAmount;
        }
    }

    private void SetSettings(int level)
    {
        _forwardPlatformCount += level * _forwardPlatformIncreaseAmount;
        // Uncomment for linear bend count increase
        //_bendPlatformCount += Mathf.FloorToInt(level / 15) * _bendPlatformIncreaseAmount;
        _bendPlatformCount += Random.Range(0, _maxBendPlatformCount);
    }
}

```

I want my LevelSettings class to access the values below:

# Answer
> 1 votes
Myself, I'd invert the dependency here:

* Rather than the current level settings class being responsible for searching the ether to find the particular settings asset it should be using...
* ...the level settings asset can be responsible for producing current level settings as a service, like a factory.

This can also make the current level settings very lightweight - a "Plain Old Data Structure". We could even implement it as an immutable struct:

```
[System.Serializable]
public struct LevelSettings {
    [SerializeField] int _forwardPlatformCount;
    public int ForwardPlatformCount { get { return _forwardPlatformCount; } }

    [SerializeField] int _bendPlatformCount;
    public int BendPlatformCount { get { return _bendPlatformCount; } }

    public LevelSettings(int forwardPlatformCount, int bendPlatformCount) {
        _forwardPlatformCount = forwardPlatformCount;
        _bendPlatformCount = bendPlatformCount;
    }
}

```

Then the work of generating a set of level settings according to a particular progression rule is the responsibility of a "Level Generation Settings" asset:

```
[CreateAssetMenu(fileName ="LevelGenerationSettings.asset", menuName ="Settings/Level Generation")]
public class LevelGenerationSettings : ScriptableObject {
    [SerializeField] LevelSettings _initialSettings = new LevelSettings(30, 0);

    [SerializeField] int _forwardPlatformIncreaseAmount;
    [SerializeField] int _bendPlatformIncreaseAmount;
    [SerializeField] int _maxBendPlatforms;

    public LevelSettings GetInitialSettings() {
        return _initialSettings;
    }

    public LevelSettings AdvanceLevel(LevelSettings current, int steps) {
        int bends = current.BendPlatformCount;
        for (int i = 0; i < steps; i++)
            bends += _bendPlatformIncreaseAmount + Random.Range(0, _maxBendPlatforms);

        int forwards = current.ForwardPlatformCount
                    + _forwardPlatformIncreaseAmount * steps;

        return new LevelSettings(forwards, bends);
    }
}

```

Your `LevelGenerator` script has knowledge about what kinds of levels it's supposed to be generating. It can hold a reference to the `LevelGenerationSettings` asset it should be using - possibly passed to it from a difficulty/mode selection script, or as part of the inspector configuration in this mode's scene file, like:

```
[SerializeField] LevelGenerationSettings _generationSettings;

```

(This also lets you swap out different settings asset files for experimental testing, even if you only use one canonical settings asset in the released game)

Then the generator can produce the current level settings like:

```
_levelSettings = _generationSettings.GetInitialSettings();

```

And advance to the next level like:

```
_levelSettings = _generationSettings.AdvanceLevel(_levelSettings, 1);

```

# Answer
> 1 votes
Yeah, what you trying to do won't work; ScriptableObjects by definition are never instantiated in-game (instead they are "instantiated" in-project.)

ScriptableObjects can have methods but as such they really function more like static classes.

So, to get a reference to them you'll need to refer to them either as an exposed variable populated in the inspector in a Monobehavior, or by loading it/them at runtime as a Resource or Addressable or AssetBundle.

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


# Question
Title: Why doesn't my button work with Unity's New Input System?
I have decided to move from Unity's old input system on to the `New Input System` to control my mobile game.

I am having some issues with buttons, especially the a and b buttons. The A button represents the `W` key on the keyboard and the B button represents the `Space` key on the keyboard, while the joystick is implemented using the new input system using `PlayerInput.actions[" "].readValue<TValue>()`, but for those two buttons I don't have any idea how to bind them to the keyboard. I have already added `OnScreenButton` but when I play the game, the buttons not working.

```
private void Update()
{
    this.thrusting = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);

    if (m_MoveAction.ReadValue<Vector2>().x > 1 || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    {
        this.turnDirection = 1.0f;
    }
    else if (m_MoveAction.ReadValue<Vector2>().x < -1 || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    {
        this.turnDirection = -1.0f;
    }
    else
    {
        this.turnDirection = 0.0f;
    }

    if (Input.GetKeyDown(KeyCode.Space))
    {
        Shoot();
    }
}

```

I have added

```
this.thrusting = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);

```

but why is it not working when I press the A button? What am I missing here?

# Answer
Because you're not using the new input system.

Everything that begins `Input.` is the *old* input system. When you enable the new input system, Unity completely disables the old one, and issues explicit error messages to alert you if you try to use any of the disabled code, like `Input.GetKey()` / `Input.GetKeyDown()`:

> InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.

(This is why it's important to read your error messages, and include them in your question if you don't understand them)

You seem to be assuming that the job of the `OnScreenButton` is to take on-screen input and route it as key presses to the *old* input system so you can read it with legacy code. But the error message tells you that's not the case - you cannot use legacy code with the new input system, full stop.

So, we need to handle our input using the new input system.

* Inside your `InputActions` asset, you'll have an `ActionMap` for your movement controls.
* Inside this action map, create a new Button-type `Action` for "Thrust" and "Shoot"
* Create bindings for these actions to the  / `w` and `Space` keys.

Just like you've done for the joystick action variable `m_MoveAction`, you can assign actions for the buttons:

```
m_ThrustAction = playerInput.actions["Thrust"];
m_ShootAction =  playerInput.actions["Shoot"];

```

Then you can replace

```
this.thrusting = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);

```

with

```
this.thrusting = m_ThrustAction.ReadValue<float>() > 0;

```

and

```
if ( Input.GetKeyDown(KeyCode.Space) )

```

with

```
if ( m_ShootAction.triggered )

```

Or you can use the `PlayerInput` component to wire-up event callbacks to fire only when the states of these actions change, instead of polling them every frame in update.
> 3 votes

---
Tags: unity
---


title: Shooting from Gun in LibGDX

text:
# Question
Title: Shooting from Gun in LibGDX
I'm trying to shoot a bullet from the tip of a gun. This gun is a Sprite object and it is constantly being rotated to point towards the mouse. The issue is that the point to shoot the bullet from is always changing because the sprite rotates. How can I calculate the point to shoot from the tip of the gun when the sprite rotates?

```
    @Override
    public void render(SpriteBatch batch) {
        super.render(batch);

        Sprite weaponSprite = this.currentWeapon.getSprite();

        Vector3 mv = screen.getBatchCamera().unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
        weaponSprite.setOriginCenter();
        weaponSprite.setRotation(CalcUtils.getAngle(new Vector2(weaponSprite.getX(), weaponSprite.getY()), new Vector2(mv.x, mv.y)));
        weaponSprite.setFlip(this.isFlipped(), false);

        batch.begin();
        if (this.isFlipped()) {
            weaponSprite.setPosition(this.getPosition().x - 3, this.getPosition().y);
        } else {
            weaponSprite.setPosition(this.getPosition().x + 23, this.getPosition().y);
        }
        weaponSprite.draw(batch);
        batch.end();

    }

```

```
    @Override
    public void update(float delta) {
        super.update(delta);

        this.shootTime += delta;

        Sprite weaponSprite = this.currentWeapon.getSprite();
        Sprite bulletSprite = this.currentBullet.getSprite();
        if (Gdx.input.isButtonJustPressed(Input.Buttons.LEFT)) {
            this.shootTime = 0;

            Vector2 bulletPosition = new Vector2(weaponSprite.getX(), weaponSprite.getY());  // this is the beginning position of the project, what the bullet will start at
            bulletSprite.setSize(2, 2);
            bulletSprite.setOriginCenter();

            if (weaponSprite.isFlipX()) {
                bulletPosition.add(-3, weaponSprite.getHeight() - 2);
            } else {
                bulletPosition.add(weaponSprite.getWidth() + 1, weaponSprite.getHeight() - 2);
            }

            Vector3 mv = screen.getBatchCamera().unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
            Projectile projectile = Projectile.create();
            projectile.beginning(bulletPosition);
            projectile.ending(new Vector2(mv.x, mv.y));
            projectile.speed(500f);
            projectile.sprite(bulletSprite);
            projectile.start();
        }
    }

```

# Answer
**libGDX**s `Vector2` class has the methods you need to calculate this.

By defining a `barrelOffset`

```
barrelOffset = new Vector2(1.0f, -0.5f).scl(0.5f); // Relative coordinates to where the barrel is in the sprite

```

as the relative position of the barrel in the sprite, we can figure out where the rotated barrel is by taking the position of the player and adding the `barrelOffset` rotated by the angle the player is facing plus the rotation origin.

`Vector2d.rotate` can do the rotation for you:

```
    Vector2 direction = (new Vector2(1.0f, 0.0f)).rotateDeg(angle); // unit vector of the direction of the player
    Vector2 origin = new Vector2(0.5f, 0.5f); // rotation origin, rotate around the center of the image. ( 0,0 would have been upper left corner)
    Vector2 offset = (new Vector2(barrelOffset)).rotateDeg(angle).add(origin); // Rotated barrel offset
    Vector2 barrelPosition = (new Vector2(position)).add(offset);

```

Full source code for the animation above is:

```
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.glutils.*;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.utils.*;

public class MyGdxGame extends ApplicationAdapter {

    public static class Bullet
    {
        public Vector2 position = new Vector2();
        public Vector2 direction = new Vector2();

        public Bullet(Vector2 position,  Vector2 direction)
        {
            this.position.set(position);
            this.direction.set(direction);
        }

        public void update(float delta) {
            float speed = 16.0f;
            position.add(direction.x * delta * speed, direction.y * delta * speed);
        }
    }

    OrthographicCamera camera;
    SpriteBatch spriteBatch;
    ShapeRenderer shapeRenderer;
    Texture texture;

    Vector2 position;
    Vector2 barrelOffset;
    float angle;

    Array<Bullet> bullets;

    @Override
    public void create() {
        float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight();
        camera = new OrthographicCamera(10, 10 / aspectRatio);
        spriteBatch = new SpriteBatch();
        shapeRenderer = new ShapeRenderer();
        texture = new Texture("hitman1_gun.png"); // From https://opengameart.org/content/topdown-shooter (Kenney)

        position = new Vector2();
        barrelOffset = new Vector2(1.0f, -0.5f).scl(0.5f); // Relative coordinates to where the barrel is in the sprite

        bullets = new Array<>();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        spriteBatch.setProjectionMatrix(camera.combined);
        spriteBatch.begin();

        Vector2 direction = (new Vector2(1.0f, 0.0f)).rotateDeg(angle); // unit vector of the direction of the player
        Vector2 origin = new Vector2(0.5f, 0.5f); // rotation origin, rotate around the center of the image. ( 0,0 would have been upper left corner)
        Vector2 offset = (new Vector2(barrelOffset)).rotateDeg(angle).add(origin); // Rotated barrel offset
        Vector2 barrelPosition = (new Vector2(position)).add(offset);

        float delta = Gdx.graphics.getDeltaTime();
        if (Gdx.input.isKeyPressed(Input.Keys.A))
            angle += delta * 90.0f;
        if (Gdx.input.isKeyPressed(Input.Keys.D))
            angle -= delta * 90.0f;
        if (Gdx.input.isKeyPressed(Input.Keys.W))
            position.add(direction.x * delta * 2.0f, direction.y * delta * 2.0f);
        if (Gdx.input.isKeyPressed(Input.Keys.S))
            position.sub(direction.x * delta * 2.0f, direction.y * delta * 2.0f);
        if (Gdx.input.isKeyPressed(Input.Keys.SPACE))
            bullets.add(new Bullet(barrelPosition, direction));

        for(Bullet bullet : bullets)
            bullet.update(delta);

        spriteBatch.draw(texture,
                position.x, position.y,
                0.5f, 0.5f,
                1, 1,
                1, 1,
                angle,
                0, 0,
                texture.getWidth(), texture.getHeight(),
                false, false);

        spriteBatch.end();

        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        shapeRenderer.setColor(Color.RED);

        for(Bullet bullet : bullets)
            shapeRenderer.circle(bullet.position.x, bullet.position.y, 0.1f, 32);

        shapeRenderer.end();
    }
}

```
> 1 votes

# Answer
You could use trigonometry to do this.

Where T is the angle:

sinT = O / H
H * sinT = O

And you can see that O (Opposite) is basically the Y axis. Do the same with cosine, and you'll get A (Adjacent) which is basically the X axis. H would be the distance from the gun's pivot to the muzzle, and T is the angle.
> 0 votes

---
Tags: java, 2d, libgdx, rotation
---


title: Acceleration along Bezier Curve

text:
# Question
Title: Acceleration along Bezier Curve
Does anyone know how to accelerate a moving object along a Bezier curve? I found a post here that seems to solve the problem but I do not understand how to apply this code, particularly what is done to the "NewT" value in the "Finally, accelerating the ships" section of the answer.

I apologise about raising a new question about this, I was prohibited from commenting on the original question. If anyone has a solution in C# that goes through and explains each step that would be highly appreciated.

\__

Further detail:

Scenario: The moving object moves with linear velocity until it reaches P1. When it reaches P1, I need to create the motion of the blue dashed path. Whilst the object follows the blue dashed path, it needs to uniformly accelerate from Velocity(start) to Velocity(end). Please note that the path is a rough sketch, in reality it should have smoother curvature without the abrupt changes in direction.

The following pieces of information are known:

* Velocity (start), e.g. 5 m/s
* Velocity (end), e.g. 10 m/s
* The locations of the four points P1 - P4
* The location of the centre of the circle

So far I have been able to successfully create a curve path by joining multiple bezier curves to form a spline:

But I do not know how to accelerate the yellow dot as it moves through the path. Any help would be really appreciated.

# Answer
> 1 votes
The behaviour you're describing is something we can get "out of the box" with a cubic Bézier spline, no new features required. You just need to set the control points accordingly.

If we want our path to begin at position `p0` with velocity `v0`, and end at `p1` with velocity `v1` after a `duration` in seconds, then our four control points are:

```
c0 = p0
c1 = p0 + v0 * duration / 3.0f
c2 = p1 - v1 * duration / 3.0f
c3 = p1

```

You can then evaluate this at a time `t` seconds after leaving the start point as:

```
float progress = t / duration;
Vector2 position = Bezier(c0, c1, c2, c3, progress);

```

...where the Bézier function is the usual:

```
Vector2 Bezier(Vector2 c0, Vector2 c1, Vector2 c2, Vector2 c3, float p) {
    float invP = 1 - P;
    return  invP * invP * invP * c0
         + 3 * invP * invP * p * c1
            + 3 * invP * p * p * c2
                   + p * p * p * c3;
}

```

If you like the shape you get using those control points, you're golden. Using the `p1`, `v1` of one segment as the `p0`, `v0` of the next segment will give you first derivative continuity across the spline (smooth connections with no sharp corners or sudden changes in speed).

# Answer
> 0 votes
The following code gets the point along a Bézier curve, for an arbitrary number of control points:

Adapted from https://stackoverflow.com/questions/785097/how-do-i-implement-a-bézier-curve-in-c

```
vector_4 getBezierPoint(vector<vector_4> points, float t)
{
    size_t i = points.size() - 1;

    while (i > 0)
    {
        for (size_t k = 0; k < i; k++)
        {
            points[k].x += t * (points[k + 1].x - points[k].x);
            points[k].y += t * (points[k + 1].y - points[k].y);
            points[k].z += t * (points[k + 1].z - points[k].z);
            points[k].w += t * (points[k + 1].w - points[k].w);
        }

        i--;
    }

    return points[0];
}

```

---
Tags: motion
---


# Question
Title: How to make a pixel painting program using Unity
So I'm making an Android app/game using Unity where the user is able to "draw" by touching the screen. The drawings will be pixel art -- basically, a pixel art drawing function -- so everything should be pixel perfect.

Some functions I will add are:

1. Changing brush size
2. Changing brush color
3. Filling areas
4. Erasing

A game called *Worldbox* has a pretty similar function, where users are able to draw "land."

I thought about using the **tilemap** function of Unity, and even made a program that does all #1~#4 well. However, if the tilemap(drawing size) exceeds 100\*100 tiles, the app took forever to load, and I concluded that tilemaps weren't suited for drawing programs.

A friend of mine said that I would have to make some kind of "editor" for this application, and Unity just isn't fit for that.

However, I only know how to make applications using Unity, so **are there any Unity functions I can use to make this app?**

The answer could be very simple(ex. Just use the tilemap function). It doesn't have to explain *how* I could make this app, but *what* I could use.

# Answer
If you’re painting an image with pixels, why not just actually paint the pixels? Set a low res UI image and then figure out where in the image clicks or taps happen. Then paint the pixel? Then you can redraw the image using the optimized image manipulation functions already built into unity.

The main challenge will be converting between click coordinates to pixel coordinates. But if you know/control the size of the screen and the size of the image, that shouldn’t be super hard.
> 1 votes

---
Tags: unity, pixel-art
---


# Question
Title: How can I create a "see behind walls" effect?
*Divinity: Original Sin 2* has a beautiful see-through system. When I go behind walls, a splash mask will appear, and when I move around the game, it changes. It's like a dissolve shader, and has a metaball effect.

How can I replicate this effect, creating a dynamic splash mask when players go behind walls?

You can see the desired effect in motion via this YouTube video.

# Answer
# Masking

To make this effect, you can mask objects by using a stencil Buffer.

> the stencil buffer is a general purpose buffer that allows you to store an additional 8bit integer (i.e. a value from 0-255) for each pixel drawn to the screen. Just as shaders calculate RGB values to determine the colour of pixels on the screen, and z values for the depth of those pixels drawn to the depth buffer, they can also write an arbitrary value for each of those pixels to the stencil buffer. Those stencil values can then be queried and compared by subsequent shader passes to determine how pixels should be composited on the screen.
>
> https://docs.unity3d.com/Manual/SL-Stencil.html
>
> https://alastaira.wordpress.com/2014/12/27/using-the-stencil-buffer-in-unity-free/
>
> http://www.codingwithunity.com/2016/01/stencil-buffer-shader-for-special.html

Wall Stencil:

```
Stencil
{
    Ref 1 // ReferenceValue = 1
    Comp NotEqual // Only render pixels whose reference value differs from the value in the buffer.
}

```

Mask Stencil:

```
Stencil
{
    Ref 1 // ReferenceValue = 1
    Comp Always // Comparison Function - Make the stencil test always pass.
    Pass Replace // Write the reference value into the buffer.
}

```

# Let's Implement.

use this as the mask:

```
Shader "Custom/SimpleMask"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _CutOff("CutOff", Range(0,1)) = 0
    }
    SubShader
    {
        LOD 100
        Blend One OneMinusSrcAlpha
        Tags { "Queue" = "Geometry-1" }  // Write to the stencil buffer before drawing any geometry to the screen
        ColorMask 0 // Don't write to any colour channels
        ZWrite Off // Don't write to the Depth buffer
        // Write the value 1 to the stencil buffer
        Stencil
        {
            Ref 1
            Comp Always
            Pass Replace
        }

        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;
            float4 _MainTex_ST;
            float _CutOff;

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

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                float dissolve = step(col, _CutOff);
                clip(_CutOff-dissolve);
                return float4(1,1,1,1)*dissolve;
            }
            ENDCG
        }
    }
}

```

use this as the wall:

```
Shader "Custom/Wall" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
        Blend SrcAlpha OneMinusSrcAlpha
        Tags { "RenderType"="Opaque" }
        LOD 200

        Stencil {
            Ref 1
            Comp NotEqual
        }

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

---

# Effect Analysis

If you want to have a procedural texture, you need some noises.

you can see this shader in ShaderToy.

To make this effect, instead of using UV Coordinates, use Polar Coordinates then set it to the noise texture.

> Uvs are typically layed out in a grid like fashion, like pixels n a screen (X = width, Y = height). Polar coordinates, however, use the x and y a bit differently. One determines how far away from the center of the circle it is and the other determies the degrees, from a 0-1 range, depending on what you need.

```
Shader "Smkgames/NoisyMask" {
    Properties {
        _MainTex ("MainTex", 2D) = "white" {}
        _Thickness ("Thickness", Range(0, 1)) = 0.25
        _NoiseRadius ("Noise Radius", Range(0, 1)) = 1
        _CircleRadius("Circle Radius", Range(0, 1)) = 0.5
        _Speed("Speed", Float) = 0.5
    }
    SubShader {
        Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha
        Cull Off

        Pass {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            #pragma target 3.0
            uniform sampler2D _MainTex; uniform float4 _MainTex_ST;
            uniform float _Thickness,_NoiseRadius,_CircleRadius,_Speed;

            struct VertexInput {
                float4 vertex : POSITION;
                float2 texcoord0 : TEXCOORD0;
            };
            struct VertexOutput {
                float4 pos : SV_POSITION;
                float2 uv0 : TEXCOORD0;
                float4 posWorld : TEXCOORD1;

            };
            VertexOutput vert (VertexInput v) {
                VertexOutput o = (VertexOutput)0;
                o.uv0 = v.texcoord0;

                o.pos = UnityObjectToClipPos(v.vertex);
                o.posWorld = mul(unity_ObjectToWorld, v.vertex);
                return o;
            }
            float4 frag(VertexOutput i, float facing : VFACE) : COLOR {

                float2 uv = (i.uv0*2.0+-1.0); // Remapping uv from [0,1] to [-1,1]
                float circleMask = step(length(uv),_NoiseRadius); // Making circle by LENGTH of the vector from the pixel to the center
                float circleMiddle = step(length(uv),_CircleRadius); // Making circle by LENGTH of the vector from the pixel to the center
                float2 polaruv = float2(length(uv),((atan2(uv.g,uv.r)/6.283185)+0.5)); // Making Polar
                polaruv += _Time.y*_Speed/10;
                float4 _MainTex_var = tex2D(_MainTex,TRANSFORM_TEX(polaruv, _MainTex)); // BackGround Noise
                float Noise = (circleMask*step(_MainTex_var.r,_Thickness)); // Masking Background Noise
                float3 finalColor = float3(Noise,Noise,Noise);
                return fixed4(finalColor+circleMiddle,(finalColor+circleMiddle).r);
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
}

```

another solution is using worley noise:

you can see this shader in ShaderToy

---

# Metaball

then I add the metaball effect from This article:

---

# Bill boarding

there is more...

If you want to rotate your mask, to look to your camera, you can use Bill board:

```
 output.pos = mul(UNITY_MATRIX_P,
              mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))
              + float4(input.vertex.x, input.vertex.y, 0.0, 0.0));

```

this is the mask with Bill boarding:

```
Shader "Custom/Mask/SimpleMaskBillBoard"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _CutOff("CutOff", Range(0,1)) = 0
        _Radius("Radius", Range(0,1)) = 0.2
        _Speed("speed", Float) = 1
        _ScaleX ("Scale X", Float) = 1.0
        _ScaleY ("Scale Y", Float) = 1.0
    }
    SubShader
    {
        LOD 100
        Blend One OneMinusSrcAlpha
        Tags { "Queue" = "Geometry-1" }  // Write to the stencil buffer before drawing any geometry to the screen
        ColorMask 0 // Don't write to any colour channels
        ZWrite Off // Don't write to the Depth buffer

        // Write the value 1 to the stencil buffer
        Stencil
        {
            Ref 1
            Comp Always
            Pass Replace
        }

        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;
            float4 _MainTex_ST;
            float _CutOff;
            float _Speed;
            float _Radius;
            float _ScaleX,_ScaleY;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_P,
                    mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))
                    + float4(v.vertex.x, v.vertex.y, 0.0, 0.0)
                    * float4(_ScaleX, _ScaleY, 1.0, 1.0));

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                float dissolve = step(col, _CutOff);
                clip(_CutOff-dissolve);
                return dissolve;
            }
            ENDCG
        }
    }
}

```

---

# Final result:

source is Available:https://github.com/smkplus/Divinity-Origin-Sin-2

---

# Useful Links

I found a good tutorial that Implemented this effect by Dissolving the world:

Dissolving the world Part 1

Dissolving the world Part 2

```
Shader "Custom/DissolveBasedOnViewDistance" {
    Properties{
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Center("Dissolve Center", Vector) = (0,0,0,0)
        _Interpolation("Dissolve Interpolation", Range(0,5)) = 0.8
        _DissTexture("Dissolve Texture", 2D) = "white" {}
    }

        SubShader{
        Tags { "RenderType" = "Opaque" }
        LOD 200

            CGPROGRAM

        #pragma surface surf Standard vertex:vert addshadow

        #pragma target 3.0

        struct Input {
            float2 uv_MainTex;
            float2 uv_DissTexture;
            float3 worldPos;
            float viewDist;
        };

        sampler2D _MainTex;
        sampler2D _DissTexture;
        half _Interpolation;
        float4 _Center;

        // Computes world space view direction
        // inline float3 WorldSpaceViewDir( in float4 v )
        // {
        //     return _WorldSpaceCameraPos.xyz - mul(_Object2World, v).xyz;
        // }

        void vert(inout appdata_full v,out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);

         half3 viewDirW = WorldSpaceViewDir(v.vertex);
         o.viewDist = length(viewDirW);

        }

        void surf(Input IN, inout SurfaceOutputStandard o) {

            float l = length(_Center - IN.worldPos.xyz);

            clip(saturate(IN.viewDist - l + (tex2D(_DissTexture, IN.uv_DissTexture) * _Interpolation * saturate(IN.viewDist))) - 0.5);

         o.Albedo = tex2D(_MainTex,IN.uv_MainTex);
        }
        ENDCG
        }
        Fallback "Diffuse"
}

```

---

Another stencil tutorial:

Stencil Tutorial
> 173 votes

# Answer
I'm developing a game called Tales of Tarium which I needed to create a similar effect.

Here's the code for the Shader:

```
Shader "Custom/Dissolve"{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _NoiseTex ("Noise (Dissolving)", 2D) = "white" {}
        _Metallic("Metallic", 2D) = "black" {}
        _NormalMap("Normal", 2D) = "bump" {}
        _Occlusion("Occlusion", 2D) = "white" {}
        _Emission("Emission ", 2D) = "white" {}
        _EmissionIntensity("Emission Intensity", Range(0,10)) = 0.19
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _DissolvePercentage("DissolvePercentage", Range(0,3)) = 0.0
        _DistaceMultiplier("DistaceMultiplier", Float) = 1
        [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Src Blend", Float) = 1
        [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Dst Blend", Float) = 0
        _AlphaCutout("Alpha Cutout", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent"}
        LOD 200
    CGPROGRAM
        // #pragma surface surf Tree fullforwardshadows addshadow
        #pragma surface surf Standard fullforwardshadows addshadow
        #pragma target 3.0

        fixed4 _Color;
        sampler2D _MainTex;
        sampler2D _NoiseTex;
        sampler2D _Metallic;
        sampler2D _NormalMap;
        sampler2D _ScreenGradient;
        sampler2D _Occlusion;
        sampler2D _Emission;
        half _Glossiness;

        half _DissolvePercentage;
        float _DistaceMultiplier;
        float _DistanceToCamera;
        float _AlphaCutout;

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_NormalMap; INTERNAL_DATA
            float3 worldPos;
            float3 worldNormal;
            float4 screenPos;
        };

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            float pixelDepth = UNITY_Z_0_FAR_FROM_CLIPSPACE(IN.screenPos.z);

            float aspectRatio = _ScreenParams.x/_ScreenParams.y;
            float2 screenPos = IN.screenPos.xy/IN.screenPos.w;
            screenPos.x *= aspectRatio;

            half distanceToCenter = 1 - distance(screenPos, float2(0.5*aspectRatio,0.5)) * _DistaceMultiplier;

            distanceToCenter = saturate(distanceToCenter);

            half grad01 = tex2D(_NoiseTex, IN.worldPos.xy).r;
            half grad02 = tex2D(_NoiseTex, IN.worldPos.xz).r;
            half grad03 = tex2D(_NoiseTex, IN.worldPos.yz).r;

            half gradient = grad01;
            gradient = lerp(gradient, grad02, IN.worldNormal.y);
            gradient = lerp(gradient, grad03, IN.worldNormal.x);

            float distanceMask = step(pixelDepth, _DistanceToCamera);

            clip (gradient - _DissolvePercentage * distanceMask * distanceToCenter);

            fixed4 c = tex2D(_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb * _Color;
            o.Alpha = 1;
            clip(c.a - _AlphaCutout);
            fixed4 m = tex2D(_Metallic, IN.uv_MainTex);
            o.Metallic = m.rgb;
            fixed4 g = tex2D(_Metallic, IN.uv_MainTex);
            o.Smoothness = g.rgb * _Glossiness;
            o.Occlusion = tex2D(_Occlusion, IN.uv_MainTex);
            fixed3 n = UnpackNormal(tex2D(_NormalMap, IN.uv_MainTex));
            o.Normal = n;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

And you'll need to add this to the player:

```
using UnityEngine;
public class Player : MonoBehaviour{
    private int _id;
    public string shaderVariableName = "_DistanceToCamera";
    private Vector3 _distanceObjectToCamera;

    public void Start(){
        _id = Shader.PropertyToID(shaderVariableName);
    }

    public void Update()
    {
        _distanceObjectToCamera = Camera.main.transform.position - this.transform.position;
        Shader.SetGlobalFloat(_id, _distanceObjectToCamera.magnitude);
    }
}

```
> 2 votes

---
Tags: unity, shaders, graphic-effects
---


title: Godot: Invalid set index error

text:
# Question
Title: Godot: Invalid set index error
I'm trying to make UI for my game and making a button that changes its own focus neighbour when pressed:

`$SettingsButton.focus_neighbour_left = $ItemGrid/Slot2`

But when I press the button, it gives this error:

`Invalid set index 'focus_neighbour_left' (on base: 'TextureButton') with value of type 'TextureButton'.`

I tried searching around but I don't know what this error is telling me or how to fix it.

To be clear, the scene tree isn't changing and Slot2 is a TextureButton.

# Answer
Thearot figured it out, I just needed to change

`$ItemGrid/Slot2`

to

`$ItemGrid/Slot2.get_path()`
> 1 votes

---
Tags: gui, godot
---


# Question
Title: Character Controller not colliding in Unity
I have a character controller on my player object however it will not collide with the terrain and will just fall through, what am i doing wrong. (PS I am really new to unity)

# Answer
To make collision between a Character Controller and scenery work in Unity, you have to ensure that both objects have a collider component. (BoxCollider, SphereCollider, CapsuleCollider or MeshCollider) Check your Character Controller properties as well to be sure.
> 2 votes

# Answer
Make sure that your character and terrain have a collider component(You can check this in inspector), and make sure that you're don't using for example: BoxCollider2D in 3d space.
> 0 votes

---
Tags: unity
---


# Question
Title: How do you exclude (gitignore) assets from Unity's package manager without messing up the references in your project?
My assumption is that, in any context , it is not a good practice to keep libraries and packages in your source control.

For instance, I have downloaded the "Platformer set" asset and imported it into my Unity project. It goes by default into ./Assets, but I have moved it into **./Assets/Packages**, folder which I have **added to my repository's .gitignore file**. This way I plan to differentiate custom assets (part of my source control) from public ones (which I plan to import on a second computer upon mapping the repository).

I have taken one of the tilesets in "Platformer set", sliced it, and created a tile palette.

Then I have used the tiles in the tile palette to edit a tilemap, building some platforms.

Finally, I delete the imported "Platformer set" found under ./Assets/Packages folder, since I would have the same result mapping my repository in a second computer (because ./Assets/Packages is not part of my source control).

My idea then would be to import the package again through the package manager, and move it to the right location. Unfortunately, at the very moment I delete the asset folder, the tilemap looses all the tiles related to that asset. Similar things would happen with animations created on imported asset's sprites, and many other types of assets.

So, long story short: **which is the right way (if it exists) to be able to exclude Unity assets from your source control using Git**, but avoiding messing up with your project files? I come from a C# application background where broken references remain there until you fix them, they don't dissappear.

**Or should I keep the packages in the source control?** A second developer mapping the Unity project with git would have these packages downloaded onto their machine as part of the mapped Unity project, even if they don't have them downloaded using their package manager in the first place (which makes you end up with a weird development environment, taking into account that the normal workflow is that you FIRST download them with the package manager into a common location in your PC and THEN you import them into your project).

# Answer
> 1 votes
For packages (not assets), you should include your project's Library folder in the .gitignore. Unity has a manifest.json file in the packages folder (that should be in your repo) that will tell it which packages to install locally.

For Assets, (not packages), unless the license forbids it, I keep them in source control if possible. This makes everything way easier. It keeps projects in sync easily between computers and makes the project loadable from everywhere. For Assets that are too big, I use git LFS (large file storage). If the license forbids it, I first try to not use that asset, or if that asset is absolutely necessary, I try to hack together some weird solution, often involving .unitypackages in some form (they keep GUIDs consistent).

For custom packages, I set up a private passworded Verdaccio package server on my google cloud, and then point unity's package manager to that server so I can sync my own content between unity projects outside of git. When switching computers, I just have to log into the server once, and unity remembers the login token for the private server.

Edit: Just to add, many of my custom packages contain assets themselves. This is fine.

---
Tags: unity, assets, git
---


# Question
Title: Roblox badge not being rewarded on live game but does in studio
I have the following code in Roblox in a file under ServerScriptService and it gives a player a badge when they touch a specific part. It works on studio locally but once published its not working.

```
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local part = game.Workspace.Levels["040"].Spawn
local BadgeID = ########
local needBadge = true

local function awardBadge(userId, badgeId)
    -- Fetch badge information
    local success, badgeInfo = pcall(function()
        return BadgeService:GetBadgeInfoAsync(badgeId)
    end)
    if success then
        -- Confirm that badge can be awarded
        if badgeInfo.IsEnabled then
            -- Award badge
            local awarded, errorMessage = pcall(function()
                BadgeService:AwardBadge(userId, badgeId)
                print("Give player badge")
                needBadge = false
            end)
            if not awarded then
                warn("Error while awarding badge:", errorMessage)
            end
        end
    else
        warn("Error while fetching badge info!")
    end
end

Players.PlayerAdded:Connect(function(player)
    part.Touched:Connect(function(p)
        print("touched:", player.UserId)
        if needBadge then
            awardBadge(player.UserId, BadgeID)
        end
    end)
end)

```

# Answer
If you tested the game in studio and collected the badge, then you will have it when you test the game on the website.
> -1 votes

---
Tags: roblox
---


# Question
Title: How can I make the script easier to use?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class MouthSpeechController : MonoBehaviour
{
    public TMP_Text[] texts;
    public bool startTalking = false;
    public float talkTime;
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool isTalking = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        if (startTalking && isTalking)
        {
            StartCoroutine(AnimateMouth());
            StartCoroutine(TalkTime());

            isTalking = false;
        }

        if (startTalking == false && isTalking == false)
        {
            isTalking = true;
        }
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (startTalking == true)
        {
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration));
        }
    }

    public IEnumerator TalkTime()
    {
        yield return new WaitForSeconds(talkTime);

        startTalking = false;
    }
}

```

The script is working but to get it working from other scripts I need first to make a reference for example :

```
public PlayerMouthSpeechController playermouthspeechcontroller;

```

Then somewhere for example in the Start to set the time :

```
private void Start()
    {
        playermouthspeechcontroller.talkTime = 10;
    }

```

Then in somewhere else and it's all in the same script I need to make it start talking :

```
playermouthspeechcontroller.startTalking = true;

```

Instead maybe to make an option using maybe a public static method that all I will need to do is to type something like this in every script I want it to talk :

```
MouthSpeechController.StartTalking(10f);

```

One line and it will start talking for 10 seconds. To leave also the other options if I want to set the time in someplace and start in other place but also to make something public static I think it's good logic to start the talking with one line.

I tried this. Added instance static variable init the instance in the Awake and added the static method at the bottom of the script. At the Start, I tried to test it but it does nothing.

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

public class MouthSpeechController : MonoBehaviour
{
    public TMP_Text[] texts;
    public bool startTalking = false;
    public float talkTime;
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool isTalking = true;
    private static MouthSpeechController instance;

    private void Awake()
    {
        instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();

        StartTalking(10f);
    }

    // Update is called once per frame
    void Update()
    {
        if (startTalking && isTalking)
        {
            StartCoroutine(AnimateMouth());
            StartCoroutine(TalkTime(talkTime));

            isTalking = false;
        }

        if (startTalking == false && isTalking == false)
        {
            isTalking = true;
        }
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (startTalking == true)
        {
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration));
        }
    }

    public IEnumerator TalkTime(float TalkTime)
    {
        yield return new WaitForSeconds(TalkTime);

        startTalking = false;
    }

    public static void StartTalking(float TalkingTime)
    {
        instance.StartCoroutine(instance.AnimateMouth());
        instance.StartCoroutine(instance.TalkTime(TalkingTime));
    }
}

```

# Answer
> 0 votes
> The problem is that you can't StartCoroutine inside static method.

Singleton pattern to the rescue.

A singleton is an object which exists exactly once in your scene and offers a way to obtain that one instance via a static method. The most barebone implementation of a singelton MonoBehaviour looks like this:

```
public class MouthSpeechController : MonoBehaviour
{
      public static MouthSpeechController instance;

      Awake()
      {
          instance = this;
      }
}

```

When you place a gameObject in your scene with this script on it, then you can access that instance from anywhere with `MouthSpeechController.instance`. You now have a script object on a gameObject and can do what you want with it.

When you look for MonoBehaviour singleton implementations on the web (like on the question here), then you are going to find a lot more convoluted versions which handle error situations like the object not existing in the scene or more than one of them existing or prevent other scripts from changing the `.instance` to something else. Using scripts like that might not be a bad idea in a larger project, but for a small project it's usually overengineering.

# Answer
> -1 votes
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class MouthSpeechController : MonoBehaviour
{
    public TMP_Text[] texts;
    public static bool startTalking = false;
    public float talkTime;
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private static bool isTalking = true;
    private static MouthSpeechController instance;

    private void Awake()
    {
        instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();

        StartTalking(10f);
    }

    // Update is called once per frame
    void Update()
    {
        if (startTalking && isTalking)
        {
            StartCoroutine(AnimateMouth());
            StartCoroutine(TalkTime(talkTime));

            isTalking = false;
        }

        if (startTalking == false && isTalking == false)
        {
            isTalking = true;
        }
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (startTalking == true)
        {
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration));
        }
    }

    public IEnumerator TalkTime(float TalkTime)
    {
        yield return new WaitForSeconds(TalkTime);

        startTalking = false;
    }

    public static void StartTalking(float TalkingTime)
    {
        isTalking = false;
        startTalking = true;

        instance.StartCoroutine(instance.AnimateMouth());
        instance.StartCoroutine(instance.TalkTime(TalkingTime));
    }
}

```

This line should be removed from the Start it's only for testing :

```
StartTalking(10f);

```

now you can call it from any script and start the talking with a single simple line this way :

```
MouthSpeechController.StartTalking(10f);

```

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


# Question
Title: What do "Character Designers" do in the game industry?
I'm curious about character designers, do they design characters in game related images like wallpapers or something like these :

# Answer
The task of "character design" is to take a character idea from a game designer and then come up with how that character could look. Which requires to visualize that look in some artistic medium. They usually go through several iterations. They create a rough sketch, ask the team for feedback regarding what does and does not work about the character, and then create more sketches until the team figured out the final look of their cast of characters.

One could consider "character designer" as a subset of "concept artists": People who come up with how things could look and then create images for internal use. The artworks they produce are usually not supposed to be seen by the public (although a particularly good piece of concept art might *occasionally* find its way onto a loading screen or advertisement banner). They primarily serve as reference for those artists who create the actual game assets or promotional material: 2d artists and 3d artists.

But in practice there is usually a lot of overlap between character design and other disciplines of game art. Especially in smaller teams, where people tend to wear many hats at once. In a smaller team, it might be just one person who comes up with the character and then skips the concept stage and creates the game-ready assets for that character right away. Or if there is a dedicated concept artist, then they might create concept art for all kinds of things in the game, not just characters.
> 2 votes

---
Tags: character, art, game-industry
---


title: Reasons to not use Root Motion

text:
# Question
Title: Reasons to not use Root Motion
Engine: Unity

3D tool: Blender

Since the start of my game dev endeavour, I can't seem to decide on the type of animation system I want to use.

Can someone please give me reasons why you would NOT use root motion and maybe a real world example, because currently I see no reason to not use root motion. I understand the loss of control when using root motion, but from my understanding, the amount of control is "enough".

Treadmill motion(stationary animations) seems like it wont look good enough because you have to perfectly match your move speed to animations. I just need either a resource or proper answer on the specifics about why you would use one over the other or a blend(treadmill for walking, root for jumping etc).

Appreciate any help provided.

# Answer
This is coming from the perspective of Unreal 4. I am not too familiar with Unity's root motion system, so forgive me if this isn't 100% relevant.

The primary benefit of root motion is your character follows the movement curve of the animation. This means if your animation has variable movement speed, the character SHOULD adjust their speed accordingly. This allows the animator to have full control of the movement speed. An example of this would be a single animation that has the character running forward, stopping, and then starting to run backwards. When using root motion, the feet of the character should plant at the proper time, without any modification. This is obviously the desired behavior, and it saves the programming team the time of having to procedurally re-create the variable speed of the character to keep the feet planted.

The primary downside to root motion is the game engine needs to support it in all of it's systems. In the case of Unreal 4, Root Motion is NOT supported on the Navmesh out of the box, so any root motion done will not check the Navmesh to see if the position being moved to is valid. Root Motion is also limited in multiplayer in Unreal 4. This is because the default movement replication system works best with a more constant movement speed. It is easier to predict movement in multiplayer when the movement speed isn't fluctuating all the time.

So at the end of the day, the choice is dependent on a few key factors:

1. Does your engine fully support root motion out of the box? If it does not, would it be easier to modify the engine to support it, or would it be easier to do it with stationary animations?
2. Who needs to control the speed of the character, the animator, or the programmer? In the case of a single player only game, designed to be as realistic as possible, it is probably fine to use root motion (unless there is a lack of support for something single player related, such as naviation). In a multiplayer game, it is most likely better for the programmer to control the movement speed (for movement prediction), and thus you should not use root motion.
> 5 votes

# Answer
It's a bit of a necro but since I came here looking for answers to a problem:

Root motion is the best visually, but it badly interacts with the other systems. I'm debugging a glitching-through-walls issue right now and I strongly suspect that root motion is the culprit. The whole interaction with things such as physics and navigation is more difficult when using root motion. Your animation tells the agent to move forward at this speed, but the navmesh agent wants to rotate, etc.

It also means you need to have your finished animations early on. When I control my AI agents with code (Transform.translate or NavMesh agent) I can use placeholders until fairly late in the game. And I can model their behaviour exactly without worrying about animation details.

Root motion is easier for the animator, but more difficult for the coder. Not using root motion is the other way around, then the animations need to handle different scenarious, and you need to set up your animator component properly.
> 3 votes

---
Tags: unity, animation, mecanim
---


# Question
Title: cant add unity scripts to obects "unity_csc.bat not found. Is your Unity installation corrupted?"
I got a new computer and on it I installed unity and signed in etc. when I load it up however and try adding scripts to objects in the scene it doesn't add them and has this error:

"cant add script component because the script class cannot be found".

I thought it might be something in the script but everything i tried didnt work even from the forums. I made sure it had the same name and the monobehaviour was there and everything. I even got a working script from a prior game i made on my other computer and put it in but it still didnt work. So i thought something was wrong with visual studio. However the last time i was playing around with visual studio and its installs my computer got sent into a bsod reboot loop and then just didnt turn on and it had to get re-imaged. The only other error that could be causing the scripts to not add maybe was this error that i got in the console:

"Exception: 'C:\Program Files\Unity\Hub\Editor\2019.1.8f1\Editor\Data\Tools\RoslynScripts\unity\_csc.bat' not found. Is your Unity installation corrupted?"

However the worse part is that that file already exists  please help! I need to gamedev on this computer! thanks in advance;

# Answer
> 1 votes
The error to this could not be traced and it is assumed that the installation was corrupted. This was fixed by re-installing all of unity and it worked!

# Answer
> 1 votes
I had a similar issue, and it was caused by the Antivirus (Avast): it had quarantined that file.

I fixed it by adding and exception for this file and removing it from quarantine.

I did reinstall Unity before stumbling on the AntiVirus causing the issue.

---
Tags: unity, visual-studio, file
---


# Question
Title: How do I lock the axis in the animation window while dragging?
I want to drag one or more keyframe curve edit points in the horizontal direction only.

Here is a rough screenshot of what I'm trying to do.

As one can see, I'm having a hard time moving the keyframes horizontally only.

Is there a way to lock the movement so that I can only move it horizontally?

# Answer
> 1 votes
Start dragging, *then* press the shift key.

---
Tags: unity, animation
---


# Question
Title: Storing stateful function-based actions in a JSON
**System:** My game uses an "ECS + event queue" architecture where every tick, various events change the state of JSON-able data. Plain JS objects.

**Problem:** I want to be able to save the game-state as JSON, and there is one place where I run into an issue: multi-turn actions. For example, the player has an "intent" array that stores the next few stages:

```
// pseudocode:
let player = {
    health: 5,
    damage: 2,
    actor: true,
    intent: [ () => wait(), () => wait(), () => uniqueContextualStatefulAction()],
}
(...)
every tick
    for every actor with intent:
        execute and remove entity.intent[0]()

```

If all actions took a single "turn" or tick, there would be no problem, as intent would be cleared. But every tick, the function (callback?) of every actor is called (with some more complexity on the side). These callbacks are often unique and contextual, for example waiting for 5 turns, then crafting a custom item out of two others, then deleting the ingredients, all modified by status effects at the time of execution (rather than creation).

My question is as such. What is an "ECS-friendly", save-game-friendly, and sanity-friendly way to handle this system? At the **extreme**, storing every instance of every function and its arguments as strings, but I really don't... want to?

There's gotta be a better way. This is also deterring me from advancing the game systems, and I tend to go into over-engineering to avoid this problem.

**Side-note:** I am open to suggestions about changing some of the architecture altogether, since I can't imagine how to do this in other architectures either. Thank you!

An example of actual in-game code:

    function createWait(ticks) {
        return {
            effect: () => {},
            duration: ticks,
            pause: timing.msPerTick,
        }
    }

    player.addPattern({
        durations: [
            { baseName: "1 tick", dur: 1 },
            { baseName: "3 ticks", dur: 3 },
            { baseName: "6 ticks", dur: 6 },
            { baseName: "12 ticks", dur: 12 },
            { baseName: "60 ticks", dur: 60 },
        ],
        intents: function() {
            let intents = [];
            for (let duration of this.durations) {
                function effect() {
                    newLine(`You wait ${duration.baseName}`)
                }
                intents.push({
                    representation: [game.word("wait"), game.word(duration.baseName)],
                    sequence: [{ effect }, createWait(duration.dur)]
                });
            }
            return intents;
        }
    });
```

# Answer
If you need to serialize the actions, you should probably represent them as data (i.e. plain JS objects, not necessarily strings) instead of functions. Since you have different kinds of actions with different "arguments", the discriminated union pattern will help. This essentially means every action has a `kind` property, and you switch on `action.kind` in functions that deal with an action (e.g. to display it or to enact it).
> 0 votes

---
Tags: javascript, architecture, software-engineering, savegame, entity-component-system
---


# Question
Title: Formula for stacking percentages to keep them from getting out of control
I have a game that has a mechanic, where a specific class can stack what are called "life stealing enchantments" to steal greater amounts of health from the enemy depending on the type of life stealing enchant they have equipped.

A player can have 14 of these equipped at any time. Lets use an example of two of them:

* Sharp Fang 10% of enemies health
* Deprived Blood Lust 25% of enemies health

Right now, for this specific class, if you have 14 Deprived Blood Lust enchants equipped that's simply 14 * .025 = 325% which is way out of control.

Other classes, will not stack their life stealing affixes, instead we would just take the best one you have equipped. This particular issue is around the class where these can stack.

Now to mitigate some of the "high excessive number", which is well over 100% of the enemies health making you essentially able to kill anything, I attempted to create a formula:

1 - 0.25 * ((13 * 0.25) / 2) // 59%

essentially for each additional Deprived Blood Lust, we divide it by 2, so each additional one would do half the damage.

This would do 59% of the enemies health in damage, much more manageable. Except for the issue that Sharp Fang (10%) is much better then Deprived Blood Lust at:

1 - 0.10 * ((13 * 0.10) / 2) // 93%

Now we have one Sharp Fang at full strength and the rest are divided by 2.

So in other words, cheaper, weaker Sharp Fang is better then more expensive Deprived Blood Lust.

What I am looking for is help in creating some kind of formula where you can do full strength for the first enchantment and then for each additional enchantment you would do less, **however higher percentages should end up with higher damage**.

This same concept should work with mixing and matching these two in any amount that is less then or equal to 14. *Assuming this is possible*

So 14 25% enchantments should be better then 14 10% enchantments, even if 13 of the 25% are not firing at full strength.

Thoughts?

# Answer
One simple way to approach this is to say that subsequent items in the stack apply to the percentage that's left after the earlier items in the stack took their bite.

* So the first buff in the stack takes 25% of 100% = 25%
* The second buff in the stack takes 25% of the remaining 75% = 18.75%
* The third buff in the stack takes 25% of the remaining 56.25% = 14.06%...

We can compute this as:

```
float GetTotalValueOfStack(float baseValue, int stackSize) {
    return 1.0f - Power(1.0f - baseValue, stackSize);
}

```

Here's how that compares with stacks of 0-14 items, each taking either a 10% or 25% nibble out of what's left after the earlier items in the stack take their piece.

| Number in Stack | Total Value with 10% Base | Total Value with 25% Base |
| --- | --- | --- |
| 0 | 0.0% | 0.0% |
| 1 | 10.0% | 25.0% |
| 2 | 19.0% | 43.8% |
| 3 | 27.1% | 57.8% |
| 4 | 34.4% | 68.4% |
| 5 | 41.0% | 76.3% |
| 6 | 46.9% | 82.2% |
| 7 | 52.2% | 86.7% |
| 8 | 57.0% | 90.0% |
| 9 | 61.3% | 92.5% |
| 10 | 65.1% | 94.4% |
| 11 | 68.6% | 95.8% |
| 12 | 71.8% | 96.8% |
| 13 | 74.6% | 97.6% |
| 14 | 77.1% | 98.2% |

By construction, this will never exceed 100%, so you never go too far out of control.

You can even use a variant on this to combine the effects of different enchantments without the total exceeding 100%:

```
float GetTotalValueOfMixedStack(List<PercentageBuff> buffs) {
    // Sort our buffs from strongest to weakest.
    buffs.Sort((a, b) => { return b.percent.CompareTo(a.percent); });

    // Accumulate each stacked buff into a running total.
    float runningTotal = 0f;
    foreach (var buff in buffs) {
        float subStack = GetTotalValueOfStack(buff.percent, buff.stackSize);
        // Each new stack nibbles from the portion left after the stack so far.
        runningTotal += (1.0f - runningTotal) * subStack;
    }

    return runningTotal;
}

```
> 3 votes

# Answer
One option would be to make certain enchantments only attachable to certain items. For example any % based attacks can only be on weapons and rings. So then you limit how many of these can appear on a whole character. Other items could add a fixed value boost rather than percentage. This inherently limits the huge percentage stacking.
> 0 votes

---
Tags: mathematics, game-mechanics, effect-modifier
---


# Question
Title: Transforming 3D coordinates to 2D isometric position
I'm trying to render isometric maps, my final goal is to render scenes that resembles Snake Rattle 'n' Roll:

---

---

So I started by rendering cubes:

---

---

For now I have an array with a collection of 3D vectors with integer components (`sf::Vector3<std::size_t>`) (no cubes located on half tiles) and I am brute forcing each cube position by multiplying that position by how much each cube should be displaced in each axis. Sorry for my poor communication skills, I hope that the code explains itself:

```
template <auto degrees>
constexpr auto degrees_to_radians_v = degrees * std::numbers::pi_v<decltype(degrees)> / decltype(degrees){180};

constexpr auto radians_60dg = degrees_to_radians_v<60.f>;
constexpr auto radians_180dg = degrees_to_radians_v<180.f>;
constexpr auto radians_300dg = degrees_to_radians_v<300.f>;

const static sf::Vector2f X_axis = {std::sin( radians_60dg), std::cos( radians_60dg)};  //  60º
const static sf::Vector2f Y_axis = {std::sin(radians_180dg), std::cos(radians_180dg)};  // 180º
const static sf::Vector2f Z_axis = {std::sin(radians_300dg), std::cos(radians_300dg)};  // 300º

struct Map : public sf::Drawable
{
    using block_position_t = sf::Vector3<std::size_t>;
    ...
};

sf::Vector2f to_screen_position(const Map::block_position_t &position)
{
    return
    {
        (position.x * X_axis.x)              + (position.z * Z_axis.x),
        (position.x * X_axis.y) - position.y + (position.z * Z_axis.y) // Y axis reversed
    };
}

```

So, each time I want to draw a cube in a certain 3D position I call `to_screen_position` to know where this position translates in the 2D position of the screen. I have the feeling that I'm overcomplicating things and I can do the same with matrix multiplication -which will allow me to even rotate the scene- so knowing that I'm bad at math I jumped to wikipedia's Transformation matrix page which is amazing but doesn't explain the kind of transformations I'm in need for.

If I'm uderstanding it properly, all transformations that wikipedia is explaining are from 2D ➡ 2D and 3D ➡ 3D but what I need is 3D ➡ 2D. What kind of matrix operations I should use for this goal?

# Answer
> 2 votes
If you multiply your matrix like this:

```
transformedPosition = matrix * inputPosition

```

Then the `matrix` variable can be `n` x `m`, where there are `n` rows matching the dimensions of the output space, and `m` columns matching the dimensions of the input space.

Each column of the matrix is the image of one of the basis vectors of the input space after your desired transformation.

So if you work out the positions you want (1, 0, 0), (0, 1, 0), and (0, 0, 1) from your input space to map into in your output space, you've got your matrix!

Let's take the example from your question:

```
sf::Vector2f to_screen_position(const Map::block_position_t &position)
{
    return
    {
        (position.x * X_axis.x)              + (position.z * Z_axis.x),
        (position.x * X_axis.y) - position.y + (position.z * Z_axis.y) // Y axis reversed
    };
}

```

Here we have the mapping:

```
(1, 0, 0) --> (X_axis.x, X_axis.y)
(0, 1, 0) --> (       0,       -1)
(0, 0, 1) --> (Z_axis.x, Z_axis.y)

```

So that's this matrix:

$$\begin{bmatrix} \text{X\_axis.x} & 0 & \text{Z\_axis.x}\\ \text{X\_axis.y} & -1 & \text{Z\_axis.y} \end{bmatrix}$$

If you want to rotate the world before applying this projection, you can inject a 3x3 rotation matrix between the projection and the input vector:

```
transformedPosition = projectionMatrix * rotationMatrix * inputPosition

```

...and multiply the two matrices together into one, to get a matrix that both rotates the world and then projects it to screen coordinates.

You can also incorporate translation by adding an extra column to this matrix, and an extra "w" coordinate to your input vector (set to 1 for position vectors so they take the translation, 0 for direction vectors so they're unaffected by translation)

Then your matrix looks like this:

$$\begin{bmatrix} \text{X\_axis.x} & 0 & \text{Z\_axis.x} & \text{translation.x}\\ \text{X\_axis.y} & -1 & \text{Z\_axis.y} & \text{translation.y} \end{bmatrix}$$

This is useful for shifting the drawn scene around in screen coordinates - equivalent to doing dolly/truck/pedestal moves with your orthographic camera.

Now if you want to insert a transformation matrix between the projection matrix and the input vector, that matrix will be a 4x4, with its last column representing world-space translation, with a 1 in the w component.

---
Tags: c++, sfml, isometric
---


# Question
Title: Enemy beelines before wandering in 2d topdown
I'm making a top down shooter in Unity. The enemy AI travels straight to the middle of the screen before actually starting wandering when I put in this code. What can I do to fix this? (I'm using Unity 2019.4.28f1 if that helps). I copied the code in this video.

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

public class EnemyWander : MonoBehaviour
{
    [SerializeField]
    float speed;
    [SerializeField]
    float range;
    [SerializeField]
    float maxDis;
    Vector2 Waypoint;
    // Start is called before the first frame update
    void Start()
    {
        setNewDes();
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, Waypoint, speed * Time.deltaTime);
        if(Vector2.Distance(transform.position,Waypoint) < range)
        {
            setNewDes();
        }
    }
    void setNewDes()
    {
        Waypoint = new Vector2(Random.Range(-maxDis, maxDis), Random.Range(-maxDis, maxDis));
    }
}

```

# Answer
With the code in `setNewDes()` you are moving the enemies towards a position that is always relative to the position of the parent `x: 0, y: 0`, which in your case appears to be the scene itself.

By adding the new position to the current position, the new calculation destination would be relative to the current position:

```
void setNewDes() {
    Waypoint = new Vector2(
        transform.position.x + Random.Range(-maxDistance, maxDistance),
        transform.position.y + Random.Range(-maxDistance, maxDistance)
    );
}

```
> 1 votes

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


title: Can't reference UI Image in Script

text:
# Question
Title: Can't reference UI Image in Script
I'm making an inventory system for my game, part of that is updating the icon when the slot is full. For some reason, I can't reference the image component on the child UI image component. I've tried linking it in the prefab GO for the slot prefab, I've tried the script below. Doesn't seem to work. It works when I drag the child onto the parent GO script. Just not in code? Am I missing something? All help is welcomed.

```
void Start()
{
    referenceImage = GetComponentsInChildren<Image>()[1];
}

```

# Answer
The `GetComponentsInChildren()` function '*Returns all components of Type `type` in the GameObject or any of its children. Works recursively.*'

If the code is executed by the parent GameObject, and it has an `Image` component, this is likely to be the one returned by the function in your case (since no order criteria are mentioned in the reference page).

Referencing GameObjects via Inspector fields isn't an in-editor workaround–it's an intended feature for programmers to use. You can get a reference via code, but it isn't going to be easy if the intended GameObject lies deep down a hierarchy. Otherwise, you can just reference it via Inspector fields and be assured *that*'s the object or Component your code is going to reference.

If you want to keep a long-term reference to an object, you may want to search it by its name. `GameObject.Find()` does exactly that. Even better, you can look for a *child* GameObject via `Transform.Find()`:

```
referenceImage = transform.Find("Image").GetComponent<Image>();

```
> 1 votes

---
Tags: unity
---


# Question
Title: Trigonometry to move an arm around axis in 3D space
Hello I have a question about rotating a Rod hinged to a fixed point (so it swings all around), and targets. short form, I would like to know how to find a rotation that would point my rod (while still attached to the fixed point) towards the position of the target.

I would also like to find the rotation as a quaternion, and/or axis-angle to prevent gimbal lock.

I am using unity

The image I made shows my problem with clarity.

# Answer
> 1 votes
Assuming your cylinder is oriented so that its local y+ axis (green arrow on the local transform gizmo) points along the length of the cylinder (like it does for the default Unity cylinder), then you're looking for a quaternion that rotates `(0, 1, 0)` to lie parallel to `(target.position - pivot.position)`.

(If that's *not* how your axes are set up for this object, be sure to edit your question so that critical details like this are made explicit)

Unity has a a couple of great convenience methods to do just this. You could try:

```
transform.rotation = Quaternion.FromToRotation(
                         Vector3.up,
                         target.position - pivot.position
                     );

```

or

```
Quaternion zToTarget = Quaternion.LookRotation(target.position - pivot.position);
Quaternion yToZ = Quaternion.Euler(90, 0, 0);
transform.rotation = zToTarget * yToZ;

```

---
Tags: unity, rotation, quaternion, angles, trigonometry
---


# Question
Title: How to handle collisions for short obstacles across a range of scales?
A naive collision system in 3D RPGs can lead to mobs getting stuck on geometry that they would realistically step over and can be a major nuisance to many players. For most games, the solution is fairly simple: disable collisions on small objects since they don't matter from a gameplay perspective.

This works, but on the assumption that the mobs are all roughly the same size. Introducing more "size categories" from gnome to dragon would require carefully managing collision lists and would likely break on weird corner-cases. The same holds true for nav meshes in 3D games that are mechanically 2D.

Therefore, I'm curious about how one can make an adaptive system to handle collisions automatically.

**Constraints & Considerations:**

* We can assume all the relevant geometry is static, allowing the use of acceleration structures.
* Small object colliders assembled into larger structures should collide as a large structure.
* The solution should be performant enough to use on a large number of mobs, not just hero characters.
* The goal is specifically to allow passage depending on mob scale. A solution that results in mobs moving on top of objects instead of passing through them is acceptable, if less desirable.
* Short obstacles may not be self-contained objects, but part of a larger mesh.
* The method should work in fully-3D games. "Draping" a navmesh would break for situations involving ledges and interiors.

# Answer
A possible solution is to use a Signed Distance Field whose resolution is dependent on the mob's scale. Since low resolutions have the effect of smoothing out the geometry, small objects will act like bumps in the ground to walk over.

The problem with this suggestion is that Signed Distance Fields are volumetric, which is less efficient space-wise than surface representations - bloating the game data and eating up RAM for larger worlds. In principle, this could be ameliorated by computing a local SDF on-demand from the triangle mesh, but presupposes a fast mesh-\>SDF algorithm & implementation. Furthermore, since each mob (or at least size category) will have to compute its own SDF, this has the potential to be very computationally expensive.

Perhaps if the world was described using Constructive Solid Geometry, the SDF could be efficiently computed in parallel. This, however, requires that there is a way to convert the SDF into an optimized mesh appropriate for rendering. Another solution might be to use Truncated Distance Fields, which lacking the sign component, are much faster to compute according to the papers I've read. Sadly, this has the downside of inviting situations where mobs may get stuck inside geometry.
> 1 votes

---
Tags: collision-detection, path-finding
---


# Question
Title: Could you explain how this GameObject rotating around another GameObject works?
I'm just learning Unity and I follow a tutorial for a simple game which I want to build up from.

I'm already mostly done with the course and at the end a "boss enemy" gets implemented.

Its special ability is, that it has some other GameObject (a fireball) floating around itself.

It is all done in a single line of code in the update method which I don't quite understand yet, so any explanation would be great.

Here is the code:

```
private void Update()
{
    fireball.position = transform.position +
        new Vector3(
            -Mathf.Cos(Time.time * fireballSpeed) * distance,
            Mathf.Sin(Time.time * fireballSpeed) * distance,
            0);
}

```
* `fireball` is the transform of the object which floats around
* `fireballSpeed` is a float which indicates the floating speed
* `distance` is the distance from the boss enemy

I get that we are just updating the transforms position but I don't quite understand the `Time.time * fireballSpeed` part. I also get that `Cos` and `Sin` are returning positions for X and Y but I need to improve my math knowledge to completely wrap my head around it to be honest.

So any explanation would be great.

# Answer
The purpose of the sine and cosine function is to turn an angle into X and Y coordinates. Here is an animation from Wikipedia (source) which visualizes what these functions do as the input angle is incrasing:

An interesting property of these functions is that they are repeating every 360°. The sine of 10° is 0.17364. The sine of 3600010° (1000 full rotations and then an additional 10°) is also 0.17364. No matter how large the input value gets, the output value keeps oscillating between +1 and -1.

Which means that feeding a continuously increasing timer into the sine and cosine functions is a perfectly valid method to create a continuous rotation.

Although there is one aspect you might want to keep in mind: **Floating point accuracy**. `Time.time` is a float. The larger a floating point value gets, the less accurate does it become. This can be a problem in a situation like this where the least significant parts of the number are the most important. So when your game runs for a very long time, then this rotating animation might get a bit choppy.

One possible fix is to use double accuracy instead, which means that you use `Time.timeAsDouble` instead of `Time.time` and `System.Math` instead of `Unity.Mathf`:

```
-Math.Cos(Time.timeAsDouble * fireballSpeed) * distance

```
> 2 votes

---
Tags: mathematics, trigonometry
---


# Question
Title: Is it okay to describe what software was used to develop the game in the credits screen?
I'm making a racing game, I've made my own game engine from scratch, but not the tools for building the game assets such as textures, 3D models, etc.

And I was thinking, I have this credits scene at the end of the story, where it basically shows some concept arts used during the development, and some photos of people involved in the development, and so I thought to add a list of software tools that were used to make the game.

Is it okay to do this? Of course this is in good faith, but is there a possibility that *someone* could come after me because I used their trademark without permission?

I mean this would basically be "free advertising" but I don't know...

What do you the gamedev community think of this?

# Answer
*I'm not a lawyer. This does not constitute legal advice.*

---

You can mention them, yes. Nothing prevent you from doing this.

In fact, some license agreement require mention, and end credits is a good place to do so.

---

For trademark and logos, you need to find what guidelines the author has for using them. If there are no such guidelines, it is probably better you ask the authors about it.

In general is it OK to show the logos as long as it is a way the way its holders agree with. And you would want a legal disclaimer (something along the lines of making it clear that they didn't make your game, and you don't work for them, ask a lawyer about such disclaimers).

---

Screenshots of the software is a different thing. If the tool is open source (under a license approved by the open source initiative), then you would be in the clear to use screenshots.

Otherwise, I'd avoid doing it without permission of the authors to be safe. *Although - in my personal opinion - legal action is probably not very likely because you are not competing with them*. But remember that screenshots could include icons and other GUI elements that could be under copyright. *It is also possible to argue that an screenshot is derivative work.*

---

About the "free advertisement" approach, end credits is not the most visible place. You may consider selling a space in a splash screen, for example for an sponsorship. But that is an entirely different thing.

The flip side is, of course, that as I said above, some license agreements require mention. Which is common with free tools and assets. Thus, you can think of this "free advertisement" as what they get in exchange. Review your licenses.
> 1 votes

# Answer
Contact the makers of the tools you are describing and ask them. You might get some free advertising in return from *them*!
> 0 votes

---
Tags: legal
---


# Question
Title: Collision objects aren't preventing falling in Unity
This is a super basic question, but I have absolutelly no clue why there is no collision and the player continues to fall. Im following FreeCodeCamp(minute 37:20). This is what I have:  What is Happening?

# Answer
Check the `Layer Collision Matrix` of your Physics 2D project settings to make sure the "Default" layer reacts to itself. I've seen this mysteriously get turned off before.

To access this, Go to **Edit \> Project Settings…** then click on the **Physics 2D** label on the left. The Layer Collision Matrix is at the very bottom of the list of settings. This matrix controls whether layers react to other layers, including themselves.
> 3 votes

---
Tags: unity, collider
---


# Question
Title: Are there common types of human skeletons in gamedev industry?
I have to decide which human(oid) skeleton I'll choose to do procedural animation with it in the future. I'm looking for a flexible set of bones that would not lead to painful model reskinning later. Are there any well-known modern variants to compare?

# Answer
> 3 votes
Yes, indeed. Unity (for instance) will accept a fairly broad variety of rigs to be converted to Humanoid Avatars as long as they follow the same basic structure. Adobe's Mixamo is one source of animations for rigs that conform to that structure; there are many others.

This is the "body" portion of Unity's humanoid Avatar configurator:

This is a fairly typical heirarchy that maps well to this system:

The rig itself looks like this:

---
Tags: skeletal-animation, 3d-modeling, skinning
---


# Question
Title: How to compute an incremental movement: \$f(t+h)-f(t)\$ or \$f(t)-f(t-h)\$?
For the sake of getting precise position, I think I need you to clarify whether or not the tutorial calculation is incorrect and my calculation is correct.

Assume we want to move an Actor up and down according to \\$f(t)=\sin(t)\\$.

# Tutorial Version

It is quoted from Unreal Engine Programming Quick Start:

```
float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));

```

# My Version

```
float DeltaHeight = (FMath::Sin(RunningTime) - FMath::Sin(RunningTime-DeltaTime));

```

# Edit

I think I have to quote the whole `Tick` function:

```
void AFloatingActor::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    FVector NewLocation = GetActorLocation();
    FRotator NewRotation = GetActorRotation();
    float RunningTime = GetGameTimeSinceCreation();

    // The declaration and initialization of
    // float DeltaHeight goes here.

    NewLocation.Z += DeltaHeight * 20.0f;       //Scale our height by a factor of 20
    float DeltaRotation = DeltaTime * 20.0f;    //Rotate by 20 degrees per second
    NewRotation.Yaw += DeltaRotation;
    SetActorLocationAndRotation(NewLocation, NewRotation);
}

```

# Answer
Both of these approaches are correct in the sense that they will both accomplish the stated goal of moving the character up and down in a sine wave.

The difference is that your version will have the character hitting the peak of the wave at every time \\$t = i \frac \pi 2 + \frac {\Delta t} 2\\$ for integer values of \\$i\\$, and the tutorial version will have the character hitting the peak at every time \\$t = i \frac \pi 2 - \frac {\Delta t} 2\\$.

(These are the points at which either formulation of the `DeltaHeight` formula will evaluate to zero while the contributing sine functions have positive values)

This is the difference of a single frame, and will not generally be perceptible in gameplay - especially if there's no visible clock or other oscillation in the game to compare the timing against for synchronization.

Both of these methods are also susceptible to drift over time due to accumulating rounding errors. If you want to ensure the sine wave is followed exactly, you can store a separate `middleHeight` value and then set:

```
NewLocation.Z = middleHeight + 20.0f * FMath::Sin(RunningTime);

```

This will peak exactly at \\$t = i \frac \pi 2\\$, and minimize drift until `RunningTime` becomes very very large.
> 1 votes

---
Tags: mathematics, unreal
---


# Question
Title: Check if a procedurally generated maze built out of cubes is solvable
I have created a procedural level generator in unity. However, occasionally the algorithm creates a level that is impossible to solve. Therefore, I tried to implement a navmesh agent to check if it is possible to get from the start to the end. However, it seems the agent really doesn't work with procedurally generated levels. I used the github repository to try and bake the navmesh during runtime, but it didn't work as intended. Half the levels that were actually solvable the agent said weren't and vis versa. (I've double checked everything).

The levels consist of a flat cube for the floor, and multiple un-climbable cubes placed throughout to be walls. The end result mimics a maze.

Does anyone know of any other algorithms that can be used to check if it is possible to get from a to b on a flat 3d plane? Thanks in advance.

# Answer
This is just a connected component search \- depth-first search is probably the easiest to get up & running.

Create a 2D array to keep track of which cells contain obstacles: `bool[,] isObstacle`. Each time you place an obstacle cube, set its corresponding entry in the array to `true`.

Then you can check whether the starting cell can reach the goal cell with something like:

```
// List the valid moves we can take from a particular cell coordinate.
static readonly Vector2Int[] neighbours = new Vector2Int[] {
    new Vector2Int(1, 0), new Vector2Int(0, 1), new Vector2Int(-1, 0), new Vector2Int(0, -1)
};

public bool IsReachable(Vector2Int start, Vector2Int end, bool[,] isObstacle) {
    int width = isObstacle.GetLength(0);
    int height = isObstacle.GetLength(1);
    var hasBeenVisited = new bool[width, height];

    // Keep a set of reachable cells to explore.
    var openSet = new Stack<Vector2Int>();

    // Initialize that set with our starting position.
    hasBeenVisited[start.x, start.y] = true;
    openSet.Add(start);

    // As long as we have reachable cells to check,
    // recursively search them and their reachable neighbours.
    while (openSet.Count > 0) {

       // Remove a reachable cell from our open set, and check if it's the goal.
       var parent = openSet.Pop();
       // If so, we're done.
       if (parent == end) return true;

       // Otherwise, check what cells we can reach from here.
       foreach (var neighbour in neighbours) {
           var child = parent + neighbour;

           // Skip cells that are out of bounds.
           if (child.x < 0 || child.y < 0 || child.x >= width || child.y >= height)
               continue;

           // Skip cells we've already visited, or that are unnavigable.
           if (hasBeenVisited[child.x, child.y] || isObstacle[child.x, child.y])
               continue;

           // Mark this cell as visited and add it to our open set to investigate
           // more deeply when we get around to it.
           hasBeenVisited[child.x, child.y] = true;
           openSet.Push(child);
       }
    }

    return false;
}

```

You can optionally speed this up using A\* to bias the search in the direction of the goal, but for small maps the basic depth first approach is good enough.

This is extremely basic, 1st year computer science material. So if this is unfamiliar to you then you may want to take some online classes to get ramped up on the fundamentals.
> 1 votes

---
Tags: unity, algorithm, procedural-generation, navmesh, maze
---


# Question
Title: Animator stuck in previous state and not transitioning, even if transition condition is true
The animator of my character gets stuck from time to time into the first attack animation instead of transitioning to the next one, even if the condition of transitioning is met. This problem gets resolved if I keep the transition condition met for a few seconds, but this can't be tolerated because i'm having a combo and the player can't be just be holding left click for seconds to continue the combo. Here's a screen showing where the Animator gets stuck and the transition doesn't pass:

I should also note that I can't just uncheck Exit Time because I can't let the player skip an attack animation within a combo.

I've got a Hit boolean that is set to true when the player left clicks. That is the condition for continuing the combo and for getting back to idle state I have a FinishCombo.

This condition is triggered when the player left clicks.

# Answer
> 4 votes
I think you'll want to make your Hit variable a trigger, not a boolean.

You can enable the trigger with SetTrigger and it will stay "armed" until it reaches a transition that uses it, then "discharge" back to its default off state.

This lets you get the effect of holding the boolean to true until you reach the exit time of the animation, but automatically, and without allowing a single hit to trigger more than one transition.

---
Tags: unity, mecanim, animator, animation-controller
---


# Question
Title: Unity APK size is too big for building the same scene
I'm developing a game that should have 15-60 levels when all the environments of the levels are the same. I created a scene (level 1) and tried to build it; the total APK is around 38MB which is fine. But When I duplicated this scene to create the other levels and build my game the file size jumps to 148MB which is problematic for me.

Things I tried:

* I optimized meshes, textures, and audio files.
* I tried toggling static batching, SRP batching, GPU Instancing.

Here's some of the editor log of the second build:

```
Build Report
Uncompressed usage by category (Percentages based on user generated assets only):
Textures               6.2 mb    1.8%
Meshes                 3.1 mb    0.9%
Animations             781.3 kb  0.2%
Sounds                 0.0 kb    0.0%
Shaders                1.8 mb    0.5%
Other Assets           652.6 kb  0.2%
Levels                 323.1 mb  91.6%
Scripts                3.6 mb    1.0%
Included DLLs          13.4 mb   3.8%
File headers           105.1 kb  0.0%
Total User Assets      352.8 mb  100.0%
Complete build size    678.6 mb
Used Assets and files from the Resources folder, sorted by uncompressed size:
 2.2 mb  0.3% Assets/Polygon/PolygonSamurai/Models/Characters.fbx
 1.2 mb  0.2% Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/UberPost.shader
 1.0 mb  0.2% Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF.asset

```

I'm sure I'm doing something wrong but I don't know where the main problem is. Any help is so appreciated.

# Answer
I solved this by doing the following:

* I placed everything in one scene
* I created a prefab of every environment
* I created a game object for each level, initially turned off
* I created a script that loads a certain level and turns on/off the corresponding level objects and environment.

With this, my game composed of 15 levels dropped from 440Mb to only 45Mb.

Note: I used GPU instancing for the materials and turned off static batching for all elements, especially trees.
> 2 votes

---
Tags: unity, optimization, build-process
---