ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 케이디 강의13 - (나뭇가지 파괴, 효과음, 이펙트, 오브젝트 변형)
    인프런 강의 - 케이디 생존게임 2022. 11. 15. 00:05
    반응형

     

     

     

    public class Twig : MonoBehaviour
    {
    
        [SerializeField]
        private int hp; // 나뭇가치 체력
    
        [SerializeField] //이펙트 파괴시간
        private float destroyTime;
    
    
    
        [SerializeField]
        private GameObject go_little_Twig; // 작은 나뭇가지 조각들
    
        [SerializeField]
        private GameObject go_hit_effect_prefab; //나뭇가지 타격 이펙트
    
        //##회전값 변수##
        private Vector3 originRot; //나무 칠때마다 기울이게 원래 로테이션 저장
        private Vector3 wantedRot; // 회전 희망방향
        private Vector3 currentRot; //현재 방향
    
        //##필요한 사운드 이름##
        [SerializeField]
        private string hit_Sound; //나무 타격음
        [SerializeField]
        private string broken_Sound; //나무 파괴음
    
    
        void Start()
        {
            originRot = transform.rotation.eulerAngles; //로테이션 값 vector3 그대로 선언했으므로 오일러로 변환시켜야함
            currentRot = originRot; // 원래 방향값 설정
        }
    
    
    
        public void Damage(Transform _playerTf) //나무 타격 ((플레이어의 위치정보 받아옴
        {
            hp--;
    
            Hit();
    
            StartCoroutine(HitSwayCoroutine(_playerTf));
    
            if(hp <= 0)
            {
                Destruction(); // 파괴함수
            }
        }
    
        private void Hit() //Rock 스크립트와 동일
        {
            SoundManager.instance.PlaySE(hit_Sound);
    
            GameObject clone = Instantiate(go_hit_effect_prefab, gameObject.GetComponent<BoxCollider>().bounds.center + Vector3.up * 0.5f,
                Quaternion.identity); 
    
            Destroy(clone, destroyTime);
        }
    
        IEnumerator HitSwayCoroutine(Transform _target) //맞은 방향으로 휘게하는 코루틴
        {
            Vector3 direction = (_target.position - transform.position).normalized;
            //나뭇가지와 플레이어가 서로 바라보는 방향 // normalized 나온 값의 합이 1이되도록 재조정해줌
            //플레이어 포지션 (x,y,z)에서 나뭇가지 포지션(x,y,z)를 빼면 방향값이 나옴
    
            Vector3 rotationDir = Quaternion.LookRotation(direction).eulerAngles;
            //방향에 대한 각도=> direction에서 나온 방향으로 바라보게 만듬 해당 값을 xyz값으로 반환
    
            CheckDirection(rotationDir); //각도 확인=>나온 각도
            
            
            
            while(!CheckThreshold())
            {
                currentRot = Vector3.Lerp(currentRot, wantedRot, 0.25f);
                //현재 회전값에 Lerp해줌 (현재 각도, 희망각도, 힘 값)
                transform.rotation = Quaternion.Euler(currentRot);
                //나온 값 적용
                // currentRot는 벡터값이지만  transform.rotation 오일러 값이므로 Quaternion.Euler를 추가하여 자동으로 대입할 수 있도록 변환
                yield return null;
            }
    
            wantedRot = originRot;
    
            while (!CheckThreshold())
            {
                currentRot = Vector3.Lerp(currentRot, wantedRot, 0.15f); //원래 위치로 돌아가는 반복문
                //현재 회전값에 Lerp해줌 (현재 각도, 희망각도, 힘 값)
                transform.rotation = Quaternion.Euler(currentRot);
                //나온 값 적용
                // currentRot는 벡터값이지만  transform.rotation 오일러 값이므로 Quaternion.Euler를 추가하여 자동으로 대입할 수 있도록 변환
                yield return null;
            }
    
        }
    
    
    
        private bool CheckThreshold() //임계점(목표근사치) 체크-> currentRot = Vector3.Lerp(currentRot, wantedRot, 0.25f);의
        {
            if (Mathf.Abs(wantedRot.x - currentRot.x) <= 0.5f && Mathf.Abs(wantedRot.z - currentRot.z) <= 0.5f)
                //Mathf.Abs를 추가하여 값을 항상 양수로 설정하여 오류 해결
                return true; //임계점도달
            return false; // 임계점 아님
        }
    
        //##얻은 방향,각도에 따른 나무 휘어짐 구현함수##
        private void CheckDirection(Vector3 _rotationDir) 
        {
            Debug.Log(_rotationDir);
    
            if(_rotationDir.y > 180) //타격 각도 180 이상인경우
            {
                if (_rotationDir.y > 300)
                    wantedRot = new Vector3(-50f, 0f, -50f);
                else if (_rotationDir.y > 240)
                    wantedRot = new Vector3(0f, 0f, -50f);
                else
                    wantedRot = new Vector3(50f, 0f, -50f);
            }
            else if (_rotationDir.y <= 180) //타격 각도 조건
            {
                if (_rotationDir.y < 60)
                    wantedRot = new Vector3(-50f, 0f, 50f);
                else if (_rotationDir.y > 120)
                    wantedRot = new Vector3(0f, 0f, 50f);
                else
                    wantedRot = new Vector3(50f, 0f, 50f);
            }
        }
    
        private void Destruction()
        {
            SoundManager.instance.PlaySE(broken_Sound);
    
            GameObject clone1 = Instantiate(go_little_Twig, gameObject.GetComponent<BoxCollider>().bounds.center + (Vector3.up * 0.5f),
        Quaternion.identity);
    
            GameObject clone2 = Instantiate(go_little_Twig, gameObject.GetComponent<BoxCollider>().bounds.center - (Vector3.up * 0.5f),
    Quaternion.identity);
    
            Destroy(clone1, destroyTime);
    
            Destroy(clone2, destroyTime);
    
            Destroy(gameObject);
        }    
    }

     

    이전시간에 배웠던 사운드 매니저를 통한 효과음 추가와 파괴된 오브젝트 생성, 파티클 추가로

    부서지는 나뭇가지를 구현하였다.

     

     

     

     

    그리고 곡괭이 스크립트의 연계를 통해 플레이어 방향을 구하고

    나뭇가지의 위치값과 합쳐 방향 ->각도를 구하고

     

    입력값에 따라 나뭇가지가 천천히 휘어지게 Lerp를 사용하여 함수를 짠 뒤

     

    각도에따라 휘어지는 함수를 실행하도록하였다.

     

    반응형
Designed by Tistory.