レベルクリア
Coddyの「Unityゲーム:ブロック崩し」コースのレッスン 11/16。
レベルのあるゲームでは、レベルを記述する方法が必要です。最も簡単なのはテキストです。レンガ1個につき1文字、行ごとに1つの文字列を使います。このゲームでは、数字はその数だけ耐久値があるレンガ、ドットは隙間を表します。レベルの各行を1つの文字列にまとめ、/で区切ることで、Inspectorの1行にレベルを収められます。Split('/')は文字列を分割して、行の配列にします。テキストから植えた庭です。
string layout = "t.t.t/.ttt.";
string[] rows = layout.Split('/');
for (int row = 0; row < rows.Length; row++)
for (int col = 0; col < rows[row].Length; col++)
if (rows[row][col] == 't') Instantiate(treePrefab, new Vector3(col, 0f, -row), Quaternion.identity);数字の文字は、その数値そのものではありません。'3'はコードが51のcharです。10個の数字は順番にコードが割り当てられているので、'0'(コード48)を引くと数値になります。つまり、'3' - '0'はintの3です。
最後のレンガが壊れるとレベルクリアです。数え方は、レンガを作るたびに1を加算し、レンガが壊れるたびに1を減算して、0になったらレベル完了です。その時点でシーンに残っているレンガを数える方法は使えません。Destroyはフレームの最後まで実行を待つため、壊れているレンガがまだ存在するからです。
チャレンジ
中級テキストからブロックを作成します。シーンではlevelsに3つのレイアウトを設定します。最初のレイアウトは、現在の壁です。
GameManagerで、rows、columns、rowHitsを削除します。public string[] levels、public Ball ball(シーンでBallをリンクします)、int level、int bricksLeftを追加します。BuildWall()をvoid BuildLevel(int index)に置き換えます。このメソッドはindexをlevelに格納し、levels[index]を/で行に分割します。各数字cについて、c - '0'回ヒットすると壊れるブロックを作成し、bricksLeftに1を加えます。ドットは空のままです。行はこれまでと同様に中央揃えで間隔を空けます。Start()からBuildLevel(0)を呼び出します。BrickBrokenで、bricksLeftから1を引きます。0になったら、ボールをパドルに戻して次のレベルを作成します。最後のレベルの次は、最初のレベルに戻ります。
Playを押して、できればレベルをクリアしてから、Checkを押してください。
自分で試してみよう
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public int rows = 5;
public int columns = 9;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public int[] rowHits = { 2, 1, 1, 1, 1 };
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
int score;
void Awake()
{
Instance = this;
}
void Start()
{
BuildWall();
ShowHud();
}
void BuildWall()
{
float left = -(columns - 1) * spacingX / 2f;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(rowHits[row]);
}
}
}
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;
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。