Menu
CoddyTech

着陆或错过

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

这个挑战完成了塔楼游戏,也完成了课程的第一个单元:起重机、下落的方块,以及使用 Mathf.Abs 进行的着陆测试。

challenge icon

挑战

困难

让每个方块落到堆叠上,或者掉落下去。

  1. 当下落方块的 y 坐标降到 top 的 y + 1,并且 x 坐标与 top 的 x 相差不到 1 时,将它的 y 坐标设为该值,将它设为 top,清空 falling,并记录 "Stack: " + count。
  2. 否则,当它低于 y = -3 时,销毁它,清空 falling,并记录 Missed!。

按“开始”并堆叠方块:每次方块落下都会记录堆叠高度。然后点击“检查”。

亲手试试

using UnityEngine;

public class Crane : MonoBehaviour
{
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private Transform top;
    [SerializeField] private float craneSpeed = 3f;
    [SerializeField] private float craneEdge = 4f;
    [SerializeField] private float fallSpeed = 7f;

    private float direction = 1f;
    private Transform falling;
    private int stack;

    void Update()
    {
        transform.position += new Vector3(direction * craneSpeed * Time.deltaTime, 0f, 0f);
        if (transform.position.x > craneEdge) direction = -1f;
        if (transform.position.x < -craneEdge) direction = 1f;

        bool drop = Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0);
        if (drop && falling == null)
        {
            Vector3 spot = new Vector3(transform.position.x, transform.position.y - 1f, 0f);
            falling = Instantiate(blockPrefab, spot, Quaternion.identity).transform;
        }

        if (falling != null)
        {
            falling.position += Vector3.down * fallSpeed * Time.deltaTime;
            // 落到堆叠的方块上:下一课再讲。
        }
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器