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:
- Blocks do not fall down to the lowest row
- 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.
- If there is only a single space between blocks, then the block above will only move .016694 rather than a full 1
- 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:
And here’s an edited version showing what should happen: