Menu
CoddyTech

テキストからレベルを作る

Coddyの「Unityゲーム:ブロック崩し」コースのレッスン 11/19。

レベルのあるゲームでは、レベルを記述する方法が必要です。最も簡単なのはテキストです。レンガ1個につき1文字、1行につき1つの文字列を使います。ここでは、数字はその回数だけ当てる必要があるレンガ、ピリオドは空白を表し、レベルの各行は/で分割された1つの文字列にまとめられます。そのため、シーンのlevelsには3つの配置が格納され、最初の配置が今日の壁になります。

string[] rows = "1.1/22".Split('/');   // "1.1" と "22"
char c = rows[1][0];                     // '2'

数字の文字は数値ではありません。'3'は、コードが51のcharです。数字のコードは順番に並んでいるので、'0'を引くと数値になります。'3' - '0'はintの3です。各行は、それぞれの長さを基準に中央揃えします。-(line.Length - 1) * spacingX / 2f。

challenge icon

チャレンジ

中級

3.3.3/22222のようなテキストから壁を作ります。

  1. GameManagerで、rows、columns、rowHitsを削除し、public string[] levels;とint level;を追加します。
  2. BuildWall()をBuildLevel(int index)に置き換えます。indexをlevelに格納し、levels[index]を'/'で分割します。各数字cについて、SetHits(c - '0')を使って中央揃えのブロックを作ります。ドットは空きになります。
  3. Start()からBuildLevel(0)を呼び出します。

「プレイ」を押します。同じ壁が、最初のレベルのテキストから作られます。その後、「確認」を押します。

自分で試してみよう

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

Unityゲーム:ブロック崩しのすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド