Blog>
Snippets

Interactive 3D Objects

Implement interactivity using raycasting to detect mouse clicks on 3D objects and execute actions such as changing color or displaying information.
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

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

function onMouseClick(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(scene.children);
  if (intersects.length > 0) {
    intersects[0].object.material.color.set(0xff0000); // Change color on click
  }
}

window.addEventListener('click', onMouseClick, false);
Initialize a Three.js scene with a simple cube and a raycaster for mouse picking. Changes color of the clicked object.
function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

animate();
Define an animate function to render the scene continuously.