Three.js网格点击事件实现报错:Cannot set properties of undefined (setting 'x') 解决方案咨询
Let's walk through fixing your error and getting the mesh click event working correctly:
Why You're Seeing This Error
The immediate issue comes from a typo in your event listener setup combined with a small logic gap in intersection checking. Let's break down the problems and fixes:
1. Wrong Click Event Name
You used mouseclick when attaching the click listener, but the standard DOM event name for mouse clicks is just click. This misnamed event can prevent your handler from firing, and in some scope contexts, lead to the "undefined" error when trying to update mouse.x/mouse.y.
2. Incorrect Intersection Check
The raycaster.intersectObject() method returns an array of intersecting objects (even if empty). Checking if(isIntersected) will always evaluate to true (since empty arrays are truthy in JavaScript), so you need to verify the array has content instead.
3. Optional: Recursive Intersection Check
If your targetMesh has child meshes, pass true as the second argument to intersectObject() to check all child objects recursively.
Corrected Code
Here's the fixed version of your code with all these adjustments:
var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(); var targetMesh; // Ensure this is assigned to your actual mesh object! function onMouseClick(event) { raycaster.setFromCamera(mouse, camera); // Add `true` as second argument if targetMesh has child meshes var intersects = raycaster.intersectObject(targetMesh); // Check if any objects were actually intersected if (intersects.length > 0) { console.log('Mesh clicked!'); // Access the clicked object directly with intersects[0].object } } function onMouseMove(event) { // Calculate normalized device coordinates (-1 to +1) for mouse position mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; } // Fix the event name from 'mouseclick' to 'click' window.addEventListener('click', onMouseClick, false); window.addEventListener('mousemove', onMouseMove, false);
Additional Notes
- Double-check that
targetMeshis properly assigned to your actual Three.js Mesh before these listeners run. IftargetMeshis undefined,intersectObjectwill throw another error. - If you're working in a framework like React or Angular, ensure
cameraandmouseare in the correct scope to be accessible by the event handler functions.
内容的提问来源于stack exchange,提问作者Arjun M Nair

