ثلاث كرات
الدرس 17 من 19 في دورة لعبة Unity: كاسر الطوب على Coddy.
يقسم تعزيز تعدد الكرات الكرة إلى نسختين تطيران من موضعها. تنسخ 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;)؛ وأضفballإليها أولًا في Start(). - اكتب
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: كاسر الطوب
تدرّب بنفسك: Playground لـ Unity