# Question
Title: List<T>.Contains(T) Method seems to return true for substrings? I don't want that
so I need to check a List of strings belonging to an AudioManager script, *from another script*, to see if it contains a specific string. Accessing that List wasn't hard. What's surprising me is that the method `List<T>.Contains(T)` is returning `true` when it should return `false`. I think this is because it returns true when a *substring* in the List matches the string I am checking for.

My first idea was to just run a for-each loop, but I assumed that was naiive; that I should use a List method. Should I just use a for-each loop? Here are the offending scripts:

This script is on my GameManager prefab. It has the `AudioManager` tag and the script is called `AudioManager.cs.`

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

public class AudioManager : MonoBehaviour
{
    private static AudioManager instance = null; // static (class level) variable
    public static AudioManager Instance { get { return instance; } } // static getter (only accessing allowed)

    public List<string> anims_w_soundFX;

    public AudioSource bgm;
    private Scene currentScene;

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else
        {
            if (this != instance) { Destroy(gameObject); }
        }
        currentScene = SceneManager.GetActiveScene();

        anims_w_soundFX = new List<string>()
        {
            "Luigi_Jump_start_wSound",
            "Luigi_Jump_down_wSound",
            "Luigi_Jump_end_wSound",
            "Luigi_Walk_wSound",
            "Luigi_Run_wSound",
            "Luigi_Battle_Punch_wSound",
            "Luigi_Battle_PunchTimed_wSound"
        };
        //@StackExchange users: ^ THIS IS ALL YOU NEED TO READ FOR THIS SCRIPT!
    }

    //(...) there's more but it only affects background music
}

```

This next script is called `SFX_Event.cs`. I use the `SetSFX()` function from this script when I place an animation event on an animation clip:

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

public class SFX_Event : MonoBehaviour
{
    private Animator anim;
    private AnimatorClipInfo[] currentClipInfo;
    private AudioClip sfxClip;
    private GameObject audioManager;
    private List<string> anims_w_soundFX;
    public AudioSource source;

    void Start()
    {
        anim = GetComponent<Animator>();
        audioManager = GameObject.FindGameObjectWithTag("AudioManager");
        anims_w_soundFX = audioManager.GetComponent<AudioManager>().anims_w_soundFX;
    }
    public void SetSFX()
    {
        currentClipInfo = anim.GetCurrentAnimatorClipInfo(0);
        string ccName = currentClipInfo[0].clip.name;
        if (anims_w_soundFX.Contains(ccName))
        {
            switch (ccName)
            {
                case "Luigi_Jump_start_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/smrpg_jump");
                    PlaySFX();
                    break;

                case "Luigi_Jump_down_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/freesfx_falling_quick");
                    PlaySFX();
                    break;

                case "Luigi_Jump_end_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/smrpg_click");
                    PlaySFX();
                    break;

                case "Luigi_Walk_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/step-floor");
                    PlaySFX();
                    break;

                case "Luigi_Run_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/step-floor");
                    PlaySFX();
                    break;

                case "Luigi_Battle_Punch_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/smrpg_mario_shell");
                    PlaySFX();
                    break;

                case "Luigi_Battle_PunchTimed_wSound":
                    sfxClip = Resources.Load<AudioClip>("SFX/smrpg_mario_hammer");
                    PlaySFX();
                    break;

                default:
                    Debug.LogError("Something went wrong finding the sfxClip in the cases. Check spelling");
                    break;
            }
        }
        else
        {
            Debug.LogError(ccName + " isn't known to the AudioManager. Add it to the list in AudioManger.cs");
        }
    }

    private void PlaySFX()
    {
        source.PlayOneShot(sfxClip);
    }
}

```

Now, at runtime, I go nuts with my character and start jumping all over the place. every once in a while, I will see this in my Console:

```
Luigi|Jump_down isn't known to the AudioManager. Add it to the list in AudioManger.cs
UnityEngine.Debug:LogError(Object)
SFX_Event:SetSFX() (at Assets/Scripts/SFX_Event.cs:70)

```

We shouldn't get far enough to see this error. I don't know how that string (ccName) is being passed or returning false in the first place because

1. That animation doesn't have an Event that calls this script--in fact, it is read-only.
2. I did DUPLICATE that animation, renamed it "Luigi\_Jump\_down\_wSound", and that one DOES have an event pointing to this script, is in the list, and works in another scene. But that animation is not being used by any animation states that get accessed in THIS scene. is Unity *sometimes* confusing the original jump\_down animation for the one I duplicated?

I am sorry that this is so complicated.

# Answer
so this will frustrate somebody because of the title and all, but I think the problem has nothing to do with substrings and everything to do with (as usual) transitions between animation states that *have* animation events and those that do do not. I am getting error logs for other animation states that have no events in them.

My theory is that an animation that does have the event calling `SetSFX()` transitions to an animation without the event, while that function is called. So it is checking against an animation it should not be.

I can fix this by turning off Exit Time and setting Duration to 0, but my animations will be jankier. I will have to think how I want to resolve this. It isn't actually hurting the game, it is just annoying. That something is quietly misfiring a few times a minute.
> 0 votes

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


# Question
Title: Differences between Unity/UE shaders and Opengl Shaders
At first, I thought that they are the same, shaders in game editor write by programmers(or use some graph flow tools nowadays) just get compiled into opengl shaders.

But now I'm writing my own render engine, and found that my engine's shader should not be replaced, since it will do the coordinate transformations.

So, is a shader in Unity/UE the same thing as a shader is in Opengl?

In other words, does the shader in game editor directly change the shaders in the pipeline, or it just use some technical to insert into the render's own shaders?

# Answer
> shaders in game editor written by programmers just get compiled into opengl shaders.

Yes, this is exactly the case. At the end of the day, whatever you write in Unity ShaderLab or build in a shader graph ultimately gets compiled down to a standard hlsl/glsl/vulkan/metal shader program (depending on your target platform).

Parts of the shader that need to work in a consistent way to play nicely with the engine's conventions are handled in a few different ways, from least to most complex:

* **Built-in variables and functions**: Unity provides many pre-defined uniform variables, helper functions, and structs that you can access via an `#include "UnityCG.cginc"` directive.

Want the coordinate transformation to apply for the current object? That's available, pre-populated by the engine into a variable called `unity_ObjectToWorld`. Want to project it through the current camera, that's `UNITY_MATRIX_MVP`. Need the position and projection parameters of the current camera? They're available as `_WorldSpaceCameraPos` and `_ProjectionParams`. These and many more are listed here
* **Preprocessor macros**: Some operations are a bit more complicated than a pre-defined variable or function, because the data types or steps of the process might be different depending on the platform, or the rendering settings, or whether you're in VR, etc.

For these cases, Unity provides macros that are recognized by its shader compiler, and expanded into the appropriate shader code depending on the context of the shader version being compiled.

