Menu
CoddyTech

Va chạ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 79 trên 85.

challenge icon

Thử thách

Trung bình

Kết thúc trò chơi khi một khối chạm vào nhân vật chạy.

  1. Trong vòng lặp các khối, sau khi một khối di chuyển, hãy đọc vị trí của nó dưới dạng Vector3 b.
  2. Khi Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f, hãy ghi nhật ký Game over, đặt enabled = false; và return;.

Nhấn Chơi và để một khối rơi trúng bạn: Console hiển thị Game over và mọi thứ dừng lại. 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;
            if (blocks[i].transform.position.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}

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