# Question
Title: Can’t understand what this shader is doing
I believe this is a fragment shader which is supposed to distort an image by creating a zoom and swirl like affect but I have no idea what the shader is actually doing

```
#version 330
in vec2 v_tex;
out vec4 color;
uniform sampler2D u_texture;
uniform float u_amount;
void main()
{
    vec2 center = vec2(0.5, 0.5);
    Vec2 displacement = normalize(v_tex - center)*u_amount;
    color = texture(u_texture, v_tex - displacement);

}

```

What is v\_tex ? Where is this vec2 coming from?

What is sampler2D u\_texture? Does this use a default texture or is it being passed in?

I understand uniform float u\_amount I believe that has to be passed on as the distortion amount?

# Answer
I am no where near a professional in shaders but I'm currently studying OpenGL and I know a couple things. I will try my best to help by answering the questions I do know about.

> What is uniform sampler2D texture? Is that only in the fragment shader? Does it need a texture passed in or does it use a default texture?

To be able to work on generated textures, the fragment shader needs a way to access that texture's object. GLSL has a built-in data type that does exactly that and that would be the `sampler`. The sampler postfix defines what type the texture object is expected to be of, for example: `sampler2D`. (There's also `sampler1D` and `sampler3D` but that's totally irrelevant).

To answer some of the questions I provide a simple example:

**Vertex Shader**

```
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;

out vec3 ourColor;

void main()
{
    gl_Position = vec4(aPos, 1.0);
    ourColor = aColor;
}

```

**Fragment Shader**

```
#version 330 core
out vec4 FragColor;

in vec3 ourColor;

void main()
{
    FragColor = vec4(ourColor, 1.0f);
}

```

> Sometimes I see fragment shaders which write "in vec2 some\_var" and state that its passed in from the vertex shader but then I don't see the vertex shader actually passing anything to the fragment shader? Is this normal?

To pass an output from the vertex shader to the fragment shader, you need to specify that the variable is an output by using the `out` keyword. In the example above, `out vec3 ourColor;` is outputted from the vertex shader to the fragment shader.

Now on the other hand, in order to accept inputs, the fragment shader needs to expect it, to specify that the fragment shader will be receiving input from the vertex shader, we use the `in` keyword. In the example above, that would be `in vec3 ourColor;`.

To summarize, the `out` keyword is used to specify that some variable is an output and the `in` keyword specifies that a certain variable type is an expected input. This works because the specified `out` and `in` variables have matching types which is `vec3`.

One thing to note is that the vertex shader **should** receive an input so it has something to work on, otherwise it won't be able to do anything. That input is in form of vertex data. On the other hand, fragment shaders are also **required** to output a `vec4` colour output variable.

For the vertex shader shown above, these would be:

```
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;

```

For the fragment shader shown above, this would be:

```
out vec4 FragColor;

```

**EDIT:**

To follow up on your revised question:

To put it simply, Uniforms are another way to send data to shaders. It is important to note that uniforms are **global** meaning that they are accessible by all shaders at any point.

> is the code I provided a vertex shader or a fragment shader? Because it wants an in vec2?

The first observation we could make in the shader code you've provided to determine which type of shader this is, is that the shader outputs a vec4, which is the required output by the fragment shader, but this isn't concrete evidence that this is a fragment shader.

To be able to better identify which shader you're currently looking at, it is important to have an idea about the role of each shader.

Put simply, the vertex shader also allows us to do stuff with the attributes of the vertices it receives as input, such as the position.

The fragment shader's responsibility is basically to calculate the final colour of pixels that are in between the vertices.

In the shader code you've provided in the question, we can determine that the operations applied are more related to calculating the final colour and outputting it using `out vec4 color;`, which is the what the fragment shader is responsible of.

> In the code v\_tex is a vec2 does that mean the vertex shader is passing in a vec2 to this fragment shader? What exactly is v\_tex?

Yes, this means that the fragment shader is expecting an input of the type `vec2`. As stated above in the answer, to accept an input from the vertex shader, we need to specify that a certain variable is expecting a value of a certain type (`vec2`) from the vertex shader using the `in` keyword. In the vertex shader, there's a variable of type `vec2` that has the `out` keyword and it matches the type of `v_tex` which is `vec2`.

`v_tex` is a `vec2` which means that it can hold 2 floats. I believe it represents the texture coordinates for the current pixel.

As for it's role in the code you've provided, as far as I can understand, `center` is being subtracted from `v_tex` and then normalized, then the result is scaled by `u_amount` which should represent the displacement amount.

The result of this operation is a normalized `vec2` that is scaled by `u_amount`. It is based on the difference between the current pixel coordinates and the centre of the texture.

To actually apply this displacement effect, we need to set the colour of the current pixel.

The `color = texture(u_texture, v_tex - displacement)` operation samples the texture `u_texture` at the texture coordinates `v_tex - displacement`.

In simpler words, what this does is that it gets the colour of the pixel that is at the `v_tex - displacement` coordinate of the `u_texture` texture and assigns it to the colour of the current pixel (which is the pixel at the `v_tex` coordinates).

The final colour is then outputted.

I don't know what the exact result of this shader output looks like but I hope that I was able to at least give you an idea about what this is doing.

If you'd like to understand more about shaders, I highly, **highly**, recommend reading the "Shaders" section in the "Getting Started" chapter of the LearnOpenGL book.

Link to the "Shaders" section: Shaders Section
> 1 votes

---
Tags: shaders, glsl
---


# Question
Title: How to Refactor a Unity PoolManager Class for Generic Object Pooling?
I'd like to refactor my pooling class to work for more object types in my top down Unity game. Right now it's working fine for player projectiles, but I want it to also work for enemy projectiles, enemies, particle effects, basically anything that may spawn and be destroyed. I also feel that it's rather clunky to assign the `projectilePrefab` directly in the manager, so I was also wondering if something like an `Interface` like `IPoolable` would be the way to go.

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

public class PoolManager : MonoBehaviour
{
    #region Pooled Objects

    [SerializeField] private Projectile _projectilePrefab;
    [SerializeField] private Enemy _enemyPrefab;

    private ObjectPool<Projectile> _projectilePool;
    private ObjectPool<Enemy> _enemyPool;

    #endregion

    [SerializeField] private int _projectilePoolAmount;
    [SerializeField] private bool _usePool = true;

    public static PoolManager Instance { get; private set; }
    private GameObject _poolContainer;

    void Awake()
    {
        Instance = this;

        _poolContainer = new GameObject($"PoolContainer - {_projectilePrefab.name}");
        _poolContainer.transform.SetParent(transform);

        InitializeProjectilePool();
    }

    private void InitializeProjectilePool()
    {
        _projectilePool = new ObjectPool<Projectile>(
            CreateProjectile,
            projectile => {
                projectile.gameObject.SetActive(true);
            }, projectile => {
                projectile.gameObject.SetActive(false);
            }, projectile => {
                Destroy(projectile.gameObject);
            }, false, 10, 200);
    }

    private Projectile CreateProjectile()
    {
        Projectile projectileInstance = Instantiate(_projectilePrefab);
        projectileInstance.transform.SetParent(_poolContainer.transform);
        projectileInstance.gameObject.SetActive(false);
        return projectileInstance;
    }
    private void KillProjectile(Projectile projectile)
    {
        if (_usePool) { _projectilePool.Release(projectile); }
        else { Destroy(projectile.gameObject); }
    }

    public Projectile GetProjectile()
    {
        var projectile = _usePool ? _projectilePool.Get() : CreateProjectile();
        projectile.Init(KillProjectile);
        return projectile;
    }
}

```

# Answer
If you want to use a separate manager for each type of prefab, you can make PoolManager an abstract generic class and then add concrete implementations. Here's an abbreviated example; for brevity, I won't rewrite the entire class (`// [...]` indicates where code has been omitted):

```
public class PoolManager<T> : MonoBehaviour where T : Component
{
    [SerializeField] private T _prefab;
    [SerializeField] private int _poolAmount;
    [SerializeField] private bool _usePool = true;

    private ObjectPool<T> pool;

    // [...]

    private T CreateInstance()
    {
        T instance = Instantiate(_prefab);
        instance .transform.SetParent(_poolContainer.transform);
        instance.gameObject.SetActive(false);
        return instance;
    }

    // [...]
}

public class ProjectilePoolManager : PoolManager<Projectile> {
    // This concrete implementation doesn't need any additional code!
}

public class EnemyPoolManager : PoolManager<Enemy> {
    // This concrete implementation doesn't need any additional code!
}

```

This is the approach I typically use.

If you want one pool manager component to manage *all* of your pools, rather than having a separate pool manager for each type of pool, that gets more complicated. It would look something like this:

```
public class PoolManager : MonoBehaviour {
    // Note that because `ObjectPool<T>` is a generic type, we can't use `ObjectPool<T>`
    // as the value type of the dictionary, so we cast to `object`.
    private Dictionary<Type, object> _pools;
    private Dictionary<Type, object> pools {
        get {
            if (_pools == null) _pools = new Dictionary<Type, object>();
            return _pools;
        }
    }

    public void CreatePool<T>(T prefab, Transform parent) where T : Component {
        var pool = new ObjectPool<T>(
            () => CreateInstance<T>(prefab, parent),
            instance => {
                instance.gameObject.SetActive(true);
            }, instance => {
                instance.gameObject.SetActive(false);
            }, instance => {
                Destroy(instance.gameObject);
            }, false, 10, 200);
        pools.Add(typeof(T), pool);
    }

    private ObjectPool<T> GetPool<T>() where T : Component {
        if (pools.TryGetValue(typeof(T), out var poolObj)) {
            var pool = poolObj as ObjectPool<T>;
            return pool;
        } else {
            return null;
        }
    }

    public T GetInstance<T>() where T : Component {
        var pool = GetPool<T>();
        if (pool == null) return null;
        return pool.Get();
    }

    public void Release<T>(T instance) where T : Component {
        var pool = GetPool<T>();
        if (pool == null) Debug.LogWarning($"Tried to release {instance}, but there's no pool of type {typeof(T).Name}");
        else pool.Release(instance);
    }

    private T CreateInstance<T>(T prefab, Transform parent) where T : Component {
        T instance = Instantiate(prefab);
        instance.transform.SetParent(parent);
        instance.gameObject.SetActive(false);
        return instance;
    }
}

```

