Three.js에서 raycasting을 다루는 방법에 대해 설명합니다.
Raycasting은 컴퓨터 그래픽스 기법 중 하나로, 사용자의 눈에는 보이지 않는 가상의 광선을 조사하여 물체의 표면이 어디에 있는지 파악하는 방법입니다.

Three.js는 이를 위해 Raycaster( )라는 이름의 객체를 지원해줍니다.
import { Raycaster } from "three";
const raycaster = new Raycaster();
setFromCamera( )
setFromCamera(THREE.Vector2, THREE.Camera);
setFromCamera( ) 메소드는 지정한 카메라의 위치에서부터 화면에서 보이는 2차원 좌표에 해당하는 위치를 향해 광선을 조사합니다.

아래와 같이 좌표를 마우스의 위치로 지정하면 커서가 클릭하는 방향으로 광선을 조사할 수 있습니다.
import { PerspectiveCamera, Vector2 } from "three";
const camera = new THREE.PerspectiveCamera(...);
const mousePos = new Vector2();
// 마우스를 클릭할 때 실행할 event handler 함수 (실제 event 설정은 생략하였음)
updateMouse = (e: MouseEvent) => {
this.mousePos.x = e.clientX;
this.mousePos.y = e.clientY;
}
raycaster.setFromCamera(mousePos, camera);
intersectObjects( )
intersectObjects(objects: Object3D[]);
intersectObjects( ) 메소드는 주어진 objects 중에서 해당 raycaster 객체가 조사한 광선과 만나는 모든 물체를 찾아 배열로 반환합니다.

// 현재 scene에 포함된 모든 물체를 대상으로
const intersects = this.raycaster.intersectObjects(scene.children)
console.table(intersects
.map(e => ({
name: e.object.name, // 이름. 해당 object의 mesh에 name이라는 값 필요
type: e.object.type, // 종류. mesh, light, camera 등의 값을 가짐
children: e.object.children.length // 한 object가 여러 개의 물체로 이루어져 있을 때
}))
);
이렇게 intersects의 물체들을 모두 출력하면 아래와 같은 결과를 볼 수 있습니다.
table의 경우 세 개가 중복되어 나오는데, 이는 table의 glb 모델링이 세 개의 부분(몸체, 다리 두 개)으로 이루어져있기 때문입니다.

728x90
'Frontend' 카테고리의 다른 글
| [Frontend][Deploy] Netlify로 프론트엔드 배포하기 (0) | 2025.09.11 |
|---|---|
| [Three] 11. Sprite & Mesh - 텍스트 출력하기 (0) | 2025.09.10 |
| [Three] Cannon.js - 물리엔진 적용하기 (1) | 2025.07.10 |
| [Three] 1인칭 화면 회전 만들기 (0) | 2025.07.09 |
| [Three] 윈도우 크기에 따라 반응형으로 만들기 (0) | 2025.07.05 |