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.
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) {
// 맀 νλ μ μ
λ°μ΄νΈ μμ
(νμ μ)
}