在 Three.js 中,贴花不适用于实例化网格体

问题描述 投票:0回答:1

涉足贴花有一段时间了。虽然它对于普通网格体的作用就像一个魅力,但它不适用于实例化网格体。我怎样才能让它与实例化网格一起工作?需要修改源代码吗?

const decals = [];

document.addEventListener('pointerdown', (e) => {
    const windowX = e.clientX;
    const windowY = e.clientY;
    const ndcX = ((windowX / window.innerWidth) * 2) - 1;
    const ndcY = -((windowY / window.innerHeight) * 2) + 1;
    
    raycaster.setFromCamera(new THREE.Vector2(ndcX, ndcY), camera);
    const intersections = raycaster.intersectObjects(scene.children);
    console.log(intersections);
    if (intersections.length) {
        // get the first object you intersect with
        const intersectedInstance = intersections[0];
        const { face: { normal }, object, point, instanceId } = intersectedInstance;
        
        // get the instance transformation matrix 
        const instanceMatrix = new THREE.Matrix4();
        instancedMesh.getMatrixAt(instanceId, instanceMatrix);

        const worldInstanceMatrix = new THREE.Matrix4();
        worldInstanceMatrix.multiplyMatrices(instanceMatrix, instancedMesh.matrixWorld);
        ///

        const dummy = new THREE.Object3D();
        const n = normal.clone();
        n.transformDirection( worldInstanceMatrix );
        n.add(point.clone());

        dummy.position.copy( point.clone() );
        dummy.lookAt( n );

        const  size = new THREE.Vector3( 1, 1, 1.0);
        
        const decalGeometry = new DecalGeometry( object, point, dummy.rotation, size ); 
        const decalMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, depthWrite: false, polygonOffset: true, polygonOffsetFactor: - 4, depthTest: false} );
                        
        const decal = new THREE.Mesh( decalGeometry, decalMaterial );
        decals.push(decal);
        decal.renderOrder = decals.length;

        scene.add(decal);
        

    }


});

任何帮助将不胜感激!

这里有一个jsfiddle链接供您参考: https://jsfiddle.net/sk3tjzpg/1/。参考之前的问题:贴花几何体未出现在 Three.js 中的实例网格上

javascript three.js 3d
1个回答
0
投票

🤖 似乎您正在尝试在 Three.js 中使用贴花并面临实例化网格的问题。

在 Three.js 中使用实例化网格时,直接实现贴花确实有点棘手,因为贴花通常应用于单个几何体,而不是整个实例化几何体。

解决此限制的一种潜在方法是,每当在实例上检测到命中时,为贴花应用程序创建一个单独的非实例网格。您本质上需要根据实例的变换矩阵定位和定向贴花网格,并相应地应用贴花。

在当前的实现中,当您检测到与实例化网格体的相交时,您可以根据命中位置和法线创建独立的贴花网格体,而不是尝试将贴花直接应用到实例化网格体。然后可以将该贴花网格作为单独的实体添加到场景中。

请记住根据实例网格的命中点和法线更新贴花网格的位置、旋转和比例,以使其正确显示。

请随意尝试此方法,如果您遇到任何具体问题或需要进一步帮助,请告诉我!祝您的 Three.js 项目一切顺利! 👍🏼🎨

© www.soinside.com 2019 - 2024. All rights reserved.