아이템 획득 후 장비 착용 연습 2
2023. 8. 11.

어제 만들던 씬에 이어서 아이템 획득 후 정보를 받아 착용해보겠다.

코드 수정. 위치를 받아와야한다. 여러개니까.

 

 

방패 먹으면 방패장착, 검 먹으면 검 장착

using System;
using System.Collections;
using System.Collections.Generic;
using Test3;
using TMPro;
using UnityEngine;

namespace Test3
{
    public class HeroController : MonoBehaviour
    {
        private float maxDistance = 100f;
        private Animator anim;
        private Vector3 targetPosition;
        private ItemGenerator itemGenerator;
        private Coroutine moveRoutine;
        private Coroutine waitRoutine;
        private Coroutine shieldRoutine;
        [SerializeField] private Transform swordTrans;
        private Transform weaponTrans;
        [SerializeField] private Transform shieldTrans;
        private ItemController item;
        public Transform WeaponTrans
        {
            get { return weaponTrans; }
        }
        private GameObject swordGo;
        private GameObject shieldGo;
        public System.Action onTriggerItem;

        // private GameEnums.eItemType itemType;
        // Start is called before the first frame update
        void Start()
        {
            this.anim = GetComponent<Animator>();
            this.itemGenerator = GameObject.FindObjectOfType<ItemGenerator>();
            this.weaponTrans = swordTrans;//weaponTrans를 검 위치로 초기화
                                          

        }

