총알도 똑같이 잘라준다.

 

총알 충돌 시 이벤트가 생기므

총알에 박스콜라이더와 리지드바디 추가

에드포스로 날릴것이므로 리지드바디 -> 다이나믹

중력은 받지 않으므로 - 그래비티 스케일 0

재사용해서 사용할것이므로 프리팹화

총알 A를 복사해서 만든후 스프라이트에 다른 모양을 넣은 후 콜라이더 크기 조절

 

총알B를 저장하면 A를 복사해서 만든 것이므로 다시 프리팹화할때 알림 문구가 뜨는데

새로운 것이면 Original클릭

 

총알이 나중에 무수히 많아질 수 있으므로 지울 수 있는 또 다른 경계선 생성할 것인데

Bullet이라는 스크립트를 새로 생성

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

public class Bullet : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "BorderBullet")
        Destroy(gameObject); //모노비헤이어에 들어 있는 자체 함수 => 매개변수 오브젝트를 삭제하는 함수
    }
}

기존에 만들어 놓았던 Border를 복사해서 이름을 바꾸고

경계선을 재설정

 

태그를 새로 만든 후 할당

 

그럼 총알이 경계선에 닿으면 사라진다.

 

이제 총알을 만들 로직을 Player 스크립트에 작성할 것이다.

전 페이지에서 만들었던 업데이트문안에 있는 함수를 따로 캡슐화로 분리한 후 이름을 Move로 바꾸었고,

총알을 만들며 총알이 충돌을 일으켜야하므로 리지드바디를 사용

 

https://docs.unity3d.com/ScriptReference/ForceMode2D.html

 

Unity - Scripting API: ForceMode2D

Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close

docs.unity3d.com

퍼블릭으로 만들어둔 공간에 프리팹 할당

실행해보면 무수히 만들어진다.

 

그림과 같이 총알끼리 물리적 충돌로 인해 여러뱡항으로 나오는데

이것은 프리팹에서 isTrigger를 체크하면 해결된다.

 

총알이 눌렀을 때만 발사되게 조건을 넣어줄 것인데

!를 사용하는것이 아닌 조건일때만 실행되게 코드를 변경해줘도 된다.(코드 스타일)

이제 다음은 총알 딜레이를 추가할 것이다.

시간에 따라 현재 딜레이에 추가해줄것이고 

발사는 딜레이에 영향을 받아줄 것이므로 Fire문 안에 넣는다.

그리고 발사 후 딜레이를 없애주기 위해 마지막엔 딜레이를 0으로 초기화

총알을 쏠 때마다 딜레이를 변경해줄 수 있다.

 

총알의 파워를 입력해줄 것인데

케이스로 나눠서 각각 파워1, 2, 3일때 다르게 나오게 수치 변경

그리고 총알마다 간격을 조절하여

현재 위치해서 벡터값을 더해주면

총알의 생성위치를 원하는 간격으로 조절할 수 있다.

 

완성된 코드

using System.Collections;
using System.Collections.Generic;
using System.Net.Http.Headers;
using UnityEngine;

public class Player : MonoBehaviour
{
    public bool isTouchTop;
    public bool isTouchBottom;
    public bool isTouchRight;
    public bool isTouchLeft;
    private Animator anim;

    public float speed;
    public float power;
    public float maxShotDelay; //실제 딜레이
    public float curShorDelay; //한발 쏜 후 딜레이

    public GameObject bulletObjA;
    public GameObject bulletObjB;

    private void Awake()
    {
        anim = GetComponent<Animator>();
    }

    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 = this.transform.position;
        Vector3 nextPos = new Vector3(h, v, 0) * speed * Time.deltaTime;
        transform.position = curPos + nextPos;

        if (Input.GetButtonDown("Horizontal") ||
            Input.GetButtonDown("Vertical"))
        {
            anim.SetInteger("Input", (int)h);
        }
    }

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

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

        switch (power)
        {

            case 1://Power One
                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.3f, transform.rotation);
                GameObject bulletCC = Instantiate(bulletObjB, transform.position, transform.rotation);
                GameObject bulletLL = Instantiate(bulletObjA, transform.position + Vector3.left * 0.3f, 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;
        }
                curShorDelay = 0;
    }

    void Reload()
    {
        curShorDelay += Time.deltaTime;

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "Border")
        {
            switch(collision.gameObject.name)
            {
                case "Top":
                    isTouchTop = true;
                    break;
                case "Bottom":
                    isTouchBottom = true;
                    break;
                case "Right":
                    isTouchRight = true;
                    break;
                case "Left":
                    isTouchLeft = true;
                    break;
            }
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        switch (collision.gameObject.name)
        {
            case "Top":
                isTouchTop = false;
                break;
            case "Bottom":
                isTouchBottom = false;
                break;
            case "Right":
                isTouchRight = false;
                break;
            case "Left":
                isTouchLeft = false;
                break;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "BorderBullet")
        Destroy(gameObject); //모노비헤이어에 들어 있는 자체 함수 => 매개변수 오브젝트를 삭제하는 함수
    }
}

 

'산대특' 카테고리의 다른 글

2D Airplane - 원근감있는 무한 배경 만들  (0) 2024.03.17
2D Airplane - 5  (1) 2024.03.14
2D Airplane - 4  (0) 2024.03.12
2D Airplane - 3  (0) 2024.03.12
2D Airplane - 1  (0) 2024.03.09

+ Recent posts