# Question
Title: How to instantiate seamless scrolling tiles
I'm trying to create in Unity an "Endless Runner" game, where the player remains stationary on the 0 of the axes while the tiles underneath him scroll with a fixed speed on the Z-Axis.
The script attached spawns 5 tiles at the start while already scrolling at the speed set in the `GameManager` and then keeps on spawning tiles based on a timer.

The issue I'm facing is the following:

The tiles that are spawned with the timer are too much distant from the starting set of tiles.

How can I calculate the correct distance between the set of the already scrolling tiles and those the script start to spawn after 5 seconds in order to have seamless scrolling?

I'm attaching the script with what I've written so far in the hope that someone knows how to proceed, or perhaps knows a different method. Thanks!

```
public class TileManager : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private GameObject[] tilesArray;
    [SerializeField] private int tilesToSpawn = 5;
    [SerializeField] private float zPosSpawn = 0f;
    [SerializeField] private float tileLength = 20f;

    public List<GameObject> tilesList;
    private float spawnRate;
    private float timeSinceLastSpawned;

    void Start()
    {
        //scrollingSpeed is -5
        spawnRate = GameManager.Instance.scrollingObjectsSpeed * -1;
        StartSpawnLogic();
    }

    void Update()
    {
        timeSinceLastSpawned += Time.deltaTime;
        SpawnTimer();
        DestroyAfterSpawn();

    }

    private void StartSpawnLogic()
        {
            for (int i = 0; i < tilesToSpawn; i++)
            {
                if (i == 0)
                {
                    SpawnTiles(0);
                }
                else
                {
                    SpawnTiles(Random.Range(0, tilesArray.Length));
                }
            }
        }

    //SPAWN FUNCTION
    private void SpawnTiles(int tileIndex)
    {
        //On Instantiation a list is filled to later dispose of the tiles after they reached a certain point
        tilesList.Add((GameObject)Instantiate(tilesArray[tileIndex], transform.forward * zPosSpawn, Quaternion.identity));
        zPosSpawn += tileLength;
    }

    //TIMER
    private void SpawnTimer()
    {
        if (timeSinceLastSpawned >= spawnRate)
        {
            timeSinceLastSpawned = 0;
            SpawnTiles(Random.Range(1, tilesArray.Length));
        }
    }

    void RemoveObjFromList(GameObject tile)
    {
        Destroy(tile);
        tilesList.Remove(tile);
    }

    private void DestroyAfterSpawn()
    {
        for (int i = 0; i < tilesList.Count; i++)
        {
            if (tilesList[i].transform.position.z <= -20f)
            {
                RemoveObjFromList(tilesList[i]);
            }
        }
    }
}

```

# Answer
> 0 votes
There are a few ways to do this, here is one way. All you need to do is move the transform.position of gameobject attached to the background sprite.

at a set speed at Time.DeldaTime, something like this (in Update()):

```
transform.position.x -= speed * Time.DeltaTime

```

Then add an if loop to catch when the bounds of the background reach a point. This is an example, basically - when the background reaches said point - change the transform.position to equal a fixed position on the other side of the screen.

```
if(tranfom.position <= -50x){
    transform.position = new Vector2(50, 0, 0,)
}

```

---
Tags: unity, c#, 3d, arcade
---


# Question
Title: Why does my collider behave strangely after a coroutine
So I'm trying to create a simple script that is going to handle the logic for cutting down a tree I'm experiencing some strange behaviour with my script.

I have a private field which holds the "HP" for the tree which starts at 100, and when I hit the tree it goes down by 25 every time, so I need to hit it four times in order for me to cut it down. Once the tree reaches `<= 0` in terms of HP it should play an animation which simulates the tree being cut down, wait a couple of seconds and then play another animation of it appearing again. Most of this works fine, it's not until after the animation, where I start my CoRoutine to wait for a couple of seconds it starts messing up.

**ISSUE**

The first time I cut it down, it works fine.. However.. After it respawns I need to hit it like 4-5 times for it to go down to 50 health and then it works like normal. So I hit it once, it gets to 75, I hit it twice, still at 75, 3 times.. still at 75.. And eventually, it starts going to to 50, 25, 0 etc.. This only happens after I cut it down the first time, and the first time it works fine.

Here is my Tree script `NormalTree.cs`

```
public class NormalTree : MonoBehaviour
{
    public static NormalTree instance;
    private int health = 100;

    public Animator animator;
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        animator = GetComponent<Animator>();
    }

    private void Update()
    {
        if (health <= 0)
        {
            KillTree();

        }
    }

    private void KillTree()
    {
        StartCoroutine(TreeSleep());
    }

    IEnumerator TreeSleep()
    {
        animator.SetBool("treedead", true);
        gameObject.tag = "DeadTree";

        yield return new WaitForSeconds(3f);

        animator.SetBool("treedead", false);
        gameObject.tag = "Tree";
        health = 100;
    }

    public Item DamageTree(int damage)
    {
        health -= damage;
        Debug.Log($"Tree health {health}");
        if (health <= 0)
        {
            return new Item { Amount = 1, ItemRarity = Item.ItemRarityEnum.Gray, ItemType = Item.ItemTypeEnum.Log };
        }
        else
        {
            return null;
        }
    }
}

```

And in my `PlayerController` I have this, which essentially checks if my hitbox collides with an object that has the tag "Tree"

```
private void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Tree"))
    {
        var wc = Skills.FirstOrDefault(x => x.Name == "Woodcutting");

        var tree = other.GetComponent<NormalTree>().DamageTree(25);

        if (tree != null)
        {
            inventory.AddItem(tree);
            wc.AddExperience(25);
            Debug.Log(wc.Level);
        }
    }
}

```

# Answer
> 1 votes
You need to right away set health back to 100.

```
private void Update()
    {
        if (health <= 0)
        {
            health = 100;
            KillTree();

        }
    }

```

Your StartCoroutine(TreeSleep()); is being called n times per frame - since health \< = 0 is true the whole time until the end of your Coroutine.

---
Tags: unity, c#, 2d, collider
---


# Question
Title: How can I spawn random objects on a plane area even if the plane position is not 0,0,0 and how to spawn also with random height?
This is the spawn script :

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

/// <summary>
/// An object spawner
/// </summary>
public class SpawnObject : MonoBehaviour
{
    #region Variables
    // needed for spawning
    [SerializeField]
    GameObject spawnObject;

    [SerializeField]
    GameObject plane;

    // spawn control
    const float MinSpawnDelay = 0.1f;
    const float MaxSpawnDelay = 0.5f;
    Timer spawnTimer;

    // spawn location support
    float randomX;
    float randomY;
    float randomZ;

    #endregion

    #region Methods
    /// <summary>
    /// Use this for initialization
    /// </summary>
    void Start()
    {
        plane = GameObject.FindWithTag("Plane");

        // save spawn boundaries for efficiency
        float randomX = Random.Range (plane.transform.position.x - plane.transform.localScale.x / 2, plane.transform.position.x + plane.transform.localScale.x / 2);
        float randomY = Random.Range (plane.transform.position.y - plane.transform.localScale.y / 2, plane.transform.position.y + plane.transform.localScale.y / 2);
        float randomZ = Random.Range (plane.transform.position.y - plane.transform.localScale.z / 2, plane.transform.position.y + plane.transform.localScale.z / 2);

        // create and start timer
        spawnTimer = gameObject.AddComponent<Timer>();
        spawnTimer.Duration = Random.Range(MinSpawnDelay, MaxSpawnDelay);
        spawnTimer.Run();
    }

    /// <summary>
    /// Update is called once per frame
    /// </summary>
    void Update()
    {
        // check for time to spawn a new enemy
        if (spawnTimer.Finished)
        {
            objectSpawn();

            // change spawn timer duration and restart
            spawnTimer.Duration = Random.Range(MinSpawnDelay, MaxSpawnDelay);
            spawnTimer.Run();
        }

    }

    /// <summary>
    /// Spawns an object at a random location on a plane
    /// </summary>
    void objectSpawn()
    {
        // generate random location and create new object
        Vector3 randomPosition = GetARandomPos(plane);

        Instantiate<GameObject>(spawnObject, randomPosition, Quaternion.identity);

    }

    /// <summary>
    /// Return random position on the plane
    /// </summary>
    public Vector3 GetARandomPos(GameObject plane){

    Mesh planeMesh = plane.GetComponent<MeshFilter>().mesh;
    Bounds bounds = planeMesh.bounds;

    float minX = plane.transform.position.x - plane.transform.localScale.x * bounds.size.x * 0.5f;
    float minZ = plane.transform.position.z - plane.transform.localScale.z * bounds.size.z * 0.5f;

    Vector3 newVec = new Vector3(Random.Range (minX, -minX),
                                 plane.transform.position.y,
                                 Random.Range (minZ, -minZ));
    return newVec;
    }

    #endregion
}

```

The object script I called it Objectsp :

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

/// <summary>
/// A enemy
/// </summary>
public class Objectsp : MonoBehaviour
{
    #region Variables
    // death support
    const float EnemyLifespanSeconds = 10;
    Timer deathTimer;

    #endregion

    /// <summary>
    /// Use this for initialization
    /// </summary>
    void Start()
    {
        // create and start timer
        deathTimer = gameObject.AddComponent<Timer>();
        deathTimer.Duration = EnemyLifespanSeconds;
        deathTimer.Run();
    }

    /// <summary>
    /// Update is called once per frame
    /// </summary>
    void Update()
    {
        // destroy enemy if death timer finished
        if(deathTimer){
            if (deathTimer.Finished)
            {
                Destroy(gameObject);
            }
        }

    }

}

```

And the timer script :

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

/// <summary>
/// A timer
/// </summary>
public class Timer : MonoBehaviour
{
    #region Variables

    // timer duration
    float totalSeconds = 0;

    // timer execution
    float elapsedSeconds = 0;
    bool running = false;

    // support for Finished property
    bool started = false;

    #endregion

    #region Properties

    /// <summary>
    /// Sets the duration of the timer
    /// The duration can only be set if the timer isn't currently running
    /// </summary>
    /// <value>duration</value>
    public float Duration
    {
        set
        {
            if (!running)
            {
                totalSeconds = value;
            }
        }
    }

    /// <summary>
    /// Gets whether or not the timer has finished running
    /// This property returns false if the timer has never been started
    /// </summary>
    /// <value>true if finished; otherwise, false.</value>
    public bool Finished
    {
        get { return started && !running; }
    }

