C#/Unity

[Unity2D] Collision, Trigger 충돌 조건 확인 & 총알 발사하기

반나무 2020. 7. 7. 17:18

hero.cs

using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
// 이동간 절대기준 사용위한 Tweening 라이브러리 사용
using DG.Tweening;
using UnityEditorInternal;
using JetBrains.Annotations;
using System;

public class hero : MonoBehaviour
{
    bool _token = false;

    bool _DontMoveDown = false;
    bool _DontMoveUp = false;
    bool _DontMoveLeft = false;
    bool _DontMoveRight = false;

    // Prefab 사용 
    // 이렇게 선언하고 만든 Prefab을 컴포넌트에 끌어놓아서 연결함
    public Player_Bullet _MyBullet; // 형 선언

    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
        

        ///////////////////////////////////////////////////////////////
        // 토큰 값에 따라 판단하고 움직임
        if (!_token) {
            

            float EndPositionX = transform.position.x;
            float EndPositionY = transform.position.y;

            // 왼쪽
            if (Input.GetKey(KeyCode.LeftArrow) && _DontMoveLeft == false)
            {
                _token = true; // 토큰 값 변경

                // 내부 컴포넌트는 GetComponent로 불러올 수 있다.
                GetComponent<Animator>().SetInteger("State", 2);  // Animator에서 State값 가져와 변경하는 코드


                //////////////////////////////////////////////////////////////
                // 움직이는 코드
                // transform.position.x값을 불러와 변경(DOMove)한다.
                EndPositionX -= 1.5f;

                // endValue = 도착지, duration = 얼마동안?(1초=1.0f)
                // OnComplete = duration이 끝나면 인자 함수를 실행해줌
                // SetEase = 움직임 자연스럽게 해주는 효과

                // 더블클릭하고 F12 누르면 함수안으로 들어가짐
                // enum 열거형 = 배열과는 다르게 상수를 정의하기위해 쓰임
                transform.DOMoveX(EndPositionX, 0.5f).OnComplete(ActionComplete).SetEase(Ease.Flash);
                
           
            // 오른쪽
            } else if (Input.GetKey(KeyCode.RightArrow) && _DontMoveRight == false)
            {
                _token = true; // 토큰 값 변경

                GetComponent<Animator>().SetInteger("State", 3);

                EndPositionX += 1.5f;
                transform.DOMoveX(EndPositionX, 0.5f).OnComplete(ActionComplete).SetEase(Ease.Flash);

            // 위
            } else if (Input.GetKey(KeyCode.UpArrow) && _DontMoveUp == false)
            {
                _token = true; // 토큰 값 변경
                
                GetComponent<Animator>().SetInteger("State", 0);

                EndPositionY += 1.5f;
                transform.DOMoveY(EndPositionY, 0.5f).OnComplete(ActionComplete).SetEase(Ease.Flash); 

           
            // 아래
            } else if (Input.GetKey(KeyCode.DownArrow) && _DontMoveDown == false)
            {
                _token = true; // 토큰 값 변경

                GetComponent<Animator>().SetInteger("State", 1);

                EndPositionY -= 1.5f;
                transform.DOMoveY(EndPositionY, 0.5f).OnComplete(ActionComplete).SetEase(Ease.Flash); 

                /*
                // 직접 움직이는 코드
                Vector3 CurrentPosition = transform.position;
                CurrentPosition.y -= 0.01f;

                transform.position = CurrentPosition;
                */
            }

            ///////////////////////////////////////////////////////////////
            // 스페이스바를 눌렀을때 총알이 나감
            if (Input.GetKeyDown(KeyCode.Space))
            {
                // State 값 불러옴
                int StateValue = GetComponent<Animator>().GetInteger("State");

                // 인스턴스(객체)화 시킴
                Player_Bullet PB = Instantiate<Player_Bullet>(_MyBullet);

                // 총알의 포지션을 캐릭터의 포지션으로 변경
                PB.transform.position = transform.position; 
                
                if(StateValue == 4)
                {
                    PB.UpShot();
                } else if(StateValue == 5)
                {
                    PB.DownShot();
                } else if(StateValue == 6)
                {
                    PB.LeftShot();
                } else if(StateValue == 7)
                {
                    PB.RightShot();
                }
            }

            ///////////////////////////////////////////////////////////////
            // 액션 끝나고 토큰값 false & Idle 상태값 변경 메소드
            void ActionComplete()
            {
                // 토큰값 false
                _token = false;

                // Idle 변경
                GetComponent<Animator>().SetInteger("State", GetComponent<Animator>().GetInteger("State") + 4);

            }
        }
    }

    // 부딫혔을때 
    private void OnCollisionEnter2D(Collision2D collision)
    {
        String name = collision.gameObject.name;

        // collosion은 상대방의 정보 가져옴
        if (name == "bot_wall")
        {
            _DontMoveDown = true;
        } else if(name == "top_wall")
        {
            _DontMoveUp = true;
        } else if(name == "left_wall")
        {
            _DontMoveLeft = true;
        } else if(name == "right_wall")
        {
            _DontMoveRight = true;
        }
    }

    // 부딫힌것을 벗어낫을때
    private void OnCollisionExit2D(Collision2D collision)
    {
        String name = collision.gameObject.name;
        // collosion은 상대방의 정보 가져옴
        if (name == "bot_wall")
        {
            _DontMoveDown = false;
        }
        else if (name == "top_wall")
        {
            _DontMoveUp = false;
        }
        else if (name == "left_wall")
        {
            _DontMoveLeft = false;
        }
        else if (name == "right_wall")
        {
            _DontMoveRight = false;
        }
    }

    // 트리거로 함
    private void OnTriggerEnter2D(Collider2D collision)
    {
        String name = collision.gameObject.name;

        // collosion은 상대방의 정보 가져옴
        if (name == "bot_wall")
        {
            _DontMoveDown = true;
        }
        else if (name == "top_wall")
        {
            _DontMoveUp = true;
        }
        else if (name == "left_wall")
        {
            _DontMoveLeft = true;
        }
        else if (name == "right_wall")
        {
            _DontMoveRight = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        String name = collision.gameObject.name;
        // collosion은 상대방의 정보 가져옴
        if (name == "bot_wall")
        {
            _DontMoveDown = false;
        }
        else if (name == "top_wall")
        {
            _DontMoveUp = false;
        }
        else if (name == "left_wall")
        {
            _DontMoveLeft = false;
        }
        else if (name == "right_wall")
        {
            _DontMoveRight = false;
        }
    }
}

 

Player_Bullet.cs

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

// 이동간 절대기준 사용위한 Tweening 라이브러리 사용
using DG.Tweening;

public class Player_Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    ////////////////////////////////////////////
    // 총알 쏘는 메소드
    public void UpShot()
    {
        // 물리를 사용해 총알을 움직임
        GetComponent<Rigidbody2D>().AddForce(new Vector2(100.0f,100.0f));
        
        // 내가 가지고있는 transform의 + 100만큼 3초동안 이동함
        //transform.DOMoveY(transform.position.y + 100.0f, 6.0f);
    }

    public void DownShot()
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0, -100.0f));
       // transform.DOMoveY(transform.position.y - 100.0f, 6.0f);
    }

    public void LeftShot()
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(-100.0f, 0));
       // transform.DOMoveX(transform.position.y - 100.0f, 6.0f);
    }

    public void RightShot()
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(100.0f, 0));
        //transform.DOMoveX(transform.position.y + 100.0f, 6.0f);
    }

    /////////////////////////////////////////////////////////
    // Collision enter시 총알 삭제
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject);
    }
}
반응형