벽
Coddy의 Unity 게임: 3D 스네이크 코스 레슨. 14개 중 4번째.
보드의 칸은 x축과 z축 모두 -7부터 7까지입니다. 보드의 중심이 0이므로, 한 번의 검사로 양쪽을 모두 확인할 수 있습니다. Mathf.Abs(x) > 7은 어느 쪽 경계를 넘었을 때나 true입니다.
뱀이 이동하기 전에 머리가 다음으로 들어갈 칸을 검사하면, 벽에 부딪힌 뱀이 경계 안쪽에서 끝나지 않고 마지막 칸에 머뭅니다. 경계가 4인 더 작은 보드에서는 다음과 같습니다.
Vector3 next = transform.position + direction;
if (Mathf.Abs(next.x) > 4) { Die(); return; }
transform.position = next;벽에 부딪히면 뱀은 영원히 멈춥니다. Update()가 가장 먼저 확인하는 bool이 이를 처리합니다. 맨 위의 return은 키 입력과 타이머를 모두 건너뜁니다.
챌린지
쉬움벽에 부딪히면 게임이 끝납니다.
public int edge = 7;과public bool alive = true;를 추가합니다.Step()에서 방향을 설정한 뒤Vector3 next = transform.position + direction;을 작성합니다. 보드 밖으로 나가면(Mathf.Abs(next.x) > edge또는 z)Die()를 호출하고 반환합니다. 그렇지 않으면 다음 위치로 이동합니다.void Die() { alive = false; }를 작성하고,Update()는if (!alive) return;으로 시작합니다.
‘플레이’를 누르고 벽 쪽으로 방향을 조작해 보세요. 뱀은 마지막 칸에서 멈춥니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // 두 이동 사이의 시간(초)
private float timer;
private Vector3 direction = Vector3.right; // 머리가 마지막 이동에서 움직인 방향
private Vector3 nextDirection = Vector3.right; // 다음 이동을 기다리는 회전 방향
void Update()
{
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;
transform.position += direction;
}
}
Unity 게임: 3D 스네이크의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드