    /// <summary>
    /// Gets whether or not the timer is currently running
    /// </summary>
    /// <value>true if running; otherwise, false.</value>
    public bool Running
    {
        get { return running; }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Update is called once per frame
    /// </summary>
    void Update()
    {
        // update timer and check for finished
        if (running)
        {
            elapsedSeconds += Time.deltaTime;
            if (elapsedSeconds >= totalSeconds)
            {
                running = false;
            }
        }
    }

    /// <summary>
    /// Runs the timer
    /// Because a timer of 0 duration doesn't really make sense,
    /// the timer only runs if the total seconds is larger than 0
    /// This also makes sure the consumer of the class has actually
    /// set the duration to something higher than 0
    /// </summary>
    public void Run()
    {
        // only run with valid duration
        if (totalSeconds > 0)
        {
            started = true;
            running = true;
            elapsedSeconds = 0;
        }
    }

    #endregion
}

```

This is the scene and settings screenshot, and since the plane is not at 0,0,0 the spawn objects are not inside the plane area. If the plane is at 0,0,0 it will work fine but I want it to work also if the plane is not at 0,0,0 and also to use height.

On the Plane Spawner I attached the Spawn Object script and on the PlanePrefab the Objectsp and the Timer scripts.

# Answer
> 0 votes
You need to create or move the spawn point to the position you want - set the spawn point to the correct transform.position and it will spawn correctly. The plane spawner is at 0, 0, 0 - and it's spawning correctly - you need to move it to be at the location you want to spawn at (x, y, z).

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


# Question
Title: How to fix the vibration while colliding?
I'm making a 2D platformer with Unity. My game has a problem:

The player vibrates when it collides with something. It seems like it's spinning or flipping very quickly. I used `transform.position` in my code before but because of some kind of vibration I changed it to `AddForce` but still I have that problem.

Thank you in advance.

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

   public class PlayerController : MonoBehaviour
   {

   [SerializeField] private float jumpSpeed;

    public float maxSpeed = 5f;
    public float maxAcceleration = 50f;
    public float maxDeceleration = 100f;

    [SerializeField] private LayerMask ground;
    private PlayerActionControls playerActionControls;
    private Rigidbody2D rb;
    private PolygonCollider2D pol;
    private Animator animator;
    private Vector2 movementInput;

    private void Awake()
    {
        playerActionControls = new PlayerActionControls();
        rb = GetComponent<Rigidbody2D>();
        pol = GetComponent<PolygonCollider2D>();
        animator = GetComponent<Animator>();
    }

    private void OnEnable()
    {
        playerActionControls.Enable();
    }

    private void OnDisable()
    {
        playerActionControls.Disable();
    }

    void Start()
    {
        playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());
    }

    private void Jump(float val)
    {
        if (val == 1 && IsGrounded())
        {
            rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);

        }
    }
    private bool IsGrounded()
    {

        Vector2 topLeftPoint = transform.position;
        topLeftPoint.x -= pol.bounds.extents.x;
        topLeftPoint.y += pol.bounds.extents.y;

        Vector2 bottomRightPoint = transform.position;
        bottomRightPoint.x += pol.bounds.extents.x;
        bottomRightPoint.y -= pol.bounds.extents.y;

        return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
    }
    void FixedUpdate()
    {

        Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

        movementInput = Vector2.ClampMagnitude(movementInput, 1f);

        Vector2 DesiredVelocity = movementInput * maxSpeed;
        AccelerateTo(DesiredVelocity);

        var scale = transform.localScale;

        if(scale.x * rb.velocity.x < 0) {
        scale.x *= -1;
        transform.localScale = scale;
    }

    void AccelerateTo(Vector2 desiredVelocity) {

       var deltaV = desiredVelocity - rb.velocity;
       var acceleration = deltaV / Time.deltaTime;
       float limit = maxAcceleration;

    if (Vector3.Dot(rb.velocity, desiredVelocity) <= 0f)
       limit = maxDeceleration;
       acceleration = Vector2.ClampMagnitude(acceleration, limit);
       Vector2 force = rb.mass * acceleration;
       rb.AddForce(force);
   }
 }
}

```

# Answer
> 0 votes
Your calling void AccelerateTo(Vector2 desiredVelocity) in your fixedUpdate().

You should not use Time.deltaTime in a fixedUpdate - you need to alter this code.

```
var acceleration = deltaV / Time.deltaTime;

```

When you use Time.DeltaTime in fixedUpdate you do not allow it to work properly. FixedUpdate has the frequency of the physics system and is called every fixed frame-rate frame.

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


title: Calculate mesh normals with added noise

text:
# Question
Title: Calculate mesh normals with added noise
I'm creating a procedurally generated planet object in Unity. I start with a cube which is created from 6 meshes (6 sides) and normalize the vertices to get a standard sphere. The problem is that there are visible seams between the meshes. I know if I set the vertex normals to the direction from the center of the sphere to the current vertex then seams will gone but my next step is to add noise to the meshes to generate terrain on the sphere.

What I already tried to remove the seams:

* Generating an extra strip around the mesh
* Generating an extra strip around the mesh which is located on the adjacent sides

The second solution is almost perfect but seams are still visible a little bit.

When I create the mesh object:

* call the built-in RecalculateNormals on the mesh (including the borders)
* remove the border vertices, indices and normals
* reassign the vertices, indices and normals to the mesh object (excluding the borders)

I use libnoisedotnet to create simplex Perlin noise on the surface:

```
private MeshData CalculateMeshData()
{
    MeshData meshData = new MeshData();
    meshData.ChunkSize = CHUNK_SIZE;
    meshData.BorderSize = BORDER_SIZE;

    int borderedResolution = meshData.BorderedResolution;
    int vertexIndex = -1;
    float faceWidth = _radius * 2 / CHUNK_SIZE;
    float currentYPosition = -_radius - faceWidth * BORDER_SIZE;

    for (int y = 0; y < borderedResolution; y++)
    {
        float currentXPosition = -_radius - faceWidth * BORDER_SIZE;
        for (int x = 0; x < borderedResolution; x++)
        {
            bool isMeshVertex = !IsBorderVertex(x, y, borderedResolution);
            Vector3 axisAOffset = _axisA * currentXPosition;
            Vector3 axisbOffset = _axisB * currentYPosition;
            Vector3 pointOnUnitCube = _center + axisAOffset + axisbOffset;
            Vector3 vertex = pointOnUnitCube.normalized;
            vertex = vertex * GetElevation(vertex);

            vertexIndex++;
            meshData.AddVertex(vertex, isMeshVertex);

            // Prevents to create more two triangles next to the edge of the mesh.
            if (x != borderedResolution - 1 && y != borderedResolution - 1)
            {
                bool isMeshTriangle = IsMeshTriangle(x, y, borderedResolution);
                meshData.AddTriangle(vertexIndex,
                                     vertexIndex + borderedResolution + 1,
                                     vertexIndex + borderedResolution,
                                     isMeshTriangle);

                meshData.AddTriangle(vertexIndex,
                                 vertexIndex + 1,
                                 vertexIndex + borderedResolution + 1,
                                 isMeshTriangle);
            }

            currentXPosition += faceWidth;
        }

        currentYPosition += faceWidth;
    }

    return meshData;
}

private float GetElevation(Vector3 position)
{
    return 1 + _noise.Evaluate(position) / 10f;
}

```

Here is the noise library what I tried to use: https://github.com/SebLague/Procedural-Planets/blob/master/Procedural%20Planet%20E03/Assets/Noise.cs

Is it possible to remove the seams fully?

# Answer
Let's modify your simplex noise function to also compute the gradient of the noise field at the sample position. This lets us share the work between the two computations, so it's cheaper than adding a second `EvaluateGradient()` method or sampling the noise field multiple times to get finite differences.

First we'll modify the signature to give us our gradient in an `out` variable:

```
public float Evaluate(Vector3 point, out Vector3 gradient)

```

Then we'll initialize our gradient to a zero vector:

```
gradient = Vector3.zero;

```

Toward the bottom of the function, you'll find four sections that look like this, computing the value contribution from each corner of the simplex:

```
if (t0 > 0)
{
    t0 *= t0;
    int gi0 = _random[ii + _random[jj + _random[kk]]]%12;
    n0 = t0*t0*Dot(Grad3[gi0], x0, y0, z0);
}

```

We're going to modify those to this:

```
if (t0 > 0) {
    // We need a t-cubed later, so we'll store this into its own variable.
    double tSquared = t0 * t0;

    // Same as before - note that this code differs slightly between the 4 corners.
    int gi0 = _random[ii + _random[jj + _random[kk]]]%12;

    // Naming our local corner gradient and dot product for re-use.
    var g = Grad3[gi0];
    double dot = Dot(g, x0, y0, z0);

    // Same calculation as before, just with our new variable names.
    n0 = tSquared * tSquared * dot;

    // Compute the gradient of t (derivative with respect to x, y, z).
    Vector3 tPrime = -2f * new Vector3((float)x0, (float)y0, (float)z0);

    // Accumulate the gradient contribution.
    gradient += (float)(4 * tSquared * t0 * dot) * tPrime
              + (float)(tSquared * tSquared) * new Vector3(g[0], g[1], g[2]);
}

```

Repeat that substitution for each of the four, making sure to change `t0`, `x0` etc. into the corresponding `t1`, `x1`. Or refactor this into a function you can call four times with different arguments - just be careful of the differences in the calculation of the gradient index.

Now in our planet generator, we'll modify your elevation function to also compute the normal vector for the point:

```
float GetElevationAndNormal(Vector3 direction, Noise out Vector3 normal) {
    // Sample the noise value and gradient at our position.
    float sample = _noise.Evaluate(direction * noiseFrequency, out Vector3 gradient);

    // Zero out the component of the gradient perpendicular to the sphere.
    var surfaceGradient = gradient - direction * Vector3.Dot(gradient, direction);

    // Compute an updated normal - leaning away from the direction of increase.
    normal = (direction - 25f * noiseAmplitude * noiseFrequency * surfaceGradient).normalized;

    // Convert our noise sample to an elevation.
    return 1.0f + noiseAmplitude * sample;
}

```

Note that because the only input to this function is the direction on the sphere, when we return to that same direction on another mesh, we'll get the same output (ie. consistent normals on both sides of the seam). So there's no need for the extra skirt geometry to try to force `RecaclulateNormals` to average-out the way you want.

I'll confess that `25f` magic number in there is a bit of a fudge factor. My calculated normals were initially too soft, but I haven't had my coffee yet so I'm struggling a bit to figure out why. It might be because I'm approximating the surface as being locally flat, and the curvature of the sphere has more impact than that. In any case, for now, scaling by 25 seems to bring this in line with the sharpness of shading you get from `RecalculateNormals` but without the seams. I'll update this if I can find a better mathematical justification for getting the right normal tilt.

If you want to elaborate on your noise sampling - say layering octaves of noise for an FBM/Turbulence effect - you can use the fact that the differential operator is linear. So the gradient of a sum of scaled noise fields is just the sum of their scaled gradients. So as you sum up the elevation from each octave, also accumulate the gradients separately, then convert to a normal as shown above.
> 1 votes

---
Tags: unity, procedural-generation, normals, seams
---


# Question
Title: Unity3D/AnimationRigging - Rig not a child Transform in the Animator hierarchy
I'm using Animation Rigging in Unity and was having some success until I realized my rig was built on the wrong GameObject. This was causing the Animator on the character to be overridden by the animator that Animation Rigging "Rig Setup" created.

I moved the `Rig Builder` component onto the `Character` GameObject that already had the `Animator` set up, but now every single rig component is causing an error. I've completely recreated the rig and all of the constraints, but still get the same error.

For example: "Could not resolve 'Character/Rig\_HandIK/LeftHandIK' because it is not a child Transform in the Animator hierarchy". `Character` is the GO with `Animator` & `Rig Builder` components, `Rig_HandIK` is a child of `Character` with a `Rig` component, and `LeftHandIK` is a child of Rig\_HandIK which has the `Two Bone IK Constraint` component.

# Answer
> 1 votes
Figured it out. While the rig gameobjects were children of the Animator, they were not siblings of the body mesh & armature. Moving them all into the same gameobject fixed the issue.

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


# Question
Title: I do not understand the code version of time based sprite animation?
I'm Universo and for the longest time had coding issues around the concept of time-based sprite animation basically, do not know how to implement it and any code or explanation simple or complex that I've found has been extremely confusing to me and was hoping to have a kind person walk me through the code step by step, explaining exactly how this is implemented correctly.

Here's what, I believe to know about the concept and or idea for time-based sprite animation it is to construct a delay or halt of some code statement using time of some kind in milliseconds with a collection of moving images and or sprites however any attempts from the tutorial's or my own brain have resulted in inaccurate various speed sprite animations and not the consistent stable speed, Id appreciate and be grateful for here's some code to show my progress and perhaps help you understand my position in this mess baring in mind, I prefer my code be as extremely simple and speedy as possible within the limitations, of course:

**JavaScript with HTML5 Canvas**

```
window.onload = function () {

var canvas = document.getElementById("canvas"); // get the canvas object

var ctx = canvas.getContext("2d");
/* make sure we have a context for that canvas so we can draw stuff */

var FrameSize = 120; //120 pixels
var FrameNumber = 0; //obvious
var img = new Image(); // make a image object
img.src = 'sprite_ani.png'; // url to the image
var last = 0; // no idea

function Render() {

  ctx.clearRect(0,0 ,640,480); // clear screen
  now = performance.now(); //to get the current timestamp in milliseconds
  delta = now - last; // last is 0, how does this work?
  last = now; // last is now, why?

  if(delta > 20 //what does this value represent??) {
     FrameNumber += FrameNumber + 1;

   /* increment FrameNumber by 1 could have been FrameNumber++ */

     delta = 20; // No idea why I need to keep this the same number??
  }

  if(FrameNumber>=4){   //just to make sure this is the end of the frame number sequence
     FrameNumber = 0; // to reset the frame number
  }
     ctx.drawImage(img,FrameSize*FrameNumber,0,120,120,0,0,120,120);

     /*
     perticularly draw a sequence of images and switch each individual image
     in that sequence based on the equation

     FrameSize
     (number to multiply the pixels by)
     * // multiply operator symbol
     FrameNumber
     (the pixels for the FrameSize to multiply with)
     */

     window.requestAnimationFrame(Render); // do the Raf stuff part one
}
window.requestAnimationFrame(Render);  // do the raf stuff part two
}

```

As you can see, it's extremely simple yet, I'm still struggling to not only understand it but extremely simply implement it, I'm not a fan of over-complicated coding hence why I ditched c++ ages ago.

Could someone in extremely simple english guide me through time-based sprite animation in the context of JavaScript preferably, Id also really appreciate various time-based sprite animation methods being explained too in extremely simple terms but not holding out, I thank you for reading this far.

# Answer
After literally years on and off trying to figure out how to do some form of time-based sprite animation here is the final code, it's basically about getting delta and then creating an accumulation of increment and comparing if that's greater then delta and if so do a frame number increase "make sure to use framenumber++, not frame number = frame number + 1 it messes it up for some reason"

```
window.onload = function () {

        var canvas = document.getElementById("canvas");

        var ctx = canvas.getContext("2d");

        var FPS = 30;
        var Accumulator = 0;
        var FrameSize = 120;
        var FrameNumber = 0;
        var FrameCounter = 1;

        var img = new Image();
        img.src = 'sprite_ani.png';
        var Accumulator = 0;
        var last = performance.now();

        function Render() {

          ctx.clearRect(0,0 ,640,480);
          now = performance.now();
          var delta = now - last;

          last = now;

          Accumulator++;
          if(Accumulator >= delta)
          {
             FrameNumber++;
             console.log(FrameNumber);
             Accumulator = 0;
          }

          if(FrameNumber>=4){

             FrameNumber = 0;
          }

             ctx.drawImage(img,FrameSize*FrameNumber,0,120,120,0,0,120,120);

            window.requestAnimationFrame(Render, 3/1000);
        }
        window.requestAnimationFrame(Render, 3/1000);

       }

```
> 0 votes

---
Tags: animation, javascript, sprites, time, deltatime
---


title: Unity - Camera Moving Vertical

text:
# Question
Title: Unity - Camera Moving Vertical
So I want to make a smooth transition with the camera from point A to point B while keeping direction and rotation.

My current approach is using Vector3.Lerp :

```
using UnityEngine;

public class CameraMoveVertical : MonoBehaviour
{
    public float cameraSpeed = 0.125f;

    public void moveCamera()
    {
        Vector3 lerpPosition = Vector3.Lerp(transform.position, new Vector3(transform.position.x, transform.position.y+50, transform.position.z), cameraSpeed);
        transform.position = lerpPosition;
    }
}

```

The camera does move but the movement is instant. Any way to make it a smooth transition?

# Answer
That script by itself won't do anything, since the `moveCamera()` function is never called. Are you calling `moveCamera` from another script?

Use a coroutine:

```
private IEnumerator MoveUp(float distance, float duration) {
    Vector3 startPosition = transform.position;
    Vector3 targetPosition = startPosition + new Vector3(0, distance, 0);
    float elapsed = 0;
    while (elapsed < duration) {
        yield return null; //wait until the next frame
        elapsed += Time.deltaTime;
        transform.position = Vector3.Lerp(startPosition, targetPosition, elapsed / duration);
    }
}

public void MoveUp() {
    StartCoroutine(MoveUp(50, 3));
}

```

A coroutine is a function that executes over time; you can use loops within a coroutine to do many kinds of animation, such as this simple position tween. Coroutines are a critical concept in Unity and you should take the time to learn them thoroughly if you're not already familiar with the topic.
> 0 votes

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


# Question
Title: Memory Usage Issue with declared variables (when swapping between states)
So my problem is that When I make a Shader variable and I swap between mainmenustate and gamestate really fast I notice my memory usage increase alot but as soon I switch my Shader varaible into a pointer memory usage dont increase until I put cameraShader = new Shader(); I tried deleting the cameraShader but memory usage still increase

BAREBONE EXAMPLE

```
#include "glfw.h"
#include "glad.h"
#include "Shader.h"
class State{
private:
Shader* cameraShader;
public:
State(glfwwindow* window, std::stack<State*>* states){

cameraShader("example.vs", "example.fs");
}
virtual ~State(){
delete cameraShader;
}
}
void update(float& dt){
}

void render(){
}

```

main

```
  #include "State.h"
  #include "stdafx.h"
  #include "Game.h"

  void Game::framebufferCallback(GLFWwindow* window, int width, int height)
  {
  glViewport(0, 0, width, height);
  }

  Game::Game()
  :previousTime(0.f), dt(0.f)
  {
  //Variables
  const unsigned int width = 854, height = 480;

  //Initiating GLFW Window
  glfwInit();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  #ifdef _APPLE_
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  #endif

  //Creating a GLFW window
  window = glfwCreateWindow(width, height, "EXAMPLE", NULL, NULL);

  //Checking if Window was initiated
  if (window == NULL) {
    std::cout << "GLFW FAILED TO INITIATE WINDOW!\n";
    glfwTerminate();
    }

  glfwMakeContextCurrent(window);

  //Setting Window's aspect ratio
  glfwSetWindowAspectRatio(window, 16, 9);

  //Centering Window
  int windowWidth, windowHeight;
  glfwGetWindowSize(window, &windowWidth, &windowHeight);
  const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
  glfwSetWindowPos(window, mode->width / 2 - windowWidth / 2, mode->height /
  2 - windowHeight / 2);

  //Checking if Glad was initiated
  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "GLAD FAILED TO BE INITIATED\n";
    }

  //Enabling OpenGl features
  glEnable(GL_CULL_FACE);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
  glEnable(GL_STENCIL_TEST);
  glEnable(GL_DEPTH_TEST);

  stbi_set_flip_vertically_on_load(true);
  //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

 //Setting-Up Viewport
 glfwSetFramebufferSizeCallback(window, framebufferCallback);

//Intitiating MainMenu
 states.push(new MainMenuState(window, &states));
 }

 Game::~Game()
{
}

int Game::glfwGetWindowShouldClose()
{
return glfwWindowShouldClose(window);
}

void Game::processWindowEvents()
{
//Calculating Deltatime
double currentTime = glfwGetTime();
dt = currentTime - previousTime;
previousTime = currentTime;
}

void Game::update()
{
processWindowEvents();
if (!states.empty()) {

    states.top()->update(dt);
    if (states.top()->getQuit()) {
        states.top()->endstate();
        delete states.top();
        states.pop();
        std::cout << "States has been deleted\n";
    }
}
else {
    glfwSetWindowShouldClose(window, GL_TRUE);
}
}

void Game::render()
{
//Clearing display
glClearColor(0.15f, .45f, .60f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

if (!states.empty()) {
    states.top()->render();
}

glfwSwapBuffers(window);
glfwPollEvents();
}

```

Shader class

```
#ifndef SHADER_H
#define SHADER_H

#include <glad/glad.h>
#include <glm/glm.hpp>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

class Shader
 {
  public:
 unsigned int ID;

 Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr)
 {
    // 1. retrieve the vertex/fragment source code from filePath
    std::string vertexCode;
    std::string fragmentCode;
    std::string geometryCode;
    std::ifstream vShaderFile;
    std::ifstream fShaderFile;
    std::ifstream gShaderFile;
    // ensure ifstream objects can throw exceptions:
    vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    try
    {
        // open files
        vShaderFile.open(vertexPath);
        fShaderFile.open(fragmentPath);
        std::stringstream vShaderStream, fShaderStream;
        // read file's buffer contents into streams
        vShaderStream << vShaderFile.rdbuf();
        fShaderStream << fShaderFile.rdbuf();
        // close file handlers
        vShaderFile.close();
        fShaderFile.close();
        // convert stream into string
        vertexCode = vShaderStream.str();
        fragmentCode = fShaderStream.str();
        // if geometry shader path is present, also load a geometry shader
        if(geometryPath != nullptr)
        {
            gShaderFile.open(geometryPath);
            std::stringstream gShaderStream;
            gShaderStream << gShaderFile.rdbuf();
            gShaderFile.close();
            geometryCode = gShaderStream.str();
        }
    }
    catch (std::ifstream::failure& e)
    {
        std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
    }
    const char* vShaderCode = vertexCode.c_str();
    const char * fShaderCode = fragmentCode.c_str();
    // 2. compile shaders
    unsigned int vertex, fragment;
    // vertex shader
    vertex = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex, 1, &vShaderCode, NULL);
    glCompileShader(vertex);
    checkCompileErrors(vertex, "VERTEX");
    // fragment Shader
    fragment = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment, 1, &fShaderCode, NULL);
    glCompileShader(fragment);
    checkCompileErrors(fragment, "FRAGMENT");
    // if geometry shader is given, compile geometry shader
    unsigned int geometry;
    if(geometryPath != nullptr)
    {
        const char * gShaderCode = geometryCode.c_str();
        geometry = glCreateShader(GL_GEOMETRY_SHADER);
        glShaderSource(geometry, 1, &gShaderCode, NULL);
        glCompileShader(geometry);
        checkCompileErrors(geometry, "GEOMETRY");
    }
    // shader Program
    ID = glCreateProgram();
    glAttachShader(ID, vertex);
    glAttachShader(ID, fragment);
    if(geometryPath != nullptr)
        glAttachShader(ID, geometry);
    glLinkProgram(ID);
    checkCompileErrors(ID, "PROGRAM");
    // delete the shaders as they're linked into our program now and no longer necessery
    glDeleteShader(vertex);
    glDeleteShader(fragment);
    if(geometryPath != nullptr)
        glDeleteShader(geometry);

}
// activate the shader
// ------------------------------------------------------------------------
void use()
{
    glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void setBool(const std::string &name, bool value) const
{
    glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void setInt(const std::string &name, int value) const
{
    glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void setFloat(const std::string &name, float value) const
{
    glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void setVec2(const std::string &name, const glm::vec2 &value) const
{
    glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec2(const std::string &name, float x, float y) const
{
    glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
}
// ------------------------------------------------------------------------
void setVec3(const std::string &name, const glm::vec3 &value) const
{
    glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec3(const std::string &name, float x, float y, float z) const
{
    glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
// ------------------------------------------------------------------------
void setVec4(const std::string &name, const glm::vec4 &value) const
{
    glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec4(const std::string &name, float x, float y, float z, float w)
{
    glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
}
// ------------------------------------------------------------------------
void setMat2(const std::string &name, const glm::mat2 &mat) const
{
    glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
// ------------------------------------------------------------------------
void setMat3(const std::string &name, const glm::mat3 &mat) const
{
    glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
// ------------------------------------------------------------------------
void setMat4(const std::string &name, const glm::mat4 &mat) const
{
    glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}

private:
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void checkCompileErrors(GLuint shader, std::string type)
{
    GLint success;
    GLchar infoLog[1024];
    if(type != "PROGRAM")
    {
        glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
        if(!success)
        {
            glGetShaderInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog;
        }
    }
    else
    {
        glGetProgramiv(shader, GL_LINK_STATUS, &success);
        if(!success)
        {
            glGetProgramInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog;
        }
    }
}
};
    #endif

```

# Answer
Shader need a:

1. Copy constructor
2. Move constructor
3. Copy assignment operator
4. Move assignment operator
5. Destructor

For stop leak videocard memory. You call glCreateXxxx and you should call glDeleteXxxx on destruction. https://khronos.org/registry/OpenGL-Refpages/gl4/
> 1 votes

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


# Question
Title: How can I play an animation as long as the player is on the pressure pad?
I'm making a 2D platformer with Unity. Recently, I implemented a pressure pad system. Basically, when the player triggers the pad, a door near there should be opened. The system works properly but the only problem is when the player stays on the pad, the `OpenWhenOn` animation (an idle animation that is for the door opening) is not playing. I want to make this keep playing as long as the player is on the pad and if it exits the trigger, the `DoorClosing` animation should be played. I wrote this code mainly for playing the animation but it doesn't work and I get `Null Reference` error all the time.

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

public class PressurePad : MonoBehaviour
{
    private Animator anim;
    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;
    public GameObject door;