This component lets you create a separate object pool for each type of prefab you want to spawn. However, take note that this particular implementation I just threw together only lets you have one spawn pool per type, which doesn't work if you have multiple prefabs with the same component type (e.g. multiple prefabs of type `Enemy`).

---

And, at the risk of going overboard on this answer, here's an implementation where pools are mapped by prefab, so you can have different pools for different prefabs with the same type:

```
public class PoolManager : MonoBehaviour {
    // Note that because `ObjectPool<T>` is a generic type, we can't use `ObjectPool<T>`
    // as the value type of the dictionary, so we cast to `object`.
    private Dictionary<Component, object> _pools;
    private Dictionary<Component, object> pools {
        get {
            if (_pools == null) _pools = new Dictionary<Component, object>();
            return _pools;
        }
    }

    public ObjectPool<T> CreatePool<T>(T prefab) where T : Component {
        var pool = new ObjectPool<T>(
            () => CreateInstance<T>(prefab),
            instance => {
                instance.gameObject.SetActive(true);
            }, instance => {
                instance.gameObject.SetActive(false);
            }, instance => {
                Destroy(instance.gameObject);
            }, false, 10, 200);
        pools.Add(prefab, pool);
        return pool;
    }

    private ObjectPool<T> GetPool<T>(T prefab) where T : Component {
        if (pools.TryGetValue(prefab, out var poolObj)) {
            var pool = poolObj as ObjectPool<T>;
            return pool;
        } else {
            return null;
        }
    }

    public T GetInstance<T>(T prefab, Transform parent) where T : Component {
        var pool = GetPool<T>(prefab);
        if (pool == null) {
            pool = CreatePool<T>(prefab);
        }
        var instance = pool.Get();
        if (instance != null) instance.transform.SetParent(parent);
        return instance;
    }

    public void Release<T>(T prefab, T instance) where T : Component {
        var pool = GetPool<T>(prefab);
        if (pool == null) Debug.LogWarning($"Tried to release {instance}, but there's no pool of type {typeof(T).Name}");
        else pool.Release(instance);
    }

    private T CreateInstance<T>(T prefab) where T : Component {
        T instance = Instantiate(prefab);
        instance.gameObject.SetActive(false);
        return instance;
    }
}

```
> 0 votes

---
Tags: unity, c#, object-pools
---


# Question
Title: How to instantiate correctly a cube prefab?
In a FPS i'm trying to instantiate cube like the old good minecraft. The problem is that the first cube i instantiate on terrain got y=0 but half of that cube is underground ... All my cube prefab are 1x1x1.

How to fix this problem ?

```
 void BuildBlock(GameObject block)
 {
     if (Physics.Raycast(shootingPoint.position, shootingPoint.forward, out RaycastHit hitInfo))
     {

         if (hitInfo.transform.tag == "Block")
         {
             // Instance over other cube
             Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x + hitInfo.normal.x / 2), Mathf.RoundToInt(hitInfo.point.y + hitInfo.normal.y / 2), Mathf.RoundToInt(hitInfo.point.z + hitInfo.normal.z / 2));
             Instantiate(block, spawnPosition, Quaternion.identity, parent);
         }
         else
         {
             // Instance on terrain
             Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x), Mathf.RoundToInt(hitInfo.point.y), Mathf.RoundToInt(hitInfo.point.z));
             Instantiate(block, spawnPosition, Quaternion.identity, parent);
         }
     }
 }

```

# Answer
Ok, the problem is that Pivot point is in center of every unity primitive, like a cube. To solve, I can create an empty object with pivot point in the bottom corner, than a child cube. Now it works
> 0 votes

# Answer
> No, it's not in a grid layout.

All objects upon creation need to align to a fixed sized grid.

The code for alignment (assuming a 40x40 grid):

```
 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x * 40+19)/40, Mathf.RoundToInt(hitInfo.point.y * 40 + 39.9f)/40, Mathf.RoundToInt(hitInfo.point.z * 40 + 19)/40);

```

The 'y + 39.9f\` gives the vertical alignment on the square above the trace, where the other two axis are centered to the grid.
> 0 votes

---
Tags: unity, vector
---


# Question
Title: If UV coordinate is Vector2, then why does UV node in shader graph output Vector4?
I'm new to shader, so please pardon my lack of knowledge. I am trying to understand what does UV node do in shader graph. I tried searching on google and in https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/UV-Node.html it was written:

> Provides access to the mesh vertex or fragment's UV coordinates. The coordinate channel of the output value can be selected with the Channel dropdown parameter.

Ok so UV node provide access to mesh vertex UV coordinates, then i google what is UV coordinate and in https://docs.unity3d.com/ScriptReference/Mesh-uv.html it was written

> Unity stores UVs in 0-1 space. \[0,0\] represents the bottom-left corner of the texture, and \[1,1\] represents the top-right. Values are not clamped; you can use values below 0 and above 1 if needed

Ok so UV coordinate is vector2 which represent the 2D coordinate between \[0,0\] and \[1,1\]. But in shader graph UV node output vector4 instead of vector2.

Where is the error of my understanding? If UV Node supposedly provide access to mesh vertex UV coordinate, then why did it output Vector4 instead of Vector2? can someone please help me clear this confusion ?

# Answer
> 3 votes
Texture coordinates are *usually* 2-dimensional. But **developers can add a third or fourth component to achieve some effects**, like sampling from a volume texture, specifying which layer of an array texture to read from, or using projective texturing.

