ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Unity]유니티 입문하기 6-3 번외(한번에 투사체 여러개 발사하기)
    프로그래밍 2023. 8. 3. 16:55

    이전 글에서 투사체를 생성하고, 발사하고, 사라지는 일련의 과정을 배웠습니다.

    이번에는 그 연장선으로, 한 번에 여러 개의 투사체를 발사해 보도록 하겠습니다.


    투사체를 여러 발 발사한다는 건, 다시 말하면 한번 클릭에 여러개의 오브젝트가 생긴다는 말입니다.

    if(Input.GetKeyDown(KeyCode.Space)){
        GameObject Bullet1 = Instantiate(BulletPrefab);
        Bullet1.transform.position = transform.position;
        Bullet1.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
    
        GameObject Bullet2 = Instantiate(BulletPrefab);
        Bullet2.transform.position = transform.position;
        Bullet2.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
    
        GameObject Bullet3 = Instantiate(BulletPrefab);
        Bullet3.transform.position = transform.position;
        Bullet3.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
    }

    즉, 가장 단순하게 접근하자면, 위와 같이 발사 키를 입력했을 때 실행될 코드를 많이 만들면 그만큼 투사체가 발사되겠죠.

     

    생성 위치가 전부 똑같아  총알이 하나로 보이지만, 하이어라키 창을 보면 분명히 3발의 총알이 생긴 것을 볼 수 있습니다.

     

    하지만 이런 방식으로 투사체를 늘리게 된다면 한번에 발사해야 하는 투사체의 수에 비례해서 코드가 끝없이 늘어나게 되고, 코드를 수정해야 할 때에도 총알 하나하나의 코드를 일일이 고쳐줘야 하는 문제가 있을 것입니다.

     

    여기서 반복문을 이용하게 됩니다.

    if(Input.GetKeyDown(KeyCode.Space)){
        for(int i=0; i<3; i++){
            GameObject Bullet = Instantiate(BulletPrefab);
            Bullet.transform.position = transform.position;
            Bullet.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
        }            
    }

    반복문을 이용하면, 총알 하나당 3줄씩 늘어나던 코드가 for문 한줄만으로 대체 가능하죠.

     

    물론 이 경우에도 반복이 너무 빨라 총알이 마치 한곳에 뭉쳐있는 것처럼 보이게 됩니다.

    이를 반복문의 특징을 이용해 해결해보도록 하죠.

     

    if(Input.GetKeyDown(KeyCode.Space)){
        for(int i=0; i<3; i++){
            GameObject Bullet = Instantiate(BulletPrefab);
            Vector3 bulletPos = transform.position;
            bulletPos.y += 0.3f * i;
            Bullet.transform.position = bulletPos;
            Bullet.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
        }        
    }

    이렇게 매 반복마다 값이 변하는 카운터 i를 이용해서 총알의 위치를 약간씩 바꿔주고 게임을 실행해 봅시다.

     

    총알이 보기 좋게 세발이 연달아 나오는 모습을 볼 수 있었습니다.

     

    이 외에도 이런 코드를 사용하면 왼쪽과 같이 총알이 가로로 일렬로 발사되게 할 수도 있고,

    if(Input.GetKeyDown(KeyCode.Space)){
        for(int i=0; i<3; i++){
            GameObject Bullet = Instantiate(BulletPrefab);
            Vector3 bulletPos = transform.position;
            bulletPos.x -= 0.3f;
            bulletPos.x += 0.3f * i;
            Bullet.transform.position = bulletPos;
            Bullet.GetComponent<Rigidbody2D>().AddForce(Vector2.up * BulletSpeed);
        }
    }

    이런 코드를 사용하면 총알이 플레이어를 중심으로 부채꼴로 나가게 할 수도 있습니다.

    if(Input.GetKeyDown(KeyCode.Space)){
        for(int i=0; i<3; i++){
            GameObject Bullet = Instantiate(BulletPrefab);
            Bullet.transform.position = transform.position;
            Vector2 bulletDir = Vector2.up;
            bulletDir.x -= 0.3f;
            bulletDir.x += 0.3f * i;
            Bullet.GetComponent<Rigidbody2D>().AddForce(bulletDir * BulletSpeed);
        }
    }
Designed by Tistory.