المستويات من النص
الدرس 11 من 19 في دورة لعبة Unity: كاسر الطوب على Coddy.
تحتاج اللعبة ذات المستويات إلى طريقة لتدوينها. النص هو الأسهل: محرف واحد لكل لبنة، وسلسلة واحدة لكل صف. هنا، الرقم هو لبنة لها عدد إصابات يساوي قيمته، والنقطة فجوة، وصفوف المستوى موجودة في سلسلة واحدة مقسّمة باستخدام /، لذا تحتوي levels في المشهد على ثلاثة تخطيطات، والأول منها هو الجدار الحالي.
string[] rows = "1.1/22".Split('/'); // "1.1" و"22"
char c = rows[1][0]; // '2'محرف الرقم ليس الرقم نفسه: '3' هو محرف من نوع char ورمزه 51. رموز الأرقام مرتبة، لذا فإن طرح '0' يعطي الرقم: '3' - '0' يساوي العدد الصحيح 3. يتم توسيط كل صف وفقًا لطوله، -(line.Length - 1) * spacingX / 2f.
التحدي
متوسطابنِ الجدار من نص، مثل 3.3.3/22222.
- في
GameManager، احذف rows وcolumns وrowHits؛ وأضفpublic string[] levels;وint level; - استبدل BuildWall() بـ
BuildLevel(int index): خزّن index في level، وقسّمlevels[index]عند'/'، وأنشئ لبنةً في المنتصف لكل رقمcباستخدامSetHits(c - '0')؛ النقطة فراغ. - تستدعي
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: كاسر الطوب
تدرّب بنفسك: Playground لـ Unity