Dear all,
I am quite new to three.js and was trying out to raycast a fbx object. The following is the code:
import * as THREE from '../build/three.module.js';
import Stats from './jsm/libs/stats.module.js';
import {
OrbitControls
} from './jsm/controls/OrbitControls.js';
import {
FBXLoader
} from './jsm/loaders/FBXLoader.js';
let container, stats;
let camera, controls, scene, renderer;
let mesh, texture;
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
var objects = [];
init();
animate();
var scene_2;
function init() {
container = document.getElementById('container');
container.innerHTML = "";
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
scene = new THREE.Scene();
scene.background = new THREE.Color(0xbfd1e5);
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 10, 20000);
controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 1000;
controls.maxDistance = 10000;
controls.maxPolarAngle = Math.PI / 2;
scene_2 = new THREE.Scene();
const loader1 = new FBXLoader();
var count = 0;
loader1.load('Medieval house 3.fbx', (fbx) => {
fbx.scale.setScalar(2);
fbx.traverse(function(child) {
if (child instanceof THREE.Mesh) {
console.log("instance");
child.geometry.computeFaceNormals();
}
});
objects.push(fbx);
fbx.position.x = 0;
fbx.position.y = 0;
fbx.scale.set(1, 1, 1);
scene_2.add(fbx);
});
controls.target.y = 500;
camera.position.y = controls.target.y + 2000;
camera.position.x = 2000;
controls.update();
container.addEventListener('mousemove', onMouseMove, false);
stats = new Stats();
container.appendChild(stats.dom);
scene.add(scene_2);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
renderer.render(scene, camera);
}
function onMouseMove(event) {
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene_2.children);
console.log(intersects.length);
}
I can seem to intersect any object. Can someone advise what’s wrong with my code?
Thanks in advance.