Menu
CoddyTech

ボールを失う

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

パドルを通り過ぎたボールは失われます。パドルの下には現在、DeathZone があります。これは、Is Trigger が設定されたボックスコライダーと DeathZone タグを持つオブジェクトです。トリガーは何も止めません。Rigidbody を持つものが入ると、OnTriggerEnter(Collider other) を送信します。ボールは GameManager にミスを報告します。GameManager は残りライフを管理し、次に何が起こるかを決定します。

水に落ちたビー玉は、スポーン地点から再びスタートします。

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Water")) Respawn();
}

void Respawn()
{
    rb.linearVelocity = Vector3.zero;
    transform.position = spawnPoint.position;
}

ボールに必要なのは、ビー玉の場合より少ない処理です。launched が false の間は、すでに Update() が毎フレームボールをパドル上に配置するため、リセットではそのフラグをクリアしてボールを停止するだけで済みます。次のフレームでボールはパドルに戻り、もう一度 Space キーを押すと発射されます。

challenge icon

チャレンジ

中級
  1. Ballでpublic void ResetToPaddle()を記述します。ボールは発射されていない状態になり、動きを止めます。
  2. BallにOnTriggerEnterを追加します。DeathZoneタグが付いたオブジェクトに入ったとき、GameManager.Instance.BallLost(this)を呼び出します。
  3. GameManagerにpublic int lives = 3とpublic void BallLost(Ball lost)を追加します。ライフを1つ減らし、失われたボールをパドルに戻します。

まだゲームオーバーの処理はないため、ライフはひとまず0未満まで減ります。

Playを押し、わざとボールを打ち損ねてから、もう一度発射し、その後Checkを押します。

自分で試してみよう

using UnityEngine;

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

    int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        BuildWall();
    }

    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;
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

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