These include things like `UnityObjectToClipPos()` which handles transforming vertices (a little more efficiently than multiplying out the matrices yourself, since it's aware of the batching/instancing Unity uses internally), or `LinearEyeDepth(i)` for decoding a sample from a depth map, whatever encoding it might use on the target platform/graphics settings.
* **Shader templates**: Working consistently with lighting can be a challenge. You'd have to copy a lot of shading boilerplate into every fragment shader, and remember to call all the right macros to get the same physically-based results as the built-in ones, under all lighting scenarios, even if you only wanted to change one small detail.

To help with this, Unity introduces what it calls a "Surface Shader". Here, you don't write a vertex or fragment program, but a "surface program," whose job is to populate a data structure with the albedo, metalness, roughness, emission, and normal of the shaded point — but not worry about any of the shading. Under the hood, when Unity compiles a vertex/fragment shader from this, it inserts your surface logic into the appropriate place in its built-in lighting shader template for each lighting configuration needed.

This lets you get consistent lighting & shading without worrying about that complexity, and your code describing the surface properties is portable between different lighting and shading models.

All that applies to shaders that you write in text. For node-graph shaders, the situation is much the same, except all the tricks above just manifest as nodes. Nodes that access useful pre-defined uniforms. Function nodes that compile down to different code depending on the platform/scenario. Shader root nodes represent different template shaders, that expose the parameters you're allowed to modify, and compile that code into the boilerplate for the parts that are standardized.
> 1 votes

---
Tags: shaders
---


# Question
Title: How to extract euler angles from transformation matrix?
I have a simple realisation of entity/component game engine.
Transform component have methods to set local position, local rotation, global position and global rotation.

If transform is being set new global position, then local position also changes, to update local position in such case I'm just applying current transform local matrix to parent's transform world matrix.

Until then I have no problems, I can get updated local transform matrix.
But I'm struggling on how to update local position and rotation value in transform. Only solution I have in mind is to extract translation & rotation values from localMatrix of transform.

For translation it's quite easy - I just take 4th column values. but what's about rotation?
How to extract euler angles from transformation matrix?

Is such solution right?:
To find rotation around Z axis, we can find difference between X axis vector of localTransform and X axis vector of parent.localTransform and store result in Delta, then: localRotation.z = atan2(Delta.y, Delta.x);

Same for rotation around X & Y, just need to swap axis.

# Answer
Normally I store all objects as 4x4 Matrices (you could do 3x3 but easier for me just to have 1 class) instead of translating back and forth between a 4x4 and 3 sets of vector3s (Translation, Rotation, Scale). Euler angles are notoriously difficult to deal with in certain scenarios so I would recommend using Quaternions if you really want to store the components instead of a matrix.

But here is some code I found a while back that works. I hope this helps, unfortunately I do not have the original source for where I found this. I have no idea what odd scenarios it may not work in. I am currently using this to get the rotation of YawPitchRoll rotated, left handed 4x4 matrices.

```
   union {
        struct
        {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;
        };
        float m[4][4];
        float m2[16];
    };

    inline void GetRotation(float& Yaw, float& Pitch, float& Roll) const
    {
        if (_11 == 1.0f)
        {
            Yaw = atan2f(_13, _34);
            Pitch = 0;
            Roll = 0;

        }else if (_11 == -1.0f)
        {
            Yaw = atan2f(_13, _34);
            Pitch = 0;
            Roll = 0;
        }else
        {

            Yaw = atan2(-_31,_11);
            Pitch = asin(_21);
            Roll = atan2(-_23,_22);
        }
    }

```

Here is another thread I found while trying to answer your question that looked like a similar result to mine.

https://stackoverflow.com/questions/1996957/conversion-euler-to-matrix-and-matrix-to-euler
> 11 votes

# Answer
There's a great writeup on this process by Mike Day: https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2012/07/euler-angles1.pdf

It is also now implemented in glm, as of version 0.9.7.0, 02/08/2015. Check out the implementation.

To understand the math, you should look at the values that are in your rotation matrix. In addition, you have to know the order in which the rotations were applied to create your matrix in order to properly extract the values.

A rotation matrix from Euler angles is formed by combining rotations around the x-, y-, and z-axes. For instance, rotating θ degrees around Z can be done with the matrix

```
     ┌ cosθ  -sinθ   0 ┐
Rz = │ sinθ   cosθ   0 │
     └   0      0    1 ┘

```

Similar matrices exist for rotating about the X and Y axes:

```
     ┌  1    0     0   ┐
Rx = │  0  cosθ  -sinθ │
     └  0  sinθ   cosθ ┘

     ┌  cosθ  0   sinθ ┐
Ry = │   0    1    0   │
     └ -sinθ  0   cosθ ┘

```

We can multiply these matrices together to create one matrix that is the result of all three rotations. It's important to note that the order that these matrices are multiplied together is important, because matrix multiplication is not commutative. This means that `Rx*Ry*Rz ≠ Rz*Ry*Rx`. Let's consider one possible rotation order, z-y-x. When the three matrices are combined, it results in a matrix that looks like this:

```
         ┌      CyCz              -CySz        Sy  ┐
RxRyRz = │  SxSyCz + CxSz   -SxSySz + CxCz   -SxCy │
         └ -CxSyCz + SxSz    CxSySz + SxCz    CxCy ┘

```

where `Cx` is the cosine of the `x` angle of rotation, `Sx` is the sine of the `x` angle of rotation, etc.

Now, the challenge is to extract the original `x`, `y`, and `z` values that went into the matrix.

Let's first get the `x` angle out. If we know the `sin(x)` and `cos(x)`, we can use the inverse tangent function `atan2` to give us back our angle. Unfortunately, those values don't appear by themselves in our matrix. But, if we take a closer look at elements `M[1][2]` and `M[2][2]`, we can see we do know `-sin(x)*cos(y)` as well as `cos(x)*cos(y)`. Since the tangent function is the ratio of the opposite and adjacent sides of a triangle, scaling both values by the same amount (in this case `cos(y)`) will yield the same result. Thus,

```
x = atan2(-M[1][2], M[2][2])

```

Now let's try to get `y`. We know `sin(y)` from `M[0][2]`. If we had cos(y), we could use `atan2` again, but we don't have that value in our matrix. However, due to the Pythagorean identity, we know that:

```
cosY = sqrt(1 - M[0][2])

```

So, we can calculate `y`:

```
y = atan2(M[0][2], cosY)

```

Last, we need to calculate `z`. This is where Mike Day's approach differs from the previous answer. Since at this point we know the amount of `x` and `y` rotation, we can construct an XY rotation matrix, and find the amount of `z` rotation necessary to match the target matrix. The `RxRy` matrix looks like this:

```
       ┌   Cy     0     Sy  ┐
RxRy = │  SxSy   Cx   -SxCy │
       └ -CxSy   Sx    CxCy ┘

```

Since we know that `RxRy` * `Rz` is equal to our input matrix `M`, we can use this matrix to get back to `Rz`:

```
M = RxRy * Rz

inverse(RxRy) * M = Rz

```

The inverse of a rotation matrix is its transpose, so we can expand this to:

```
┌ Cy   SxSy  -CxSy ┐┌M00  M01  M02┐   ┌ cosZ  -sinZ  0 ┐
│  0    Cx     Sx  ││M10  M11  M12│ = │ sinZ   cosZ  0 │
└ Sy  -SxCy   CxCy ┘└M20  M21  M22┘   └   0      0   1 ┘

```

We can now solve for `sinZ` and `cosZ` by performing the matrix multiplication. We only need to calculate the elements `[1][0]` and `[1][1]`.

```
sinZ = cosX * M[1][0] + sinX * M[2][0]
cosZ = coxX * M[1][1] + sinX * M[2][1]
z = atan2(sinZ, cosZ)

```

Here's a full implementation for reference:

```
#include <iostream>
#include <cmath>

class Vec4 {
public:
    Vec4(float x, float y, float z, float w) :
        x(x), y(y), z(z), w(w) {}

    float dot(const Vec4& other) const {
        return x * other.x +
            y * other.y +
            z * other.z +
            w * other.w;
    };

    float x, y, z, w;
};

class Mat4x4 {
public:
    Mat4x4() {}

    Mat4x4(float v00, float v01, float v02, float v03,
            float v10, float v11, float v12, float v13,
            float v20, float v21, float v22, float v23,
            float v30, float v31, float v32, float v33) {
        values[0] =  v00;
        values[1] =  v01;
        values[2] =  v02;
        values[3] =  v03;
        values[4] =  v10;
        values[5] =  v11;
        values[6] =  v12;
        values[7] =  v13;
        values[8] =  v20;
        values[9] =  v21;
        values[10] = v22;
        values[11] = v23;
        values[12] = v30;
        values[13] = v31;
        values[14] = v32;
        values[15] = v33;
    }

    Vec4 row(const int row) const {
        return Vec4(
            values[row*4],
            values[row*4+1],
            values[row*4+2],
            values[row*4+3]
        );
    }

    Vec4 column(const int column) const {
        return Vec4(
            values[column],
            values[column + 4],
            values[column + 8],
            values[column + 12]
        );
    }

    Mat4x4 multiply(const Mat4x4& other) const {
        Mat4x4 result;
        for (int row = 0; row < 4; ++row) {
            for (int column = 0; column < 4; ++column) {
                result.values[row*4+column] = this->row(row).dot(other.column(column));
            }
        }
        return result;
    }

    void extractEulerAngleXYZ(float& rotXangle, float& rotYangle, float& rotZangle) const {
        rotXangle = atan2(-row(1).z, row(2).z);
        float cosYangle = sqrt(pow(row(0).x, 2) + pow(row(0).y, 2));
        rotYangle = atan2(row(0).z, cosYangle);
        float sinXangle = sin(rotXangle);
        float cosXangle = cos(rotXangle);
        rotZangle = atan2(cosXangle * row(1).x + sinXangle * row(2).x, cosXangle * row(1).y + sinXangle * row(2).y);
    }

    float values[16];
};

float toRadians(float degrees) {
    return degrees * (M_PI / 180);
}

float toDegrees(float radians) {
    return radians * (180 / M_PI);
}

int main() {
    float rotXangle = toRadians(15);
    float rotYangle = toRadians(30);
    float rotZangle = toRadians(60);

    Mat4x4 rotX(
        1, 0,               0,              0,
        0, cos(rotXangle), -sin(rotXangle), 0,
        0, sin(rotXangle),  cos(rotXangle), 0,
        0, 0,               0,              1
    );
    Mat4x4 rotY(
         cos(rotYangle), 0, sin(rotYangle), 0,
         0,              1, 0,              0,
        -sin(rotYangle), 0, cos(rotYangle), 0,
        0,               0, 0,              1
    );
    Mat4x4 rotZ(
        cos(rotZangle), -sin(rotZangle), 0, 0,
        sin(rotZangle),  cos(rotZangle), 0, 0,
        0,               0,              1, 0,
        0,               0,              0, 1
    );

    Mat4x4 concatenatedRotationMatrix =
        rotX.multiply(rotY.multiply(rotZ));

    float extractedXangle = 0, extractedYangle = 0, extractedZangle = 0;
    concatenatedRotationMatrix.extractEulerAngleXYZ(
        extractedXangle, extractedYangle, extractedZangle
    );

    std::cout << toDegrees(extractedXangle) << ' ' <<
        toDegrees(extractedYangle) << ' ' <<
        toDegrees(extractedZangle) << std::endl;

    return 0;
}

```
> 12 votes

# Answer
There's a function in scipy called "scipy.spatial.transform". You can look over in Rotation method which is trasform between euler\_angles \<-\> R-matrix \<-\> quaternion.
> -1 votes

---
Tags: mathematics, transformation, angles
---


title: Component Based Spells/Abilities

text:
# Question
Title: Component Based Spells/Abilities
This has been a bit of a long time coming challenge for me, if you look back at previous questions for Component based spells you are likely to find my old questions, given that they are 1 + 2 years old respectively and I'm on attempt three, I thought I'd try again hopefully with more knowledge!

I am attempting to build a ScriptableObject based spell system, where each spell is made up of five components, Spell\_Cast, Spell\_Aim, Spell\_Visual, Spell\_Motion, Spell\_Behaviour and a bunch of information on the spell itself (Cast, Cost, Max Targets, Base Spell Power, Range, Radius) etc.

Currently I am trying to get bare bones examples working.

For my proof of concept spells, I have picked "Mage Hand" and "Mage Light"

Mage Hand:

* Spell Cast : Channel (Casts while button is held)
* Spell Aim : Raycast (Target Object)
* Spell Visual : A Prefab model of a hand.
* Spell Motion : Projectile (Hand will fire from player to target)
* Spell Behaviour: This parents the target object to the Mage Hand Effect Instance, Disables Gravity, Freezes Rotation and Holds it in-front of the player while the button is held.

Mage Light:

* Spell Cast : Instant (Casts instantly)
* Spell Aim : Raycast (Target Object)
* Spell Visual : A Prefab model of a particle system and light.
* Spell Motion : Projectile (Light will fire from player to target)
* Spell Behaviour: Most of this spell takes place on the Visual Prefab itself, the spell just fires it towards the target, and in PostEffect sets a self destruct timer based on spell power. The prefab handles 'sticking/unsticking' itself to things and destroying itself with monobehaviours.

Both these spells work but I am feeling quite unsure about the spell behaviours, currently there are 1 behaviour scriptableobject per spell.

These are not generalised, I realise I could rework the Behaviour class so it just holds a list of actions to run on the target whatever it may be, but I don't understand how I could make a spell like Mage Hand work using only general actions and the fact it would need to do some actions just once (What if I added an effect that reduces the weight of held item?), but do the actual 'holding' of the object every frame while the button is held.

Take for example my 'Mage Hand' behaviour, there are a lot of sub behaviours (Holding T lets you slightly adjust the hand, or Press ScrollWheel throws the object which i'm not happy with but I went with 'just get something working' philosophy)

I am storing all of the spell state data on SpellCastData and any action I use too often in a behaviour gets moved to the base Spell\_Behaviour class so I'm not repeating myself.

Below (first) is component I use to store and cast spells (Entity\_Cast\_Comp), second is the behaviour for 'Mage Hand'

So, all of that out of the way my question is: **How do I generalise a spell such as Mage Hand that I could then turn my Spell Behaviour objects into a collection of generalised actions?**

Thanks for reading this far!

```
public class Entity_Cast_Comp : MonoBehaviour
{
    [HideInInspector]
    public GameObject parent;
    [Header("Available Spells")]
    public List<Spell> spells = new List<Spell>();
    [Header("Debug information")]
    public bool debug = false;

    //events
    [HideInInspector]
    public UnityEvent OnSpellsChanged;

    private void Start()
    {
        parent = this.gameObject;
    }

    public void Cast(Spell spell, KeyCode button)
    {
        SpellCastData data = new SpellCastData();
        data.button = button;
        data.caster = parent;
        //TODO : This seems like a bad idea
        data.castLocation = parent.transform.Find("CastPointRight");

        //check the spell isnt already casting
        if (data.spellRunning == false && GameObject.FindObjectOfType<UI_Controller>().UIOpen() == false)
        {
            data.spellRunning = true;
            data.SetState(SpellStates.AIMING);
            StartCoroutine(DoCast(spell, data));
        }
    }

    public void AddSpell(Spell spell)
    {
        if (!spells.Contains(spell))
        {
            spells.Add(spell);
            OnSpellsChanged.Invoke();
        }
    }

    public void RemoveSpell(Spell spell)
    {
        if (spells.Contains(spell))
        {
            spells.Remove(spell);
            OnSpellsChanged.Invoke();
        }
    }

    private IEnumerator DoCast(Spell spell, SpellCastData data)
    {
        while (data.spellRunning)
        {
            data.UpdateButtonState();

            switch (data.state)
            {
                case SpellStates.AIMING:
                   yield return spell.spellAim.Aim(spell, parent, data);

                break;

                case SpellStates.CASTING:

                    yield return spell.spellCast.Cast(spell, parent, data);
                    yield return spell.spellAim.DrawAim(spell, parent, data);

                    foreach (var target in data.targets)
                    {
                        if (!data.effectInstances.ContainsKey(target))
                        {
                            //TODO : F
                            data.effectInstances[target] = spell.spellVisual.SpawnEffect(data.castLocation.position, parent.transform.rotation);
                            data.targetsHit.Add(target, false);
                        }

                    }

                    foreach (var target in data.targets)
                    {
                        while (data.targetsHit[target] == false)
                        {
                            yield return spell.spellMotion.Move(spell, parent, data, target);
                        }
                    }

                    foreach (var target in data.targets)
                    {
                        if (data.preEffectDone.ContainsKey(target) == false)
                        {
                            yield return spell.spellBehaviour.PreEffect(spell, parent, data, target);
                            data.preEffectDone.Add(target, true);
                        }

                        yield return spell.spellBehaviour.Effect(spell, parent, data, target);
                    }

                break;

                case SpellStates.CANCELLING:

                    data.spellRunning = false;
                    data.Reset();
                yield break;

                case SpellStates.FINISHED:

                    foreach (var target in data.targets)
                    {
                        yield return spell.spellBehaviour.PostEffect(spell, parent, data, target);
                    }

                    data.Reset();
                yield break;
            }

            yield return null;
        }

        yield break;
    }

}

```

This is the spell behaviour for 'Mage Hand'

```
[CreateAssetMenu(menuName = scriptableObjectPath + componentPath + "TeleHold")]
public class Spell_Effect_TelekineticHold : Spell_Behaviour
{
    public float speed = 5f;
    public float moveSpeed = 3.5f;
    public float xOffsetMin = 0f;
    public float xOffsetMax = 2f;
    public float yOffsetMin = 0f;
    public float yOffsetMax = 2f;
    public float zOffsetMin = -0.5f;
    public float zOffsetMax = 1f;

    private Transform pivotPoint;

    private float zOffset = 0;
    private float xOffset = 0;
    private float yOffset = 0;

    private Vector3 targetOffset = new Vector3();

    public float smoothTime = 0.3F;

    private Vector3 targetOriginalRotation;
    private Vector3 velocity = Vector3.zero;
    private Quaternion quaternion;

    public override IEnumerator Effect(Spell _parent, GameObject caster, SpellCastData data, GameObject target)
    {
        //hold target in place as long as casting and target exists
        if (target)
        {

            //TODO : Extra action keys shouldnt be hard coded
            if (Input.GetKey(KeyCode.T))
            {
                xOffset += Input.GetAxisRaw("Mouse X");
                yOffset += Input.mouseScrollDelta.y * 0.25f;
            }
            else
            {
                zOffset += Input.mouseScrollDelta.y * 0.25f;
            }

            //TODO : Extra action keys shouldnt be hard coded
            //and this probably doesnt want to work like this?
            if (Input.GetKey(KeyCode.Mouse2))
            {

                yield return PostEffect(_parent, caster, data, target);
                AddForce(target, data);
                data.spellRunning = false;
                yield break;
            }

            xOffset = Mathf.Clamp(xOffset, xOffsetMin, xOffsetMax);
            yOffset = Mathf.Clamp(yOffset, yOffsetMin, yOffsetMax);
            zOffset = Mathf.Clamp(zOffset, zOffsetMin, zOffsetMax);

            int targetIndex = data.targets.FindIndex(x => x == target);
            //TODO : Improve multi hand stacking
            targetOffset = new Vector3(xOffset + 1.4f * targetIndex, yOffset, 0);

            if (data.effectInstances[target] != null)
            {
                Widget targetWidget = target.GetComponent<Widget>();
                Vector3 targetPosition = (pivotPoint.position + targetOffset) + (pivotPoint.forward * zOffset * 5f);
                if (targetWidget)
                {
                    targetPosition.y = targetPosition.y + targetWidget.carryTargetPositionOffset.y;
                    target.transform.localPosition = Vector3.zero + targetWidget.carryTargetPositionOffset;
                }
                else
                {
                    target.transform.localPosition = Vector3.zero;
                }

                data.effectInstances[target].transform.DOMove(targetPosition, smoothTime);

                data.effectInstances[target].transform.rotation = data.caster.transform.rotation;
            }

            yield return null;
        }
        else
        {
            yield break;
        }
        yield break;
    }

    public override IEnumerator PreEffect(Spell _parent, GameObject caster, SpellCastData data, GameObject target)
    {
        //Debug.Log("pre effect");
        if (target)
        {
            SetSpellDataPreviousParent(data, target);
            pivotPoint = caster.transform.Find("MageHandRight").transform;
            ParentToEffectInstance(target, data);
            targetOriginalRotation = target.transform.eulerAngles;
            CopyPhysicsSettings(target);
            DisablePhysics(target);
        }

        yield break;
    }

    public override IEnumerator PostEffect(Spell _parent, GameObject caster, SpellCastData data, GameObject target)
    {
       // Debug.Log("post effect");
        if (target)
        {
            target.transform.eulerAngles = targetOriginalRotation;
            RemoveParentToEffectInstance(target, data);
            RestorePhysicsSettings(target);
            ResetVariables();
            DeleteEffectInstance(data, target);
        }
        yield break;
    }

    private void ResetVariables()
    {
        zOffset = 0;
        xOffset = 0;
        yOffset = 0;
    }

}

```

Here's a picture of a how it currently looks, as perhaps I havent explained myself well enough, I have a system in place working, but I consider it to be far too brittle to be worth going ahead with, as simple spells like 'Fireball' etc would easy enough to implement but I have no idea how I would implement Mage Hand In a very generic way.

# Answer
> 1 votes
You could use a main "Spell" C# object with all parameters (Cost, etc.) as public fields, so you can change them in the editor, and also setup public fields for Visual, Motions... Those last fields should be of type SpellVisual, SpellMotion... (I will talk about them later). If some fields have some finite options (like active/passive spell for example) you can use simple drop-down lists, or have the main "Spell" abstract and use child classes for "ActiveSpell", "PassiveSpell", etc.

For "SpellVisual" you can setup a main `abstract` C# object, and then child of this object like for example a "particle circle" visual effect, an "3d model rotating" effect, etc. Like the first object, expose all specific parameters as public fields to be changed in the inspector, like particle config, duration, etc. And do the same for others objects type like "SpellMotion" and others you need...

Then, when all C# objects are set-up, you just have to create prefabs which uses the classes defined earlier, and all specific spell stuff are then configured in the inspector. (Just in case you realize you need as many "SpellXXX" prefabs as "Spells" prefabs, it may be better to move all stuff directly in the "Spell" class)

**As a rule of thumbs, you should ask if something is game-theme related. If no =\> C#, if yes =\> Prefab/Object config.**

For example, never create a FireAreaDamageEffect class, but treat all types of damage as a list, and then create a AreaDamageEffect with a list of damage types, which should be global to the whole game.

---

Here are the main advantage of this solution:

* If you are working as a team on this project, spells can be created and edited by a non-developer person, like a character designer.
* If you want players to extend your game with mods, they don't need access to the source code
* For testing, you don't need to recompile or restart game to change parameters, including visual ones (can be changed directly in unity inspector during playtest)

The only disadvantage I can think of right now is that you need more work at first to setup the system, but you will gain time from it even if working alone on the project.

---
Tags: unity, game-design, component-based
---


# Question
Title: When updating app from Google Play will the app data be deleted?
My question is pretty simple.

I developed a game, uploaded it on the store. In order to keep player level record and UI prefs it writes an ini file.

When the next update is up on the store and the users will update will they lose their progress? Will the file be deleted?

Thanks

# Answer
> 1 votes
When updating the app, all the saved data will remain the same. This includes local files you write to, which you seem to be using.

---
Tags: game-maker, savegame, google-play
---


# Question
Title: How can I render 3D objects and particle systems in front of a Screen Space - Overlay Camera?
I am using Unity 2019 with the Universal Render Pipeline. I have a canvas that is using Screen Space - Overlay render mode. I cannot change my render mode to Screen Space - Camera, because it is not currently supported by the Universal Render Pipeline.

How can I have a particle system, or any other 3D objects, render on top of my canvas?

# Answer
> 1 votes
**To render 3D objects on top of your canvas:**

1. Create a new Canvas in Screen Space - Overlay.
2. Add a RawImage to that canvas.
3. Create a new Render Texture.
4. Add the Render Texture to the Raw Image.
5. Create a new Camera.
6. Set the camera to Solid Color background with an alpha of 0.
7. Set the output texture of the camera to be the Render Texture you created.

**You can now render 3D objects on top of your canvas; however, there are extra steps for particle systems:**

8. Create a material. Set its shader to Universal Render Pipeline/2D/Sprite-Lit-Default.
9. Add your particle sprite to the Diffuse of your material.
10. In the Renderer settings of your particle system, replace the material with the one you just created.

**You should be good to go!**

(If you have any problems, try going to your Render Settings and change the Anti Aliasing to 8x.)

WARNING: This will eat your battery. Be sure to disable the camera when not in use.

---
Tags: unity, rendering, camera, particles, draw-order
---


# Question
Title: Cube doesn't render as expected when rotated (representing 3D in 2D)
Cube.  When I rotate the object around OZ moves to the left.  Rotation around OX - the cube rises up.  Rotation around the OY-the cube is compressed.  The function I use for rotation:

```
void rotation(double angleX, double angleY, double angleZ, int x, int y, int z)
{
    angleX = angleX * M_PI / 180;
    angleY = angleY * M_PI / 180;
    angleZ = angleZ * M_PI / 180;

    double cX = cos(angleX);
    double sX = sin(angleX);
    double cY = cos(angleY);
    double sY = sin(angleY);
    double cZ = cos(angleZ);
    double sZ = sin(angleZ);

    double x0 = x;
    double y0 = y * cX + z * sX;
    double z0 = z * cX - y * sX;

    double x1 = x0 * cY - z0 * sY;
    double y1 = y0;
    double z1 = z0 * cY + x0 * sY;

    double x2 = x1 * cZ + y1 * sZ;
    double y2 = y1 * cZ - x1 * sZ;

    SDL_RenderDrawPoint(ren, x2, y2);
}

```

Used matrices. However, the result was the same.

# Answer
> 1 votes
I don't have SDL installed, so I couldn't run your code. However, from what I can see the problem is not the calculation of the rotations (not 100% certain if they do not contain any mistakes, but they look fine), but the object you are rotating.

The problematic line is this function call in your main function:

```
rotation(angleX, angleY, angleZ, v[i].x, v[i].y, 100);

```

What you want to do, is to rotate a cube, a 3-dimensional object, and draw it to your screen. But what you are actually doing is the equivalent of rotating a piece of paper (2-dimensional) with a drawn cube on it and printing this to your screen. Every point you pass to your function has the same z-value.

With the paper example in mind, let's go through your images and the effects you are seeing (take a real one and draw your cube on it, if you can't imagine it). Note that rotations always rotate around the coordinate origin (the point at x=0, y=0, z=0).

**Rotation around the z-axis (second image)**

This is like putting your finger onto the point where your coordinate origin is and starting to rotate the paper around this axis. Since your cube is not at the coordinate center:

```
int centerX = SCREEN_WIDTH / 3;
int centerY = SCREEN_HEIGHT / 2 + 100;

```

it is not only rotated, but also translated. The farther away your finger is from the cube, the larger the translations.

**Rotation around the x-axis (third image)**

This is basically like gluing the piece of paper to your fingertip (don't do that) and tilting your wrist joint so that your finger goes upwards. The paper moves upwards, and so does the cube. Additionally, the paper also gets tilted which has the effect, that your cube gets visually compressed in the y-direction since you can see less of the papers surface. In the extreme case, you would only see the upper side of the paper, degenerating your cube into a line.

**Rotation around the y-axis (fourth image)**

Same as the x-axis but tilt your wrist joint to the left instead upwards. So the cube moves to the left and gets visually compressed in the x-direction.

**Solution**

The solution should be obvious: Use 3d points by adding a z-component.

What you did with your cube is that you already manually applied a parallel projection to it before all other transformations. But the projection usually has to be the last step after all other transformations. I say usually since I can't rule out, that there are some fancy effects/techniques, that do it differently.

However, I think it might be helpful for you, to read at least some tutorials about transformations. Read for example those two:

They might be related to OpenGL, but the information you get from those two are universal. Make sure you read them in the order I linked them.

One remark regarding this part of your title: "(representing 3D in 2D)". Every "3d game" calculates a representation of your 3d scene in 2d since your screen is 2 dimensional. This is also true for VR. In VR you just do it twice, one representation for each eye, tricking your brain into believing you see in 3d.

**Additional note**

Don't do `using namespace std;`. See this Stackoverflow question to understand why.

---
Tags: c++, 2d, 3d, sdl2
---


# Question
Title: How can I scale the SCNPhysicsShape when scaling a SCNNode?
I wrote a script that would match all models to one size, no matter the original size of the source model. So now these models fit precisely in the scene, but unfortunately when I add `SCNPhysicsBody` to them (with `SCNPhysicsShape`), their colliders (shapes) are not scaled. They do not match the current size of a node.

How can I fix this?

# Answer
> 0 votes
The problem is that `SCNPhysicsShape` (and physics generally in SceneKit) does not actually respect node scale. It will not use the new scale, instead it will create a SCNPhysicsShape respecting the old scale of node.

But you can force to use the new scale.

Just create a physics body with nil (or null if you are using xamarin ios) for the shape parameter.

E.g.:

```
body = SCNPhysicsBody(node, nil)

```

or for xamarin ios

```
body = SCNPhysicsBody.Create(node, null)

```

---
Tags: ios, scenekit
---


# Question
Title: Replacing UI GameObjects with Scriptable Object script
In my game I'm trying to make a series of mock web pages. To make it easier, I thought I'd make all the webpage UI into Scriptable Objects and have a game manager script determining what content to display on the UI. However, I'm doing a small test that isn't going as planned.

Because the content, style, and layout of each page may be quite different, I decided to make a webpage-styled template and have the content manager switch out scriptable object properties as a GameObject so that it takes everything that will be in the prefab. This doesn't seem to be working and I'm not sure what I'm doing wrong.

For now, I'm just testing this method with a very basic script. It's not changing the main content as a GameObject, though it is doing it on my tab textmesh property. It seems to have an issue with transplanting a prefab into the defined content space, but no errors are popping up. I'd appreciate some advice here.

Web Content Scriptable Object Script:

```
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu]
public class WebContent : ScriptableObject
{
    public string tabTitle; //WebPage Title
    public GameObject canvasContent; //Web Page UI Content I want to change via prefab attached to a  Scriptable Object
}

```

Content Display Script:

```
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ContentDisplay : MonoBehaviour
{
    public WebContent content;
    public TextMeshProUGUI TabName;
    public GameObject mainContent;

    // Update is called once per frame
    void Update()
    {
        TabName.text = content.tabTitle.ToString(); //This works
        mainContent = content.canvasContent; // This doesn't work

    }
}

```

# Answer
In order to put a prefab into your scene, you need to Instantiate it. This also applies to UI elements.

Assuming `mainContent` is a child-node of the content display game object, you need to destroy the old child-node, instantiate the new and make it the new child-node. This code is untested, but should work:

```
 Destroy(mainContent);
 GameObject newContent = Instantiate(content.canvasContent, this.transform);
 mainContent = newContent;

```

But destroying and instantiating a game object is costly and might have unintended side-effects. So you should not do that in `Update()`. You should only do this when the content actually changed. You can actually do that by turning `content` into a property. This allows you to run some code whenever that value gets changed.

```
private WebContent content;
public WebContent Content {
      get => content;
      set {
            content = value;
            TabName.text = content.tabTitle.ToString();
            Destroy(mainContent);
            GameObject newContent = Instantiate(content.canvasContent, this.transform);
            mainContent = newContent;
      }
}

```

(again, untested code)
> 1 votes

---
Tags: unity, scriptable-object
---


# Question
Title: Touch input not working well for mobile game made with Unity 2D
I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9+), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related.

This is the code attached to the player:

```
 void FixedUpdate()
 {
     Jump();
     Dead();
 }

 void Jump()
 {
     if (Input.touchCount > 0 && isGrounded)
     {
         gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce * Time.fixedDeltaTime), ForceMode2D.Impulse);
     }
 }

```

Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.

# Answer
Your main problem is that you're checking for input in `FixedUpdate`.

`FixedUpdate` is not guaranteed to run every frame, or only once per frame. It will run however many times the physics simulation needs to "catch up" to the current frame time, acting in `fixedTimestep` intervals.

So by handling input here, you run the risk of skipping or double-handling inputs if you're not careful. The simplest fix is to move your input detection code into `Update` instead

Your second problem is that you're integrating your impulse over time - an impulse like a jump should be an instantaneous push, that doesn't vary in scale depending on how long your simulation step is. So don't multiply by `deltaTime` here.

You may also want to apply rigidbody interpolation to help with the perceived lag/choppiness. This can come from the mismatch between the physics sim time and the display time, making it look like your game is running at a lower framerate than it is. Turning on interpolation smoothes this out so you don't see juddering.
> 1 votes

---
Tags: unity, c#, mobile, touch, jumping
---


# Question
Title: Pseudocode for calculating per vertex normals for a trianglestrip mesh
I have a terrain that is defined as a trianglestrip mesh. Now I'm trying to calculate the normals of each vertex but I've realised that my normal way of calculating vertex normals only works with triangle meshes. I'm finding it hard to wrap around my head how to get the triangles from trianglestrip to calculate the normal in code. I can imagine it but just can't understand how that translates into code.

Can someone help me with some pseudocode or anything of that matter that demonstrates how I could cycle an array that contains indices used in a trianglestrip to calculate the normals?

EDIT:

I ended up finding this answer on stackoverflow and it looked like a very efficient and easy way to generate normals from a heightmap: https://stackoverflow.com/questions/49640250/calculate-normals-from-heightmap/49640606?noredirect=1#

The question defines the point and it's neighbours as follows for clarity. O being the vertex we're calculating a normal for:

```
  T
L O R
  B

```

Having translated it to my own cordinate system (right handed because of opengl), I ended up with the calculation of a normal of a vertex as:

```
Vec3 normal = Normalize(Vec3((R-L)/2, 1.0f, (B-T)/2));

```

I implemented that. Here's the constructor for a terrain in my code (fair warning, I am writing my own engine with its own math library. You should be able to infer the meanings of some things by their names though):

```
Terrain :: Terrain(unsigned int size)
{
    unsigned int xSegments = size;
    unsigned int ySegments = size;

    srand(time(NULL));
    m_NoiseMap = CreateScope<NoiseMap>(xSegments + 1, ySegments + 1);
    m_NoiseMap->GenerateNoise(rand() % 9999, 25, 0.015, 0.52, Vec2(0.4), 4);

    float dX = (float)size  / xSegments;
    float dY = (float)size / ySegments;

    auto heightMap = *m_NoiseMap;

    for (unsigned int y = 0; y <= ySegments; ++y)
    {
        for (unsigned int x = 0; x <= xSegments; ++x)
        {
            auto height = heightMap[x][y];
            auto position = Vec3(dX * x * 2.0f - 1.0f, height, dY * y * 2.0f - 1.0f);

            Positions.push_back(position);
            UV.push_back(Vec2(dX * x, 1.0f - y * dY));

            float heightR, heightL, heightU, heightD = height;

            if (y > 0)
                heightU = heightMap[x][y - 1];

            if (x > 0)
                heightL = heightMap[x - 1][y];

            if ( y < ySegments)
                heightD = heightMap[x][y + 1];

            if (x < xSegments)
                heightR = heightMap[x + 1][y];

            Normals.push_back(Normalize(Vec3((heightR - heightL)  / 2, 1.0f, (heightD - heightU) / 2)));
        }
    }

    bool oddRow = false;

    for (int y = 0; y < ySegments; ++y)
    {
        if (!oddRow)
        {
            for (int x = 0; x <= xSegments; ++x)
            {
                Indices.push_back(y       * (xSegments + 1) + x);
                Indices.push_back((y + 1) * (xSegments + 1) + x);
            }
        }
        else
        {
            for (int x = xSegments; x >= 0; --x)
            {
                Indices.push_back((y + 1) * (xSegments + 1) + x);
                Indices.push_back(y       * (xSegments + 1) + x);
            }
        }
        oddRow = !oddRow;
    }

    Topology = TRIANGLE_STRIP;
    Finalize();
}

```

Unfortunately, when I do this, I get this as the result once I'm done lighting the mesh:

Which just looks random if you ask me. I've set the normal to be flat in the shader as I'm trying to make low poly terrain and do not need smooth shading. Anyone have any clues where I'm going wrong?

Thank you

# Answer
> 1 votes
After coming across this resource: http://www.videotutorialsrock.com/opengl\_tutorial/terrain/home.php and reading the comment from DMGregory, I decided to get the cross products in each triangle surrounding the vertex on the heightmap. The code for generating the normals looks as follows:

```
Vec3 sum(0.0f, 0.0f, 0.0f);

Vec3 out;
if (y > 0)
    out = Vec3(0.0f, heightMap[x][y - 1] - heightMap[x][y], -1.0f);

Vec3 in;
if (y < ySegments - 1)
    in = Vec3(0.0f, heightMap[x][y + 1] - heightMap[x][y], 1.0f);

Vec3 left;
if (x > 0)
    left = Vec3(-1.0f, heightMap[x - 1][y] - heightMap[x][y], 0.0f);

Vec3 right;
if (x < xSegments - 1)
    right = Vec3(1.0f, heightMap[x + 1][y] - heightMap[x][y], 0.0f);

if (x > 0 && y > 0)
    sum += Normalize(Cross(out, left));

if (x > 0 && y < ySegments - 1)
    sum += Normalize(Cross(left, in));

if (x < xSegments - 1 && y < ySegments - 1)
    sum += Normalize(Cross(in, right));

if (x < xSegments - 1 && y > 0)
    sum += Normalize(Cross(right, out));

tempNormals.push_back(sum);

```

After storing the normals in a temporary vector, I smoothed the normals like this to get nicer edges:

```
Normals.resize(tempNormals.size(), Vec3(0.0f, 1.0f, 0.0f));

const float FALLOUT_RATIO = 0.5f;

for (unsigned int y = 0; y <= height; y++)
{
    for (unsigned int x = 0; x <= width; x++)
    {
        Vec3 sum = tempNormals[(y * width) + x];

        if (x > 0)
            sum += tempNormals[(y * width) + (x - 1)] * FALLOUT_RATIO;

        if (x < xSegments - 1)
            sum += tempNormals[(y * width) + x + 1] * FALLOUT_RATIO;

        if (y > 0)
            sum += tempNormals[((y - 1) * width) + x] * FALLOUT_RATIO;

        if (y < ySegments - 1)
            sum += tempNormals[((y + 1) * width) + x] * FALLOUT_RATIO;

        auto magnitude = sqrt(pow(sum.x, 2) + pow(sum.y, 2) + pow(sum.z, 2));

        if (magnitude == 0)
            sum = Vec3(0.0f, 1.0f, 0.0f);

        Normals[(y * width) + x] = sum;
    }
}

```

Results:

DISCLAIMER: While I did manage to get it done using the finite difference method, it didn't look good on low poly meshes. Using the cross product of each triangle yielded much more accurate results

---
Tags: graphics-programming, normals
---


# Question
Title: I can't clear the paint image in my Canvas
I'm trying to make the Mario move, but somehow it leaves traces behind, can anybody help???

```
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var mario;
var marioSprite;
var tiles;
var speedX = 1;

//marioSprite Specification
mario = {
    //target picture specification X & Y, Width & Height
    px:276,
    py: 44,
    pwidth: 16,
    pheight: 16,
    //drawing on Canvas specification X & Y, Width & Height
    cx: 16,
    cy: 116,
    cwidth:16,
    cheight:16,
}

//draw Mario in Canvas
function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);
    });
    this.position = function() {
        this.mario.cx += speedX;
    }
    position();
}//drawMarioSprite() end

//drawTiles and tilesLoop
function drawTiles() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        tilesLoop();
    });
}
function tilesLoop(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
            ctx.drawImage(tiles,
                0, 0, 26, 26,
                x*12, y*12, 20, 20);
        }
    }
}//drawTiles() end

function draw(){

    drawMarioSprite();
    drawTiles();
    window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);

```

thank you

# Answer
> 1 votes
use `ctx.clearRect(0,0,canvas.width,canvas.height);`

```
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var mario;
var marioSprite;
var tiles;
var speedX = 1;

//marioSprite Specification
mario = {
    //target picture specification X & Y, Width & Height
    px:276,
    py: 44,
    pwidth: 16,
    pheight: 16,
    //drawing on Canvas specification X & Y, Width & Height
    cx: 16,
    cy: 116,
    cwidth:16,
    cheight:16,
}

//draw Mario in Canvas
function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);
    });
    this.position = function() {
        this.mario.cx += speedX;
    }
    position();
}//drawMarioSprite() end

//drawTiles and tilesLoop
function drawTiles() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        tilesLoop();
    });
}
function tilesLoop(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
            ctx.drawImage(tiles,
                0, 0, 26, 26,
                x*12, y*12, 20, 20);
        }
    }
}//drawTiles() end

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height); //HERE
    drawMarioSprite();
    drawTiles();
    window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
```

```
<canvas id="screen"></canvas>
```

---
Tags: javascript, html5, game-loop, html-canvas
---


# Question
Title: Is there a way to setup a notification from Unreal Engine when it finishes packaging / building my game?
In Unity I was able to use a post build script to send myself an email when Unity finishes building a game. Is there a way to make a script run when Unreal Engine is done packaging a game?

Or any other way to set up a notification sound or visual prompt in my Windows PC to alert me when it finishes packaging?

# Answer
> 1 votes
Yes, this is possible. I recommend using Jenkins CI for automating Unreal Engine's RunUAT.bat.

There are great references here, if you are unfamiliar: https://github.com/skymapgames/jenkins-ue4/tree/master/build-scripts

Jenkins CI has an email extension (https://plugins.jenkins.io/email-ext/) that will email you upon the completion of a pipeline. You can set up your build scripts to automate RunUAT.bat, build inside Jenkins CI, then use that plugin to email you upon completion. Hope this helps!

---
Tags: unreal-4, unreal, scripting
---


title: Applying animations to 2x2 Rubik's cube

text:
# Question
Title: Applying animations to 2x2 Rubik's cube
I built a 2x2 Rubik's cube with javafx and my next goal is to apply animations to it. For that I need to keep track of the individual cubes. But I could not find one. Then I simply set up four `Group` objects namely `front`,`back`,`right` and `left` and assigned the respective cubes to them. I added buttons for the rotations. Here's my code,

```
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.scene.AmbientLight;
import javafx.scene.DepthTest;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.SubScene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author deb-l-ana
 */
public class NewFXMain extends Application {

    @Override
    public void start(Stage primaryStage) {
        System.out.println(Platform.isSupported(ConditionalFeature.SCENE3D));
        primaryStage.setTitle("Coordinate axex");
        Group root=new Group();
        SubScene scene=new SubScene(root,300,300,true,SceneAntialiasing.BALANCED);
        PerspectiveCamera camera = new PerspectiveCamera(true);
        root.setDepthTest(DepthTest.ENABLE);
        camera.setNearClip(0.1);
camera.setFarClip(10000.0);

        camera.getTransforms().addAll (new Translate(0, 0, -1000));

        Cube c1 = new Cube(50,Color.BLACK.brighter(),Color.BLACK.brighter(),Color.ORANGE.brighter(),Color.BLACK.brighter(),Color.BLUE.brighter(),Color.YELLOW.brighter());
         c1.setTranslateX(105);

        Cube c2 = new Cube(50,Color.BLACK.brighter(),Color.BLACK.brighter(),Color.BLACK.brighter(),Color.GREEN.brighter(),Color.BLUE.brighter(),Color.YELLOW.brighter());
        c2.setTranslateX(50);

        Cube c3 = new Cube(50,Color.WHITE.darker(),Color.BLACK.brighter(),Color.BLACK.brighter(),Color.GREEN.brighter(),Color.BLUE.brighter(),Color.BLACK.brighter());
        c3.setTranslateX(50);
        c3.setTranslateZ(55);

        Cube c4 = new Cube(50,Color.WHITE.darker(),Color.BLACK.brighter(),Color.ORANGE.brighter(),Color.BLACK.brighter(),Color.BLUE.brighter(),Color.BLACK.brighter());
        c4.setTranslateX(105);
        c4.setTranslateZ(55);

        Cube c5 = new Cube(50,Color.BLACK.brighter(),Color.RED.brighter(),Color.ORANGE.brighter(),Color.BLACK.brighter(),Color.BLACK.brighter(),Color.YELLOW.brighter());
         c5.setTranslateX(105);
         c5.setTranslateY(55);

        Cube c6 = new Cube(50,Color.BLACK.brighter(),Color.RED.brighter(),Color.BLACK.brighter(),Color.GREEN.brighter(),Color.BLACK.brighter(),Color.YELLOW.brighter());
        c6.setTranslateX(50);
        c6.setTranslateY(55);

        Cube c7 = new Cube(50,Color.WHITE.darker(),Color.RED.brighter(),Color.BLACK.brighter(),Color.GREEN.brighter(),Color.BLACK.brighter(),Color.BLACK.brighter());
        c7.setTranslateX(50);
        c7.setTranslateZ(55);
        c7.setTranslateY(55);

        Cube c8 = new Cube(50,Color.WHITE.darker(),Color.RED.brighter(),Color.ORANGE.brighter(),Color.BLACK.brighter(),Color.BLACK.brighter(),Color.BLACK.brighter());
        c8.setTranslateX(105);
        c8.setTranslateZ(55);
        c8.setTranslateY(55);
        Rotate rotateX = new Rotate(30, 0, 0, 0, Rotate.X_AXIS);
        Rotate rotateY = new Rotate(20, 0, 0, 0, Rotate.Y_AXIS);
        scene.setOnMouseDragged(me -> {
            mousePosX = me.getSceneX();
            mousePosY = me.getSceneY();
            rotateX.setAngle(rotateX.getAngle()-(mousePosY - mouseOldY));
            rotateY.setAngle(rotateY.getAngle()+(mousePosX - mouseOldX));
            mouseOldX = mousePosX;
            mouseOldY = mousePosY;
        });

        root.getTransforms().addAll(rotateX, rotateY);
        Group k=new Group(c1,c2,c3,c4,c5,c6,c7,c8);
        k.setRotationAxis(Rotate.Y_AXIS);
        k.setRotate(180);
        root.getChildren().addAll(k,new AmbientLight());
        scene.setCamera(camera);
        \\Animation section
        Button F = new Button("F");
        Button F_ = new Button("F_");
        Button B = new Button("B");
        Button B_ = new Button("B_");
        Button L = new Button("L");
        Button L_ = new Button("L_");
        Button R = new Button("R");
        Button R_ = new Button("R_");
        Button X = new Button("X");
        Button X_ = new Button("X_");
        Button Y = new Button("Y");
        Button Y_ = new Button("Y_");
        Button Z = new Button("Z");
        Button Z_ = new Button("Z_");

        Group front=new Group(c1,c2,c5,c6);
        Group back=new Group(c3,c4,c7,c8);
        Group right=new Group(c1,c4,c5,c8);
        Group left=new Group(c2,c3,c6,c7);

        PerspectiveCamera camera2 = new PerspectiveCamera(true);

        F.setOnAction(e -> {
            front.setRotationAxis(Rotate.Z_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(100), front);
            rt.setByAngle(90);
            rt.play();
                });

        F_.setOnAction(e -> {
            front.setRotationAxis(Rotate.Z_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(100), front);
            rt.setByAngle(-90);
            rt.play();
                });
        //moves- normal letters represent clockwise and underscored represents anticlockwise rotations.

        F.setTranslateY(200);
        F_.setTranslateY(170);
        B.setTranslateY(140);
        B_.setTranslateY(110);
        L.setTranslateY(80);
        L_.setTranslateY(50);
        R.setTranslateY(20);
        R_.setTranslateY(-10);
        //The rest are not being added right now
        /*X.setTranslateY(-40);
        X_.setTranslateY(-70);
        Y.setTranslateY(-100);
        Y_.setTranslateY(-130);
        Z.setTranslateY(-160);
        Z_.setTranslateY(-190);*/

        Group r=new Group(F,F_,B,B_,L,L_,R,R_);
        Scene s=new Scene(r,600,600,true);
        camera2.setNearClip(0.1);
        camera2.setFarClip(10000.0);
        root.getChildren().addAll(front);

        B.setOnAction(e -> {
            back.setRotationAxis(Rotate.Z_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(100), back);
            rt.setByAngle(90);
            rt.play();
                });

        B_.setOnAction(e -> {
            back.setRotationAxis(Rotate.Z_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(100), back);
            System.out.println("hhhh");
            rt.setByAngle(-90);
            rt.play();
                });
        root.getChildren().addAll(back);

        L.setOnAction(e -> {
            left.setRotationAxis(Rotate.X_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(1000), left);
            rt.setByAngle(90);
            rt.play();
                });

        L_.setOnAction(e -> {
            left.setRotationAxis(Rotate.X_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(1000), left);
            rt.setByAngle(-90);
            rt.play();
                });
        root.getChildren().addAll(left);

        R.setOnAction(e -> {
            right.setRotationAxis(Rotate.X_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(1000), right);
            rt.setByAngle(90);
            rt.play();
                });

        R_.setOnAction(e -> {
            right.setRotationAxis(Rotate.X_AXIS);
            RotateTransition rt = new RotateTransition(Duration.millis(1000), right);
            rt.setByAngle(-90);
            rt.play();
                });
        root.getChildren().addAll(right);
        camera2.getTransforms().addAll (new Translate(0, 0, -1000));
        s.setCamera(camera2);
        r.getChildren().addAll(scene);
        primaryStage.setScene(s);
        primaryStage.show();

    }
    double mousePosX,mousePosY,mouseOldX,mouseOldY;
     /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    public class Cube extends Group {
        final Rotate rx = new Rotate(0,Rotate.X_AXIS);
        final Rotate ry = new Rotate(0,Rotate.Y_AXIS);
        final Rotate rz = new Rotate(0,Rotate.Z_AXIS);
        public Cube(double size, Color back,Color bottom,Color left,Color right,Color top,Color front) {

                getTransforms().addAll(rz, ry, rx);

                //FIRST RECTANGLE BACK FACE
                TriangleMesh re1 = new TriangleMesh();
                re1.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re1.getTexCoords().addAll(
                        0,0
                );
                re1.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );

                MeshView rectangle1 = new MeshView(re1);
                rectangle1.setCullFace(CullFace.NONE);
                PhongMaterial mat = new PhongMaterial(back);

                rectangle1.setMaterial(mat);
                rectangle1.setTranslateX(-0.5*size);
                rectangle1.setTranslateY(-0.5*size);
                rectangle1.setTranslateZ(0.5*size);

                //SECOND RECTANGLE
                TriangleMesh re2 = new TriangleMesh();
                re2.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re2.getTexCoords().addAll(0,0,
                        0,0
                        );
                re2.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );
                MeshView rectangle2 = new MeshView(re2);
                PhongMaterial mat2=new PhongMaterial(bottom);
                rectangle2.setMaterial(mat2);
                rectangle2.setCullFace(CullFace.NONE);
                rectangle2.setTranslateX(-0.5*size);
                rectangle2.setTranslateY(0);
                rectangle2.setRotationAxis(Rotate.X_AXIS);
                rectangle2.setRotate(90);

                //CREATE THIRD RECTANGLE
                TriangleMesh re3 = new TriangleMesh();
                re3.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re3.getTexCoords().addAll(0,0,
                        0,0
                        );
                re3.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );
                MeshView rectangle3 = new MeshView(re3);
                PhongMaterial mat3=new PhongMaterial(right);
                rectangle3.setMaterial(mat3);
                rectangle3.setCullFace(CullFace.NONE);
                rectangle3.setTranslateX(-1*size);
                rectangle3.setTranslateY(-0.5*size);
                rectangle3.setRotationAxis(Rotate.Y_AXIS);
                rectangle3.setRotate(90);

                //CREATE FOURTH RECTANGLE
                TriangleMesh re4 = new TriangleMesh();
                re4.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re4.getTexCoords().addAll(0,0,
                        0,0
                        );
                re4.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );
                MeshView rectangle4 = new MeshView(re4);
                PhongMaterial mat4=new PhongMaterial(left);
                rectangle4.setMaterial(mat4);
                rectangle4.setCullFace(CullFace.NONE);
                rectangle4.setTranslateX(0);
                rectangle4.setTranslateY(-0.5*size);
                rectangle4.setRotationAxis(Rotate.Y_AXIS);
                rectangle4.setRotate(90);

                //CREATE FIFTH RECTANGLE
                TriangleMesh re5 = new TriangleMesh();
                re5.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re5.getTexCoords().addAll(0,0,
                        0,0
                        );
                re5.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );
                MeshView rectangle5 = new MeshView(re5);
                PhongMaterial mat5=new PhongMaterial(top);
                rectangle5.setMaterial(mat5);
                rectangle5.setCullFace(CullFace.NONE);
                rectangle5.setTranslateX(-0.5*size);
                rectangle5.setTranslateY(-1*size);
                rectangle5.setRotationAxis(Rotate.X_AXIS);
                rectangle5.setRotate(90);

                //CREATE SIXTH RECTANGLE
                TriangleMesh re6 = new TriangleMesh();
                re6.getPoints().addAll(
                        0,0,0,
                        0,(float)size,0,
                        (float)size,(float)size,0,
                        (float)size,0,0
                );
                re6.getTexCoords().addAll(0,0,
                        0,0
                        );
                re6.getFaces().addAll(
                        0,0, 1,0, 3,0,
                        1,0, 2,0, 3,0
                );
                MeshView rectangle6 = new MeshView(re6);
                PhongMaterial mat6=new PhongMaterial(front);
                rectangle6.setMaterial(mat6);
                rectangle6.setCullFace(CullFace.NONE);
                rectangle6.setTranslateX(-0.5*size);
                rectangle6.setTranslateY(-0.5*size);
                rectangle6.setTranslateZ(-0.5*size);

                getChildren().addAll(
                        rectangle1,
                        rectangle2,
                        rectangle3,
                        rectangle4,
                        rectangle5,
                        rectangle6
                );

        }
    }
}

```

As I executed my program, the moves F,F\_, B, B\_ didn't work. Can anyone please suggest me what algorithm I should follow to make a proper animation of the cube and also why the mentioned moves were not working ?

# Answer
I just realize this. You can not repeat elements in a group. Once you put them in a group they stop belonging to the other group. In this case because left and right are defined last they work. If you change the code to

```
    Group right=new Group(c1,c4,c5,c8);
    Group left=new Group(c2,c3,c6,c7);
    Group front=new Group(c1,c2,c5,c6);
    Group back=new Group(c3,c4,c7,c8);

```

The opposite is true and now B and F buttons work but not L and R.

Perhaps someone can point how to achieve this.
> 1 votes

# Answer
A possible solution could be to create a class that simply contains four cubes.

```
public class CubeGroup {

    private ArrayList<Cube> cubes = new ArrayList<Cube>(4);

    public CubeGroup(Cube c1, Cube c2, Cube c3, Cube c4) {
        this.cubes.addAll(c1, c2, c3, c4);
    }

    ...

}

```

Being my first answer here, I am unsure if this can properly answer your question, but I believe this is a good way to solve the issue.
> 0 votes

---
Tags: java, animation, javafx
---


# Question
Title: How are methods like Awake, Start, and Update called in Unity?
I'm developing with Unity 5 and I know that there are some methods you can use like in the code below:

```
public class MyGameElement : MonoBehaviour
{
    private void Awake() { }
    private void Start() { }
    private void Update() { }
    private void FixedUpdate() { }
    // and more
}

```

I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references.

The second 'strange' thing for me is that the methods aren't overwritten.

So my question is now is there anything that Unity has implemented into the `MonoBehaviour` class that the methods can call?

# Answer
> 6 votes
The methods you name are called with Unity's Messaging System. The MonoBehaviour responds to messages when recieved. Messages are sent by Unity when those events are triggered. The methods you implement, can be private, because technically, it's the Component invoking its own methods, in response to receiving a message.

I don't know if Unity implements a different internal message system from the one exposed in the API, but I doubt it.

In the docs, notice all those 'magic methods' are actually in the 'Messages' section of the MonoBehavior.

There is a nice description on Stackoverflow and more info is available in the Component.SendMessage doc.

# Answer
> 2 votes
This would be relatively trivial to perform from the mono runtime. The unity scripts are bundled into the Assembly-UnityScript.dll .NET assembly. When this is loaded by the mono runtime, options are available.

```
mono_set_dirs( "/Library/Frameworks/Mono.framework/Home/lib", "/Library/Frameworks/Mono.framework/Home/etc" );
mono_config_parse( nullptr );
const char* managedbinarypath = "C:/Assembly-UnityScript.dll";
MonoDomain* domain = mono_jit_init(managedbinarypath)
MonoAssembly* assembly = mono_domain_assembly_open (domain, managedbinarypath);
MonoImage* image = mono_assembly_get_image (assembly);

//you could add some internal call bindings and field bindings
mono_add_internal_call( "Namespace.Class::Method", reinterpret_cast<void*>(InternalFunction));
class = mono_class_from_name( image, "Namespace", "Class" );
native_handle_field = mono_class_get_field_from_name(class, "FieldInClass" );

//you could invoke the Main method of the Main class if it exists
MonoClass* main_class = mono_class_from_name( image, "Namespace", "MainClass" );
const bool include_namespace = true;
MonoMethodDesc* entry_point_method_desc = mono_method_desc_new("Namespace.MainClass:EntryPointMethod()", include_namespace );
MonoMethod* entry_point_method = mono_method_desc_search_in_class( entry_point_method_desc, main_class );
mono_method_desc_free( entry_point_method_desc );
mono_runtime_invoke( entry_point_method, nullptr, nullptr, nullptr );

//alternatively, you could invoke an Update method
void* iter = NULL;
MonoClass* class;
MonoMethodDesc* desc;
MonoMethod* method;
while(class = mono_image_get_classes(image, &iter))
{
    //if the class has an Update method
    desc =  mono_method_desc_new("*:Update()", false);
    method = mono_method_desc_search_in_class(desc, class);
    if (method != NULL){
        //store MonoMethod* method in array somewhere

    }
    mono_method_desc_free(desc);
}

//traverse array of update methods sometime and invoke them
mono_runtime_invoke(array[0], nullptr, nullptr, nullptr);

//finish
mono_jit_cleanup( domain );

```

Where `mono_image_get_classes` is defined:

MonoClass*
mono_image_get_classes (MonoImage *image, gpointer *iter)
{
    int num_types;
    int *index;

    if (!iter)
        return NULL;

    index = (int *) iter;

    /* skip the <Module> */
    if (!*index)
        *index = 1;

    num_types = mono_image_get_table_rows (image, MONO_TABLE_TYPEDEF);

    if (*index < num_types) {
        (*index)++;
        return mono_class_get (image, *index | MONO_TOKEN_TYPE_DEF);
    } else {
        *index = 0;
        return NULL;
    }
}
```

# Answer
> 1 votes
They are internal event handler methods. The engine probably calls them via `Invoke("Method")` though I am not sure on the internal implementation.

The important thing is that they are named exactly and that the script inherits MonoBehaviour.

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


# Question
Title: How to reset a gameobject to it's prefab condition?
I have a `GameObject` with a ragdoll in it. Gameobject comes from a prefab which is pooled. So whenever the enemy is killed it's disabled then enabled when spawn.

Problem is that the ragdoll settings and it's condition cannot be reset by enabling. i.e. enemy stays dead even though respawned.
Is there a way to easily reset a GameObject to prefab state?

Solution online is to keep all the transforms and re-apply them by code. Is this the only way?

# Answer
In general, its how pooling works. But there are some triks. For example, you can create a simple script, which will cahe its transform state on Awake(), and then restore every time when OnEnable called. This can be a bit heavy to have additional scripts on every bone. Som better solution is to have another, only one, which will iterate all root transform\`s childs.

Like this:

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

public class RestoreTransforms : MonoBehaviour
{
    private List<Transform> _transforms = new List<Transform>();
    private List<Vector3> _positions = new List<Vector3>();
    private List<Quaternion> _rotations = new List<Quaternion>();

    private void Awake()
    {
        var allTransforms = GetComponentsInChildren<Transform>();
        foreach(var t in allTransforms)
        {
            _transforms.Add(t);
            _positions.Add(t.position);
            _rotations.Add(t.localRotation);
        }
    }

    private void OnEnable()
    {
        for (int i = 0; i < _transforms.Count; ++i)
        {
            _transforms[i].position = _positions[i];
            _transforms[i].localRotation = _rotations[i];
        }
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: I installed Linux Build Support, but I need an archive to build, how can I get this?
I\`m building a game for Mac, Windows and Linux, I builded the Windows and Mac game, but in Linux, says that need a x86\_64 archive, like the image shows, what do I do?

# Answer
This is Unity asking where you want it to put the built application and what to name it.
> 1 votes

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


# Question
Title: How to pass an argument with ref keyword to a local funtion/ how to work around it?
Unity 2019.3

I am writing a few extension methods to make my life a little bit easier, but this one is bogging me down.

I am loading stuff with Unity's Addressable system, and I would like use it by extension methods.

I am passing in my variables (reference type & value type, doesn't matter) to my extension methods, hoping to set them and and hide some complexity and source of bugs, and errors. It seems to me they are passed by value, because when I am trying to use them outside the extension methods, they are not set, null, etc. Not working.

There is a callback called Completed, and I am subscribing with a lambda expression...

I tried with the ref keyword, but obviously the compiler is yelling, that she doesn't want to pass my ref, out whatever parameters to local functions... :(

I tried it out with no local functions, and it did not work without the ref keywork, but it did with it!

You get the idea! Please see my code below!

This is the one that I can't get to work...

```
///Trying to set the generic variable data from the Addressable assetref
public static void TryLoadData<T>(this AssetReference assetref, T data)
    {
        var handle = assetref.LoadAssetAsync<T>();

        handle.Completed += loadedresult =>
            {
                T result = loadedresult.Result;
                if (result == null) return;
                data = result;
            };
    }

```

This one does, but only with ref...

```
///Setting the generic data parameter to the parameter g.
public static void SwapTest<T>(this T g,ref T data) where T : class=> data = g;

```

I am not sure if there is a workaround, I thought of pointers, or global variables, but not sure which one is the right way to go.

Thanks

# Answer
> 1 votes
The problem is that as-written, your `T data` reference could conceivably be a local struct allocated on the stack, that's vanished from existence by the time `handle.Completed` is called. Or a reference type variable that belongs to such an ephemeral struct. That could leave us with effectively a dangling pointer when the callback is ready to call, so the C# language specification makes this illegal.

You'll need to give your function something that can guarantee some independent lifecycle management, so we have a strong guarantee that the variable we're trying to set still exists as long as our callback holds a reference to it.

Here's one way you can tackle that:

```
public enum LoadStatus {
    Loading,
    Invalid,
    DataReady
}

public class Loadable<T> {

    public T data { get; private set; }
    public LoadingStatus status { get; private set; }

    public void OnComplete(AsyncOperationHandle<T> handle) {
        T result = handle.Result;
        if(result == Default(T)) {
            status = LoadingStatus.Invalid;
            return;
        }
        data = result;
        status = LoadingStatus.DataReady;
    }
}

```

Then you can either pass your `Loadable<T>` by reference (which happens without the `ref` keyword since it's a class type), or return a new `Loadable<T>` from your extension method.

```
public static void TryLoadData<T>(this AssetReference assetref, Loadable<T> data)
{
    var handle = assetref.LoadAssetAsync<T>();
    handle.Completed += data.OnComplete;
}

public static Loadable<T> TryLoadData<T>(this AssetReference assetref)
{
    var handle = assetref.LoadAssetAsync<T>();

    var data = new Loadable<T>();
    handle.Completed += data.OnComplete;
    return data;
}

```

Heck, you could even skip the extension method and build this functionality right into the Loadable class:

```
[System.Serializable]
public class Loadable<T> {
    [SerializeField, AssetReferenceTypeRestriction(typeof(T))]
    AssetReference _reference;

    [SerializeField] // Allow peeking at the data in the Inspector.
    T _data;
    public T data { get { return _data; } private set { _data = value; } }
    public LoadingStatus status { get; private set; }

    public void TryLoadAsync() {
        var handle = _reference.LoadAssetAsync<T>();
        handle.Completed += OnComplete;
    }

    public void OnComplete(AsyncOperationHandle<T> handle) {
        T result = handle.Result;
        if(result == Default(T)) {
            status = LoadingStatus.Invalid;
            return;
        }
        data = result;
        status = LoadingStatus.DataReady;
    }
}

```

Now you can write something like....

```
// This line makes the generic concrete so it works in the Inspector,
// though apparently it won't be needed anymore in Unity 2020+ :D
public class LoadableTexture2D : Loadable<Texture2D> {}

public LoadableTexture2D myTexture;

```

And get an inspector that allows you to assign the asset reference and peek at the loaded data in one neat bundle. You could even add in a UnityEvent to invoke when the asset finishes loading, if that's useful for your case.

You can kick off the load with:

```
myTexture.TryLoadAsync();

```

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


title: My HTML Canvas went blank

text:
# Question
Title: My HTML Canvas went blank
I tried to draw Mario Sprites in my HTML Canvas, but it always went blank. Anybody knows why?

```
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var mario;
var marioSprite;
var tiles;
var speedX = 1;

//marioSprite Specification
mario = {
    //target picture specification X & Y, Width & Height
    px:276,
    py: 44,
    pwidth: 16,
    pheight: 16,
    //drawing on Canvas specification X & Y, Width & Height
    cx: 16,
    cy: 116,
    cwidth:16,
    cheight:16,
}

//draw Mario in Canvas
function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);
    });
    this.position = function() {
        this.mario.cx += speedX;
    }
    position();
}//drawMarioSprite() end

