Menu
CoddyTech

꼬리

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

꼬리는 머리 바로 뒤에 있는 tail[0]부터 끝까지의 세그먼트 목록인 List<Transform> tail입니다. 장면에서는 Inspector에서 Tail1과 Tail2라는 두 개의 세그먼트로 뱀을 시작합니다.

각 단계에서 모든 세그먼트는 바로 앞에 있는 세그먼트의 칸으로 이동하고, tail[0]은 머리가 있던 칸으로 이동합니다. 순서가 중요합니다. 앞에서부터 이동하면 tail[1]은 이미 이동한 tail[0]의 칸을 복사하게 되고, 꼬리 전체가 한 칸에 겹쳐 쌓입니다. 뒤에서부터 이동하면 각 세그먼트는 아직 바뀌지 않은 칸을 복사합니다. 승객들이 한 자리씩 뒤로 이동하는 것도 같은 방식입니다.

string[] seats = { "Ana", "Ben", "Cy" };
for (int i = seats.Length - 1; i > 0; i--)
{
    seats[i] = seats[i - 1];
}
seats[0] = "Dee";   // Dee, Ana, Ben

tail[0]이 이전 칸으로 이동한 다음에 머리가 마지막으로 한 번 이동합니다.

challenge icon

챌린지

중급
  1. using System.Collections.Generic;와 public List<Transform> tail = new List<Transform>();를 추가하세요. 씬에서 이 목록을 Tail1과 Tail2로 채웁니다.
  2. 머리가 움직이기 바로 전에 Step()에서 꼬리를 이동시키세요. 뒤쪽 세그먼트부터 앞에 있는 세그먼트의 칸으로 이동하고, tail[0]은 머리가 있던 칸으로 이동합니다.

Play를 눌러 방향을 조작해 보세요. 꼬리가 머리가 지나간 경로를 따라옵니다. 그런 다음 Check를 누르세요.

직접 해보기

using UnityEngine;
using UnityEngine.InputSystem;

public class Snake : MonoBehaviour
{
    public float tick = 0.15f;   // 두 칸 이동 사이의 시간(초)
    public int edge = 7;         // 보드의 칸 범위는 -edge부터 edge까지
    public bool alive = true;
    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;
        }

        transform.position = next;

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

    void Die()
    {
        alive = false;
    }
}
quiz icon실력 점검

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

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