You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js网格点击事件实现报错:Cannot set properties of undefined (setting 'x') 解决方案咨询

Fixing "Cannot set properties of undefined (setting 'x')" in Three.js Mesh Click Handling

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 targetMesh is properly assigned to your actual Three.js Mesh before these listeners run. If targetMesh is undefined, intersectObject will throw another error.
  • If you're working in a framework like React or Angular, ensure camera and mouse are in the correct scope to be accessible by the event handler functions.

内容的提问来源于stack exchange,提问作者Arjun M Nair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:52:46