Menu
CoddyTech

점점 더 빠르게

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

Snake는 성장할수록 더 어려워집니다. 먹이를 먹을 때마다 틱이 조금씩 짧아져 뱀이 더 빠르게 움직입니다. 바닥값을 두면 게임을 계속 플레이할 수 있습니다. 틱이 도달할 수 있는 최솟값입니다.

Mathf.Max는 두 숫자 중 더 큰 값을 반환하므로 바닥값을 설정할 수 있습니다. Mathf.Max(value, floor)는 절대로 floor보다 작지 않습니다. 업그레이드할 때마다 더 빠르게 발사하지만, 0.2초보다 더 자주 발사하지는 않는 포탑은 다음과 같습니다.

cooldown = Mathf.Max(cooldown - 0.05f, 0.2f);

Mathf.Min은 그 반대인 천장값입니다. 둘을 혼동하기 쉽습니다. 위 예시에서 Min을 사용하면 첫 번째 업그레이드에서 쿨다운이 0.2로 줄어듭니다. Update()의 타이머는 매 프레임마다 tick을 읽으므로, 틱이 짧아지면 다음 단계부터 카운트됩니다.

challenge icon

챌린지

어려움
  1. public float speedUp = 0.005f;와 public float minTick = 0.08f;를 Snake에 추가하세요.
  2. 뱀이 먹이를 먹으면 tick을 speedUp만큼 짧게 하되, minTick보다 짧아지지 않도록 하세요.

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;
        }

        for (int i = 0; i < tail.Count - 1; i++)
        {
            if (tail[i].position == next)
            {
                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;
        GameManager.Instance.GameOver();
    }
}
quiz icon실력 점검

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

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