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);
}
}
'C# > C# 학습 (TIL)' 카테고리의 다른 글
C# CLR(공통언어런타임) / CIL(공통 중간 언어) / C#의 메모리 관리 방식 (0) | 2022.06.28 |
---|---|
C# 오브젝트 풀링 (0) | 2022.06.26 |
유니티 Roll a ball 실습 (0) | 2022.06.26 |
C# 중급문법 Day9 디자인패턴 : 커맨드패턴, 퍼사드패턴 (0) | 2022.06.24 |
C# 중급문법 Day8 Coroutine (코루틴) (0) | 2022.06.23 |