You can author these 3D "UVW" coordinates (or 4D coordinates, though I don't know a common name for the fourth component) in your modelling software, or using the Mesh.SetUVs method, which has overrides for working with `Vector3` or `Vector4` in addition to the usual `Vector2`.

The Shader Graph does not know a priori which mesh you will use the shader on, or how many dimensions a given UV channel might have, so it errs on the side of too much and picks the largest option supported by a single vertex attribute. That way if you do something unusual with a third or fourth component, you're not locked out of using that vertex data in the graph.

When Unity compiles this graph down to actual shader code, it may make variants that strip out the unneeded components, since it can follow through the graph to see if they're ever used in an expression. That would be worth experimenting with, as I haven't tested that myself yet.

---
Tags: unity, shaders, uv-mapping, unity-shader-graph
---


# Question
Title: Implement Singleton that loads before Awake
I would have liked to comment on this answer, but I don't have enough reputation so I had to open this new one. The issue with it (and with the rest of the answers) is that it doesn't work well if another instance tries to access the singleton in its own `Awake`. As far as I know, the order in which `Awake` functions execute can't be configured, so nothing prevents some other class to call the singleton getter before it has initialized the instance:

```
public class SomeClass : MonoBehaviour {
    private static SomeClass _instance;

    public static SomeClass Instance { get { return _instance; } }

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        } else {
            _instance = this;
        }
    }
}

public class SomeOtherClass : MonoBehaviour {
    private void Awake() {
        Foo bar = ResourceManager.Instance.bar; // NullReferenceException here
    }
}

```

I have been trying to change the implementation to initialize `_instance` in the getter, but I can't get through the static enforcement. Any ideas on how to ensure that `SomeClass` gets its `_instance` running before any `Awake` on other classes may ask for it?

# Answer
As mentioned in the comments, for simple cases, this can be solved by moving your earlier dependency up in the Script Execution Order settings.

Another way is to make `Instance` a getter method that finds the reference in the scene if it hasn't yet been assigned, and initializes it on demand:

```
public abstract class Singleton<T> : MonoBehaviour where T :Singleton<T>
{

    static T _instance;

    public static T Instance {
        get {
            if (_instance == null) {
                _instance = FindAnyObjectByType<T>();
                // Here you can assert and
                // log an error if the scene
                // is missing an instance.
                _instance.Init();
            }
            return _instance;
        }
    }

    // Override this for any code that should
    // run before this object's first use.
    virtual void Init() {}

    // This bit is optional. You can leave it out
    // for lazy initialization on first use,
    // or keep it to always initialize on load.
    void Awake() {
        if (!Object.ReferenceEquals(_instance, this)
        {
            if (_instance != null) {
                Destroy(this.gameObject);
            } else {
                _instance = (T)this;
                Init();
            }
        }
    }
}

```

This version searches the active scene, but you can implement more complex logic in the getter for searching multiple scenes or constructing the instance on demand if needed.
> 1 votes

---
Tags: unity, c#, design-patterns
---


# Question
Title: How does vector raised to the power of another vector work?
I was watching this tutorial and at timestamp 3:03 he did this:

This blows my mind because I didn't expect that to actually work, how the heck does that work ???? For example, if I have vector (2, 3, 4), that means:

$$ {(2, 3, 4)}^{(8, 8, 8)} $$

How does that work mathematically?

# Answer
> 2 votes
The Shader Graph documentation for Power Node says:

> The following example code represents one possible outcome of this node.
>
> ```
> void Unity_Power_float4(float4 A, float4 B, out float4 Out)
> {
>     Out = pow(A, B);
> }
>
> ```

And if we then look up the documentation for the `pow()` function using `float4` it says (emphasis mine):

> `pow(float4, float4)`
> Returns the **componentwise** result of raising x to the power y.

Thus the comment by @PepeOjeda is correct and with respect to Shader Graph, you have: $$(2,3,4)^{(8,8,8)} = (2^8,3^8,4^8)$$

From a `float4` is a vector perspective this might feel like misleading overload. But from a SIMD (single instruction, multiple data) perspective, the operation makes sense. In that context, the `float4` can be seen as parallel data packaged together for parallel processing, hence the componentwise math operation. As @DMGregory points out, this convention is common in in shader languages and many operators are treated this way. For example, if you search the Math class docs for "returns the componentwise", you'll see over a dozen functions operate as described.

---
Tags: unity, mathematics, shaders, vector, unity-shader-graph
---


# Question
Title: Angry Birds style aiming (ballistic trajectory)
Could you please provide guidance on how to create the curved part?

regard,

# Answer
> 0 votes
This is basic gaming physics.

There are two general solutions. The first is call "analytical" or closed form, as it is a single equation that can give you the position of the particle/bird at any time t. See here for more:

> x(t) = x0 + v0 * t + 0.5g * t^2

Link: Calculating trajectory

Where x0 is the starting position, v0 is the staring velocity, g is gravity, and t is time.

The second is approach is numerical, which is much more common in games because it allows for a lot more variety in what happens. In this approach there is an integration loop, often the game loop itself, that marches the particle/bird forward in time. Based on the current position, velocity, forces, it computes the position and velocity at the next time step:

> a(t) = SUM forces(t) / mass
> v(t+1) = v(t) + a(t) * dt
> x(t+1) = x(t) + v(t) * dt

Each equation gives the value at the next time step based on the current time step. Position is updated by velocity. Velocity is updated by acceleration. Acceleration is the sum of all forces acting on the bird - in the simplest case just gravity. The acceleration a(t) is just a rewrite of Newton's 2nd law, F=ma. Doing this on every timestep moves the bird along the trajectory.

The reason this second, numerical, approach is much more common is greater flexibility. If your bird hits a building, or is knocked off course, or bounces on the ground, then you just introduce some new forces at any time. This would be much harder to do with a closed form approach.

It can be worthwhile to experiment with both when learning since you discover a lot about physics. There are many articles out there on basic game physics.
Link: https://www.toptal.com/game/video-game-physics-part-i-an-introduction-to-rigid-body-dynamics

---
Tags: 2d, physics, mathematics, algorithm, gdevelop
---


# Question
Title: Simulate Velocity For A Projectile Moving Along A Spline
* I'm using Unity's latest Splines package(v2.5) to move a projectile across a spline with speed. It works perfectly and the projectile moves across the spline to it's target with linear speed.
* But I'd like to make it look even better by making it behave a bit more realistically. Maybe someone smarter than me can articulate how projectiles move better, but essentially, I think when a projectile is thrown it should have a burst of speed at the start and begin to rise slower as it reaches its peak height. Then as it starts to fall it should gradually begin to fall faster.
* I'd like to use math to accomplish this, rather than something like an animation curve. The reason is because sometimes enemies will be in different positions. So, the spline will look different depending on the enemy's position.

---

**Here's the code I'm using:**

```
public SplineContainer spline;
public float speed;
public float distancePercentage;
public float splineLength;

private IEnumerator MoveTheProjectile()
{
    // Move the projectile across the spline
    while (distancePercentage < 1f)
    {
        distancePercentage += speed * Time.deltaTime / splineLength;
        currentPosition = spline.EvaluatePosition(distancePercentage);
        projectile.transform.position = currentPosition;

        yield return null;
    }
}

```

---

Since I'm already using a speed variable to move the projectile, I think implementing this should be possible. Is anyone able to please assist me with a method of changing the speed of the projectile to be more realistic? Thanks so much!

# Answer
> I think when a projectile is thrown it should have a burst of speed at the start and begin to rise slower as it reaches its peak height. Then as it starts to fall it should gradually begin to fall faster.

It's not possible to achieve a realistic-looking acceleration with the solution you're using.

The motion of an object traveling in an environment with gravity is often represented using a ballistic trajectory that ignores air resistance. Under such conditions, we can break the motion of the projectile into two components, the *horizontal* (x) velocity and the *vertical* (y) velocity. Physical forces will then change these velocity components over time.

If the projectile is unpowered and we ignore air resistance, the only force acting on the projectile mid-flight is the force of gravity, which will change *only the y-component* of the velocity. The x-component will remain constant.

You're calculating movement along a parabolic curve using a function which doesn't give you separate control over the X and Y axes. You can speed up or slow down movement along the curve, but this would affect movement along both the X-axis and Y-axis. This won't look right because it's not physically accurate.

You'd probably be better off giving up on bezier curves. You could use a ballistic equation (there are several implementations here), but it sounds like you want something that just looks nice and doesn't need to be super realistic.

---

Here's a script that moves a projectile from A to B along a parabolic curve. This script doesn't use actual physics; instead, we use a sine curve to add vertical motion to what would otherwise be a straight-line course from A to B. You can adjust the height of the arc and the duration of the animation. I've included a custom editor for previewing the parabola.

```
public class ParabolaAnimator : MonoBehaviour {
    public IEnumerator FakeBallisticArc(Transform transform, Vector3 start, Vector3 end, float parabolaHeight, float duration) {
        float elapsed = 0;
        while (elapsed < duration) {
            yield return null;
            elapsed += Time.deltaTime;

            float t = elapsed / duration;
            transform.position = Evaluate(start, end, parabolaHeight, t);
        }
    }

    public Vector3 Evaluate(Vector3 start, Vector3 end, float parabolaHeight, float t) {
        t = Mathf.Clamp01(t);
        Vector3 straightLinePoint = Vector3.Lerp(start, end, t);
        float t2 = Mathf.Sin(t * Mathf.PI); // Curves from 0 to 1 and then back to 0
        float extraHeight = parabolaHeight * t2;
        return straightLinePoint + new Vector3(0, extraHeight, 0);
    }

#if UNITY_EDITOR
    [UnityEditor.CustomEditor(typeof(ParabolaAnimator))]
    private class ParabolaAnimatorEditor : UnityEditor.Editor {

        private Transform projectile;
        private Vector3 start;
        private Vector3 end;
        private float parabolaHeight = 2;
        private float duration = .75f;

        private void Awake() {
            var animator = target as ParabolaAnimator;
            projectile = animator.transform;
        }

        private void OnEnable() {
            var animator = target as ParabolaAnimator;
            start = animator.transform.position + new Vector3(0, 1, 0);
            end = animator.transform.position + new Vector3(0, 3, 5);
        }

        private void OnSceneGUI() {
            Handles.color = Color.red;
            UnityEditor.Handles.lighting = false;
            start = UnityEditor.Handles.PositionHandle(start, Quaternion.identity);
            UnityEditor.Handles.Label(start + Vector3.up, "Start");
            end = UnityEditor.Handles.PositionHandle(end, Quaternion.identity);
            UnityEditor.Handles.Label(end + Vector3.up, "End");

            var animator = target as ParabolaAnimator;

            Vector3 a, b;
            float step = .05f;
            for (float t = 0; t < 1; t += step) {
                a = animator.Evaluate(start, end, parabolaHeight, t);
                b = animator.Evaluate(start, end, parabolaHeight, t + step);
                UnityEditor.Handles.DrawLine(a, b);
            }
        }

        public override void OnInspectorGUI() {
            base.OnInspectorGUI();

            UnityEditor.EditorGUILayout.LabelField("Debug", UnityEditor.EditorStyles.boldLabel);

            var animator = target as ParabolaAnimator;

            start = UnityEditor.EditorGUILayout.Vector3Field("Start", start);
            end = UnityEditor.EditorGUILayout.Vector3Field("End", end);
            parabolaHeight = UnityEditor.EditorGUILayout.FloatField("Height", parabolaHeight);
            parabolaHeight = Mathf.Max(parabolaHeight, 0);

            if (Application.isPlaying) {
                duration = UnityEditor.EditorGUILayout.FloatField("Duration", duration);
                duration = Mathf.Max(duration, .1f);
                projectile = UnityEditor.EditorGUILayout.ObjectField(projectile, typeof(Transform), true) as Transform;
                GUI.enabled = (projectile != null);
                if (GUILayout.Button("Test")) {
                    animator.StartCoroutine(animator.FakeBallisticArc(projectile, start, end, parabolaHeight, duration));
                }
            }
        }
    }
#endif
}

```

If you're not happy with the vertical motion, you can replace the sine curve in `Evaluate()` with an Animation Curve or another formula.

This script does not check for obstacles along the trajectory, so if there is a risk of obstacles, you may need to write some additional code to check for obstacles (e.g. with raycasts) and update the trajectory settings accordingly.
> 0 votes

# Answer
This is basic physics.

There are two general solutions. The first is call "analytical" or closed form, as it is a single equation that can give you the position of the particle at any time t. See here for more: Link: Calculating trajectory

The second is approach is numerical, which is much more common for physics because it allows for a lot more variety in what happens. In this approach one marches the object forward in time. Based on the current position, velocity, forces, you could compute the position and velocity at the next time step:

> a(t) = SUM forces(t) / mass
> v(t+1) = v(t) + a(t) * dt
> x(t+1) = x(t) + v(t) * dt

Each equation gives the value at the next time step based on the current time step. Position is updated by velocity. Velocity is updated by acceleration. Acceleration is the sum of all forces acting on the object - in the simplest case just gravity. The acceleration a(t) is just a rewrite of Newton's 2nd law, F=ma. Note that x, v and a are each 2D or 3D vectors. Doing this on every timestep moves the object along the trajectory. Link: https://www.toptal.com/game/video-game-physics-part-i-an-introduction-to-rigid-body-dynamics

The reason this second, numerical, approach is much more common is greater flexibility. If your object hits a building, or is knocked off course, or bounces on the ground, then you just introduce some new forces at any time. This would be much harder to do with a closed form approach.

The use of splines, or sine function (by @Kevin), won't easily achieve this since the speed and acceleration along the path must also change to look realistic. Splines are very similar to the closed form approach -- they specify a known curve for the motion. As mentioned already, any additional obstacles, collisions, or other forces won't be easily captured with this strategy.
> 0 votes

# Answer
Remove the spline and split speed into 2 components X,Y ie Vector2.

Fix a horizontal velocity.X from the spline. Apply a negative rather large value to velocity.Y, and each step adjusted for delta time subtracts gravity.
> -2 votes

---
Tags: unity, c#, mathematics, projectile-physics, splines
---


# Question
Title: Drag and Drop Godot 4: Disappears when dropped outside allowed area
I'm trying to make a simple drag and drop function, and it works when dragging from one area to another, but if I accidentally drop the sprite outside the allowed areas, it just disappears. I've been trying to have it set up so that the sprite, if dropped outside the area, returns to its last known location. Here is the code I have, although it does not work as the sprite still disappears:

```
extends TextureRect

var original_position : Vector2

func _get_drag_data(at_position):
    original_position = position

    var preview_texture = TextureRect.new()
    preview_texture.texture = texture
    preview_texture.expand_mode = 1
    preview_texture.size = Vector2(90,90)

    var preview = Control.new()
    preview.add_child(preview_texture)

    set_drag_preview(preview)

    texture = null
    return preview_texture.texture

func _can_drop_data(at_position, data):
    return data is Texture2D

func _drop_data(at_position, data):
    if _can_drop_data(at_position, data):
        texture = data
    else:
        texture = data
        position = original_position

```

My node tree looks like:

* Node2D
    + TextureRect
        - Panel
    + TextureRect
        - Panel

# Answer
> 3 votes
Before Godot calls `_drop_data`, it will call `_can_drop_data`. Furthermore, if `_can_drop_data` returned `false`, Godot will not call `_drop_data`.

So in this code:

```
func _can_drop_data(at_position, data):
    return data is Texture2D

func _drop_data(at_position, data):
    if _can_drop_data(at_position, data):
        texture = data
    else:
        texture = data
        position = original_position

```

Calling `_can_drop_data` from `_drop_data` is redundant, and the execution flow will never enter the `else` statement.

---

The above, of course, is only called when attempting to drop on the `TextureRect` with the shown script. So that code won't handle dropping outside.

Try checking for `NOTIFICATION_DRAG_END` in `_notification`, where you can check if drag failed:

```
func _notification(what:int) -> void:
    if what == NOTIFICATION_DRAG_END and not is_drag_successful():
        print("Drag Failed")

```

---
Tags: godot, godot-4
---


# Question
Title: How does one detect a button release with Unity's new input system?
I'm attempting to upgrade my technique from the classic input methods to the new Input System for Unity; but I'm finding it a little sprawling and unhelpful so far.

I know that if I have an action, let's call it `Fire`, and I want it to come from a variety of input devices and call a specific function, let's say `Obliterate(InputAction.CallbackContext ctx)` when it's used, all I have to do is something like this:

```
controls.Player.Fire.performed += ctx => Obliterate(ctx);

```

However, what if I'm attempting to detect if the button has been not pressed, but released, possibly after some delay? I can't find anything on that, maybe I'm overlooking it. Can someone give me a hand?

# Answer
> 1 votes
If you use the Hold Interaction, then the Cancelled event gets called when the button is released, with the Performed event happening if the item is held for the given duration.

As of Unity 2022.3.10f1 (my current version), Cancelled also gets called on release even after you've held for the full amount of time, which seems counter to Internet wisdom.

# Answer
> 4 votes
OK, here's what I've figured out. The type of the action needs to be Value, not Button or Pass Through—this can be changed in the editor by selecting the action from the list; there's a drop down available in its settings. (Don't forget to save the asset and regenerate the C# code.)

Once this is done, the button behaves more like an axis, and invokes `.canceled` on its release. For a hold action, you can use a coroutine; simply set a control boolean to true and call `StartCoroutine` with it in your `.performed` callback. When the button or control is released, it will trigger `.canceled`, which can call another function that toggles the boolean back to false, and breaks the internal control loop in your coroutine allowing it to exit.

This allows for one action to be performed for a brief press, and another to be performed after a hold in continuum, until the button is released.

---
Tags: unity, c#, input, controllers
---


# Question
Title: Can't compare integer variable loaded from save data, but another identical variable works fine
this works:

```
func _on_HeadstrongRush_pressed():
    if headstrong_rush_ps < 5:
        if headstrong_rush_ps > 0:
            has_headstrong_rush_skill = true
        headstrong_rush_ps += 1
        skill_points -= 1
    $AllUIHere/Skills/WardenSkills/Set1/HeadstrongRush/SkillLevel.text = str(headstrong_rush_ps)

```

so why doesn't this work :

```
func _on_PomelStrike_pressed():
    if pomel_strike_ps < 5:
        if pomel_strike_ps > 0:
            has_pomel_strike_skilll = true
        pomel_strike_ps += 1
        skill_points -= 1
    $AllUIHere/Skills/WardenSkills/Set1/PomelStrike/SkillLevel.text = str(pomel_strike_ps)

```

The error is that I can't compare `pomel_strike_ps` using `<` but both variables `pomel_strike_ps` and `headstrong_rush_ps` are two integers, side by side.... Chat GTP says that the problem is that the variable is probably not initialized in time, tried to put `onready var` and nothing changed, tried waiting and nothing changes.

# Answer
Apparently it was a bug, solved it by deleting this line in the savedata section of the script:

```
if "pomel_strike_ps" in player_data:
    pomel_strike_ps = player_data["pomel_strike_ps"]

```

I started the game, played it and it didn't crash. Then I did `control` \+ `z` to return the deleted code, and it worked.
> 0 votes

---
Tags: godot, savegame, gdscript
---


# Question
Title: What is this jitter caused by moving at high speed?
I used jumping real high as an example to show the jitter.

what is causing the jitter issue? I can provide code for various parts of my engine if requested.

# Answer
The jitter is caused because the two 60 Hz timer functions (camera and physics) are out of sync.

Placing the camera update code in a `afterPhysicsStep` function will solve the issue
> 0 votes

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


title: Why is my enemy not moving?

text:
# Question
Title: Why is my enemy not moving?
I'm trying to make a 2D Unity platform game for a school project, but I can't seem to get the enemy to move.

```
using UnityEngine;

public class EntityMovement : MonoBehaviour {
    public float speed = 1f;
    public Vector2 direction = Vector2.left;

    private Rigidbody2D rigidbody;
    private Vector2 velocity;

    private void Awake() {
        rigidbody = GetComponent<Rigidbody2D>();
    }

    private void OnBecameVisible() {
        enabled = true;
    }

    private void OnBecameInvisisble() {
        enabled = false;
        GetComponent<Rigidbody>().WakeUp();
    }

    private void OnEnable() {

    }

    private void OnDisable() {
        GetComponent<Rigidbody>() .velocity = Vector2.zero;
        GetComponent<Rigidbody>().Sleep();
    }

    private void FixedUpdate() {
        velocity.x = direction.x * speed;
        velocity.y += Physics2D.gravity.y * Time. fixedDeltaTime;

        rigidbody.MovePosition(rigidbody.position + velocity * Time.fixedDeltaTime);
    }
}

```

# Answer
> 1 votes
In the `OnEnable()` and `OnDisable()` functions, you used `GetComponent<Rigidbody>()` which is for 3D instead of `GetComponent<Rigidbody2D>()`. You could either switch it to `GetComponent<Rigidbody2D>()` (why would you do this), or logically replace it with the `Rigidbody2D rigidbody`.

# Answer
> 0 votes
You should fix the OnEnable() and OnDisable() method's GetComponent() part. This should be Rigidbody2D. Also you have already set rigidbody in Awake(). Therefore you do not need to use GetComponent anymore.

---
Tags: unity, c#, 2d, platformer, rigidbody
---


# Question
Title: Canvas that should only be visible for local player is also visible for remote players
I'm using Unity NetCode for Game Objects. I have a player Prefab, inside it I have a canvas as a child of my player Prefab (I don't know if it's the best approach), which contains inventory, status, etc. But when I instantiate more than one player, the canvas is also visualized by the other players. I wish to find a solution to solve this problem.

# Answer
> 0 votes
There are three broad ways to solve this:

1. Keep the canvas inside the player prefab, but when instantiating a non-local player, destroy the canvas after spawning it.

This is probably the simplest to implement from your current setup. Make a script that, on `Start()`, queries whether it belongs to the local player, and if not, destroys the object it's attached to. The downside is that you go to all the work of instantiating the canvas first, so to save that redundant work, it may be preferable to...
2. Remove the canvas from the player prefab. When instantiating a local player, instantiate their UI canvas separately and wire it up.

This requires a bit more code, in case things in the canvas and in the prefab need to reference each other, but it's not too bad if you plan for it. If the wiring needed for local players is particularly complex, you may prefer to...
3. Make separate prefabs for local vs remote players, and spawn the appropriate asset depending on which kind of player it's being instantiated for.

---
Tags: unity, unity-ui, unity-networking
---


# Question
Title: How to setup a loading screen using SDL_Threads?
I am trying to set up a basic toy example of how a loading screen would work in SDL. Here is my code below.

```
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_thread.h>

#define DELAY  10

std::string status = "state 0";

static int LoadThread(void* data)
{
    //Delay to simulate loading
    SDL_Delay(DELAY);
    status = "delay 0";
    SDL_Delay(DELAY*10);
    status = "delay 1";
    SDL_Delay(DELAY*100);
    status = "delay 2";
    SDL_Delay(DELAY*5);
    status = "delay 3";
    SDL_Delay(DELAY*6);
    status = "delay 4";
    SDL_Delay(DELAY*5);
    status = "delay 5";
    SDL_Delay(DELAY*2);

    status = "finished";
    return 0;
}

int main(int argc, char *argv[])
{
    SDL_Thread *p = SDL_CreateThread(LoadThread, "LoadingAssetsThread", nullptr);

    std::string currentStatus = status;

    while(true)
    {
        if (status != currentStatus)
        {
            std::cout << status << " " << tState << std::endl;
            currentStatus = status;
        }

        if (currentStatus == "finished") break;
    }

    SDL_WaitThread(p, nullptr);

    return 0;
}

```

Basically I want to show a series of lines of text stating what is the current asset that is being loaded, i.e. textures, sound, etc one after as they complete loading in the separate thread.

Is this the right approach? The reason being, in my real world code, I noticed when optimization is turned on (-O3 option in g++) sometimes certain steps in "currentStatus" will be skipped over and won't display in the main thread. I am using a std::cout to illustrate but in reality there is a function that draws the text to a SDL window.

Put another way, there is a variable that the loading function has to update as it sequentially loads one asset after another and the main game loop renders a different message to the player based on what that variable is at any given time during the loading process.

---Update---

After a bit more diagnosing I realize what is happening is that the loading thread is loading some of the assets so fast that it happens within one single update of the main game loop for example:

```
void loadThread()
{
   state = "loadTiles";
   Load_Tiles();
   state = "loadSound";
   Load_Sound();
   state = "loadGraphics";
   Load_Graphics();
}

```

if for instance, Load\_Tiles and Load\_Sound both occur quickly enough then from the perspective of the main game loop it will only see the `state` as "LoadGraphics". Do I need some way of pausing the loading process until the main thread is updated? I can put in a SDL\_Delay() but that seems hacky.

# Answer
A single valued integer of machine word size(32 or 64 bits) is guaranteed to provide consistent atomic reads and writes across **one read-only thread and a single read-write thread**.

---

Define an `int` or `long`(see above), or your favorite alias, status variable for each thread and an array of strings to draw.

The string array will help with language translations later on.

Either, `if` each thread status variable and draw the string from the array.

Or, draw the base text for each of the string values and append the completion values.

This way:

* No synthetic or synchronizing delays,i.e. mutexes, are needed
* The string draw order is maintained and nothing completed gets skipped
* More frequent progress indicators will be shown on slower computers (thread completion percentage).

---

As a side note setting the optimization level above `-O2` is usually overkill and *may* even lead to decreased run-time performance.
> -1 votes

---
Tags: sdl2, multithreading, loading
---


# Question
Title: How to stop the UI from moving when changing screen resolution
* Added screen resolution settings
* Change screen resolution in game
* Everything is already anchored
* GUI gets the hell out of the screen, moves around and goes everywhere

# Answer
> 1 votes
This is the approach I take at the time of writing:

* I set stretch modo to canvas\_items in Project Settings -\> Display -\> Window
* I organize the main scene like this:

```
Main (Control)
├ World (Control)
│ ├ Background (if necessary)
│ ├ SubViewportContainer
│ │ └ WorldViewport
│ │   └ (load world scene here)
│ └ Postprocessing (if necessary)
└ UI (Container)
  ├ HUD (Control)
  └ (Menus, loading screen, etc)

```
* I design the UI to the window size I have configured in Project Setting, and due to the stretch mode, it scales with the Window/Screen.
* The resolution for the game is separate since it is on a separate viewport, this way I can offer settings to change that resolution without affecting the UI.

Notes:

* I do not use the Godot's API to change scenes. This has tradeoffs that I'll not go into here, but yes... It requires more code.
* I took the idea of putting the game world in a separate viewport from this video: How to make a silky smooth camera for pixelart games in Godot (3.x).
* I have not incorporated settings to allow the user to customize the scaling of the UI in my games at the time of writing. However, as you has found out, changing the main resolution scales the UI, and having the game in a separate viewport would have its resolution unaffected by that, and with proper use of containers/anchors you could keep it on the correct position on screen (or you can always throw some code on resize).
* I would probably continue to evolve this in the future. So, I'm not saying this is the definite solution. However, I'm saying this approach solve the problem at hand, and you probably can adapt it to your needs.
* How does the game world communicate with the HUD? You can use an autoload for that, although I have moved to static code (The solution to How to write a static event emitter in GDScript? has proven useful). *In general, I'm avoiding autoloads so my code needs less setup to reuse from project to project. With that said, I also want to point out I'm aware of developers doing everything in autoloads so they can keep using Godot's API to change scenes.*

---
Tags: gui, godot
---


title: Selecting Tiles Correctly With Scroll

text:
# Question
Title: Selecting Tiles Correctly With Scroll
I would like to understand the process of selecting the correct tile from a scaled Surface when I have information about the number of tiles on the x and y axes, the length of the Surface, and also considering the scroll factor

Firstly, I have the following variables:

```
WIDTH = 640
HEIGHT = 320
TILE_SIZE = 32
MAX_COL = WIDTH // TILE_SIZE
MAX_ROW = HEIGHT // TILE_SIZE

```

Then, I create the base `Surface` with `screen = pg.display.set_mode((WIDTH, HEIGHT), pg.RESIZABLE)`, and a dummy Surface as follows: `dummy = pg.Surface([WIDTH, HEIGHT])`.

Next, I create grids using some clever math and a `scroll` variable (which changes when I press the D button, moving everything backward):

```
for v in range(MAX_COL):
    # vertical / col
    pg.draw.line(dummy, (0, 0, 0), (TILE_SIZE * v - scroll_x, 0), (TILE_SIZE * v - scroll_x, HEIGHT))
    # horizontal / row
for h in range(MAX_ROW):
    pg.draw.line(dummy, (0, 0, 0), (0 - scroll_x, TILE_SIZE * h), (MAX_COL * TILE_SIZE - scroll_x, TILE_SIZE * h))

```

Finally, I `scale it` (using tw and th, calculated dimensions to maintain aspect ratio, but for now, it can be anything):

```
f = pg.transform.scale(s, (tw, th))
screen.blit(f, (pad_x, pad_y)) # center the window

```

Now, I want to choose a tile so that when I click it, it shows on which field I currently am. I achieve this by dividing my mouse `X` and `Y` coordinates from `pg.mouse.get_pos()` with the size of a `scaled tile`, and the result looks something like this:

Now I can go ahead and print this tile as a tuple - `(2, 2)`

But the problem comes when I move with my map and everything changes its position:

To select a tile like this, I would normally use my `scroll` variable and manipulate it (such as adding that information to the mouse `x` coordinate). However, it seems a bit tricky because when I scale everything, my scroll isn't accurate anymore, at least not for working with a mouse. So, I am wondering if someone knows how to maintain my coordinate system while also considering my scroll factor. For example here Id like to get (2, 2) as well but thats not what I get

# Answer
You must apply the inverse of the draw operations in reverse order to the mouse position.

```
(mx,my) = pg.mouse.get_pos()
mx -= pad_x
my -= pad_y # undo blit center offset
mx /= tw
my /= th # undo the scaling

# mx and my is now in dummy space screen coordinates(not scrolled)

# Scroll X and Y are in dummy coordinate space
tile_x = (mx + scroll_x) // TILE_SIZE
tile_y = (my + scroll_y) // TILE_SIZE

# tile_x is equal to the original h value of grid square under the mouse
# tile_v is equal to the original v value of grid square under the mouse

```

---

Affine transformations(translations, i.e. +/- on X,Y,Z,W) are non-linear in nature.

You can build a complete transformation matrix for drawing operations and invert the matrix to give a single operation to undo the screen mouse to source space.
> 0 votes

---
Tags: python, pygame, coordinates, grid, scrolling
---


# Question
Title: How to call every method with a certain name from a set of classes in C#
I have the following case: I have a class called `App.cs` and here I have a function called Render, that runs once every frame:

```
public static class Render(){
   DrawBuffer.Clear(); //clear the last frame
   //DrawStuff, Logic, etc.

   DepthBuffer.Calculate(); //compute the depth of the scene for the current frame
}

```

Now, I want to be able to add game logic, and drawing objects, but not directly from within `App.cs` for cleanness, so I'm trying to implement a system of "scripting" for my own 3D render engine similar to Unity3D. So, lets suppose I have the following scripts: `Script1.cs`, `Script2.cs` and `Script3.cs`. I want to be able to have certain names for methods within those scripts that do certain things. For example let's say that scripts can definte the method `GameLoop()` which would be the equivalent of `Update()` from Unity and `Init()` which would be the equivalent of `Start()` from Unity. Let's focus on `GameLoop()` first. `Script1.cs` might look something like this:

```
using MyRenderEngine;
using System;

public class Script1
{
   public void Init(){
      //Called at the beginning
   }
   public void GameLoop(){
      //Called every frame
   }
}

```

`Script2.cs` and `Script3.cs` would look very similar to this.

Now, the subject of this question is how would I make every GameLoop() of every script be called in the main game loop?
The most obvious method would be in `App.cs` to have in the `Render()` method:

```
Script1 script1 = new Script1();
Script2 script2 = new Script2();
Script3 script3 = new Script3();

public static void Render(){
   //Clear last frame
   script1.GameLoop();
   script2.GameLoop();
   script3.GameLoop();
   //Compute depth buffer
}

```

But would be very awkward to have to add a call in the main render loop(`Render()`) for each script.
I can create a list of `object` that can hold a reference to each script and to add a foreach loop in the `Render()` to call the `GameLoop()` from within each of them, but I would need to add scripts to that list manually, which would be the same as calling the method directly.
The second solution I found would be to create an interface, let's say `Behaviour3D` that each script need to implement and that contain the methods `GameLoop()` and `Init()` that can be overrode by each class implementing `Behaviour3D`, but I would need to create a list and update it manually. I could maybe use `Reflexion` to obtain automatically a list of all classes that implement `Behaviour3D` interface, but I have a motto: "Avoid Reflection as much a possible". Now I have 2 questions:

1. How does Unity do it?(How MonoBehaviour works)
2. How would you do it?

# Answer
Add a base **abstract class** `Behaviour3D`.

There is no need for reflection.

```
public abstract class Behaviour3D
{
   internal static List<Behaviour3D> myObjects = new();
   internal static List<Behaviour3D> myObjectsRemove = new();

   // ...
   public Behaviour3D()
   {
      myObjects.Add(this);
      // ...
   }

   public virtual BeforeUpdate()
   {
   }

   public virtual Update()
   {
   }
   public virtual Render()
   {
   }

   // Removal methods
   public void Remove()
   {
      myObjectsRemove.Add(this);
   }
   public static void Remove(Behaviour3D r)
   {
      myObjectsRemove.Add(r);
   }
   public static void RemoveAll()
   {
      myObjects.Clear();
      myObjectsRemove.Clear();
   }

   internal static void InternalGameLoop(){
      //Clear last frame

      // remove deleted objects
      foreach(var removeItem in Behaviour3D.myObjectsRemove)
         item.Behaviour3D.myObjects.Remove(removeItem);
      myObjectsRemove.Clear();

      foreach(var item in Behaviour3D.myObjects)
         item.BeforeUpdate();
      foreach(var item in Behaviour3D.myObjects)
         item.Update();
      foreach(var item in Behaviour3D.myObjects)
         item.Render();

      //Compute depth buffer
   }

```

Each derived class has the opportunity to override the methods as they see fit:

* `BeforeUpdate()`
* `Update()`
* `Render()`

Any parameters such as timing can be provided by protected variables.

Your main programs base entry point,`App.cs` simply calls every step:

`Behaviour3D.InternalGameLoop()` passing any of the needed protected variables.
> 0 votes

---
Tags: unity, c#, 3d, game-loop, monobehaviour
---


# Question
Title: How do i check if the script is executing in editor mode or runtime mode?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[ExecuteAlways]
public class SliderManager : MonoBehaviour
{
    public Slider slider;
    public GameObject[] Objects = new GameObject[100];
    public GameObject Model;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        SetSlider((int)slider.value);
    }

    protected void SetSlider(int x)
    {
        for (int i = 0; i < Objects.Length; i++)
        {
            bool mustBeAnObject = i < x;

            if ((mustBeAnObject) && (Objects[i] == null))
                Objects[i] = Instantiate(Model);
            else if ((!mustBeAnObject) && (Objects[i] != null))
            {
#if UNITY_EDITOR
                DestroyImmediate(Objects[i]);
#else

#endif
            }
        }
    }
}

