# Raycasting 실전 활용 예시
월드 카메라 위치에서 마우스가 클릭한 스크린좌표로 Raycasting을 해서
오브젝트들을 탐지하는 경우를 코드로 구현하는 예시를 알아보자
주의할 점은
마우스가 클릭한 스크린 좌표를 월드좌표로 변환해야한다
2D(스크린)에서 3D(월드)로 변환하려면, 그 과정에서 z값이 필요한데
near 값을 입력해주면 딱 시작 지점이 지정된다
이렇게 하면,
카메라에서 마우스 포지션(월드)으로 방향이 나오게 된다
해당 방향은 방향만을 활용하기위해 정규화를 진행하면된다
if(Input.GetMouseButtonDown(0))
{
Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
Vector3 worldDir = worldMousePos -Camera.main.transform.position;
worldDir = worldDir.normalized;
Debug.DrawRay(Camera.main.transform.position, worldDir * 100.0f, Color.red, 1.0f);
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, worldDir, out hit, 100.0f))
{
Debug.Log($"Raycast Camera {hit.collider.gameObject.name}");
}
}
# Camera.main.ScreenPointToRay
스크린좌표를 가져와서 Raycasting을 하는 경우가 많기에
Camera.main.ScreenPointToRay 메서드를 활용하면
쉽게 코드를 작성할 수 있다
if (Input.GetMouseButtonDown(1))
{
// 간소화 버전
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(Camera.main.transform.position, ray.direction * 100.0f, Color.red, 1.0f);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100.0f))
{
Debug.Log($"Raycast Camera {hit.collider.gameObject.name}");
}
}
'게임 엔진 - 유니티 > [루키스] 유니티' 카테고리의 다른 글
| [유니티 Note] 섹션 6-1 (0) | 2025.07.02 |
|---|---|
| [유니티 Note] 섹션 5-6 (0) | 2025.07.02 |
| [유니티 Note] 섹션 5-4 (0) | 2025.07.02 |
| [유니티 Note] 섹션 5-3 (0) | 2025.07.02 |
| [유니티 Note] 섹션 5-2 (0) | 2025.07.02 |