Menu
CoddyTech

丢掉一个球

Coddy Unity 游戏:打砖块 课程的第 8 课,共 19 课。

越过挡板的球就算丢失了。现在,挡板下方的场景中有一个 DeathZone:这是一个带有盒型碰撞体的对象,其 Is Trigger 已启用,标签为 DeathZone。触发器不会阻挡任何东西;当带有 Rigidbody 的物体进入触发器时,它会发送 OnTriggerEnter(Collider other)。球会将丢失情况报告给 GameManager,由它管理生命值并决定接下来要做什么。

掉进水里的弹珠会回到生成点:

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

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

球的处理比弹珠简单。它的 Update() 已经会在每一帧将球放到挡板上,前提是 launched 为 false,因此重置时只需清除该标志并让球停下:下一帧会将球带回挡板上,然后你可以再次按 Space 发射它。

challenge icon

挑战

中等

没接住球会损失一条命,并让球回到挡板上。

  1. 在 Ball 中,编写 public void ResetToPaddle():设置 launched = false;,并将速度设为 Vector3.zero。
  2. 在 Ball 的 OnTriggerEnter 中,进入标签为 DeathZone 的对象时,调用 GameManager.Instance.BallLost(this)。
  3. 在 GameManager 中,添加 public int lives = 3; 和 public void BallLost(Ball lost):减少一条命,然后调用 lost.ResetToPaddle();

按下“开始”并故意错过球:球会再次停在挡板上。然后点击“检查”。

亲手试试

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 游戏:打砖块中的所有课

自己练习: Unity 在线编辑器