```

I'm using the \[ExecuteAlways\] to run the code in both editor mode and runtime mode. the problem is in the bottom when i'm using Destroy i need to check if it's in editor mode to use DestroyImmediate and if in runtime to use Destroy.

i tried to use #if UNITY\_EDITOR but not sure how to continue with it and if to use that way or to use:

```
if(Application.isPlaying)

```

and also, as a side question, should i use the attribute \[ExecuteAlways\] or should i make another Editor type script?

a bit messed.

# Answer
> 1 votes
The answer to your question is:

```
Application.isPlaying == true // you are not in editor mode
Application.isPlaying == false // you are in editor mode

```

As for your other questions:

ExecuteInEditMode is limited and does not call all the functions of the MonoBehaviour as it would when running in PlayMode.

It also doesn't work well when the MonoBehaviour is in a prefab and in the Prefab editor.

There are good reasons to use ExecuteInEditMode if it works for what you need, but if you can refactor your code to use Editor scripts it will give you more power and control over your ability to write good manipulators and editor tools.

Things like "Undo" and marking objects dirty so the scene manager knows it needs to save.

# Answer
> 0 votes
The Application.IsPlaying (obsolete) will return true even in the editor. To know if you are in editor, use Application.IsEditor. false means runtime, true means editor. At least since version 2019 Regards, Robert

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


# Question
Title: How to handle different components of the same entity having different indices?
I'm currently working on a little ECS project and a couple doubts came to my head when dealing with systems.

Let's say I have a model component, a position component and a scale component. Each component has its own component array and each entity has a number of indices to access those components. Also, every component has a field for the `entityID`. The reason why I went with this design over using the `entityID` as the index to every component array was to both be more memory efficient and more time efficient when looping over the less populated component arrays.

Now lets say I'm designing my rendering system. This system needs to use the model, position and scale components, but these have different indices (because they are different components) so in order to get them the system goes through every element in the model component array, and for each component it uses the `entityID` to get handles for the other components it needs.

Now this works, but the issue that I'm having is that this completely invalidates the cache advantages that you would get by using a structure of arrays design, since you are now using the entity ID to index into another array. On the other hand, putting all of these fields into the same component would be better for optimizing the render system, but then something like the physics system that might only need the position would be wasting cache space on useless data like the model, the scale, etc. Are there any good solutions for this, or is this a loose loose scenario where one is forced to make tradeoffs?

# Answer
> 0 votes
The advantage to the ECS model is the parallel direct indexing of data.

If the sparcity of the *data elements*, not usage, becomes to great, less than half on memory constrained systems, split the single ECS into 2 or more **mutually exclusive** ECS\`s, and loop through each in applicable system code.

> but then something like the physics system that might only need the position would be wasting cache space on useless data like the model, the scale, etc.

No, any data not needed by any particular system is not a waste, it is simply not accessed, and becomes stale in the cache and frees up more cache space for currently used data. (Not necessarily always true, but CPU-Memory caching techniques are quite complex and architecture specific, beyond the scope of this answer)

Expansion on the caching point: Yes misses will occur on the less frequented arrays, but the overall cache will suffer more by using indirect references (both the address value region and the pointed to data region must also be cached).

---
Tags: software-engineering, entity-component-system
---


# Question
Title: Is it ok if root motion animation doesn't start from the world origin?
I've been testing/exploring character movement with root motion in Unreal. I've modelled a simple character in Blender, animated a walk cycle with root motion, and in the end I've got the desired result - movement seemed to work and look just as it should. But in the process I've noticed a little detail.

For adding the root motion itself, I've followed a tutorial by Mark Masters, a professional game animator, so the root motion in my animation (as well as Mark's) starts a bit behind the world origin and then moves forward beyond it. In Unreal it looks like this (here character moves from left to right):

But I've noticed that in the vast majority of the tutorials related to setting up the movement system (and in Unreal docs as well), the root motion starts exactly from the world origin, not behind it (i.e. in those animations in Unreal the red line looks like in the second picture from the very start).

My question is: does it matter/have any consequences down the line (in Unreal/gamedev implementation in general) if the root motion starts anywhere outside the world origin? Thanks!

# Answer
Root motion is based on the objects' world origin.

It is important to note that the object does not move, only the Skeletal Mesh component.

The Get Actor Position will return its spawn location, not the current location. Get the world position of the Skeletal Mesh component of the actor instead.

The same thing happens when physics is turned on on a static mesh component that is not the root component.
> 0 votes

---
Tags: animation, unreal, root-motion
---


# Question
Title: Sawblade's spin stops or jitters when swiping to steer it
* I have a 3D object, a blade, that I want to rotate **continuously** on the x axis, like it's cutting through something.
* I also want the player to control its *z-axis* rotation by swiping.

It's mainly working fine with no issues, but when I'm in the moving phase of the touch (swiping), the blade jitters a little and has trouble with the x-axis continuous rotation.

I've read answers on a bunch of forums, but I couldn't find one that addressed an example similar to mine because I can't use *global axis*, I believe, because if I swipe and the blade tilts to the right, for example, then the continuous rotation on the global *x-axis* would mess up the rotation.

Here's the script attached on the blade:

```
using UnityEngine;