//drawTiles and tilesLoop
function drawTiles() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/MASTONO ALI/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        tilesLoop();
    });
}
function tilesLoop(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
            ctx.drawImage(tiles,
                0, 0, 26, 26,
                x*12, y*12, 20, 20);
        }
    }
}//drawTiles() end

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawMarioSprite();
    drawTiles();
    window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);

```

# Answer
You probably don't want to call the drawing code inside the `'load'` event handler, since for that to happen more than once, you would need to load the image multiple times which you also don't want to do. See the docs

You should load the images once at startup and then draw them from the pre-loaded data.

In this case, since you do the drawing code repeatedly with `requestAnimationFrame`, once the image actually loads it will be drawn correctly, if you just remove the `load` eventlisteners and just directly call the drawing code.

That is, change

```
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);
    });

```

to

```
    ctx.drawImage(marioSprite,
        mario.px, mario.py, mario.pwidth, mario.pheight,
        mario.cx, mario.cy, mario.cwidth, mario.cheight);

```

and

```
    tiles.addEventListener('load', e => {
        tilesLoop();
    });

```

to

```
    tilesLoop();

```
> 1 votes

---
Tags: javascript, html5, game-loop, html-canvas
---


# Question
Title: Getting array of points shaping curve from 2 vector3 points
What I want is to get path for DoTween method DoPath(), which as a parameter expects array of vectors shaping the direction of the path. I googled some stuff and found out nothing. Just think bezier curve is good idea but i dont even know how it works. Here is an ilustration of my problem

The movement must be curved, don't need linear one. Thanks in advance

# Answer
So, I have found this article about bezier curves, which helped me a lot. This is code I wrote, hope it'll useful for someone

```
public static Vector3[] GetQuadraticBezierPoints(Vector3 startpoint, Vector3 endPoint, float curveHeigh) {
    Vector3 heighPoint = startpoint + (endPoint - startpoint) / 2 + Vector3.up * curveHeigh;

    Vector3[] res = new Vector3[100];
    int maxT = 1;
    int index = 0;

    for (float t = 0; t <= maxT; t += 0.01f) {
        Vector3 newPoint = (Mathf.Pow(1 - t, 2) * startpoint) + (2 * (1 - t) * t * heighPoint) + (t * t * endPoint);
        try {
            res[index++] = newPoint;
        }
        catch {
            break;
        }
    }
    return res;
}

