게임/Unity

[Unity] 화면 외부에서 오브젝트 생성

Nakuri 2022. 11. 27. 19:07
728x90

개요

적을 랜덤한 위치에서 생성시키는데, 화면 안에서도 생성되니 어색하다.

때문에 화면 밖에서 적을 생성시키기 위해 이것저것 시도해봤다.

 

본론

1. 원 범위로 생성

public Vector3 SpawnEnemy()
{
    Vector3 playerPosition = _playerTransform.position;
    float radius = 25f;
    float x = Random.Range(-radius + playerPosition.x, radius + playerPosition.x);
    float y = Mathf.Sqrt(Mathf.Pow(radius, 2) - Mathf.Pow(x - playerPosition.x, 2)) + playerPosition.y;
    y *= Random.Range(0, 2) == 0 ? -1 : 1;

    Vector3 randomPosition = new Vector3(x, y, 0);
    Instantiate(enemy, _playerTransform);
}

처음에는 플레이어 기준으로 대강 반지름을 잡고 원범위로 나오게 작성했다.

간편하지만, 보이듯이 y축에 가까워 질 수록 적이 화면에 늦게 표시되는 문제점이 있다.

2. 직사각형 형태로 생성

void SpawnEnemy(){
    int flag = Random.Range(0, 2);
    float xOffset = 20.0f;
    float yOffset = 10.0f;
    Vector3 playerPosition = playerTransform.position;
    Vector3 randomPosition = Vector3.zero;

    float x = 0.0f;
    float y = 0.0f;
    if (flag == 0)
    {
        x = playerPosition.x;
        x += Random.Range(0, 2) == 0 ? -xOffset : xOffset;
        y = Random.Range(playerPosition.y - yOffset, playerPosition.y + yOffset);
    }
    else
    {
        x = Random.Range(playerPosition.x - xOffset, playerPosition.x + xOffset);
        y = playerPosition.y;
        y += Random.Range(0, 2) == 0 ? -yOffset : yOffset;
    }
    randomPosition = new Vector3(x, y, 0);
    Instantiate(enemy, _playerTransform);
}

위의 문제를 해결하기 위해 직사각형 형태로 적을 생성시켰다.

전보단 나은 결과이지만 해상도 변경에 따른 대응을 할 수 없다.

3. 직사각형 형태로 생성 (해상도 대응)

private Vector3 GetRandomPosition(Transform playerTransform)
{
    Vector3 randomPosition = Vector3.zero;
    float min = -0.1f;
    float max = 1.1f;
    float zPos = 10;

    int flag = Random.Range(0, 4);
    switch (flag)
    {
        case 0:
            randomPosition = new Vector3(max, Random.Range(min, max), zPos);
            break;
        case 1:
            randomPosition = new Vector3(min, Random.Range(min, max), zPos);
            break;
        case 2:
            randomPosition = new Vector3(Random.Range(min, max), max, zPos);
            break;
        case 3:
            randomPosition = new Vector3(Random.Range(min, max), min, zPos);
            break;
    }
    randomPosition = Camera.main.ViewportToWorldPoint(randomPosition);
    Instantiate(enemy, _playerTransform);
}

 

위의 형태와 비슷하게 생성되지만, 이제는 해상도와 비율 변경에 대응할 수 있다.

ps. Camera.main의 성능이 2020.2 버전부터 개선되었다고 한다. 그래서 그냥 써봤다.

 

결론

이번에는 Camera.ViewportToWorldPoint로 문제를 해결했다.

하지만 스크린 좌표를 월드포인트로 전환해도 될 것 같긴한데..

다음에 시도해봐야겠다.

 

참조

Unity - 스폰(Spawn) 구현하기

Unity에서 화면 외의 위치를​​ 검색하는 방법

'게임 > Unity' 카테고리의 다른 글

[Unity] Rider Debugging  (0) 2023.03.28
[Unity] \uFFFD Warning  (0) 2023.01.31
[Unity] RedRunnder 오픈소스 분석  (0) 2022.12.14
[Unity] 다중 오브젝트 풀링 (Multiful Object Pooling)  (0) 2022.11.06