본문 바로가기
유니티 공부/Unity

Unity - GraphicRaycaster(2D), Physics.Raycast(3D)

by 코딩하는 돼징 2023. 10. 31.
반응형

Physics.Raycast

일반적으로 3D 레이캐스팅을 수행한다. Ray를 통해 충돌하는 오브젝트를 찾는다.

public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);

origin에서 시작하여 direction으로 maxdistance만큼 ray를 쏜다. 이 ray는 현재 Scene에 있는 모든 Collider를 감지하기 위해 사용된다. 또한 선택적으로 LayerMask를 통해 특 정레이어에 속한 Collider만 충돌 검출을 할 수 있다.


간단한 예제 코드

public class PhysicsRaycastExample : MonoBehaviour
{
    public Transform target;

    private void Update()
    {
        Ray ray = new Ray(transform.position, Vector3.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.transform == target)
            {
                Debug.Log("hit the target!");
            }
        }
    }
}

 


GraphicRaycaster

2D UI요소(canvas내의 요)를 기반으로한 이벤트 처리를 위한 레이캐스터이다. 화면 상의 위치를 클릭하거나 터치할때 레이 캐스팅을 수행하여 어떤 UI요소가 클릭됐는지 확인한다. 


간단한 예제 코드

public class GraphicRaycasterExample : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // GraphicRaycaster는 보통 Canvas객체에 존재
            GraphicRaycaster raycaster = GetComponentInParent<GraphicRaycaster>();

            if (raycaster != null)
            {
                // UI이벤트 데이터 위치를 마우스 클릭 위치로 설정
                PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
                pointerEventData.position = Input.mousePosition;

                // 레이캐스트 결과를 저장할 리스트 생성
                List<RaycastResult> results = new List<RaycastResult>();

                // 레이캐스트 실행
                raycaster.Raycast(pointerEventData, results);

                foreach (RaycastResult result in results)
                {
                    if (result.gameObject.CompareTag("HandSlot"))
                    {
                        Debug.Log("HandSlot 클릭됨!");
                    }
                }
            }
        }
    }
}

 

 

반응형

댓글