```

This script creates 100 points, shaping curve, based on curveHeigh value, which also helps to create heigPoint variable, which is a 'control point'
> 0 votes

---
Tags: unity, c#, curves, tweening
---


# Question
Title: Is Updating Sprite/Entity Movement Using Framerate Necessary?
Apologies if this is a dumb question I'm still new to this, but I'm trying to understand if calculations of sprite movements/hitboxes/etc. is necessary or is generally better than just using fixed values to calculate movement or events (i.e movement += velocity/framerate vs. movement += velocity/constant).

The main reason I ask is that while following tutorials for basic movements they use the frame rate to determine how to move the sprites, but I haven't seen a full explanation as to why things are done that way. While I was using these tutorials, things seemed to work well, but after I moved past them I've run into odd issues. I'm not sure if that was just because the games in the tutorials were very simple, like pong and breakout, and I just didn't notice these problems.

For example, I made a very simple demo where I take a sprite and have it bounce off the edges of the screen. When it reaches the edge the velocity reverses and it goes in the opposite direction. While the numbers show as correctly calculated, visually it's wrong, either rebounding early or beyond the edges of the screen. However, when I replace frame rate with a constant number it works perfectly. Even when I replace the frame rate with a random value of particular range (say 45-60) it works well. It seems to me on the occasion that the frame rate dips below 30, it throws off everything and doesn't recover.

I've heard about limiting frame rate and that makes sense in a capping the top way, but is limiting it below also something that is done? If so, it doesn't seem too different from just putting in a constant and I wonder what benefits using frame rate even has at that point.

tl;dr: I guess what I'm asking is **what are the pros and cons of using frame rate to determine how things move/interact vs using constant values and will it create problems down the line if I try to forgo frame rate completely?**

# Answer
No\*

* To a first approximation, *nothing* in games is "necessary". If your code compiles, you can ship it. Whether or not anyone thinks the game is any *good* is another question.

---

So, what is scaling by framerate or delta time *good* for?

It's good if your framerate can change. Obviously, if your framerate is constant, then replacing any framerate scaling with a suitably-chosen constant is equivalent. But there are multiple kinds of framerate change we might care about:

* **Runtime changes**: many games render as fast as the hardware can support. That means your framerate can vary between devices, from minimum-spec up to cutting-edge hardware. It also means your framerate can fluctuate during play, if your game is currently processing a heavier-than-normal or lighter-than-normal scene, or if a background process temporarily hogs some of the device's resources.

In these situations, if you've made all your movement a constant each frame, then in scenarios where your framerate is super high your gameplay runs faster than intended. (Ever play an old DOS game on a modern PC, and everything's just a blur?) And in scenarios where your framerate drops, your gameplay becomes more sluggish.

This is bad for the player experience, making the game feel inconsistent, and it can even introduce unfairness in competitive games, by giving some players more reaction time or faster responsiveness than others.
* **Development changes**: your framerate in the shipped game might well be a constant, but will it be the *same* constant as at the start of your project?

Say you were initially aiming for 60 fps, but it turns out by the time you implement all of your features, you can only support 30 fps on your target hardware, so you have to drop your framerate. If all your gameplay simulation uses hard-coded constants, now you have to go re-tune *all* of those magic numbers to try to get equivalent behaviour at 30 fps as you had at 60. The same goes if you made your game for 60 FPS, and now want to make a VR port at 90 or 120 fps to keep up with player head movement and minimize nausea.

If you'd coded all your features to scale correctly with the framerate / delta time, even if that value was a constant, now you have just one master constant to change in one place, and most of your tuning *should* adapt correctly to the new framerate - if you did your math right. Obviously you still need to test and spot-fix, but this can reduce weeks of refactoring to maybe just hours, depending on your scope.

I'd also argue that scaling by framerate / delta time has another useful outcome: it keeps your tuning parameters in intuitive, meaningful units.

```
position.x += velocity.x * deltaTime;

