下一关
Coddy Unity 游戏:打砖块 课程的第 12 课,共 19 课。
最后一块砖被打破时,这一关就通关了。计数规则:每生成一块砖,计数加一;每打破一块砖,计数减一;计数为 0 时,这一关就结束。
此时统计场景中剩余的砖块行不通:Destroy 会等到当前帧结束时才执行,所以正在被打破的砖块仍然存在。
最后一关之后会回到第一关。除法的余数可以让数字循环回绕:
int next = (2 + 1) % 3; // 0:经过 3 个层级中索引为 2 的层级后,回到 0球会先回到球拍上,这样新一面砖墙就不会在球飞行时开始出现。
挑战
中等清除砖块后会生成下一关。
- 在
GameManager中,添加public Ball ball;(在场景中将其关联)和int bricksLeft;;BuildLevel 每生成一块砖,就将其加 1。 - BrickBroken 将 bricksLeft 减 1。当它变为 0 时,调用
ball.ResetToPaddle();和BuildLevel((level + 1) % levels.Length);
按下 开始 并清除一关:球会停在挡板上,同时出现一面新的砖墙。然后点击 检查。
亲手试试
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public string[] levels;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
int score;
int level;
void Awake()
{
Instance = this;
}
void Start()
{
BuildLevel(0);
ShowHud();
}
void BuildLevel(int index)
{
level = index;
string[] rows = levels[index].Split('/');
for (int row = 0; row < rows.Length; row++)
{
string line = rows[row];
float left = -(line.Length - 1) * spacingX / 2f;
for (int col = 0; col < line.Length; col++)
{
char c = line[col];
if (c == '.') continue;
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(c - '0');
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
ShowHud();
}
public void BallLost(Ball lost)
{
lives--;
ShowHud();
lost.ResetToPaddle();
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
Unity 游戏:打砖块中的所有课
自己练习: Unity 在线编辑器