유니티

[유니티 2D] 미로 - Bullet(총알) 만들기

labj 2024. 3. 10. 02:53

Hierarchy창에서 + 아이콘을 클릭하고 2D Object > Sprites > Circle을 선택합니다

게임오브젝트의 이름을 Bullet으로 바꿉니다.

 

총알이 1초 후에 사라지게 하기 위해서 C# 코드를 만듭니다.

BulletDestroy.cs C# 코드의 Start() 함수에 Destroy 로직을 사용합니다.

* BulletDestroy.cs

…
public class BulletDestroy : MonoBehaviour
{
    void Start()
    {        
         Destroy(gameObject, 1);
    }
    
    void Update()
    {
    }
}

 

 

Bullet 게임오브젝트에 BulletDestroy.cs C# 코드를 연결합니다.

 

 

Hierachy창의 Bullet 게임오브젝트을 왼쪽 마우스버튼으로 끌어다가 Assets 폴더에 놓습니다.

Bullet.prefab 파일이 만들어집니다. Prefab 파일을 복제해서 총알로 사용합니다.

 

 

Bullet이 발사되려면 Rigidbody 2D(물리법칙) 컴포넌트가 필요합니다.

Assets 폴더에서 Bullet.prefab 파일을 선택하고, Inspector창에서 Add Component 버튼을 클릭하여 Physics 2D > Rididbody 2D를 추가합니다.

 

 

Bullet.prefab 파일을 이용해서 Bullet을 복제하고 발사합니다BulletController.cs C# 코드를 작성합니다왼쪽 마우스버튼을 클릭하여 복제된 Bullet을 발사합니다.

* BulletController.cs

…
public class BulletController : MonoBehaviour
{
    public GameObject bulletPrefab;
    public float speed = 20f;

    void Start()
    {        
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = Instantiate(bulletPrefab);
            bullet.transform.position = gameObject.transform.position;
            bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
        }
    }
}

 

 

Assets 폴더의 BulletController.cs 파일을 Car 게임오브젝트에 연결합니다.

 

Assets 폴더의 Bullet.prefab 파일을 Car 게임오브젝트에 있는 BulletController(Script) 컴포넌트에 있는 BulletPrefabNone(GameObject)에 넣습니다플레이 버튼을 클릭하여 Car 게임오브젝트에서 Bullet이 발사되는지 확인합니다.

 

 

플레이 버튼을 클릭하여 Car 게임오브젝트에서 Bullet이 발사되는지 확인합니다.

 

 

Car 게임오브젝트의 방향으로 Bullet 발사되게 합니다.

Car 게임오브젝트가 움직인 방향을 Move.cs 변수에 저장합니다.

* Move.cs

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

public class Move : MonoBehaviour
{
    public float xx = 0;

    void Start()
    {
        
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            xx = 1;
            GetComponent<SpriteRenderer>().flipX = false;
            transform.Translate(10 * Time.deltaTime, 0, 0);
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            xx = -1;
            GetComponent<SpriteRenderer>().flipX = true;
            transform.Translate(-10 * Time.deltaTime, 0, 0);
        }
        …
    }

}

 

 

BulletController.cs에서 Move.csxx 변수의 값에 따라서 Bullet의 방향을 바꿉니다.

*BulletController.cs

    …
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = Instantiate(bulletPrefab);
            bullet.transform.position = gameObject.transform.position;

            if (GetComponent<Move>().xx == 1)
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
            }
            else if (GetComponent<Move>().xx == -1)
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * -1 * speed;
            }
            else
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
            }
        }
    }
}

 

 

Bullet으로 Ghost 게임오브젝트를 맞추어도 Bullet이 그냥 통과합니다.

Ghost 게임오브젝트, Bullet.prefabCollider 적용되어 있지 않아서 통과하는 것입니다.

Ghost 게임오브젝트에 Polygon Collider를 적용합니다.

 

 

 

Rigidbydy2D 컴포넌트를 추가하고 플레이버튼을 클릭하면 유령 게임오브젝트가 밑으로 떨어집니다.

Gravity Scale1로 되어 있어서 밑으로 떨어집니다. 0으로 바꾸면 떨어지지 않고 그대로 있습니다. 

 

 

Bullet.prefabCircle Collider를 적용합니다.

 

 

Bullet.prefabCircle Collider가 적용되면서 앞으로 발사되던 BulletCar게임오브젝트에서 멈춘 상태로 있다가 아래로 떨어집니다Bullet 복제본이 생성되자마자 Car 게임오브젝트의 Collider와 닿아서 멈춘 상태가 되는 것입니다이 문제를 해결하기 위해서 레이어 계층을 만들어서 서로 보지 않게 합니다Car 게임오브젝트는 Player 레이어, Bullet 게임오브젝트는 Bullet 레이어로 합니다.

 

 

Player 레이어와 Bullet 레이어가 서로 보지 않게 설정합니다Edit > Project Settings… > Physics 2D 를 선택합니다Layer Collision Matrix에서 BulletPlayer가 서로 만나는 체크박스를 없앱니다플레이를 해 보면 Car 게임오브젝트와 Bullet이 서로 부딛치지 않습니다.

 

 

Project Settings…를 이용하지 않는 방법은 Bullet의 복제본이 만들어 질 때 x좌표 위치를 Player 게임오브젝트의 밖에 만들면 됩니다BulletController.cs의 로직을 수정합니다.

* BulletController.cs

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = Instantiate(bulletPrefab);
            // bullet.transform.position = gameObject.transform.position; //주석처리함
            if(player.GetComponent<Move>().xx == 1)
            {
                bullet.transform.position = new Vector3(
                        player.transform.position.x + 1,
                        player.transform.position.y,
                        player.transform.position.z
                    );
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
            } else
            {
                bullet.transform.position = new Vector3(
                        player.transform.position.x - 1,
                        player.transform.position.y,
                        player.transform.position.z
                    );
                bullet.GetComponent<Rigidbody2D>().velocity = -1 * transform.right * speed;
            }
        }
    }
}

 

 
BulletController.cs에서 Move.csxx 변수의 값에 따라서 Bullet의 방향을 바꿉니다.

* BulletController.cs

    …
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = Instantiate(bulletPrefab);
            bullet.transform.position = gameObject.transform.position;

            if (GetComponent<Move>().xx == 1)
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
            }
            else if (GetComponent<Move>().xx == -1)
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * -1 * speed;
            }
            else
            {
                bullet.GetComponent<Rigidbody2D>().velocity = transform.right * speed;
            }
        }
    }
}