Unity

[Unity] 오브젝트 풀링 + 가장 가까운 적 방향으로 공격

Yannoo 2022. 4. 22. 18:34
728x90

위의 파티클이 가장 가까운 적을 향해서 주기적으로 반복된다.

 

    private IEnumerator Generate()
    {
        while(true)
        {
            Vector3 enemyPosition = FindClosestEnemy().transform.position;

            GameObject earthQuake = earthQuakeQ.Dequeue();  //큐에서 뽑아서
            earthQuake.SetActive(true);     //활성화 하고

            //earthQuake.transform.localEulerAngles =new Vector3(0,enemyPosition.y,0);
            //y축만 가장 가까운 적의 방향으로 조절 -> x,z축만 가져와서 바라보게 하기.
            Vector3 targetPosition = new Vector3(enemyPosition.x,earthQuake.transform.position.y,enemyPosition.z);
            earthQuake.transform.LookAt(targetPosition);

            earthQuake.GetComponent<EarthQuakeOrigin>().off +=()=>earthQuakeQ.Enqueue(earthQuake);
            //earthQuake의 off를 통해 큐로 돌아오도록 설정
            earthQuake.GetComponent<EarthQuakeOrigin>().off +=()=>earthQuake.SetActive(false);

            audioSource.Play();


            yield return new WaitForSeconds(period);            
        }

    }

우선 스포너(파티클 생성기)와 스폰 될 대상(여기서는 위 사진의 파티클) 두 개의 프리팹이 필요하다.

스포너에서는 start 함수에서 파티클을 넉넉하게 4~5개 정도 만들어둔 후

코루틴을 통해서 파티클의 활성화와 비활성화를 반복한다. 위의 코드는 스포너에서 파티클을 큐에서 꺼내오고(디큐) 활성화, 파티클의 사용이 끝나면(이벤트 off를 통해 관리) 다시 큐에 집어넣고(인큐) 비활성화하는 코루틴이다.

 

또 가장 가까운 적의 방향을 향해 파티클이 실행되도록 LookAt을 활용했는데,

Y축 기준의 회전만 필요한 상황이었기에 LookAt으로 바라볼 대상의 포지션을 Vector3(적 포지션.x, 파티클 포지션.y, 적 포지션.z) 이렇게 만들었다.

 

 

public class EarthQuakeOrigin : MonoBehaviour
{
    public event Action off;
    

    void Start()
    {
        
    }
    void OnEnable()
    {
        StartCoroutine(Finish());

    }

    
    void Update()
    {
        
    }

    public virtual void Die()
    {
        if(off!=null)
            off();
    }

    private IEnumerator Finish()
    {
        yield return new WaitForSeconds(GetComponent<ParticleSystem>().main.duration);
        //yield return new WaitForSeconds(2.5f);
        Die();
    }
}

파티클에는 이벤트 off만 추가해두고, 파티클이 끝나면 Die 함수를 실행하여 off 이벤트를 받기만 하면 된다.

이런 방식으로 구현하면 스포너에서 파티클에 대한 모든 것을 관리할 수 있어서 편리하다.

 

파티클 스크립트에 충돌에 의한 공격 기능만 덧붙이면 완성이다.

 

 

 

 

 

 

 

 

728x90