public class BladeMovement : MonoBehaviour
{
    public float continuousRotationSpeed = 600f;
    public float swipeRotationSpeed = 0.4f;
    private Quaternion initialRotation;
    private Quaternion currentRotation;
    private Vector2 touchStartPos;
    private bool isTouching = false;

    void Start()
    {
        initialRotation = transform.rotation;
        currentRotation = initialRotation;
    }

    void Update() {
        transform.Rotate(continuousRotationSpeed * Time.deltaTime, 0, 0);

        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            switch (touch.phase)
            {
                case TouchPhase.Began:
                    touchStartPos = touch.position;
                    isTouching = true;
                    break;

                case TouchPhase.Moved:
                    if (isTouching)
                    {
                        float swipeDeltaX = touch.position.x - touchStartPos.x;
                        float swipeRotation = swipeDeltaX * swipeRotationSpeed;
                        Quaternion targetRotation = Quaternion.Euler(0, 0, swipeRotation) * currentRotation;
                        transform.rotation = targetRotation;
                        Debug.Log("BUGGGGGG");
                    }
                    break;

                case TouchPhase.Ended:
                    isTouching = false;
                    break;
            }
        }
        else
        {
            currentRotation = transform.rotation;
        }
    }
}

```

# Answer
> 0 votes
When the touch moves, you apply your z twist rotation to the cached `currentRotation`, not to the actual current rotation of the blade (which was changed earlier in this `Update()` pass when `transform.Rotate()` spun it a little more). Then you overwrite the blade's current rotation with that stale value, undoing any `transform.Rotate()` calls that happened since the last time `currentRotation` was updated.

You only update `currentRotation` when no fingers are touching the screen, which effectively stalls the blade during a drag.

Try something like this instead: accumulate the rotation angles you want on x and z, then apply them all at once. A pair of degree angles `bladePose` takes over from the quaternion `currentRotation`.

```
float twistAtTouchStart;
Vector2 bladePose;

