Skip to content

5. 랜덤하게 적군 생성하기

Lee Seokhyun edited this page Aug 26, 2020 · 1 revision

이번 챕터에서 배울 것

  • 랜덤하게 적군을 생성하는 방법

EnemySpawner(적군 생성기)

image

다른 설명 말고 코드로 직접 들어가 봅시다.

IEnumerator SpawnLoop()
{
    // 본격적으로 적군을 생성하기 전 일정시간 대기 합니다.
    if (this.startDelay > 0.0f)
    {
        yield return new WaitForSeconds(this.startDelay);
    }

    while (true)
    {
        // 웨이브를 수행합니다.
        // 적군은 한꺼번에 수십마리가 나오고 끝이 아니라 몇마리가 뭉쳐 나오고 잠시 후 또 뭉쳐나오고를 반복 합니다.
        // 이렇게 작은 단위로 반복하며 생성되는데 보통 슈팅게임에서 한번에 생성되는 단위를 웨이브라고 부릅니다.
        RunWave();

        // 다음 웨이브까지 대기하며 기다립니다.
        float interval = Random.Range(this.intervalMin, this.intervalMax);
        yield return new WaitForSeconds(interval);
    }
}

무한 루프를 돌며 적군을 생성합니다.

void RunWave()
{
    // 이번 웨이브에서 얼마나 많은 적군을 생성할지 결정합니다.
    int count = Random.Range(this.countMin, this.countMax + 1);
    for (int i = 0; i < count; ++i)
    {
        // 랜덤하게 하나의 적군 프리팹을 선택합니다.
        int enemyIndex = Random.Range(0, this.prefabEnemies.Length);

        // 선택한 프리팹을 인스턴스화 하여 적군 객체를 생성합니다.
        Enemy enemy = GameObject.Instantiate(this.prefabEnemies[enemyIndex], transform, false);

        // 초기 생성 위치를 설정합니다. GetRandomPosition매소드에서 랜덤으로 위치를 계산해서 넘겨 줍니다.
        enemy.transform.position = GetRandomPosition();
        enemy.Wakeup();
    }
}

위 매소드는 이 클래스의 핵심 부분으로 랜덤한 적군을 생성하고 위치를 설정하는 역할을 합니다.

Vector3 GetRandomPosition()
{
    float x = Random.Range(-this.spawnArea.x, this.spawnArea.x);
    float y = Random.Range(-this.spawnArea.y, this.spawnArea.y);
    float z = Random.Range(-this.spawnArea.z, this.spawnArea.z);

    return transform.position + new Vector3(x, y, z);
}

GetRandomPosition 매소드는 초기 생성 위치를 랜덤하게 계산해주는 역할을 합니다. Random.Range 매소드를 통해서 범위 내에 랜덤하게 좌표값을 결정합니다.

private void OnDrawGizmos()
{
    Vector3 leftTop = transform.position + new Vector3(-this.spawnArea.x, this.spawnArea.y, this.spawnArea.z);
    Vector3 rightTop = transform.position + new Vector3(this.spawnArea.x, this.spawnArea.y, this.spawnArea.z);
    Vector3 leftBottom = transform.position + new Vector3(-this.spawnArea.x, this.spawnArea.y, -this.spawnArea.z);
    Vector3 rightBottom = transform.position + new Vector3(this.spawnArea.x, this.spawnArea.y, -this.spawnArea.z);

    Gizmos.color = Color.red;
    Gizmos.DrawLine(leftTop, rightTop);
    Gizmos.DrawLine(rightTop, rightBottom);
    Gizmos.DrawLine(rightBottom, leftBottom);
    Gizmos.DrawLine(leftBottom, leftTop);
}

이 매소드는 적군 생성 위치를 씬뷰에 표시해주는 기능을 합니다. 디버깅을 위해 들어간 코드로 실제 게임에는 영향을 미치지 않습니다.

image

정리

적군을 생성하는 방법은 생각보다 간단합니다. 랜덤하게 프리팹을 선택하고 인스턴스화 한 뒤 랜덤한 위치를 설정해주면 끝입니다. 다음 챕터에서는 여기에서 생성한 적군을 이동하는 방법에 대해 배워보겠습니다.