본문 바로가기

TIL (since 2023.08.07 ~ )

2023-11-20 TIL(Unity 최종 프로젝트 21일차)

오늘은 플레이어가 투척물을 던지는 것까지 구현이 되었지만 투척물에서부터 발생하는 이벤트가 따로 구현이 되어있지 않아서 해당 부분을 구현을 했다.

먼저 투척물을 만들게 된 계기가 필드 보스 중 하나를 특정 영역까지 유도하면 쓰러뜨릴 수 있기 때문에 해당 기능을 기획을 한 것인데, 그러려면 투척물의 폭발 범위 안에 몬스터가 존재한다면 밀쳐지는 기능이 추가되어야 한다.

투척물은 Grenade 스크립트로 관리를 하고 있기 때문에 해당 스크립트에서 구현을 하면 된다.

 

 

Grenade 수정

public class Grenade : MonoBehaviour
{
    public GameObject[] grenades;
    public int hasGrenades;
    public GameObject grenadeObj;
    public Rigidbody rigid;
    public GameObject meshObj;
    public GameObject effectObj;
    public float explosionRadius = 5f; // 폭발 반경

    public void Init()
    {
        rigid = GetComponent<Rigidbody>();

        if (rigid != null)
        {
            // Vector3.up * (높이값) + transform.forward * 전진 힘 => 포물선
            float throwForce = 5f; // 던지는 힘 설정
            float throwHeight = 10f;
            rigid.AddForce(Vector3.up * throwHeight + transform.forward * throwForce * rigid.mass, ForceMode.Impulse);
        }
        StartCoroutine(Explosion());
    }


    IEnumerator Explosion()
    {
        yield return new WaitForSeconds(2.5f);
        rigid.velocity = Vector3.zero;
        rigid.angularVelocity = Vector3.zero;

        // Physics.OverlapSphere
        Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);

        foreach (Collider col in colliders)
        {
            //col.gameObject.CompareTag("Enemy");
            if(col.TryGetComponent(out Rigidbody targetRigidbody))
            {
                targetRigidbody.AddExplosionForce(1000f, transform.position, explosionRadius);
            }
        }

        Destroy(gameObject, 0);
    }

}

 

해당 기능을 구현하면서 배운 점은 "Physics.OverlapSphere" 와 "AddExplosionForce"이다.

먼저 Physics.OverlapSphere는 콜라이더를 구체의 형태로 씌워서 충돌처리를 감지하는 기능이다.

필요한 값은 위치값과 폭발반경범위이다. 그리고 AddExplosionForce는 특정 힘만큼 폭발하는 효과를 가지고 있는 기능이다. 이렇게 코드를 작성하고 나니 투척물의 일정반경에 충돌처리를 일으킬 수 있는 오브젝트의 정보를 가져와서 해당 오브젝트들에 힘을 가해주는 효과가 생겨나서 기획에서 원했던 대로 처리가 잘 이루어졌다.