Cursor & Raycasting
Raycasting shoots a ray from the camera through the cursor into the 3D scene — how Three.js determines what the mouse hovers over or clicks on.
Raycaster Setup
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (e) => {
mouse.x = (e.clientX / innerWidth) * 2 - 1;
mouse.y = -(e.clientY / innerHeight) * 2 + 1;
});
Hit Testing in the Loop
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(meshes);
if (hits.length > 0) {
hits[0].object.material.emissive.set(0x333333);
} else {
meshes.forEach(m => m.material.emissive.set(0x000000));
}
Mouse Parallax Depth
gsap.to(scene.rotation, {
y: mouse.x * 0.1,
x: -mouse.y * 0.05,
duration: 1,
ease: 'power2.out',
});
What to Experiment With
- On click, fire a GSAP scale animation on the hit object
- Use raycasting with a
PlaneGeometryfloor for world-space mouse position - Move a 3D cursor sphere to follow the nearest surface hit
레이캐스팅은 카메라에서 커서를 통해 3D 씬으로 레이를 쏩니다 — Three.js가 마우스가 무엇을 호버하거나 클릭하는지 판별하는 방법입니다.
레이캐스터 설정
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (e) => {
mouse.x = (e.clientX / innerWidth) * 2 - 1;
mouse.y = -(e.clientY / innerHeight) * 2 + 1;
});
루프에서 히트 테스트
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(meshes);
if (hits.length > 0) {
hits[0].object.material.emissive.set(0x333333);
} else {
meshes.forEach(m => m.material.emissive.set(0x000000));
}
마우스 패럴랙스 깊이
gsap.to(scene.rotation, {
y: mouse.x * 0.1,
x: -mouse.y * 0.05,
duration: 1,
ease: 'power2.out',
});
실험해보기
- 클릭 시 히트된 오브젝트에 GSAP scale 애니메이션 추가
PlaneGeometry바닥으로 레이캐스팅해 월드 공간 마우스 위치 구하기- 가장 가까운 표면 히트를 따라 3D 커서 구체 이동