Menu
CoddyTech

长大

Coddy Unity 3D 贪吃蛇游戏 课程的第 8 课,共 14 课。

吃东西会让蛇增加一节。新的一节会出现在这一步开始前尾巴末端所在的位置:尾巴向前移动,新的一节填入尾巴末端离开的格子,所以蛇会从后面变长。

尾巴移动后,那个格子就不在蛇身上了,所以要先记住它。然后,当蛇头到达食物时,在那里实例化一节并将其添加到列表中,这样从下一步开始它就会跟着移动。创建了却没有添加的一节永远不会移动。火车也会用同样的方式在后面加一节车厢:

Vector3 back = wagons[wagons.Count - 1].position;
// ……火车继续行驶……
Transform wagon = Instantiate(wagonPrefab, back, Quaternion.identity);
wagons.Add(wagon);

在调用 Eat() 之前先增长。Eat() 会移动食物,而下一课会让它寻找蛇身没有占据的格子,其中也包括新的一节。

challenge icon

挑战

中等

每吃到一个食物,蛇尾就会增加一节。

  1. 在 Snake 中,添加 public Transform segmentPrefab;(场景会将它关联起来)。
  2. 在 Step() 中,蛇尾移动前,保存 Vector3 tailEnd:它表示最后一节蛇身所在的格子;如果蛇尾为空,则表示蛇头所在的格子。
  3. 吃到食物时,将 Instantiate(segmentPrefab, tailEnd, Quaternion.identity) 添加到 tail,然后调用 Eat()。

点击“开始”,吃几个食物:蛇每次都会长出一个方块。然后点击“检查”。

亲手试试

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Snake : MonoBehaviour
{
    public float tick = 0.15f;   // 每两步之间的间隔秒数
    public int edge = 7;         // 棋盘格子的范围从 -edge 到 edge
    public bool alive = true;
    public List<Transform> tail = new List<Transform>();
    private float timer;
    private Vector3 direction = Vector3.right;       // 蛇头上一步移动的方向
    private Vector3 nextDirection = Vector3.right;   // 等待下一步执行的转向

    void Update()
    {
        if (!alive) return;

        Keyboard keyboard = Keyboard.current;
        if (keyboard != null)
        {
            if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) Turn(Vector3.forward);
            if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) Turn(Vector3.back);
            if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) Turn(Vector3.left);
            if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) Turn(Vector3.right);
        }

        timer += Time.deltaTime;
        if (timer >= tick)
        {
            timer -= tick;
            Step();
        }
    }

    void Turn(Vector3 newDirection)
    {
        if (newDirection != -direction)
        {
            nextDirection = newDirection;
        }
    }

    void Step()
    {
        direction = nextDirection;
        Vector3 next = transform.position + direction;
        if (Mathf.Abs(next.x) > edge || Mathf.Abs(next.z) > edge)
        {
            Die();
            return;
        }

        for (int i = tail.Count - 1; i > 0; i--)
        {
            tail[i].position = tail[i - 1].position;
        }
        if (tail.Count > 0)
        {
            tail[0].position = transform.position;
        }
        transform.position = next;

        if (GameManager.Instance.IsFood(next))
        {
            GameManager.Instance.Eat();
        }
    }

    void Die()
    {
        alive = false;
    }
}

Unity 3D 贪吃蛇游戏中的所有课

自己练习: Unity 在线编辑器