Why won't my blocks fall?

In my grid-based blocks game I had trouble with the falling code for the game’s blocks.

Here’s the code snippet:

void Update()
    {
        for (int i = (int)transform.position.y; i >= 0; i--)
        {
            if (transform.position.y >= 0 && SpawnBlocks.allBlocks[(int)gameObject.transform.position.x, i] == null)
            {
                StartCoroutine(LerpPosition(new Vector2(transform.position.x, i), 1));
            }
        }

        
    }


IEnumerator LerpPosition(Vector2 targetPosition, float duration)
    {
        float time = 0;
        Vector2 startPosition = transform.position;

        while (time < duration)
        {
            transform.position = Vector2.Lerp(startPosition, targetPosition, time * duration);
            time += Time.deltaTime;
            yield return null;
        }
        transform.position = targetPosition;

        SpawnBlocks.allBlocks[(int)transform.position.x, (int)transform.position.y] = gameObject;
        gameObject.name = "(" + transform.position.x.ToString() + "," + transform.position.y.ToString() + ")";
    }

Each block checks through a list to see whether there is a block beneath it. If there isn’t, then it should smoothly lerp down that many blocks to fill it in.

There are three problems occurring however:

  1. Blocks do not fall down to the lowest row
  2. Even after one block has fallen down, blocks above that block in the same column won’t go down and will be stuck up there.
  3. If there is only a single space between blocks, then the block above will only move .016694 rather than a full 1
  4. Instead of actually Lerping, blocks would just appear at the space beneath.

I do not know why the blocks act like this.

Here’s an example pic of what is happening:
178332-i1.png

And here’s an edited version showing what should happen:
178333-i2.png

Your use of Lerp is incorrect. The third parameter, where you have passed in timeElapsed needs to a value between 0 and 1. You can think of it as a percentage of the required movement. At 0 the position will at the start (initPos). At 1 the position given will be the object final position (targetPos). At 0.5 it will be exactly halfway between initPos and targetPos. In your sample, you declare a float variable and set it to zero each time you iterate in your loop, and then add Time.deltaTime * 4 (or roughly the time taken for 4 frames) so you will always get a small number for your timeElapsed (close to 0) , resulting in a position very near to initPos.

I don’t know how the code you supplied is being called but I find Lerp is easiest to use in a coroutine. There are some examples of how it is used here