Part 6: Clearing Rows

Christiane Snyder
8/8/2016

To finish off what we’ll cover in the scope of this lesson, we’ll show you how to check if a row is full, delete the row and update/move down the other cubes in the scene.

When a block lands before another block is spawned, PuzzleSystem should check if a row is full and if so, clear it. So we’ll add the following to PuzzleSystem’s Update() function, right after checking if the CurrentBlock is null:

void Update () {

   if (CurrentBlock != null) {

       CheckRows();

    ...

And these changes inside the SpawnPiece() function:

//We have a total of 15 columns that a block can be placed in, so don't need to check rows until

//there is atleast 4 blocks because thats the minimum of what can fill the rows

if (Blocks.Count > 3) {

    CheckRows ();

}

We'll also need to add a new CheckRows() function:

public void CheckRows(){

 

   for (int i = 1; i < 21; i++) {

   //Create a list to hold all blocks that have a child cube in the 'i'th row

        List<GameObject> Row = new List<GameObject> ();

 

        //Loop through all blocks and their child cubes

        foreach (GameObject block in Blocks) {

            foreach (Transform comp in block.transform) {

                if (Mathf.RoundToInt(comp.position.y) == i) {

                    Row.Add (comp.gameObject);

                }

            }

        }

        //If the row list has 15 cubes in it, the row is full. Delete these gameobjects

       if (Row.Count > 14) {

           List<GameObject> ToDelete = new List<GameObject> ();

           foreach (GameObject comp in Row) {

               Destroy (comp);

           }

           //Delete any blocks that now have no child cubes

           //If the block still ha child cubes, recalculate their row values since

           //        a row has been deleted

           foreach (GameObject block in Blocks) {

               if (block.transform.childCount == 0) {

                   ToDelete.Add (block);

               } else {

                   block.GetComponent<Block> ().Recalculate (i);

               }

           }

 

           //After deleting a row, delete all empty blocks

           for(int d = ToDelete.Count -1 ; d >=0; d--){

               Blocks.Remove (ToDelete[d]);

               Destroy(ToDelete[d]);

           }

       }

  }

}

 

We’ll have each of the blocks internally check and update their children, so add a Recalculate(int row) function to Block.cs:

public void Recalculate(int row){

   foreach (Transform child in transform){

        if(Mathf.RoundToInt(child.position.y) > row){

            float y = Mathf.Round (child.position.y - 1.0f);

            if (y < 0f) {

               y = 0f;

            }

            child.transform.position = new Vector3(Mathf.Round (child.position.x), y, 6.0f);

        }

    }

}

And that's it! You should be able to build you iOS project, load it up to your phone and play Tetris in VR!