Menu
CoddyTech

دعها تسقط

جزء من قسم أساسيات البرمجة النصية في Unity في رحلة Unity على Coddy. الدرس 77 من 85.

challenge icon

التحدي

متوسط

اجعل كل كتلة في القائمة تسقط. احتفظ بكل ما أنجزته في الخطوات السابقة.

  1. أضف [SerializeField] private float fallSpeed = 5f;.
  2. في نهاية Update()، استخدم حلقة foreach (GameObject block in blocks).
  3. أضف فيها Vector3.down * fallSpeed * Time.deltaTime إلى block.transform.position.

اضغط على «العب»: ستهطل الكتل متجاوزةً العداء. ثم اضغط على «تحقق».

جرّب بنفسك

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer -= spawnEvery;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }
    }
}

جميع دروس أساسيات البرمجة النصية في Unity

تدرّب بنفسك: Playground لـ Unity