Menu
CoddyTech

Ba mạng

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

Bước này hoàn thiện Catch the Star: một trò chơi di chuyển, tính điểm, tăng tốc rồi kết thúc, tất cả trong một tập lệnh. enabled = false tắt tập lệnh, và Unity ngừng gọi Update().

challenge icon

Thử thách

Trung bình

Bỏ lỡ ba lần thì trò chơi kết thúc.

  1. Thêm [SerializeField] private int lives = 3;.
  2. Trong else if khi bỏ lỡ, trừ 1 khỏi lives và ghi nhật ký "Missed! Lives: " + lives.
  3. Sau đó, khi lives == 0, ghi nhật ký Game over và đặt enabled = false;, thao tác này sẽ dừng Update().

Nhấn Chơi và để bỏ lỡ ba ngôi sao: Console hiển thị Game over và trò chơi dừng lại. Sau đó nhấn Kiểm tra.

Tự làm thử

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;
    [SerializeField] private float speedUp = 0.5f;
    private int score;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;

        if (Vector3.Distance(transform.position, star.position) < 1f)
        {
            score++;
            fallSpeed += speedUp;
            Debug.Log("Caught! Score: " + score);
            ResetStar();
        }
        else if (star.position.y < 0f)
        {
            ResetStar();
        }
    }

    void ResetStar()
    {
        star.position = new Vector3(Random.Range(-4f, 4f), 6f, 0f);
    }
}
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