    public float deactivationDelay = 2f;

    int objectsInContact;
    Coroutine waitingToDeactivate;

    IEnumerator Timer()
    {
        yield return new WaitForSeconds(deactivationDelay);

        // Tell our listeners we're switched OFF.
        if (OnDeactivate != null)
            OnDeactivate.Invoke();

        // Return to ready-to-activate state:
        waitingToDeactivate = null;
    }

    void OnTriggerEnter2D(Collider2D other)
    {

        if (other.CompareTag("Player"))

        {
            anim.Play("OpenWhenOn");

        }

        door.GetComponent<Animator>().Play("OpenWhenOn");

        objectsInContact++;

        // Pressure pad pressed.
        if (objectsInContact == 1)
        {

            if (waitingToDeactivate != null)
            {
                // Cancel deactivation timer.
                StopCoroutine(waitingToDeactivate);
                waitingToDeactivate = null;

            }
            else if (OnActivate != null)
            {
                // Tell our listeners we're switched ON.
                OnActivate.Invoke();
            }

        }
    }

    void OnTriggerExit2D(Collider2D other)
    {
        objectsInContact--;

        // Pressure pad released.
        if (objectsInContact == 0)
        {
            // Start a delay before telling anyone.
            waitingToDeactivate = StartCoroutine(Timer());
        }
    }
}

```

**This is my Animator Controller. `HasExitTime` is disabled for all the transitions. The condition for the transition between `OpenWhenOn` and `DoorClosing` is set to false.**

# Answer
I'd recommend you do something like this:

1. Set up your Animator control graph with 4 animation states:

* Opening
    * Open (single frame with the door stationary in its open position)
    * Closing
    * Closed (single frame with door stationary in its closed position)
2. Add two "Trigger" parameters to your graph:

* "StartOpening"
    * "StartClosing"
3. Add transitions:

* from Opening to Open with "HasExitTime" so it transitions to the Open state when the Opening animation is finished, holding the door open
    * from Closing to Closed with "HasExitTime" so it transitions to the Closed state when the Closing animation is finished, holding the door shut
    * from Open/Opening to Closing with a condition on "StartClosing"
    * from Closed/Closing to Opening with a condition on "StartOpening"
4. Wire up the UnityEvents on your PressureSwitch:

* OnActivate should call your door's `Animator.SetTrigger()` method, with the argument "StartOpening"
    * OnDeactivate should call your door's `Animator.SetTrigger()` method, with the argument "StartClosing"

This lets you wire up the door open-close behaviour without hard coupling between the pressure switch and the door, and you don't even need a custom door script!

Of course, you could also write a `DoorControl` script to slightly simplify the Inspector setup by letting the door manage its own animator state:

```
[RequireComponent(typeof(Animator))]
public class DoorControl {

