无法使用带有OBJ Loader的动画置换着色器(TypeError:mesh is undefined)

时间:2017-07-20 22:23:41

标签: javascript three.js shader objloader

我试图在OBJ对象上放置带有动画位移的基本着色器。着色器在CubeBufferGeometry上工作正常,但我无法使用它来使用OBJLoader。

            // OBJ Loader
            var loader = new THREE.OBJLoader();
            loader.load( "obj/statue.obj", function ( group ) {
                geometry = group.children[ 0 ].geometry;
                geometry.attributes.uv2 = geometry.attributes.uv;
                geometry.center();

                mesh = new THREE.Mesh( geometry, material );
                mesh.scale.multiplyScalar( 15 );
                mesh.position.y = -700;

                mesh.traverse( function( node ) {
                    if( node.material ) {
                    node.material.side = THREE.DoubleSide;
                    }
                }); 
                mesh.traverse(function (child) {
                    if (child instanceof THREE.Mesh) {
                    child.geometry.computeFaceNormals();
                    }
                });

                scene.add( mesh );

                // Vertex Displacement
                vertexDisplacement = new Float32Array(geometry.attributes.position.count);
                    for (var i = 0; i < vertexDisplacement.length; i += 1){
                        vertexDisplacement[i] = Math.sin(i);
                }

                geometry.addAttribute('vertexDisplacement', new THREE.BufferAttribute(vertexDisplacement, 1));


            } );

但是,在我的渲染/动画函数中,我的网格变量是未定义的(我已经将var mesh作为全局变量)。我想这是因为我的网格也在OBJLoader函数中定义了?

我得到:&#39; TypeError:网格未定义&#39;

这是我的渲染/动画功能:

        var delta = 0;
        function animate() {

            requestAnimationFrame( animate );

            mesh.rotation.x += 0.005;
            mesh.rotation.y += 0.01;

            delta +=0.1;

            mesh.material.uniforms.delta.value = 0.5 + Math.sin(delta) * 0.5;

            for (var i = 0; i < vertexDisplacement.length; i += 1) {
                vertexDisplacement[i] = 0.5 + Math.sin(i * delta) * 0.25;
            }
            mesh.geometry.attributes.vertexDisplacement.needsUpdate = true;


            renderer.render( scene, camera );

        }

1 个答案:

答案 0 :(得分:1)

您需要设置网格变量。

尝试访问尚未设置的声明全局变量将导致undefined

&#13;
&#13;
var mesh;
console.log(mesh);
// undefined
mesh = function(){};
console.log(mesh);
// function(){}
&#13;
&#13;
&#13;