let INTERSECTED = null; // 当前高亮对象

    // 鼠标移动事件处理
    function onMouseMove(event) {
        const mouse = new THREE.Vector2();
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(mouse, camera);

        const intersects = raycaster.intersectObjects(scene.children, true);

        // 如果有交点
        if (intersects.length > 0) {
            const target = intersects[0].object;

            // 如果目标对象的名称以 "xiao" 或 "货架" 开头
            if (target.name.startsWith("xiao") || target.name.startsWith("货架")) {
                if (INTERSECTED !== target) {
                    // 如果有之前高亮的对象,恢复其材质
                    if (INTERSECTED) {
                        INTERSECTED.material = INTERSECTED.originalMaterial;
                    }

                    // 设置当前对象为高亮
                    INTERSECTED = target;
                    INTERSECTED.material = new THREE.MeshBasicMaterial({
                        color: 0x00ff00,
                        side: THREE.DoubleSide,
                        wireframe: true, // 可以选择是否使用线框模式
                    });

                    // 将高亮的对象添加到 OutlinePass
                    outlinePass.selectedObjects = [INTERSECTED];
                }
            } else {
                // 如果离开 "xiao" 或 "货架",恢复之前的高亮对象
                if (INTERSECTED) {
                    INTERSECTED.material = INTERSECTED.originalMaterial;
                    INTERSECTED = null;
                    outlinePass.selectedObjects = []; // 清空选中的对象
                }
            }
        } else {
            // 如果没有对象被高亮,恢复之前的对象
            if (INTERSECTED) {
                INTERSECTED.material = INTERSECTED.originalMaterial;
                INTERSECTED = null;
                outlinePass.selectedObjects = []; // 清空选中的对象
            }
        }
    }

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