The Wall
Lesson 5 of 19 in Coddy's Unity Game: Brick Breaker course.
The bricks stand in a grid: rows from the top down, columns left to right, each a copy of the Brick prefab made in two nested loops. One row first:
float left = -(columns - 1) * spacingX / 2f;
for (int col = 0; col < columns; col++)
{
Vector3 pos = new Vector3(left + col * spacingX, topY, 0f);
Instantiate(brickPrefab, pos, Quaternion.identity, wall);
}Between n columns there are n minus 1 gaps, so the first one is half of (n - 1) * spacing to the left: 5 columns 2 apart stand at -4, -2, 0, 2 and 4. Each row goes spacingY lower than the last. The fourth argument of Instantiate is the parent, so every brick sits under the Wall object. With a script type such as Brick as the prefab field, Instantiate returns the new brick's script.
Challenge
MediumBuild a centered wall of bricks.
- In
GameManager, addpublic Brick brickPrefab;,public Transform wall;,rows = 5,columns = 9,spacingX = 1.75f,spacingY = 0.75f,topY = 6f. BuildWall(): a brick underwallfor each row and col, at xleft + col * spacingX, ytopY - row * spacingY, z 0, withleft = -(columns - 1) * spacingX / 2f.Start()callsBuildWall().
Press Play: 45 bricks stand in a grid (they do not break yet). Then Check.
Try it yourself
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
void Awake()
{
Instance = this;
}
// Later: the wall of bricks, the score, the lives and the levels.
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground