Menu
CoddyTech

Sống sót và ghi điểm

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 80 trên 85.

Bước này hoàn thiện trò Dodge the Blocks: bộ đếm thời gian tạo khối, danh sách di chuyển và dọn dẹp khối, kiểm tra va chạm, cùng điểm số tính theo giây. (int) đặt trước một số thực sẽ loại bỏ phần thập phân.

challenge icon

Thử thách

Trung bình

Thêm điểm số và các khối rơi ngày càng nhanh.

  1. Thêm private float score; và [SerializeField] private float speedUp = 0.2f;.
  2. Ở đầu Update(), cộng Time.deltaTime vào score và cộng speedUp * Time.deltaTime vào fallSpeed.
  3. Khi va chạm, ghi nhật ký "Game over! Score: " + (int)score. (int) bỏ phần thập phân: 12.7 hiển thị thành 12.

Nhấn Chơi và cố sống sót: khi va chạm, trò chơi sẽ ghi nhật ký điểm số của bạn. 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;
    [SerializeField] private float fallSpeed = 5f;

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

        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
            Vector3 b = blocks[i].transform.position;
            if (Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f)
            {
                Debug.Log("Game over");
                enabled = false;
                return;
            }
            if (b.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

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