Menu
CoddyTech

Để chúng rơi

Thuộc phần Những kiến thức cơ bản về lập trình trong Unity trong hành trình Unity của Coddy. Bài học 77 trên 85.

challenge icon

Thử thách

Trung bình

Làm cho mọi khối trong danh sách rơi xuống. Giữ lại mọi thứ từ các bước trước.

  1. Thêm [SerializeField] private float fallSpeed = 5f;.
  2. Ở cuối Update(), lặp qua danh sách bằng foreach (GameObject block in blocks).
  3. Trong vòng lặp, cộng Vector3.down * fallSpeed * Time.deltaTime vào block.transform.position.

Nhấn Chơi: các khối rơi xuống qua người chạy. Sau đó nhấn Kiểm tra.

Tự làm thử

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));
        }
    }
}

Tất cả bài học trong Những kiến thức cơ bản về lập trình trong Unity

Tự luyện tập: Playground Unity