    [SerializeField, HideInInspector]
    Animator _animator;

    [SerializeField]
    bool _isOpen;

    void OnValidate() {
        _animator = GetComponent<Animator>();
        SetOpen(_isOpen);
    }

    void Start() {
        SetOpen(_isOpen);
    }

    public void Open() {
        SetOpen(true);
    }

    public void Close() {
        SetOpen(false);
    }

    public void SetOpen(bool open) {
        _isOpen = open;
        _animator.SetBool("Open", _isOpen);
    }
}

```

Now you can use a single boolean instead of two triggers to control your door (the `SetBool` method takes two arguments, so we can't wire that one up via the Inspector). And hooking up your events is a little easier - you can just call `DoorControl.Open()` or `DoorControl.Close()` without needing to type the exact name of the animation parameter - that knowledge is delegated to the `DoorControl`, keeping your setup less coupled.
> 0 votes

# Answer
I think you could simply

```
this.gameObject.GetComponent<Animator>().Play("DoorOpening");

```

So it will just play and loop.

If you prefer using the animator itself you can also duplicate the open door animation and have a new trigger for it, so when you trigger it will stay in that forever, or it will change based on your animator

For example, if you have the pressure pad in an `OnTriggerEnter()` you need to access the Animator of the door and then use my script:

```
public Animator anim;

