Hi, I am new to Three.js.
I have a question about raycaster.intersect.
The question is why console shows an error saying “Uncaught TypeError: Cannot read properties of undefined (reading ‘visible’)”
I want to use raycaster.intersect to find out the face of the mesh that my mouse is pointing to.
picture below is my bowser
Here is HTML code
<html>
<head>
<title>Three.js Boilerplate</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
<script src="bower_components/numjs/dist/numjs.min.js"></script>
<script src="/assets/OrbitControls.js"></script>
<script src="/examples/local-deformation/assets/OBJLoader.js"></script>
<script src="/examples/local-deformation/assets/MTLLoader.js"></script>
<script src="/examples/local-deformation/scripts.js"></script>
</body>
</html>
Here is Javascript code
const mouse = {
x: undefined,
y: undefined
}
const raycaster = new THREE.Raycaster()
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75,
window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 200;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;
var keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);
var fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);
var backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();
scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);
let mesh
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath('/examples/local-deformation/assets/');
mtlLoader.setPath('/examples/local-deformation/assets/');
mtlLoader.load('head.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('/examples/local-deformation/assets/');
objLoader.load('head.obj', function (object) {
object.traverse(function (node) {
if (node.type === 'Mesh'){ mesh = node};
});
this.mesh = mesh
scene.add(mesh);
});
});
var animate = function () {
requestAnimationFrame( animate );
renderer.render(scene, camera);
raycaster.setFromCamera(mouse, camera)
const intersects = raycaster.intersectObject(mesh)
if (intersects.length> 0) {
console.log(intersects[0])}
};
animate();
addEventListener('mousemove',(event) =>
{
mouse.x = (event.clientX / innerWidth)*2 -1
mouse.y = -(event.clientY / innerHeight)*2 +1
// console.log(mouse)
})