I have a 3D file, which contains houses, I want to click on each house to display custom information. As far as I know it’s possible to use Raycaster but it currently doesn’t fetch each house exactly like I want it to.
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
renderer.domElement.addEventListener('click', onClick, false);
// Load 3D
const loader = new GLTFLoader();
loader.setDRACOLoader(dracoLoader);
loader.load('assets/files/MockUp.gltf', function (gltf) {
console.log(gltf);
model = gltf.scene;
model.position.set(1, 1, 0);
model.scale.set(0.01, 0.01, 0.01);
scene.add(model);
// mixer = new THREE.AnimationMixer(model);
// mixer.clipAction(gltf.animations[0]).play();
init();
}, undefined, function (e) {
console.error(e);
});
function init() {
requestAnimationFrame(init);
controls.update();
renderer.render(scene, camera);
}
let INTERSECTED;
function onClick() {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
if (intersects.length > 0) {
console.log('Intersection:', intersects[0]);
if (INTERSECTED != intersects[0].object) {
if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
INTERSECTED = intersects[0].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex(0xff0000);
}
} else {
if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
INTERSECTED = null;
}
}