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) {
    // ๋งค ํ”„๋ ˆ์ž„ ์—…๋ฐ์ดํŠธ ์ž‘์—… (ํ•„์š” ์‹œ)
}