   void OnTriggerEnter(Collision other)
{
  if(other.compareTag("Player")
anim.Play("DoorOpening");
}

```

This is just an example, but you can use it anywhere
> 0 votes

# Answer
I can't see anywhere where you're setting the condition to true to move between the `DoorOpening` and `OpenWhenOn` animations. Try removing the condition on the transition between `DoorOpening` and `OpenWhenOn`, if there's no condition then `OpenWhenOn` should play automatically after the `DoorOpening` animation plays.
> 0 votes

---
Tags: unity, animation, animator
---


# Question
Title: Synchronize running code over the network Unity
I want my code to run/perform the same on different Unity clients. I don't know if this is hard to achieve.

Here hare my problems:

* The enemies movement: I have a pathfinding that should always give the same results on server and on clients. Because I use the same pathfinding algorithm on server and client, and the position the algorithm chooses is synchronized with a network transform. But it does not give the same results on client and on server.
* Bullets make enemies die over all clients: I have a script with OnTriggerEnter2D(Collider2D collision) that never gets called at the same moment on clients and server. The clients might miss touching a bullet on an enemy on server but not on a client. So in server enemies died and on client they have not. How to synchronize OnTriggerEnter2D() ?

I will update the question to improve it with more examples when I find them.

# Answer
> 1 votes
What you're describing is "determinism" - this is the situation where two instances of your program can independently arrive at the same outcome, consistently, given the same input.

Determinism will not solve your problem here, because you do not have the same input.

The copy of your game running on the player's computer (the client) knows what move button they pressed at time 15:01.000. The copy running on the server does not find out about that action until one packet latency later - maybe 15:01.033, a full frame later.

From the client's perspective, you dodged the bullet just in time. From the server's perspective, you were a frame too late and the bullet hit you. Those are both correct simulation results for the input they were given. So even if your simulation rules are perfectly deterministic, you can get divergence: give different input, and you will get different results.

The simplest way to solve this is to decide by fiat that one of these versions of events will be honoured as the authoritative truth, and the other will be regarded as a temporary mirage, that quickly gets corrected to match this truth. In a client-server game, we'll usually choose the server to be this authority (because it can make it more difficult for players to cheat), and we call it an "authoritative server" model.

Here, the client's simulation result is considered to be a "prediction" - visualizing for the player what the results of their action should probably be, while we wait for confirmation from the server. The server independently simulates the results of the actions as it receives player input, and sends updates describing the outcomes.

When a client receives an update from the server that differs from its version of events, it applies a correction: blending (or in some cases, snapping) its local state to match the server's.

You can sometimes work around this to a degree with some time travel: when the server learns about some new player input, it estimates the time that input was sent, and rewinds the game simulation to that moment, applies the input, then re-simulates forward to find out what happened. This maintains one "consensus timeline" that more closely matches each player's view of the sequence of events in the game - especially relating to their own actions. But it can still run into surprises, where an action by a remote player that the local client doesn't know about yet changes the outcome of an event they've already predicted and displayed - so you still need to correct to the authoritative version of events in this case.

For your specific situations:

* The client can perform the pathfinding query, then choose the first waypoint on the path and send that to the server so that it and all connected clients can animate the entity moving to that point. Keep sending the next waypoint each time you reach the previous one. You may need to re-path periodically if you learn about a new obstacle partway through pathing.
* OnTriggerEnter with a bullet can trigger an animation (eg. a flinch) and sound effect so that the player gets immediate visceral feedback about the collision - but it should not be responsible for damaging or killing the entity on the client.

Instead, the server should be responsible for adjudicating whether a lethal hit occurred. When it does, it can send an "Entity killed" message to all connected clients, who can respond by transitioning that entity into its death state. The animation we started playing locally can help disguise the delay between the hit and the confirmation of the kill.

If no confirmation arrives, the entity can shrug off the illusory hit ("it just grazed me!") and continue unharmed. You may need to add a little extra showmanship though when killing an entity with a bullet that missed in your local simulation. Some extra particle effects can help sell the cause of death so it doesn't look like the entity just spontaneously croaked.

---
Tags: unity, networking, mirror-networking
---


# Question
Title: Attaching scripts which trigger on specified events to objects
I'm new to Unity and C#. For concreteness, I'll phrase the question in terms of building a TCG like Magic: the Gathering or Hearhtstone, although the method seems of more general utility.

Suppose we wish to create cards that have special properties, such as: "when played, does \[a thing\]", or "Immunity to fire". Having created a card class, here is the pseudo-code that I would like to write, when initializing the 'library' of cards:

```
Card testCard = new Card( /*generic arguments here like HP, etc*/);

testCard.abilities = [fireImmunity, drawCardOnPlay, ...];

```

Where I would have defined the abilities fireImmunity, drawCardOnPlay, and all others in some convenient location. Of course, I could manually define these abilities on each card, but that seems like a short route to insanity: many cards will share the abilities.

*First question*: it seems I need to create a 'container' on each card to hold the abilities of that card; how does one do this, and what's it called? How/ where to write the abilities list that will go into these containers? First thought was the container should be a list, but I don't know what type of objects we should populate it with.

*Second question*: in order to handle effects that occur at specified times ("when drawn", "at end of turn", etc) I think I need to be able to create custom events, similar to the built in ones such as onCollisionEnter. These custom events would then be referenced in the scripts such as drawCardOnPlay. How to do this and what's it called?

*Third question*: is this unnecessary? Is there a more obvious way to do these things?

I'm certain this has answers somewhere (here, probably), but without knowing what these things are called I haven't made any progress. I've read some similar questions here but none that have addressed the implementation.

# Answer
> 1 votes
First, I'd recommend making each card a `GameObject`. You'll likely want one anyway for the sake of having a visual object with a position/orientation in the scene and a collision representation for the player to click on. Then you can attach behaviours to it as components. This will help you avoid making one `Card` uberclass that does everything any card could ever do, keeping the code more modular and easier to maintain.

So you might have...

* A `PlayableCard` component that specifies how the card may be played, and has an attachment point for "OnPlayed" effects like your "drawCardOnPlayed" example
* A `Health` component that tracks the initial and current health of the card, and has an attachment point for "OnDamaged" effects like your "fireImmunity" example and "OnKilled" effects
* A `Cost` component that specifies the resources needed to play a card, etc...

You can mix and match these and other components to get a wide variety of card types, while each class stays focused and reasonably simple. It also means you don't pay for what you don't use. Cards that have no cost or no health don't reserve memory for storing resource and health variables you never look at.

Now on to these "attachment points" which seems to be the main point of your question.

We'll often implement these using the Observer Pattern, where each card component exposes an `event` (or maybe `UnityEvent` for convenient viewing and editing in the Inspector) for each interesting thing that can happen to it - like the `Health` component exposing a `public UnityEvent<DamageEvent> OnDamaged` \- then attaching an ability/effect just means subscribing to that event.

But there are some quirks of card games like the ones you reference that will often make us reach for a more custom version of this:

* **Card abilities often stack or modify one another.**

If I have a card that says "Takes double damage from fire" and "When this card takes damage, you gain an equal amount of life" then I could reasonably expect the damage doubling to take effect first, and pass that modified damage value to the life-giving effect, so that I heal double.

So, you'll likely want to implement your own container of effect objects or event handler delegates. That container can implement a prioritization (like a `SortedList<float, CardEffectDelegate>`), so you can ensure the effects trigger in the desired order.

This container can also include a chaining mechanism, so that the outcome of one effect handler can be passed as input into the next handler. This might be as simple as making your argument a mutable reference type, so the changes spill over automatically. Or if you prefer immutability, each handler can take an event and return the next event to pass to the next handler in sequence - returning the input unchanged if nothing special needs to happen.
* **The response to one event often triggers another event.**

I might have a card that says something complicated like "When this card is destroyed, flip a coin. On heads, draw a card. You may choose to play that card immediately at no cost. If you do, your opponent gains 1 life."

Each step of this rule would need some time to be animated on the screen (flipping the coin, drawing the card), and potentially wait for player input (choosing whether to play the card). That means we can't execute the whole set of card effects synchronously in a single frame. We need to have an ability to partially execute a set of modifiers on a card, then suspend execution to resume later.

This gets a little easier if you think of your game's "rule interpreting engine" as being a virtual machine. It has a program counter (the current card effect it's evaluating for a given game event), and an execution stack (the card effects/events to resolve after this one has been dealt with). (This is very closely analogous to the Stack in Magic the Gathering, which is a literal pile of cards you use to step through the resolution of its card effects)

With this model, each card effect handler could be an `IEnumerator` that `yield`s new card events as needed, or a delegate that takes a reference to the virtual machine, and asks it to add new events onto its stack when needed.

Lastly, it looks like you plan to have a number of effects that might be shared between many cards. For these, it's convenient to set them up as a `ScriptableObject`. This lets you create each distinct version of an effect as an asset file in your project folder that you can edit in the Inspector. Many cards can reference this effect without duplicating the data in many places, making it easier to tune and keep track of.

For instance, your fire immunity might use code something a bit like this...

```
// This represents what's common to card effects in general.
public abstract class CardEffect : ScriptableObject {

    [SerializeField, Tooltip("Order of precedence - lower numbers take effect first")]
    protected float _priority;

    // Handle subscribing to any events that are needed for this
    public abstract void ApplyTo(Card card);
}

// This attribute lets us create new damage multiplier effects in the Unity editor menus.
[CreateAssetMenu(fileName = "NewDamageMultiplier.Asset",
                 menuName = "Card Effects/Damage Multiplier")]
public class DamageMultiplierEffect : CardEffect {

    [SerializeField]
    DamageType _typesToAffect = DamageType.All;

    [SerializeField]
    float _multiplier = 1.0f;

    public override void ApplyTo(Card card) {
        var health = card.GetComponent<Health>();
        health.OnDamage.Add(ModifyDamage, _priority);
    }

    void ModifyDamage(EffectStack stack) {
        var damage = stack.CurrentEvent as DamageEvent;

        if ((damage.type & _typesToAffect) != DamageType.None) {
            damage.amount *= _multiplier;
        }
    }
}

```

So fire immunity is a `DamageMultiplier` asset with `_typesToAffect = DamageType.Fire` and `_multiplier = 0.0f` assigned in the Inspector.

Your card archetype can have a `List<CardEffect>`, containing references to all the effect assets that need to apply to this card. When instantiating the card, you can walk through each effect in the list and call its `ApplyTo` to wire it up to the events in the card's lifecycle that the effect should respond to. That might be different events on different components for each effect, but we don't need to know that detail - we've delegated the responsibility to each concrete `CardEffect` subclass, so each one can be highly custom and flexible.

---
Tags: unity, c#, card-game, effect-modifier
---


# Question
Title: How can I handle hundreds of calculation heavy nodes at the same time?
I'm currently trying to implement a basic boids simulation with godot in c#.

Currently I managed to implement evasive behavior which works fine for a boid count of roughly 300. Everything beyond that is CPU limited and the simulation starts to lag.

I want to increase the amount of boids more into a number of thousands. What I tried for now is an offload of the evasive behavior into a thread per boid. But I soon realized that one thread for each boid is probably not the right way to achieve this.

So my question is: **What is the proper way to handle such amounts of nodes?**

I know my code is in c#. I don't need a proper solution in c# but rather a hint on where and how to offload the workload into a thread or something like this.

My world script does the following:

* Add n boids to the scene with randomized position and rotation (It's a wip so please ignore the messy rng stuff :D )
* Start a time for text update
* Pick one boid as the chosen one for visualization and speed read

```
using Godot;
using System;

public class World : Node2D
{
    [Export]
    private PackedScene boidScene = ResourceLoader.Load("Boid.tscn") as PackedScene;
    private Boid chosenOne;
    private int boidCount = 350;
    private string groupName = "boids";

    public override void _Ready() {
        base._Ready();
        AddBoids();
        StartTextUpdateTimer(CreateTimer());
        PickChosenOne();
    }

    private void AddBoids() {
        var random = new Random();
        var screensize = GetViewport().Size;
        var rng = new RandomNumberGenerator();
        for (int i = 0; i < boidCount; i++) {
            var boid = boidScene.Instance() as Boid;
            boid.GlobalPosition = new Vector2(rng.RandfRange(0f, screensize.x), rng.RandfRange(0, screensize.y));
            var direction = (random.NextDouble()* (Math.PI * 2))-Math.PI;
            boid.GlobalRotation = (float)direction;
            AddChild(boid);
        }
    }

    private void StartTextUpdateTimer(Timer timer) {
        timer.Connect("timeout", this, "_On_Timer_Timeout");
        timer.WaitTime = 1.0f;
        timer.OneShot = false;
        timer.Start();
    }

    private Timer CreateTimer() {
        var timer = new Timer();
        AddChild(timer);
        return timer;
    }

    private void _On_Timer_Timeout() {
        RichTextLabel richTextLabel = GetNode("Speed") as RichTextLabel;
        richTextLabel.Text = "Chosen speed: " + chosenOne.LinearVelocity.Length();
    }

    private void PickChosenOne() {
        var index = new RandomNumberGenerator().RandiRange(0, GetTree().GetNodesInGroup(groupName).Count);
        chosenOne = GetTree().GetNodesInGroup(groupName)[index] as Boid;
        chosenOne.Chosen = true;
    }
}

```

And my boid scene does the following:

* Adds itself to the boids group
* Add raycasts for collision scanning (I want to simulate the view with a viewing distance)
* On each tick: Get boids in perception and evade from closest one.

using Godot;
using System;
using System.Linq;
using System.Collections.Generic;

public class Boid : RigidBody2D
{
    [Export]
    private string groupName = "boids";

    [Export]
    public int MinSpeed { get; set;} = 80;

    [Export]
    public int MaxSpeed { get; set; } = 120;

    [Export]
    public int Torque { get; set; } = 25;

    [Export]
    public bool Chosen { get; set; } = false;

    private int perceptionRadius = 150;
    public int EvasionDistance { get; } = 80;

    private float radStep = 10 * Mathf.Pi / 180;

    private Color vis_color = new Color(.867f, .91f, .247f, 0.1f);
    public List<RayCast2D> RayCasts { get; } = new List<RayCast2D>();

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        AddToGroup(groupName);
        AddRayCasts();
        ApplyInitialImpluse();
    }

    private void AddRayCasts()
    {
        float i = 0;
        while (i < 2 * Mathf.Pi)
        {
            if (IsInVisibleArea(i))
            {
                var rayCast = new RayCast2D();
                AddChild(rayCast);
                rayCast.Enabled = true;
                rayCast.CastTo = new Vector2(0, -perceptionRadius).Rotated(i);
                RayCasts.Add(rayCast);
            }
            i += radStep;
        }
    }

    private bool IsInVisibleArea(float i)
    {
        // Note: Blindspot between 225° and 315°
        return (i < 5 * Mathf.Pi / 4 || i > 7 * Mathf.Pi / 4);
    }

    private void ApplyInitialImpluse()
    {
        var rng = new RandomNumberGenerator();
        var impulse = new Vector2(rng.RandiRange(MinSpeed, MaxSpeed), 0).Rotated(Rotation);
        ApplyImpulse(new Vector2(), impulse);
    }

    public override void _IntegrateForces(Physics2DDirectBodyState state)
    {
        base._IntegrateForces(state);
        TeleportOnScreenExit(state);
        MaintainSpeed();
        HashSet<Vector2> nodesInPerception = GetNodesInPerception();
        List<Vector2> closest = GetClosestPoints(nodesInPerception, 1);
        Evade(closest, state);
    }

    private void Evade(List<Vector2> closest, Physics2DDirectBodyState state)
    {
        closest.ForEach(node =>
        {
            var distanceToNode = Position.DistanceTo(node);
            if (distanceToNode < EvasionDistance)
            {
                var angle = GetAngleTo(node);
                state.AngularVelocity = (-angle) * (1 / (distanceToNode / 2)) * Torque;
            }
        });
        state.LinearVelocity = new Vector2(MinSpeed, 0).Rotated(Rotation);
    }

    private List<Vector2> GetClosestPoints(HashSet<Vector2> nodesInPerception, int amount)
    {
        List<Vector2> closest = new List<Vector2>();
        if (nodesInPerception.Count > 0)
            closest = nodesInPerception.OrderBy(node => Position.DistanceTo(node)).Take(amount).ToList();

        return closest;
    }

    private HashSet<Vector2> GetNodesInPerception()
    {
        var setOfColliders = new HashSet<Vector2>();
        RayCasts.ForEach(rayCast =>
        {
            if (rayCast.IsColliding())
                setOfColliders.Add(rayCast.GetCollisionPoint());
        });
        return setOfColliders;
    }

    public override void _Draw()
    {
        base._Draw();
        if (Chosen)
        {
            DrawCircle(new Vector2(), perceptionRadius, vis_color);
            float i = 0;
            while (i < 2 * Mathf.Pi)
            {
                if (IsInVisibleArea(i))
                {
                    DrawLine(new Vector2(0, 0), new Vector2(0, -perceptionRadius).Rotated(i), new Color("#ff8888"), 1);
                }
                i += radStep;
            }
        }
    }

    private void TeleportOnScreenExit(Physics2DDirectBodyState state)
    {
        var xform = state.Transform;
        var screensize = GetViewportRect().Size;
        if (xform.origin.x < 0)
            xform.origin.x = screensize.x;
        if (xform.origin.x > screensize.x)
            xform.origin.x = 0;
        if (xform.origin.y < 0)
            xform.origin.y = screensize.y;
        if (xform.origin.y > screensize.y)
            xform.origin.y = 0;

        state.Transform = xform;
    }

    private void MaintainSpeed()
    {
        if (LinearVelocity.Length() < MinSpeed)
            AppliedForce = new Vector2(MinSpeed, 0).Rotated(Rotation);
        else
            AppliedForce = new Vector2();
    }
}
```

# Answer
1. Divide your boids and the objects they need to perceive into a spatial partition, so you only ever need to examine a small number of objects in a small number of cells.
2. Instead of sweeping a fan of rays, cheat. Use the spatial partition to find candidate closest objects, then fire a single ray at the best candidate to confirm whether it's visible.

This both massively reduces your number of (potentially expensive) rays to check, and also helps ensure you don't miss objects that fit between two rays of your fan.
3. Think of the work of updating each boid (or every boid in each partition cell) as a job. You can then divide those jobs between any number of worker threads.

You can do this by having a single queue that each worker thread pulls from once it's finished its previous job (easier for load-balancing so all threads are kept busy), or a queue for each worker where you have some centralized logic for divvying-up the work (easier for tuning data locality and minimizing cache conflicts)

This lets you tune the number of threads to what the hardware handles well, separate from the number of boids/cells. More boids or more cells just means a longer queue. Having just a few threads minimizes the overhead of spinning them up / shutting them down, and switching between them. Many solutions will keep a "thread pool" of such workers around as long-lived, general-purpose resources so they're ready to go on demand. There's such a pool in the C# .Net runtime you can tap into with a parallel for, as one example.
4. Where you can, avoid creating `new` reference types like lists inside your hot inner loop. This involves allocating memory and garbage collection book-keeping, which slow down your code. And the garbage eventually piles up and forces the garbage collector to run, taking up more time. Instead, see of you can re-use one set of book-keeping data structures per thread.
> 1 votes

---
Tags: c#, multithreading, godot, gdscript
---


# Question
Title: Function Not Storing New Value of Variables?
I'm currently building a small-scope RPG and running into an issue with modifying variables. My goal is to alter my character's stats when I run a procedure to change their equipment. My code is as follows:

```
public class Player: MonoBehaviour   {
    //Base stat variables
        public static int PAtk = 12;
        public static int PDef = 6;
    //Battle-exclusive stats.  Will have equipment added onto them.
        public static int Attack = PAtk;
        public static int Defense = PDef;
    //Equipment variables.
        public string weapon;
        public string armor;

    private void Awake()
    {
        //Get equipment
        EquipWeapon("Bronze Sword");
        EquipArmor("Bronze Armor");
    }

void EquipWeapon(string WeaponName)
    {
        weapon = WeaponName;
        EquipmentManager.GetComponent<Equipment>().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName);
    }
void EquipArmor(string ArmorName)
    {
        armor = ArmorName;
        EquipmentManager.GetComponent<Equipment>().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName);
    }
}

public class Equipment: MonoBehaviour  {
    //Create dictionary to give each weapon a key ID.  This will be used for calling items in another array.
        Dictionary<string, int> WeaponDictionary = new Dictionary<string, int>();
    //Create weapon array for stats.
    public int[,] WeaponStats;

    // Start is called before the first frame update
    void Awake()
    {   //Declare weapon IDs
            WeaponDictionary.Add("Bronze Sword", 0);
            WeaponDictionary.Add("Bronze Armor", 1);
        //Declare stat array
        //Table: ID, Atk, Def
        WeaponStats = new int[,]
        {
            {0,4,0},
            {1,0,4}
        };
    }

    public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment)
    {
        BattleAtk = BaseAtk + WeaponStats[WeaponDictionary[Equipment], 1];
        Debug.Log(BattleAtk + "Battle Power");
        BattleDef = BaseDef + WeaponStats[WeaponDictionary[Equipment], 2];
        Debug.Log(BattleDef + "Battle Defense");
    }
}

```

The general gist of it is once `EquipWeapon` or `EquipArmor` is ran, the equipment variables in the `Player` class will be updated. Afterwards, another function in the Equipment class will be ran with variables from the `Player` class passed over, in order to be modified by the `WeaponStats` array.

The Debug logs in `EquipStatIncrease` show me that I am getting the desired results. However, the Attack parameter that is being placed into the function is not being permanently modified. During the first execution of the `EquipStatIncrease` method, I will get a result of `16 BattleAtk` and `6 BattleDef`, due to the weapon being equipped. However, once it's run a second time to equip the armor, I'm shown a result of `12 BattleAtk` and `10 BattleDef`, even though `BattleAtk` should have stayed at 16. This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this. In the `EquipStatIncrease` parameters, `BattleAtk` gives the message `Parameter 'BattleAtk' can be removed if it is not part of a shipped public API; its initial value is never used` However, I don't know what action to take to resolve this.

I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable. If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases `BattleAtk` and `BattleDef`), then I don't see how an int function would work.

# Answer
You are only modifying the local copy of the parameter. This happens, because an `int` is a value type. You must pass a reference type to your method. Pass it the player itself. A class is a reference type and a variable or parameter of a reference type contains a reference to the object, not a copy of the object.

```
public void EquipStatIncrease(Player player, string equipment)
{
    player.Attack = player.PAtk + WeaponStats[WeaponDictionary[equipment], 1];
    ...
}

```

call it with

```
EquipmentManager.GetComponent<Equipment>().EquipStatIncrease(this, WeaponName);

```

Where I assume that you are calling this inside the player class.

---

Okay, I just saw that you have declared the fields as static in player. This means that these values will be the same for all the players. If this was your intent, leave it like this, otherwise use instance fields. You can access static fields through the type name: `Player.PAtk` (and don't need a reference).

If `PAtk` and `PDef` are not changing, you could declare them as `const` (constants are automatically static): `public const int PAtk = 12, PDef = 6;`

If all the fields used in `EquipStatIncrease` are static, you not even need the player parameter.

```
public void EquipStatIncrease(string equipment)
{
    Player.Attack = Player.PAtk + WeaponStats[WeaponDictionary[equipment], 1];
    ...
}

```

Another way of handling it is to pass the variables to be changed by reference, either with the `ref` or the `out` keyword (there is also an `in` keyword, but doesn't help here). Use `ref` you want to pass the variable in and out, e.g. if you want to increment it. Use the `out` keyword if you want to assign it a value by ignoring its old value.

```
public void EquipStatIncrease(
    int BaseAtk, ref int BattleAtk, int BaseDef, ref int BattleDef, string Equipment)
{ ... }

```

you must use the `ref` (or `out`) keyword at the call sites too:

```
EquipmentManager.GetComponent<Equipment>()
    .EquipStatIncrease(PAtk, ref Attack, PDef, ref Defense, WeaponName);

```
> 1 votes

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


title: Make objects stack in unity?

text:
# Question
Title: Make objects stack in unity?
I have two kinematic rigidbody cubes from the standard 3D objects, I have also enabled contact pairs mode to "all contact pairs", how do I make it so that no matter what angle they collide in they perserve the same angle but just get out of each others space making it look like they're in contact e.g. collided?

Here is my attempt at doing that:

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

 public class Physics : MonoBehaviour
{
  private Collider collider1;
  private bool grounded = false; //used to determine if the collider hit something so it doesnt keep going down

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

// Update is called once per frame
void Update()
{
    if (!grounded) //if the collider hit something, stop going down
    {
        collider1.transform.Translate(0f,-.1f,0f,Space.World);

    }
}

private void OnCollisionEnter(Collision collision)
{
    grounded = true; //the collider hit something
    if(collider1.transform.position.y != collider1.bounds.extents.y) //if this is true, it means it is at the floor so dont move it
    {
        transform.position = new Vector3(collider1.transform.position.x, collision.collider.bounds.size.y + collider1.bounds.extents.y, collider1.transform.position.z); //attempts to put the collider on top of whatever it get

    }

 }

}

```

This works if the cubes are right on top of each other with no angle:

It also works if one of the cubes collides at a angle to the other cube, when they collide the bottom cube perverse its angle of collision and and the top cube just gets out of the space of the other collider making it look like they have collided:  What doesn't seem to work is if both cubes collide with each other at a angle, although they **preserve their angle** of collision, and also **get out of each others space**, they **do not remain in contact with each other** which if they did would make it look like they have collided.

Instead there is a gap between them, how do I get rid of the gap e.g. make it so that no matter what angle the objects are at they get out of each others space, preserve the angle, and remain in contact with each other to give the illusion that they have collided?

# Answer
As I mentioned in a comment, you can use a `BoxCast` to scan possible positions for a box along a line, and stop it at the moment it touches another object. Something like this:

```
Vector3 GetStackedPosition(Vector3 lowest, float maxHeight, Vector3 halfExtents, Quaternion orientation) {

    Vector3 start = lowest;
    start.y += maxHeight;

    if (!Physics.BoxCast(start, halfExtents, Vector3.down, out RaycastHit hit, orientation, maxHeight))
        return lowest;

    Vector3 result = start;
    result.y -= hit.distance + 2f * Physics.defaultContactOffset;

    return result;
}

```

If you're spawning all these cubes on the same frame, then be sure to call `Physics.SyncTransforms` after placing each one, so that the physics engine knows where its collider ends up and can use it as a potential obstacle for the next cast.
> 1 votes

# Answer
Simply set the inverse inertia tensor to all zeros. The simple explanation here is that the inertia tensor of an object describes how that object resists rotation when acted upon by outside forces. A zero inverse inertia tensor implies that the object has infinite inertia in all directions, and thus resists all rotation produced by physics.

https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/2.%20Setup/2b.%20Motion%20Properties/Scripts/SetInertiaInverseBehaviour.cs

Another option is to use angular constraints.

https://docs.unity3d.com/Manual/class-RotationConstraint.html
> 0 votes

---
Tags: unity, physics, 3d
---


# Question
Title: Issues with the value of transform.position.x
I'm trying to do something very basic: "IF value of tranform.position.x equals 4.5 DO something"

Here is my code:

```
if(transform.position.x.Equals(4.5)){
        //(float)transform.position.x == (float)myGM.BottomRightCorner.x
        if(directionToMove.Equals(0.1f)){
            directionToMove = -0.1f;
            print("Direction To Move Changed");
        } else{
            directionToMove = 0.1f;
            print("Direction To Move Changed");
        }
    }
    transform.Translate(new Vector2(directionToMove, 0));

```

I've tried `if(transform.position.x == 4.5)`, `if(transform.position.x == 4.5f`, `if(transform.position.x.Equals(4.5)`, `if(transform.position.x.Equals(4.5f)`and of course I've tried putting the 4.5 in a variable (constant and regular)... but no matter what, when `transform.position.x` has a value of 4.5... nothing happens. it completely skips the if statement. I've been programming for 5 hours so far today, so my brain might just have crashed... Just for the sake of it, I did try `if(4.5 == 4.5)` just to make sure I wasn't going crazy and somehow wrote the if statement incorrectly... but no, that worked just fine (Thank god...)

I'd greatly appreciate it if anyone can point out any clues as to what I'm doing wrong here.

p.s. I'm aware that my code is not the most efficient thing in the world... I'm trying to see what I can do by myself without following any tutorial. As for what the statement is meant to do... before the transform reaches 4.5, starting from 4.0, increase the transform.position by 0.1f. Once it does reach that, decrease the transform.position by 0.1f.

Basically, move to one side of the screen, then go back to the other side of the screen. Initially, there was a check for the other side, but I stripped this to bare-bones to try and figure it out.

p.s.2: As a side note, this function is called via an "InvokeRepeating()". I'm going to try calling the method in another way, just in case... if that works, I'll remove this post.

# Answer
You should never test floating point values for equality. The reason is that floating point values always have a certain uncertainty.

There are some values which can be expressed in decimal notation, but can actually not be expressed as floating point values. The reason is that floating point values are binary and not decimal internally. The value for `0.8f` is invalid, for example. So the result of `0.7f + 0.1f` will be "rounded up" to `0.8000001f`. When you keep adding to and subtracting from floating point values, like you are doing here, such rounding errors accumulate.

For that reason, you should always check if floating point values are within a range which you consider "close enough" for your purpose. Unity has a utility method for that: `Mathf.Approximately(transform.position.x, 4.5f)`. But this method is still rather strict, because it only considers the smallest possible difference between two floating point values as "close enough". Sometimes you might have to use a larger tolerance factor. For example, when you consider `0.1f` "close enough", you can use `if(Mathf.Abs(transform.position.x - 4.5f) <= 0.1f)`.

For more information on common mistakes when dealing with floating point values (applicable to almost any programming language), check out the famous website What Every Programmer Should Know About Floating-Point Arithmetic.
> 0 votes

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


# Question
Title: "Invalid call. Nonexistent function 'travel' in base 'Nil'."?
I was perfect as I could possibly be with this code but for some reason every time I try to play the game it just breaks. It says "Invalid call. Nonexistent function 'travel' in base 'Nil'." So I'm pretty sure I gotta reinstall Godot because there's legit nothing wrong with the code. I triple checked and it should be working just fine. The issue is with the onready var animationState but that doesn't make sense because there's nothing wrong with that line of code. No typos, no anything. I just want the animations to play when they are moving and not moving. Can someone please tell me what the heck is wrong with this before I throw my computer out the window? Thanks.

```
extends KinematicBody2D

const ACCELERATION = 500
const MAX_SPEED = 80
const FRICTION = 500

var velocity = Vector2.ZERO

onready var animationPlayer = $AnimationPlayer
onready var animationTree = $AnimationTree
onready var animationState = animationTree.get("perameters/playback")

func _physics_process(delta):
    var input_vector = Vector2.ZERO
    input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
    input_vector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
    input_vector = input_vector.normalized()

    if input_vector != Vector2.ZERO:
        animationTree.set("parameters/Idle/blend_position", input_vector)
        animationTree.set("parameters/Walk/blend_position", input_vector)
        animationState.travel("Walk")
        velocity = velocity.move_toward(input_vector * MAX_SPEED, ACCELERATION * delta)
    else:
        animationState.travel("Idle")
        velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)

    velocity = move_and_slide(velocity)

```

# Answer
> 1 votes
Answering for completeness sake. This is pretty straightforward to debug: only animationState uses the function 'travel', and the error clearly states that that variable is Nil, so it wasn't properly initialized. Double checking the corresponding line shows the typo: 'paremeter' instead of 'parameter'.

# Answer
> -1 votes
It was a typo, my bad. Got the answer from a different Q&A

---
Tags: 2d, animation, godot, animation-states
---


# Question
Title: Godot 3.X Implementing a smooth movement for pitch, yaw & roll
I'm implementing pitch, yaw and roll on airplane object, but when rotating the object (either pitch, roll or yaw), it starts rotating slowly but then the rotating movement goes awfully fast very quickly. it's quite jarring. i'm not sure how to make more smooth.

**The issues:**

* I think the problem lies in the acceleration when the object rotates, i want to be an uniform speed
* Other problem from this code, it's that if want to change the rotating direction it's slow to change, takes a while to rotate to the opposite direction

The player input code:

```
extends Node
const MAX_CAM_ANGLE = 30
var pitch_dir = 0
var yaw_dir = 0
var roll_dir = 0
var thrust = 0.5
var input = ''
func _ready():
    $DebugStats.add_property($Plane, "transform:origin", "round")
    $DebugStats.add_property($Plane, "force", "round")
    $DebugStats.add_property($Plane, "torque", "round")
    $DebugStats.add_property(self, "pitch_dir", "round")
    $DebugStats.add_property(self, "input", "")

func _physics_process(delta):
    process_inputs(delta)
    process_movement(delta)

func process_inputs(delta):
    if Input.is_action_pressed("p1_fire"):
        $Plane.fire_weapon()
        input = 'fire'
    if Input.is_action_pressed("ui_up"):
        thrust += delta
        input = 'accel'
    if Input.is_action_pressed("ui_down"):
        thrust -= delta
        input = 'slow'
    if Input.is_action_pressed("p1_pitch_up"):
        pitch_dir += delta
        input = 'up'
    if Input.is_action_pressed("p1_pitch_down"):
        pitch_dir -= delta
        input = 'down'
    if Input.is_action_pressed("p1_roll_left"):
        roll_dir += delta
        input = 'yaw left'
    if Input.is_action_pressed("p1_roll_right"):
        roll_dir -= delta
        input = 'yaw right'
    if Input.is_action_pressed("p1_yaw_left"):
        yaw_dir += delta
        input = 'yaw left'
    if Input.is_action_pressed("p1_yaw_right"):
        yaw_dir -= delta
        input = 'yaw right'

    if Input.is_action_pressed("ui_quit"):
        get_tree().quit()

#TODO Adjust values to make movement more smooth
func process_movement(delta):
     thrust = clamp(thrust, 0.2, 1)
     pitch_dir  = clamp(pitch_dir, -.6, .6)
     yaw_dir  = clamp(yaw_dir, -.6, .6)
     roll_dir  = clamp(roll_dir, -.6, .6)
     $Plane.calc_force(thrust, pitch_dir, roll_dir, yaw_dir)

```

The plane movement script:

```
extends RigidBody

const v3 = Vector3(0, 0, 0)
const scalar_z = Vector3(0, 0, -1)
var force = v3
var torque = v3
var drag = v3
var lift = v3
var thrust = v3

const MAX_THRUST_TURN = 150
const MAX_THRUST = 1  # temporal value just to debug the rotating problem
const MAX_CAM_ANGLE = 30
const DRAG_CONST = 1 # temporal value just to debug the rotating problem

# Calculates flying speed and direction
func calc_force(thrust, pitch_dir, roll_dir, yaw_dir):
    var speed = MAX_THRUST * (thrust)
    var drag_coef = DRAG_CONST / MAX_THRUST / MAX_THRUST
    thrust = transform.basis.z * (-speed)
    drag = transform.basis.z * drag_coef
    lift = transform.basis.y * drag_coef

    force = thrust + drag + lift
    var pitch = global_transform.basis.x * pitch_dir * MAX_THRUST_TURN
    var yaw = global_transform.basis.z * yaw_dir * MAX_THRUST_TURN
    var roll = global_transform.basis.z * roll_dir * MAX_THRUST_TURN
    torque = pitch + yaw + roll

# Applies all force at once in the airplane object
func _integrate_forces(state):
    add_central_force(force)
    add_torque(torque)

```

How i can make the rotating movement more smoother? Note: this is an arcade game, not really interested in a complex solution for the physics.

Note 2: if you want to test it, you can check out here https://github.com/balmeidaa/godot\_sky\_aces

# Answer
While completely new to game development, I have an idea what the problem is. If I understand correctly, the movement should be uniform, but the movement accelerates at every delta by delta.

Recall that for `_physics_process` `delta` is a fixed fraction of a second, by default 1/60 seconds. Let's take thrust as an example. When the `ui_up` control is first pressed, 1/60 (~0.01666) is added to thrust, so assuming the thrust start value of 0.5, the new value becomes 0.51666, and after another 1/60 seconds (when `_physics_process` is called next), the new value becomes 0.53333, etc. After 1 second, the thrust value is at 1.5 and still increasing by delta at every delta, so it keeps accelerating.

If you are after a constant speed change when the control is pressed, you probably want to record the first button press, increase by a fixed predetermined amount (you can experiment to find the right amount), and then record when the button is released and decrease by the same amount again. In other words, don't use delta at all. That way, you avoid the acceleration. I hope that helps. :)
> 1 votes

---
Tags: godot, control, motion-control
---


# Question
Title: What is the difference between Serializable, and System.Serializable?
What is the difference between `Serializable`, and `System.Serializable`?

I'm guessing `SerializeField` is only for attributes of a class. What is the difference between the above two, then?

# Answer
> 2 votes
Unless I'm mistaken, there is no difference - `System.Serializable` is just the fully qualified name of `Serializable`.

C# has this notions of *namespaces*; a namespace is a way to organize code (it's a "space for (type) names") - think of a namespace as of a box that contain stuff you might want to use. This helps organize things and avoid naming conflicts (if, say, two independently developed libraries use the same name for a class).

So, the Serializable attribute is declared/placed within the System namespace. When you say `System.Serializable`, you're just saying "get Serializable from System".

But if you have a `using System;` statement at the top, you can omit the namespace and just write `Serializable`; the compiler can then infer that it means `System.Serializable`, saving you a few keystrokes.

---
Tags: unity, serialization
---


# Question
Title: Adventure Games - When and how to start mapping?
I've created a playable oblique-styled adventure game in HTML5, using Tiled for tilemapping. I have a storyline set up, and am ready to make my final draft map.

The game world will be loosely based on areas of East Asia.

The issue is, my game is more dependent on player interacting with NPCs than on locations. How do you go about designing a map? Should I throw down the loose representation of a city, and then fit my game into it?

I guess I'm not sure how you'd go about creating a meaningful map for an adventure game or of any special considerations.

While I'm looking for an objective answer, opinions can help a lot too.

# Answer
There is a reason the Thriving Ghost Town \- villages represented by about 3 buildings and huge metropoles represented by about 20 - is such a common trope in games. Even a small town of realistic size would be far too large for most story-focused game concepts. You simply don't have the resources to add content to make all of it interesting, and even if you would, it would just end up distracting from your main plot. So exploring and navigating it will inevitably become tedious and boring for the player.

So you usually tightly pack all story- and gameplay-relevant locations of your game into small, densely-packed maps. Avoid adding any locations which are irrelevant to the player, except when it's for aesthetics. When you feel that such unrealistically small cities break immersion too much (usually they don't - players are quite used to this), you can hand-wave it by implying that the parts of a city the player can explore is just a very small part of it and the city is actually much larger. An interesting way to do this is by having an overview map the player can navigate on which highlights "areas of interest" the player can explore but also implies that there is quite a lot of "uninteresting" city between them they wouldn't want to explore anyway when they could, like in this example from Baldur's Gate:
> 2 votes

# Answer
There is a concept in writing called "economy". You often encounter it as part of the phrase "economy of character" or "economy of plot".

Readers have to become immersed in the story. They have to get to know each character to be able to build a relationship, to care about them to the level that you need for your story to have impact. That means you have to tell stories involving each character that show off their personality, their motivations etc.

The more characters or locations you have, the more such background you need to provide, and the longer it takes until you can start telling the actual story. This is why writers are encouraged to be economical about characters, to reduce the number of characters in the story. One way to do this is to "merge" several characters into one (which is why so many unvelievable things happen to the same person in long-running TV shows).

The same applies to your game's story, the setting, the characters. Try to have your game take place in the smallest number of locations you can. Avoid long "empty spaces" between the locations with nothing to do for the player, just because they would exist in the real world. They are just an annoyance that the player has to click past when moving back and forth between two of the important locations.

Instead, plan your few locations so they optimize gameplay. Place related locations (e.g. locations that are part of the same puzzle) near each other, or provide some kind of fast travel between them (maybe a door that unlocks only from one side), so that once they've encountered all the parts of the puzzle and can be expected to know what they have to do, they can just pop back and forth and finish the puzzle.

Also, don't be afraid to "close down" "suburbs" that are done. Many games put you in one suburb, then once you've solved all the puzzles there, open the path to the next suburb (which they make the player's goal from the start), and give them no way back. This means that each suburb is self-contained, and you don't have to worry that a player leaving an item behind in suburb A might make it impossible to solve the puzzle in suburb B, because items in one suburb do not affect those in another one.

This way, not only does it become easier for you to avoid game-breaking bugs, but it is also clear to players that they don't have to rummage through the previous suburb's locations when they can't find a solution in the current suburb.

(Which of course doesn't mean there should be only one suburb open at a time -- one of my favorite aspects of adventures is that if I am stuck in one suburb, I can go to another one and solve the puzzles there, and then go back with a fresh mind and probably solve the puzzle)

And finally, it makes it more likely that you will actually manage to finish building the game before your budget runs out. And you can always go back and add side quests once the core game is done. Build your "minimum viable product", then go back and flesh out the game with more locations if you think they add something and don't slow down the core of the game.
> 0 votes

---
Tags: tilemap, tiles, adventure-games
---