三个球
Coddy Unity 游戏:打砖块 课程的第 17 课,共 19 课。
多球道具会将球一分为二:两个球从它所在的位置飞出。Instantiate 会像复制预制体那样复制场景对象,但只有 Inspector 会保存的内容会被复制过来:公共字段和 [SerializeField] 字段,例如 speed 和 paddle。像 launched 这样的私有字段初始值为 false,速度初始值为零,因此必须发射副本,否则它会停留在球拍上。
Ball copy = Instantiate(source, source.transform.position, Quaternion.identity);
copy.Launch(new Vector3(0.2f, 1f, 0f));GameManager 会用一个 List<Ball> 保存所有正在游戏中的球,以便之后找到它们。
挑战
困难接住多球强化道具,球就会分成三个。
- 在
GameManager中添加List<Ball> balls = new List<Ball>();(并添加using System.Collections.Generic;);在 Start() 中先将ball添加到其中。 - 编写
public void SplitBall():在balls[0]的位置创建两个副本,分别朝(-0.6f, 1f, 0f)和(0.6f, 1f, 0f)的方向发射,并将它们都添加到 balls 中。 - 在
PowerUp中,多球强化道具调用GameManager.Instance.SplitBall()。
按下“开始”并接住一个粉色道具:三个球就会飞起来。然后点击“检查”。
亲手试试
using UnityEngine;
using UnityEngine.SceneManagement;
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 Ball ball;
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
public GameObject gameOverPanel;
public GameObject[] powerUps;
public float dropChance = 0.15f;
int score;
int level;
int bricksLeft;
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');
bricksLeft++;
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
bricksLeft--;
ShowHud();
if (Random.value < dropChance)
{
GameObject prefab = powerUps[Random.Range(0, powerUps.Length)];
Instantiate(prefab, brick.transform.position, Quaternion.identity);
}
if (bricksLeft == 0)
{
ball.ResetToPaddle();
BuildLevel((level + 1) % levels.Length);
}
}
public void BallLost(Ball lost)
{
lives--;
ShowHud();
if (lives == 0)
{
gameOverPanel.SetActive(true);
lost.gameObject.SetActive(false);
}
else lost.ResetToPaddle();
}
public void PlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
Unity 游戏:打砖块中的所有课
自己练习: Unity 在线编辑器