I'm trying to put a basic shader with animated displacement on an OBJ object. The shader works fine on a CubeBufferGeometry, but I can't get it to work with 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));
} );
However, in my render/animate function, my mesh variable is undefined (I already have var mesh as a global variable). I think this is because my mesh is also being defined in the OBJLoader function?
I get: 'TypeError: mesh is undefined'
Here's my render/animate function:
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 );
}
You need to set your mesh variable.
Trying to access a declare global variable that has not been set will result in
undefined