次のレベル
Coddyの「Unityゲーム:ブロック崩し」コースのレッスン 12/19。
最後のブロックが壊れると、レベルクリアです。カウントは、ブロックを作るたびに1増やし、壊れるたびに1減らします。0になるとレベルクリアです。
その瞬間にシーンに残っているブロックを数えても機能しません。Destroyはフレームの終わりまで実行されないため、壊れているブロックがまだ存在しているからです。
最後のレベルの次は、再び最初のレベルです。割り算の余りを使うと、数を一周させることができます。
int next = (2 + 1) % 3; // 0: 3つのレベルのうちインデックス2の次は0に戻る新しい壁の下でボールが飛んでいる状態にならないように、まずボールをパドルに戻します。
チャレンジ
中級ブロックをすべて消すと、次のレベルが始まります。
GameManagerにpublic Ball ball;(シーンで関連付けます)とint bricksLeft;を追加します。BuildLevelでは、ブロックを1つ作るごとに値を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プレイグラウンド