المستوى التالي
الدرس 12 من 19 في دورة لعبة Unity: كاسر الطوب على Coddy.
يُكتمل المستوى عند تحطّم آخر طوبة فيه. العدّ: أضف واحدًا لكل طوبة تُبنى، واطرح واحدًا لكل طوبة تتحطّم، وعندما يصل العدد إلى 0 يكون المستوى قد اكتمل.
لا يفيد عدّ الطوب الذي لا يزال في المشهد في تلك اللحظة: إذ تنتظر Destroy حتى نهاية الإطار، لذا تبقى الطوبة التي تتحطّم موجودة.
بعد المستوى الأخير يأتي الأول مجددًا. باقي القسمة يعيد العدد إلى بدايته:
int next = (2 + 1) % 3; // 0: بعد الفهرس 2 من أصل 3 مستويات، نعود إلى 0تعود الكرة إلى المضرب أولًا، كي لا يبدأ الجدار الجديد والكرة منطلقة في الهواء.
التحدي
متوسطيؤدي تكسير الطوب إلى بناء المستوى التالي.
- في
GameManager، أضفpublic Ball ball;(يربطه المشهد) وint bricksLeft;؛ وتضيف BuildLevel واحدًا لكل قطعة طوب تبنيها. - تُنقص BrickBroken قيمة bricksLeft بمقدار واحد. عند وصولها إلى 0، استدعِ
ball.ResetToPaddle();وBuildLevel((level + 1) % levels.Length);
اضغط على «العب» واجتز مستوى: تنتظر الكرة على المضرب ويظهر جدار جديد. ثم اضغط على «تحقق».
جرّب بنفسك
using UnityEngine;
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 int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
int score;
int level;
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');
}
}
}
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: كاسر الطوب
تدرّب بنفسك: Playground لـ Unity