개발/Unity

유니티 3D 간보기 - 골드메탈 3D강좌:아이템 먹기/장착

huiyu 2022. 2. 6. 18:09

오늘도 아래 강좌 이어서,

https://youtu.be/APS9OY_p6wo

 

- 오브젝트 감지

    private void OnTriggerStay(Collider other)
    {
        if (other.tag == "Weapon")
        {
            nearObject = other.gameObject;
        }

        Debug.Log(nearObject.name);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Weapon")
        {
            nearObject = null;
        }
    }

> OnTriggerStay와 OnTriggerExit를 통해 충돌 물체 감지
 - OnTriggerStay : Trigger와 접촉하고 있는 모든 Collider other에 대해 프레임당 한번 호출
 - OnTriggerExit : Collider other가 접촉을 중단한 경우 호출
> Weapon 오브젝트와 충돌시 nearObject를 충돌한 오브젝트로 설정.

- 무기입수 : 충돌이 발생한 오브젝트에 E키를 눌렀을 경우 입수.

    void Interaction()
    {
        if(iDown && nearObject != null && !isJump && !isDodge)
        {
            if(nearObject.tag == "Weapon")
            {
                Item item = nearObject.GetComponent<Item>();
                int weaponIndex = item.value;
                hasWeapon[weaponIndex] = true;

                Destroy(nearObject);
            }
        }
    }

 > iDown : Input System에서 알파벳 E키를 눌렀을 경우 동작.
  - 객체에 붙은 'Item' 스크립트를 통해 접근. 설정한 무기 Index값으로 hasWeapon 활성화.
   충돌 발생한 오브젝트는 Destroy()

- 무기 장착
 1) 캐릭터 손 위치에 Cylinder 모양의 객체 추가(Renderer는 꺼서 게임 화면에는 안보이게)
 2) 생성한 실린더 아래에 무기 프리팹을 하나씩 위치(비활성화)
 3) 숫자 1~3키(sDown1~3) 입력 시 무기 교체

    void Swap()
    {
        //이미 장착하고 있는 경우는 교체하지 않는다.
        if(sDown1 && (!hasWeapon[0] || equipWeaponIndex == 0))
        {
            return;
        }
        if (sDown2 && (!hasWeapon[1] || equipWeaponIndex == 1))
        {
            return;
        }
        if (sDown3 && (!hasWeapon[2] || equipWeaponIndex == 2))
        {
            return;
        }

        //키 입력에 따라 무기 인덱스 활성화
        int weaponIndex = -1;
        if (sDown1) weaponIndex = 0;
        if (sDown2) weaponIndex = 1;
        if (sDown3) weaponIndex = 2;

        //각 키 입력이 들어오고, 다른 동작 중이 아닐 경우
        if ((sDown1 || sDown2 || sDown3) && !isJump && !isDodge)
        {
            //장착중인 무기는 비활성화
            equipWeapon?.SetActive(false);

            //장착할 무기 활성화
            equipWeaponIndex = weaponIndex;
            equipWeapon = weapons[weaponIndex];
            equipWeapon.SetActive(true);

            //장착 애니메이션 활성화
            animator.SetTrigger("doSwap");

            isSwap = true;
            //스왑종료 알리기
            Invoke("SwapOut", 0.4f);
        }
    }
    
    void SwapOut()
    {
        isSwap = false;
    }

* isSwap은 다른 동작중(점프나 dodge, 이동중) 동작되는 것을 방지.

 

장착 완료!

 

728x90
반응형