        // Update is called once per frame
        void Update()
        {
            if (Input.GetMouseButtonDown(0))//좌클릭시
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.red, 3f);//ray그리기
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit, maxDistance)) //충돌검사
                {

                    // this.transform.position = hit.point;
                    if (hit.collider.tag == "Item")// 아이템 클릭시
                    {

                        Debug.LogFormat("tag:{0}", hit.collider.tag);
                        //this.Move();
                        Move(new Vector3(hit.point.x, 0, 0));
                    }
                    else if (hit.collider.tag == "Ground")// Ground 클릭시
                    {
                        Debug.LogFormat("tag:{0}", hit.collider.tag);

                        Move(hit.point);

                    }
                }

            }
        }

        private void Move(Vector3 targetPos)
        {
            this.targetPosition = targetPos;
            Debug.Log("move");
            if (this.moveRoutine != null)
            {
                this.StopCoroutine(this.moveRoutine);//이미 코루틴이면 실행 중지
            }
            this.moveRoutine = this.StartCoroutine(this.CoMove());//코루틴 시작
        }

        private IEnumerator CoMove()
        {
            while (true)
            {
                this.transform.LookAt(this.targetPosition);
                anim.SetInteger("State", 1);//Run animation
                this.transform.Translate(Vector3.forward * 2 * Time.deltaTime);//정면으로 이동

                // Debug.Log(weaponTrans.transform.position);
                float distance = Vector3.Distance(this.transform.position, this.targetPosition);
                if (distance < 0.1f)
                {
                    Debug.Log("Stop");
                    anim.SetInteger("State", 0);//Idle
                    break;
                }
                yield return null;
            }
            Debug.Log("<color=yellow>도착!</color>");
        }

        private IEnumerator CoEquipSword()
        {
            yield return null;//다음 프레임
            Debug.LogFormat("[CoEquipSword] childCount:{0}", this.weaponTrans.childCount);
            this.EquipSword();

        }
        private IEnumerator CoEquipShield() {
            yield return null;//다음 프레임
            this.EquipShield();
        }
        private void OnTriggerEnter(Collider other)
        {
            if (other != null)
            {//충돌하면
                if (other.tag == "Item")
                {
                    Debug.Log("아이템과충돌!");
                    Destroy(other.gameObject);

                    Debug.LogFormat("=> {0}", this.weaponTrans.childCount);

                    //this.onTriggerItem();

                    item = other.gameObject.GetComponent<ItemController>();

                    if (item != null)
                    {
                        Debug.LogFormat("<color=red>ItemType: {0}</color>", item.ItemType);
                        
                        if (item.ItemType == GameEnums.eItemType.Sword)
                        {
                            this.SwordTransform();//검 위치 받아옴
                            // Debug.Log(this.weaponTrans.position);                           
                            this.RemoveEquippedItem();
                            if (this.waitRoutine != null)
                            {
                                this.StopCoroutine(this.waitRoutine);//이미 코루틴이면 실행 중지
                            }
                            this.waitRoutine = this.StartCoroutine(this.CoEquipSword());//코루틴 시작                           

                        }
                        else if (item.ItemType == GameEnums.eItemType.Shield)
                        {
                            this.ShieldTransform();//방패 위치 받아옴                        
                            this.RemoveEquippedItem();
                            if (this.shieldRoutine != null)
                            {
                                this.StopCoroutine(this.shieldRoutine);//이미 코루틴이면 실행 중지
                            }
                            this.shieldRoutine = this.StartCoroutine(this.CoEquipShield());//코루틴 시작                           

                        }
                    }
                }
            }

        }
        public bool HasWeapon()
        {
            return this.weaponTrans.childCount > 0;
        }
        public Transform ShieldTransform()
        {
            this.weaponTrans = this.shieldTrans;
            return this.weaponTrans;
        }
        public Transform SwordTransform()
        {
            this.weaponTrans = this.swordTrans;
            return this.weaponTrans;
        }

        private void RemoveEquippedItem()
        {

            //자식이 있는가?
            Debug.LogFormat("자식의수: {0}", this.weaponTrans.childCount);
            if (this.weaponTrans.childCount == 0)
            {
                //자식이 없다 (착용중인 무기가 없다)
                Debug.Log("착용중인 무기가 없습니다.");
            }
            else
            {
                //자식이 있다 (착용중인 무기가 있다)                
                Transform child = this.weaponTrans.GetChild(0);   //첫번째 자식                                                                  //무기를 제거 
                Destroy(child.gameObject);//무기 제거
                Debug.LogFormat("childCount:{0}", this.weaponTrans.childCount);

            }
        }
        private void EquipSword()
        {

            Debug.Log("생성시 부모를 지정");
            //this.SwordTransform();
            bool hasWeapon = this.HasWeapon();
            if (!hasWeapon)
            {
                this.swordGo = this.itemGenerator.GenerateItem(GameEnums.eItemType.Sword, this.weaponTrans.position);
                //GenerateItem은 instantiate할 때 부모 설정 안된다.
                //만들어지고나서 부모 설정 
                this.swordGo.transform.SetParent(this.WeaponTrans);

                Debug.Log("Sword 장착");
            }
            else
            {
                Debug.Log("이미 착용중입니다.");
            }
        }

        private void EquipShield()
        {

            Debug.Log("생성시 부모를 지정");
            //this.SwordTransform();
            bool hasWeapon = this.HasWeapon();
            if (!hasWeapon)
            {            
                this.shieldGo = this.itemGenerator.GenerateItem(GameEnums.eItemType.Shield, this.weaponTrans.position);
                //GenerateItem은 instantiate할 때 부모 설정 안된다.
                //만들어지고나서 부모 설정 
                this.shieldGo.transform.SetParent(this.WeaponTrans);

                Debug.Log("Shield 장착");
            }
            else
            {
                Debug.Log("이미 착용중입니다.");
            }
        }

        private ItemController weapon;
        private ItemController shield;
        public void Equip(GameObject itemGo)
        {
            var itemController = itemGo.GetComponent<ItemController>();
            switch (itemController.ItemType)
            {
                case GameEnums.eItemType.Sword:
                    this.weapon = itemController;
                    break;
                case GameEnums.eItemType.Shield:
                    this.shield = itemController;
                    break;
            }
        }

        public void UnEquipWeapon()
        {
            if (this.weaponTrans.childCount > 0)
            {
                Destroy(this.weaponTrans.GetChild(0).gameObject);   //들고 있는 무기 제거 
            }
        }
    }
}

 

myoskin