본문 바로가기
C#/C# 학습 (TIL)

C# OverlapSphere / 콜라이더 배열

by jjiing 2022. 6. 26.

overlapsphere

구체 모양으로 충돌체의 정보를 받아오는 함수이다.

범위 충돌을 다룰 때 용이하다.

 Collider[] hitColliders = Physics.OverlapSphere(transform.position, 5f);

현재 위치에 반지름이 5f인 구체를 그리고 그 안에서 충돌하는 콜라이더를 모두 배열로 받아온다.

 

 

 

해당 실습은 타겟을 향해 레이캐스트를 쏘면서 동시에 
일정 타겟이 범위 내에 존재한다면(overlapsphere 사용)  target의 위치로 움직이게 하는 실습이다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player2 : MonoBehaviour
{
    public GameObject target;
    public bool isRayBall;
    

    void Start()
    {
        isRayBall = false;
        
    }

    void Update()
    {
        Vector3 Dis = target.transform.position - transform.position;   //타겟과 나와의 방향

        //레이캐스트
        Debug.DrawRay(transform.position, Dis * 1f, Color.red);
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Dis, out hit, 5f))
        {
            if (hit.transform.gameObject.name == "ball")
                isRayBall = true;
            else
                isRayBall = false;

        }

        //콜라이더
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, 5f);
        for (int i = 0; i < hitColliders.Length; i++)
        {
            //충돌체가 볼 스크립트를 가지고 있다면
            if (hitColliders[i].GetComponent<ball>() != null && isRayBall)
            {
                transform.position += Dis * Time.deltaTime * 1f;    //이동

            }
        }
        
    }
    private void OnDrawGizmos()	//확인을 용이하게 하기 위해 원 기즈모를 그려준다.
    {
        Gizmos.color = new Color(1, 1, 1, 0.2f);
        Gizmos.DrawSphere(transform.position, 5);
    }
}