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

챌린지

중급

Step()에서 벽 검사 후, next가 마지막 꼬리 부분을 제외한 다른 꼬리 부분의 칸이라면 Die()를 호출하고 반환하여 머리가 움직이지 않도록 합니다.

Play를 누르고 뱀을 길게 키운 다음 자신의 꼬리를 물고, Check를 누릅니다.

직접 해보기

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;
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

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