SnippetTipsRaycaster

Raycasting

The Raycaster is a tool used to check whether a ray emitted from a specific point in a 3D environment intersects with objects. It is primarily used to enable interactions based on user input.


ray-result

Steps

Initialize the Raycaster and Mouse Vector:

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

Normalize Mouse Coordinates:

When the mouse is clicked, normalize the mouse coordinates based on the size of the browser window.

function OnPointerDown(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1; 
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; 
}

Set Up the Raycaster

Set the raycaster based on the normalized mouse coordinates and the camera.

raycaster.setFromCamera(mouse, camera);
 

Handle Intersection Results

When an intersection is found, perform operations on the corresponding object. For example, this code changes the object’s color.

const intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
    intersects.forEach(intersect => {
        intersect.object.material.color.set(Math.random() * 0xffffff); // 랜덀 μƒ‰μƒμœΌλ‘œ λ³€κ²½
    });
}

Complete Code

const avatar = REDBRICK.AvatarManager.createDefaultAvatar();
const camera = WORLD.getObject("MainCamera");
avatar.setFollowingCamera(camera);
avatar.setDefaultController();
 
const objects = []; // μ—¬λŸ¬ 개의 객체λ₯Ό μ €μž₯ν•  λ°°μ—΄
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
 
// 객체 생성 및 배열에 μΆ”κ°€
for (let i = 0; i < 10; i++) {
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const cube = new THREE.Mesh(geometry, material);
    cube.position.set(Math.random() * 10 - 5, Math.random() * 10 - 5, Math.random() * 10 - 5);
    WORLD.add(cube);
    objects.push(cube);
}
 
// 마우슀 클릭 이벀트 ν•Έλ“€λŸ¬
function OnPointerDown(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
 
    raycaster.setFromCamera(mouse, camera);
    const intersects = raycaster.intersectObjects(objects); // μ—¬λŸ¬ 객체와 ꡐ차 검사
 
    if (intersects.length > 0) {
        intersects.forEach(intersect => {
            intersect.object.material.color.set(Math.random() * 0xffffff); // 랜덀 μƒ‰μƒμœΌλ‘œ λ³€κ²½
        });
    }
}
 
function Start() {
    // μ΄ˆκΈ°ν™” μž‘μ—… (ν•„μš” μ‹œ)
}
 
function Update(dt) {
    // 맀 ν”„λ ˆμž„ μ—…λ°μ΄νŠΈ μž‘μ—… (ν•„μš” μ‹œ)
}