Unity - 2D 종스크롤 슈팅 : 총알 발사 구현하기

TXMAY·2023년 9월 21일
0

Unity 튜토리얼

목록 보기
22/33
post-thumbnail

이번 강좌는 총알 발사 구현에 관한 강좌다.


준비하기

'Bullets' 스프라이트를 플레이어 스프라이트처럼 준비한다.

프리펩

총알 스프라이트를 드래그하여 배치하고 충돌 이벤트를 위한 Collider와 Rigidbody를 추가한다.
그리고 Gravity Scale을 0으로 설정한다.
그런 다음 Hierarcy 창에 있는 오브젝트를 Project 창으로 끌고 와 프리펩을 만들어 준다.
프리펩 : 재활용을 위해 에셋으로 저장된 게임 오브젝트
이런 식으로 플레이어의 총알을 하나 더 만든다. (스프라이트 이름 중 Player Bullet이라는 이름의 스프라이트를 사용한다)

발사체 제거

'Bullet.cs' 파일을 생성한 후, 다음과 같이 코드를 작성한다

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "BorderBullet")
        {
            Destroy(gameObject);
        }
    }
}

그리고 이전에 생성했던 Border 오브젝트를 복사하여 태그를 'BorderBullet'으로 바꿔준 후, 카메라 밖에 위치하도록 크기와 위치를 조정한다.
그런 다음 총알 프리펩에 코드를 추가한다.

발사체 생성

'Player.cs' 파일에 다음과 같이 코드를 추가하고 수정한다.

...

public GameObject bulletObjA;
public GameObject bulletObjB;
...

void Update()
{
    Move();
    Fire();
}

void Move()
{
    float h = Input.GetAxisRaw("Horizontal");
    if ((isTouchRight && h == 1) || (isTouchLeft && h == -1))
    {
        h = 0;
    }
    float v = Input.GetAxisRaw("Vertical");
    if ((isTouchTop && v == 1) || (isTouchBottom && v == -1))
    {
        v = 0;
    }
    Vector3 curPos = transform.position;
    Vector3 nextPos = new Vector3(h, v, 0) * speed * Time.deltaTime;
    transform.position = curPos + nextPos;
    if (Input.GetButtonDown("Horizontal") || Input.GetButtonUp("Horizontal"))
    {
        anim.SetInteger("Input", (int)h);
    }
}

void Fire()
{
    GameObject bullet = Instantiate(bulletObjA, transform.position, transform.rotation);
    Rigidbody2D rigid=bullet.GetComponent<Rigidbody2D>();
    rigid.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
}
...

Instantiate(obj, pos, deg) : 매개변수 오브젝트 생성
그리고 Inspector에서 총알 프리펩을 넣고 총알 프리펩에 Is Trigger를 활성화한다.
Hierarchy에 추가한 총알 오브젝트는 삭제한다.

발사체 다듬기

버튼을 눌렀을 때, 총알이 나가도록 하고, 총알이 나가는 딜레이를 주겠다.
다음과 같이 코드를 추가한다.

public float maxShotDelay;
public float curShotDelay;
...

void Update()
{
    ...
    
    Reload();
}
...

void Fire()
{
    if (!Input.GetButton("Fire1"))
    {
        return;
    }
    if (curShotDelay < maxShotDelay)
    {
        return;
    }
    ...

    curShotDelay = 0;
}

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

마우스 좌클릭을 누르면 일정한 간격으로 총알이 발사된다.

발사체 파워

파워 아이템을 먹으면 나오는 총알이 달라지도록 만들어 보겠다. (아이템은 나중에 구현한다)
다음과 같이 코드를 추가하고 수정한다.

...

public float power;
...

void Fire()
{
    ...
    
    switch (power)
    {
        case 1:
            GameObject bullet = Instantiate(bulletObjA, transform.position, transform.rotation);
            Rigidbody2D rigid = bullet.GetComponent<Rigidbody2D>();
            rigid.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
            break;
        case 2:
            GameObject bulletR = Instantiate(bulletObjA, transform.position + Vector3.right * 0.1f, transform.rotation);
            GameObject bulletL = Instantiate(bulletObjA, transform.position + Vector3.left * 0.1f, transform.rotation);
            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;
        case 3:
            GameObject bulletRR = Instantiate(bulletObjA, transform.position + Vector3.right * 0.25f, transform.rotation);
			GameObject bulletCC = Instantiate(bulletObjB, transform.position, transform.rotation);
			GameObject bulletLL = Instantiate(bulletObjA, transform.position + Vector3.left * 0.25f, transform.rotation);
			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;
}

Inspector 창에서 power의 값을 바꾸면 나오는 총알의 종류가 달라진다.


파워에 따라 발사하는 총알의 종류를 바꾸니 슈팅 게임에서 보는 것처럼 총알이 나가서 멋졌다.

profile
게임 개발 공부하는 고양이

0개의 댓글