void Update() {
    bladePose.x += continuousRotationSpeed * Time.deltaTime;
    bladePose.x %= 360; // Wrap to keep the value in -360...+360

    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        switch (touch.phase)
        {
            case TouchPhase.Began:
                touchStartPos = touch.position;
                twistAtTouchStart = bladePose.y;
                isTouching = true;
                break;

            case TouchPhase.Moved:
                if (isTouching)
                {
                    float swipeDeltaX = touch.position.x - touchStartPos.x;
                    float swipeRotation = swipeDeltaX * swipeRotationSpeed;
                    bladePose.y = twistAtTouchStart + swipeRotation;
                }
                break;

            case TouchPhase.Ended:
                isTouching = false;
                bladePose.y %= 360;
                break;
        }
    }

    transform.rotation = Quaternion.Euler(0, 0, bladePose.y)
                       * Quaternion.Euler(bladePose.x, 0, 0);
}

```

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


# Question
Title: Unity IAP - Collection was modified; enumeration operation may not execute
In **Unity**, after importing **UnityIAP Version: 2.3.0**, I have a **button** to which I attached an **IAP Button** component like in the image below:

My **SkinsPanel** class looks like this:

```
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Purchasing;

public class SkinsPanel : MonoBehaviour
{
    [SerializeField] private RectTransform SorcererPurchaseButton; //reference to the button that is being pressed
    private string sorcererID = "com.company.test.sorcererID";

    public void OnPurchaseComplete(Product product)
    {
        if (product.definition.id == sorcererID)
        {
            SorcererPurchaseButton.gameObject.SetActive(false);
            //SorcererPurchaseButton.DOAnchorPos(new Vector2(1000, 1000), 0f);
        }
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        Debug.Log("Failed");
    }
}

