Menu
CoddyTech

충돌!

Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 67개 중 63번째.

challenge icon

챌린지

중급

이제 위험 요소를 추가해 봅시다. 이전 단계의 내용을 모두 유지하고, 블록이 러너에 닿으면 게임을 끝내세요.

  • 둘 다 너비가 1단위인 정육면체이므로, x 위치 차이가 1 미만이고 y 위치 차이가 1 미만이면 블록이 러너에 닿습니다.
  • 블록이 이동한 뒤 매 프레임마다 모든 블록을 확인하세요. 닿으면 Game over를 로그에 출력하고 enabled = false로 스크립트를 끄세요. 그러면 러너, 블록, 블록 생성이 모두 멈춥니다.

Play를 눌러 얼마나 오래 버틸 수 있는지 확인한 다음, Check를 누르세요.

직접 해보기

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float fallSpeed = 5f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer = 0f;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
            if (blocks[i].transform.position.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}

Unity 스크립팅 기초의 모든 레슨