Menu
CoddyTech

자기 자신을 물기

Coddy의 Unity 게임: 3D 스네이크 코스 레슨. 14개 중 10번째.

뱀은 벽에 부딪힐 때처럼 머리가 자기 꼬리에 부딪히면 죽습니다. 검사는 같은 위치, 즉 머리가 움직이기 전에 앞에 있는 칸인 next에서 수행하므로 게임이 끝날 때 머리는 그 자리에 그대로 있습니다.

한 세그먼트는 안전합니다. 이 단계에서는 마지막 세그먼트도 위로 이동해 자기 칸에서 빠져나오므로, 꼬리 끝을 따라 그 칸으로 들어가는 머리는 마지막 세그먼트에 절대 닿지 않습니다. 큐브 네 개로 이루어진 뱀은 이런 방식으로 2 x 2 정사각형을 영원히 돌 수 있습니다. 검사는 마지막 세그먼트를 제외하도록 끝에서 하나 앞까지만 반복합니다:

// 마지막 항목을 제외한 모든 항목
for (int i = 0; i < items.Count - 1; i++)
{
    Debug.Log(items[i].name);
}

벽과 꼬리 모두 치명적이므로 게임에서 질 수 있으며, 다음 장에서는 점수와 다시 플레이하는 방법을 추가합니다.

challenge icon

챌린지

중급

꼬리를 물면 게임이 끝납니다.

  1. Step()에서 벽 검사 후, i < tail.Count - 1 조건으로 꼬리를 반복해 확인하고 마지막 세그먼트는 제외합니다.
  2. tail[i].position == next이면 Die()를 호출하고 반환하여 머리가 움직이지 않도록 합니다.

‘플레이’를 누르고, 뱀을 길게 만든 다음 꼬리 쪽으로 방향을 틀어 보세요. 뱀이 멈춥니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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>();
    public Transform segmentPrefab;
    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;
        }

        Vector3 tailEnd = tail.Count > 0 ? tail[tail.Count - 1].position : transform.position;
        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))
        {
            tail.Add(Instantiate(segmentPrefab, tailEnd, Quaternion.identity));
            GameManager.Instance.Eat();
        }
    }

    public bool Occupies(Vector3 cell)
    {
        if (transform.position == cell) return true;
        foreach (Transform segment in tail)
        {
            if (segment.position == cell) return true;
        }
        return false;
    }

    void Die()
    {
        alive = false;
    }
}

Unity 게임: 3D 스네이크의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드