Menu
CoddyTech

墙

Coddy Unity 游戏:打砖块 课程的第 5 课,共 19 课。

砖块排列成网格:行从上到下,列从左到右。通过两个嵌套循环,每个砖块都是由 Brick 预制体创建的。先创建一行:

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);
}

n 列之间有 n - 1 个间隔,因此最左边的砖块距离中心为 (n - 1) * spacing 的一半:5 列砖块间隔为 2 时,位置分别是 -4、-2、0、2 和 4。每一行都比上一行低 spacingY。Instantiate 的第四个参数是父对象,因此每块砖都位于 Wall 对象下。将脚本类型(例如 Brick)用作预制体字段时,Instantiate 会返回新砖块的脚本。

challenge icon

挑战

中等

搭建一面居中的砖块墙。

  1. 在 GameManager 中添加 public Brick brickPrefab;、public Transform wall;、rows = 5、columns = 9、spacingX = 1.75f、spacingY = 0.75f、topY = 6f。
  2. BuildWall():每行和每列都在 wall 下放置一个砖块,x 坐标为 left + col * spacingX,y 坐标为 topY - row * spacingY,z 坐标为 0,其中 left = -(columns - 1) * spacingX / 2f。
  3. Start() 调用 BuildWall()。

按下 Play:45 块砖排成网格(它们暂时还不会破碎)。然后点击 Check。

亲手试试

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    void Awake()
    {
        Instance = this;
    }

    // 之后再添加砖墙、分数、生命值和关卡。
}

Unity 游戏:打砖块中的所有课

自己练习: Unity 在线编辑器