```

Nothing incredible complicated, a reference to the **button** and two functions: **OnPurchaseComplete** and **OnPurchaseFailed**.

Now, if the user completes the purchase succesfully:

I'm getting a **Collection was modified; enumeration operation may not execute.** error:

Full stack trace:

```
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.ThrowHelper.ThrowInvalidOperationException (System.ExceptionResource resource) (at <9577ac7a62ef43179789031239ba8798>:0)
System.Collections.Generic.List`1+Enumerator[T].MoveNextRare () (at <9577ac7a62ef43179789031239ba8798>:0)
System.Collections.Generic.List`1+Enumerator[T].MoveNext () (at <9577ac7a62ef43179789031239ba8798>:0)
UnityEngine.Purchasing.CodelessIAPStoreListener.ProcessPurchase (UnityEngine.Purchasing.PurchaseEventArgs e) (at Assets/Plugins/UnityPurchasing/script/CodelessIAPStoreListener.cs:175)
UnityEngine.Purchasing.StoreListenerProxy.ProcessPurchase (UnityEngine.Purchasing.PurchaseEventArgs e) (at Library/PackageCache/com.unity.purchasing@2.2.1/Runtime/managed/Purchasing/StoreListenerProxy.cs:34)
UnityEngine.Purchasing.PurchasingManager.ProcessPurchaseIfNew (UnityEngine.Purchasing.Product product) (at Library/PackageCache/com.unity.purchasing@2.2.1/Runtime/managed/Purchasing/PurchasingManager.cs:250)
UnityEngine.Purchasing.PurchasingManager.OnPurchaseSucceeded (System.String id, System.String receipt, System.String transactionId) (at Library/PackageCache/com.unity.purchasing@2.2.1/Runtime/managed/Purchasing/PurchasingManager.cs:112)
UnityEngine.Purchasing.JSONStore.OnPurchaseSucceeded (System.String id, System.String receipt, System.String transactionID) (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Purchasing.FakeStore.<>n__0 (System.String id, System.String receipt, System.String transactionID) (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Purchasing.FakeStore+<>c__DisplayClass15_0.<FakePurchase>b__0 (System.Boolean allow, UnityEngine.Purchasing.PurchaseFailureReason failureReason) (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Purchasing.UIFakeStore+<>c__DisplayClass14_0`1[T].<StartUI>b__0 (System.Boolean result, System.Int32 codeValue) (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Purchasing.UIFakeStore.OkayButtonClicked () (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Purchasing.UIFakeStore.<InstantiateDialog>b__16_1 () (at <828972e73f634ff790a93860533a30ad>:0)
UnityEngine.Events.InvokableCall.Invoke () (at /Users/bokken/buildslave/unity/build/Runtime/Export/UnityEvent/UnityEvent.cs:166)
UnityEngine.Events.UnityEvent.Invoke () (at /Users/bokken/buildslave/unity/build/Runtime/Export/UnityEvent/UnityEvent/UnityEvent_0.cs:58)
UnityEngine.UI.Button.Press () (at /Applications/Unity/Hub/Editor/2019.4.17f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/UI/Core/Button.cs:68)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at /Applications/Unity/Hub/Editor/2019.4.17f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/UI/Core/Button.cs:110)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at /Applications/Unity/Hub/Editor/2019.4.17f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at /Applications/Unity/Hub/Editor/2019.4.17f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update() (at /Applications/Unity/Hub/Editor/2019.4.17f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:377)

```

I understand this issue would be caused if I were to iterate over a collection with something like a **foreach** and modifying/removing the elements over the iteration.

If I were to to simply change the position of the button like:

```
//SorcererPurchaseButton.gameObject.SetActive(false);
SorcererPurchaseButton.DOAnchorPos(new Vector2(1000, 1000), 0f);

```

this would work without any issues.

What is the issue here? Is it some Unity IAP bug?

# Answer
It looks like this error is occurring inside `CodelessIAPStoreListener.ProcessPurchase()` \- you can look at the source code here.

```
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
{
    PurchaseProcessingResult result;

    // if any receiver consumed this purchase we return the status
    bool consumePurchase = false;
    bool resultProcessed = false;

    foreach (IAPButton button in activeButtons)
    {
        if (button.productId == e.purchasedProduct.definition.id)
        {
            result = button.ProcessPurchase(e);

            if (result == PurchaseProcessingResult.Complete) {

                consumePurchase = true;
            }

            resultProcessed = true;
        }
    }

    // ...

```

`IAPButton.ProcessPurchase()` is called inside a `forEach` loop, and it in turn invokes the `onPurchaseComplete` event:

```
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
{
    onPurchaseComplete.Invoke(e.purchasedProduct);

    return (consumePurchase) ? PurchaseProcessingResult.Complete : PurchaseProcessingResult.Pending;
}

```

So when your `OnPurchaseComplete()` listener is called, you are inside a `foreach` loop that's iterating over `IAPButton` objects.

When you set the button game object to inactive, that calls `OnDisable()` on all its components, including the `IAPButton`, which says:

```
void OnDisable()
{
    if (buttonType == ButtonType.Purchase)
    {
        CodelessIAPStoreListener.Instance.RemoveButton(this);
    }
}

```

And removing the button means:

```
public void RemoveButton(IAPButton button)
{
    activeButtons.Remove(button);
}

```

So this modifies the `activeButtons` collection that `CodelessIAPStoreListener` is in the middle of iterating. It's not legal to modify an enumerable collection while you're iterating it, so that's the reason for the error you're seeing.

What you can do instead is defer the hiding of this button until after this iteration has completed - say by setting a "to hide" flag or adding it to a list of buttons to hide that another function will process later in the frame (maybe in `LateUpdate()`, just before the next frame is rendered), or by using a coroutine to hide it at the end of the frame. Or you could disable just the visible components of the button, without triggering the `IAPButton`'s `OnDisable()` by deactivating the whole game object.
> 1 votes

# Answer
I solved this by adding an "IAP Listener" object into the scene. You can add a script to it and call a function when purchase is complete.
> 1 votes

---
Tags: unity, c#, in-app-purchase
---


# Question
Title: How to store condition dependent item information in JSON
I'm developing a RPG-game. After searching about various ways to save item information in RPG-game, I determined to save information in JSON files. The problem is that in my game, some equipment's stat depends on the character condition.

```
class Equipment {
    String name;
    double strength;
    double agility;

    Equipment(String name) {
        this.name = name;
    }

    checkCondition(Character character) {
        switch (this.name) {
            case "itemA" -> {
                strength = 20;
                      //This is what I mean by "condition dependent item"
                agility = character.strength > 30 ? 20 : 10;
            }

            case "itemB" -> strength = 40;
        }
    }
}

```

As you can see, "itemA"'s stat is dependent to characters' strength.

```
{
    "name": "itemB",
    "strength": 40,
    "agility": 0
}

```

This is how I planned to save the items, but "itemA" doesn't seem to fit in this form. Please let me know you have an idea to solve this problem.

# Answer
I wouldn't do this based on item name. Instead, I'd implement a system of modifiers to describe what an item does, something like...

```
{
    name: "itemA",
    displayName: "Slippers of Mighty Grace",
    effects: [
        {
            type: "statCheck",
            stat: "strength",
            threshold: 31,
            effectsIfMet: [
                {
                    type: "statBoost",
                    stat: "agility",
                    value: 20
                }
            ],
            effectsIfNotMet: [
                {
                    type: "statBoost",
                    stat: "agility",
                    value: 10
                }
            ]
        }
    ]
}

```

When you load this item from JSON, you string together a matching pattern of polymorphic effect nodes, each with their own `Apply` method, something like this:

```
public class StatCheckEffect implements ItemEffect {
    public Stat stat;
    public int threshold;

    public ItemEffect[] effectsIfMet;
    public ItemEffect[] effectsIfNotMet;

    public void Apply(Character char) {
        if (char.GetStat(stat) >= threshold) {
            for(ItemEffect effect : effectsIfMet)
                effect.Apply(char);
        } else {
            for(ItemEffect effect : effectsIfNotMet)
                effect.Apply(char);
        }
    }
}

public class StatBoostEffect implements ItemEffect {
    public Stat stat;
    public int value;

    public void Apply(Character char) {
        char.ModifyStat(stat, value);
    }
}

```

When the item is equipped, you run the `Apply()` methods on all its top-level effects. When the character's status changes in a way that might affect equipment properties, you reset the character's stats to base and re-run the `Apply()` methods of all equipped gear to find the new net result. (More sophisticated caching to avoid redundant processing is possible, but do it the simple way first to check if you really need the added complexity)
> 6 votes

---
Tags: java, rpg, data-structure, json, effect-modifier
---


# Question
Title: I want to acheve this effect of trees changing texture based on distance to the player
The effect also applies to mountains and terrain, trees in the back look like shadows which with a dark sky look nice and in the day I can make them look like grey fog. I was thinking of simply adding a tween and slowly change the texture as the player gets closer or further... except there's only problem?

How do I get the player distance? I've already tried similar things and getting the distance between two nodes ends up lagging a lot, by using areas just one check per frame is enough to destroy my frame rate on my other computer or straight up crash the game on this other one... by using `get_tree().get_node()` it get's better but still causes performance issues and using a timer instead of `_physics_process()` mitigates the problem a little bit...but if there are more than a few trees or heels, the problem comes back.

# Answer
> 3 votes
You want to do this in the material applied to the meshes.

The idea is to take the distance to the camera for the fragment, and use that to decide how to color it.

To get the distance to the camera we can use `length(VERTEX)`, and to use that to decide what color to use we can use a combination of `mix` and `step` (or `smoothstep`):

```
shader_type spatial;

uniform sampler2D texture_away: source_color;
uniform sampler2D texture_near : source_color;
uniform float dist;

void fragment() {
    ALBEDO = mix(
        texture(texture_near, UV),
        texture(texture_away, UV),
        step(dist, length(VERTEX))
    ).rgb;
}

```

So where the distance is less than `dist` you get `texture_near`, but when it is away you get `texture_away`.

**Notes**:

* You would need to set values for the uniforms under "Shader parameters" in the inspector.
* Below I explain that adding this effect is easier with material overlay. Howver, if you cannot use material overlay, you would have to modify the materials you have to include a modified version of the code above. The gist of it is that instead of `texture(texture_near, UV)` you want to put whatever they were setting to `ALBEDO` before.
* It is also possible to use a color uniform instead of a texture, which I'll do for the overlay version below.
* You can also modify the above code to use `smoothstep` instead of `step`. There is an example of using `smoothstep` at the end of the answer.

---

I suppose you want to combine this with other effects. So… The easier way would be to apply it as material overlay (a material set in `material_overlay`)… In which case we want the case where you are near be transparent. So we could do this:

```
shader_type spatial;

uniform vec3 color: source_color;
uniform float dist;

void fragment() {
    ALBEDO = color;
    ALPHA = mix(
        0.0,
        1.0,
        step(dist, length(VERTEX))
    );
}

```

This way, when it is close to the camera you see `color`, and when it is away you get transparency, which in a material overlay leaves whatever color was there.

By the way, we actually don't need `mix` in this case, we can do this instead:

```
shader_type spatial;

uniform vec3 color: source_color;
uniform float dist;

void fragment() {
    ALBEDO = color;
    ALPHA = step(dist, length(VERTEX));
}

```

Now for an smooth transition we do this:

```
shader_type spatial;

uniform vec3 color: source_color;
uniform float start_dist;
uniform float end_dist;

void fragment() {
    ALBEDO = color;
    ALPHA = smoothstep(start_dist, end_dist, length(VERTEX));
}

```

Here you get no effect up until `start_dist`. Between `start_dist` and `end_dist` you get a smooth transition between that to `color`. And beyond `end_dist` you only get `color`.

I hope this is clear enough for you to add to your project.

---
Tags: textures, godot
---


# Question
Title: How to assign a new value to a global variable in GML
I have a variable called `global.goldchance = irandom(99);`. I use it to get a random number from 0 to 99. However, I need to be able to run it again so that the variable gets a new random number. Writing `var goldchance = irandom(99);` doesn't work as that will destroy the variable afterward. Simply writing the global variable again in a new location won't work as that is just stating it and doing nothing with it. How do I do this?

# Answer
If you want to change the value of a GLOBAL variable you would just assign it a new value the same you would with a normal variable. You would just insert:

```
    global.goldchance = value;

```

"Simply writing the global variable again in a new location won't work as that is just stating it and doing nothing with it." -- Yes it will, as long as you're assigning a value to it.
> 1 votes

---
Tags: game-maker, random
---


# Question
Title: Unity Mirror AWS clients won't connect to server
My Unity project uses the Mirror Networking component and I am using an AWS free tier EC2 instance to host it. I configured the instance following this guide from the Mirror documentation, including adding a security rule to open port 7777, the default port used by Mirror. One difference is that I use a Windows build on the server as the host rather than a dedicated server build because I am unable to build the project as a dedicated server build without running into issues.

When I run the server on the AWS instance and try to connect a client to it, I get the error:

"\[SimpleWebTransport\] EXCEPTION: SocketException Message: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

UnityEngine.Logger:Log (UnityEngine.LogType,object)".

The error is hard to find a solution for because it very generic. I am using the SimpleWebTransport since I want WebGL clients to be able to connect. Portchecker tells me that port 7777 (for Mirror) and 22 (for SSH) are closed, but 3389 for remote desktop protocol is open and I can connect to the instance through RDP. It seems weird that port 7777 would be closed despite me adding a security rule for it to be open but the Mirror documentation said that the port would only be open when the game is running, so I am unsure if this is an issue with my AWS configuration or the game.

# Answer
> 0 votes
I fixed it by adding an inbound security rule in the Windows Defender Firewall for port 7777 inside the instance.

I set the rules on the AWS security group and my local Windows Firewall, but forgot about the Windows Firewall for the OS on the instance. This is a step in Mirror's documentation, but they didn't specify whether it was the firewall on the instance or locally and I assumed it was locally.

---
Tags: unity, networking, websocket, mirror-networking, hosting
---


# Question
Title: How to correctly instantiate a cube over another, or side-by-side another one
In a Minecraft spawn system like, I can't make works correctly following code. Specifically, if I use Code 1 it works only when I instantiate a cube over another one, not one aside other. The opposite if I use Code 2.

Can you help me write correct code to make it works ?

```
void BuildBlock_v2(GameObject block)
{
    Quaternion rotation;
    rotation = Quaternion.Euler(0, 0, 0);

    if (Physics.Raycast(shootingPoint.position, shootingPoint.forward, out RaycastHit hitInfo))
    {

        float playerRotationY = Mathf.Round(shootingPoint.rotation.eulerAngles.y);
        if (playerRotationY >= 0 && playerRotationY < 45)
            rotation = Quaternion.Euler(0, -180, 0);
        else if (playerRotationY >= 45 && playerRotationY < 135)
            rotation = Quaternion.Euler(0, -90, 0);
        else if (playerRotationY >= 135 && playerRotationY < 225)
            rotation = Quaternion.Euler(0, 0, 0);
        else if (playerRotationY >= 225 && playerRotationY <= 315)
            rotation = Quaternion.Euler(0, -270, 0);
        else
            rotation = Quaternion.Euler(0, 0, 0);

        GameObject hitObject = hitInfo.collider.gameObject;
        if (hitInfo.transform.tag == "Block")
        {
            float height = hitObject.GetComponent<Renderer>().bounds.size.y;
            float y = hitObject.transform.position.y;

            //
            // Code 1 : works when I instantiate a cube over another one, not one aside other
            //Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x + hitInfo.normal.x / 2), hitInfo.point.y + 0.5f , Mathf.RoundToInt(hitInfo.point.z + hitInfo.normal.z / 2));

            // Code 2: it  works when I instantiate a cube side by side another, but not one over another
            Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x + hitInfo.normal.x / 2), y, Mathf.RoundToInt(hitInfo.point.z + hitInfo.normal.z / 2));
            Instantiate(block, spawnPosition, rotation, parent);

        }
        else if (hitInfo.transform.tag == "Terrain")
        {
            // Instance on ground
            //Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x), Mathf.RoundToInt(hitInfo.point.y)+0.5f, Mathf.RoundToInt(hitInfo.point.z));
            Vector3 spawnPosition = new Vector3(Mathf.RoundToInt(hitInfo.point.x), hitInfo.point.y + 0.5f, Mathf.RoundToInt(hitInfo.point.z));
            Instantiate(block, spawnPosition, rotation, parent);
        }
    }
}

```

# Answer
Assuming that your blocks are individual game objects with 1 unit of size, they are axis aligned, and the origin of all blocks is at their center:

The raycast.transform.position gives you the origin of the cube that was hit. Raycast.normal gives you the normal direction of the face of the cube the raycast hit. The placement position of the new cube is therefore at old cube position + hit normal * cube size. Assuming cube size of 1, this can be ignored.

I'm on my phone right now so writing code would be difficult. I think this is enough for you to update your code. Let me know if you need more.
> 0 votes

---
Tags: unity, mathematics
---


# Question
Title: How to meet quality standard for audio files to upload to the Unity Store?
I have some 8-bit classical music that I want to release on the Unity store, for the most part the Unity Store Submission Guidelines make sense, but for this one part that goes.

> 2.7.b Audio files are clear and audible. Audio tracks do not exceed -0.3 dB on peak meters.

Was wondering what exactly getting your music up to that standard means? I have read the submission guidelines carefully and I believe I adhere to them, but for this one part that I'm uncertain about.

Source

# Answer
That is talking about volume. It says that the tracks need to be heard and they shouldn't be compressed so much that you can't understand them. Finally, if you were to look at the music under a peak meter, it must not exceed the listed value. Basically, try not to hurt people's ears with your music.
> 1 votes

---
Tags: unity, assets, audio
---


# Question
Title: tubular mesh around any y=f(x). issue calculating normals
I used this to help create a 3d cylindrical mesh that wraps around any y = f(x).
Each vertex is calculated by a point P:

```
  const P = (x,y,dy,r,u) => {
      const normal = -1/dy;
      return {
        x: x + r*Math.cos(u),
        y: y + r*Math.cos(u) * normal,
        z: r*Math.sin(u)
      }
    }

```

Images: x^2 sin(x)

As you can see there are issues when |dy| \< 1. Obviously this is because of my calculation of the normal.
In general, I want the cylinders to face the proper direction, without any scaling.

I had tried to do a piecewise for |dy| \< 1 but it isn't the elegant solution im looking for. I know that when the cylinder is facing vertically, the vertices are a function of x and z ( dy = inf so normal = 0 accounts for this), and when the cylinder is facing horizontally the vertices should be strictly in terms of y and z. This is where I get the divide by zero discontinuity and and the weird scaling when dividing by |dy| \< 1

Basically, I am looking for some f(dy) that determines how much the x and y component contribute to the generation of the vertices.
full code

# Answer
I'm not sure how this function is trying to work, but an easier way for your application would be to precalculate the points for a circle at the origin and perpendicular to your line. Assuming your line is 2d and axis aligned and made up of points from p1 to pn, for any given line segment px to px+1, you can calculate an orthogonal basis matrix. Normalize the vector from px to px+1. We will call this line. Assume that line is aligned with the world forward/backward and up/down directions. Therefore, the world right vector is always perpendicular, so take Line X Right to get the Up vector of the line segment. With these three vectors, you can build a basis matrix to transform the points. Multiple each point by the basis matrix and add the new position to Px+1. The points are now all transformed into the space of the end point of the line segment regardless of how vertical it is.
> 0 votes

---
Tags: javascript, 3d-meshes
---


# Question
Title: Is shader array shared with other shader or not?
The documentation for `Material.SetFloatArray` it states:

> Sets a float array property on the material. If a float array property with the given name already exists, the old value is replaced.

If I set the same array on multiple shaders, is the float array shared among shaders like texture, or will every shader have its own copy of the array? (Which multiplies the amount of RAM needed by the amount of shader that use it.) If the array is not shared, then is there any way to set array in such a way that the array is shared between shaders?

# Answer
> 1 votes
The data is not shared when you use `Material.Set*`. This is unique to a single material instance.

It sounds like you're looking for `Shader.SetGlobalFloatArray`. This sets a float array that's accessible to all materials, not just a single instance of a particular material.

In general, if you want it to be used by just one material instance, use the `Material` version. If you want it to be global / accessible between different shaders and material instances, use the `Shader` version.

---
Tags: unity, shaders
---