```

If `position` is in tile units and `deltaTime` is in seconds, then `velocity` represents tiles per second. This is a nice clear number for a designer to reason about. If I want the player to move 3 tiles in a half-second dash, that's a velocity of 6.

Without the `deltaTime`, then I have to mentally figure-in the framerate whenever I'm choosing a tuning value like this. For the tile example, well, if we're running at 60 fps, that 3-tile half-second dash is 0.1 tiles per frame. It takes a bit more mental math and imagination to picture the effect of that number.

Now, there are hazards to using a variable timestep in your game simulation. This introduces some non-determinism into your code. Two runs of your game with identical input might not produce exactly identical results, because of small variances in timing leading to differences in rounding, etc.

This can be a point of frustration during development, making it difficult to replicate, isolate, and fix bugs that rely on very precise timing. And it can lead to inconsistencies in play or exploits (eg. deliberately dropping the framerate until you can clip through walls because the timestep has gotten so large that a single movement step teleports you all the way from one side to the other, without ever colliding with the wall in-between)

For this reason, it's often recommended that games use a "fixed timestep" for gameplay simulation:

* Each simulation step always uses the same, constant timestep (but you still scale by this constant delta time, so that your code and tuning all adapt correctly if you ever change the constant)
* In order to keep up to the present moment, the game runs the simulation step as many times as necessary to account for the total time elapsed before this frame
* In order to present a smooth result, any non-simulation-critical effects (eg. UI animations) are scaled to the actual, variable time delta of the current frame, and simulation outputs are interpolated or extrapolated to the appropriate intermediate state.

This gets us the consistency benefits of a constant framerate, with the flexibility, responsiveness, and scaling benefits of a variable framerate, letting our games run predictably on a range of devices under a range of conditions. I present a more in-depth motivation for this convention in this answer.

> I've heard about limiting frame rate and that makes sense in a capping the top way, but is limiting it below also something that is done?

Yes. Fixed timestep game loops typically have a maximum number of times they'll attempt to step the simulation in a single frame. So if frames run longer than that, the simulation is allowed to fall behind real-time, so the gameplay can slow down - hopefully giving the device enough headroom to finish whatever heavy processing is hogging the resources, so the game can recover back to its target framerate later.

This avoids a "death spiral" where frames get longer and longer because we keep running more and more simulation steps to try to catch up to real-time on hardware that just can't go that fast.

But it still has the advantage that on more capable hardware, we can run the rendering loop as fast as we want above this minimum cut-off. 500 fps? Sure, if your video card can take it and your monitor can display it, go for it!

> For example, I made a very simple demo where I take a sprite and have it bounce off the edges of the screen. When it reaches the edge the velocity reverses and it goes in the opposite direction. While the numbers show as correctly calculated, visually it's wrong, either rebounding early or beyond the edges of the screen.

It sounds like your code has a bug. Post a question about it, demonstrating a Minimal Complete Verifiable Example, and we can help you debug it to get correct behaviour at any framerate.
> 3 votes

---
Tags: movement, frame-rate
---