Menu
CoddyTech

撞上了!

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 79 课,共 85 课。

challenge icon

挑战

中等

当方块碰到跑者时结束游戏。

  1. 在方块循环中,方块移动后,将它的位置读取为 Vector3 b。
  2. 当 Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f 时,记录 Game over,设置 enabled = false;,然后执行 return;。

按“开始”,让一个方块落到你身上:控制台会显示 Game over,然后一切都会停止。接着按“检查”。

亲手试试

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

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器