Menu
CoddyTech

충돌!

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

challenge icon

챌린지

중급

블록이 러너에 닿으면 게임을 끝내세요.

  1. 블록 반복문에서 블록이 이동한 후, 위치를 Vector3 b로 읽으세요.
  2. Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f이면 Game over를 로그에 기록하고, enabled = false;를 설정한 다음 return;하세요.

‘플레이’를 누르고 블록이 여러분에게 떨어지게 하세요. Console에 Game over가 표시되고 모든 것이 멈춥니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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 -= spawnEvery;
            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 스크립팅 기초의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드