YunDev

Unity - 플레이어 총알 발사 구현하기! 본문

Programming/Unity

Unity - 플레이어 총알 발사 구현하기!

S준 2020. 4. 1. 08:30

 

 

안녕하세요!! 오늘은 슈팅게임에서 플레이어가 총알을 발사하는 코드에 대해서 알아보려고 합니다.

 

 

그 전에 스프라이트가 있어야합니다.

 

스프라이트 출처 : https://blog.naver.com/gold_metal/221709884923

 

[유니티 강좌] 오브젝트 생성과 삭제

일단 총알 스프라이트 부터.이번 강좌에서 가장 중요한 오브젝트와 생성과 삭제를한번 더 다뤄보도록 하겠...

blog.naver.com

 

 

 

1. 총알 발사 조건 정하기

 public ObjectManager objectManager;
 public bool isButtonA;
  public float maxShotDelay;
  public float curShotDelay;


 void Update()
    {
        
        Fire();
        Reload();
    }
    
public void ButtonADown()
    {
        isButtonA = true;
    }

     public void ButtonAUp()
    {
        isButtonA = false;
    }



void Fire()
    {
      

        if (!isButtonA)
            return;

        if (curShotDelay < maxShotDelay)
            return;

      
   void Reload()
    {
        curShotDelay += Time.deltaTime;
    }

 

 

모든 버튼들은 Down, Up 함수가 있는데 Down은 버튼이 눌렸을 때, Up은 버튼을 누르다 뗏을 때입니다.                     

조건문 !isButtonA는 isButtonA가 false(! = 기준의 반대)라면 총알 발사 함수를 실행하지 않습니다. Up 함수는 안누르는 것을 의미하기 때문이죠. 

maxShotDelay는 총알 연사 속도를 제한합니다. Reload함수에서 curShotDelay를 현재 지나가고 있는 시간을 계속 더합니다. 제가 만약 maxShotDelay를 0.15로 설정해두면 0 ~ 0.14초 까지는 총알을 발사할 수 없는 것이죠.

 

 

 

2.총알 만들기

 

GameObject[] bulletPlayerA = new GameObject[100];
GameObject[] bulletPlayerB = new GameObject[100];



public GameObject MakeObj(string type)
    {

        
        switch (type)
        {
          
            case "BulletPlayerA":
                targetPool = bulletPlayerA;
                break;
            case "BulletPlayerB":
                targetPool = bulletPlayerB;
                break;
          
          
         
        
        }

        for (int index = 0; index < targetPool.Length; index++)
        {
            if (!targetPool[index].activeSelf)
            {
                targetPool[index].SetActive(true);
                
                return targetPool[index];
            }

        }

        return null;
              
    }

 

이건 플레이어 파일 코드가 아닌  ObjectManager 스크립트의 함수입니다. 플레이어에서 총알을 생성하면 매개변수 type을 받아서 type의 값에 따라 targetPool의 값이 넣어집니다. for문에서는 타겟풀의 값, 즉 생성만 한 타겟풀의 개수만큼을 돌면서 비활성화된 index번째를 활성화 시키는 것이죠.

 

정리 : 타겟풀의 생성된 오브젝트 개수만큼 for문을 돌면서 비활성화가 되있는 index번째를 활성화시킨다.

 

 

 

3.총알 발사 로직

 

public int power;


	switch (power)
        {
            case 1:

                GameObject bullet = objectManager.MakeObj("BulletPlayerA");
                bullet.transform.position = transform.position;

             Rigidbody2D rigid = bullet.GetComponent<Rigidbody2D>();
             rigid.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
                break;

            case 2:
                GameObject bulletR = objectManager.MakeObj("BulletPlayerA");
             bulletR.transform.position = transform.position + Vector3.right * 0.1f;

             GameObject bulletL = objectManager.MakeObj("BulletPlayerA");
             bulletL.transform.position = transform.position + Vector3.left * 0.1f;

             Rigidbody2D rigidR = bulletR.GetComponent<Rigidbody2D>();
             Rigidbody2D rigidL = bulletL.GetComponent<Rigidbody2D>();
             rigidR.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
             rigidL.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
                break;

            default:
                GameObject bulletRR = objectManager.MakeObj("BulletPlayerA");
             bulletRR.transform.position = transform.position + Vector3.right * 0.35f;

             GameObject bulletCC = objectManager.MakeObj("BulletPlayerB");
             bulletCC.transform.position = transform.position;

             GameObject bulletLL = objectManager.MakeObj("BulletPlayerA");
             bulletLL.transform.position = transform.position + Vector3.left * 0.35f;


             Rigidbody2D rigidRR = bulletRR.GetComponent<Rigidbody2D>();
             Rigidbody2D rigidCC = bulletCC.GetComponent<Rigidbody2D>();
             Rigidbody2D rigidLL = bulletLL.GetComponent<Rigidbody2D>();
             rigidRR.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
             rigidCC.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
             rigidLL.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
                break;
        }

   
        curShotDelay = 0;
    }

 

power의 값을 1 ~ 3까지 넣는다고 가정하면 switch문을 통해 power 값이 1이면  작은 총알, 2이면 양옆의 작은 총알,     값이 3이상이라면 기본으로 좌,우,중간(큰 총알)으로 발사하는 것이죠.

 

 

 

 

일단 이 코드는 슈팅게임 초반부분이라면 이해도 잘안가실 수 있습니다.

유니티 창에서 해야하는 것들을 제가 다 넣기도 애매해서 코드만 넣었습니다... 

구체적인 정보는 영상을 보시는게 좋으실 것 같네요!!

 

다음편은 오브젝트 풀링을 사용 해야하는 이유로 올리도록 하겠습니다~~!