Unable to apply animated displacement shader when using OBJ Loader due to mesh being undefined error (TypeError: mesh is undefined)

I'm facing an issue with adding a basic shader with animated displacement to an OBJ object. The shader works perfectly on a CubeBufferGeometry, but I can't seem to make it 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));


            } );

In the render/animate function, I encountered an issue where my mesh variable is showing up as undefined (even though I have defined it as a global variable). This might be happening because I am also defining the mesh within the OBJLoader function?

The error message I receive is: 'TypeError: mesh is undefined'

Below is 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 );

        }

Answer №1

Ensure you initialize your mesh variable.

If you attempt to retrieve a globally declared variable that has not been initialized, you will receive the value undefined

let mesh;
console.log(mesh);
// undefined
mesh = function(){};
console.log(mesh);
// function(){}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect jQuery's resizable controls

Check out this jSFiddle. I am attempting to add event handlers for resizing $('oWrapper_'+num). However, the resizing does not occur. This is because $('#oWrapper_'+num) has not been added to the dom at the time of execution, so the se ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Improving iframe functionality in AngularJS

I've been experimenting with AngularJS to dynamically update an iframe whenever a query is triggered. It works like this: a query is made, the embed link is fetched from the database, and then it's used in the iframe alongside the title and video ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Looking for a way to extract a dynamic URL from a website's div element?

Is there a way for my app to load dynamically by extracting and reading the changing URL from a webpage? //webpage <div style="display:none" id="urladdress"> //dynamic url **https://freeuk30.listen2myradio.co ...

"Can Three.js be used with Web Workers? When I try to use importScripts("three.js"), it throws an error

When trying to importScripts("three.js"), an error is thrown: Uncaught ReferenceError: window is not defined: for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) { Removing all references to the window object in thre ...

Show and hide elements using jQuery's toggle functionality

Here is some HTML code that I have: <div id="text-slide"><ul class="menu"> <li><a href="" id="toggle1">Webdesign</a> </li><div class="toggle1" style="display:none;width:45%; position:absolute;left: 16%; top:0;"> ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

How to access a timeout variable from a different function within a JavaScript function

Within my JavaScript code, I have the following scenario: first_function: function() { var timeout = setTimeout(function() { // performing some actions }, 300000); }, In a separate function, once a cr ...

Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page <div class="check-outer"> <label>Place of operation</label> <div class="checkDiv"> <div ng-repeat="place in places"> <div class="checkbox-wrapper"> ...

Synchronizing subscriptions

Currently, I am engaged in a project for my organization and am strictly upholding the Non-Disclosure Agreement (NDA) that I have signed. In adherence to this confidentiality agreement, I present the following code snippet devoid of any sensitive details: ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

displaying and activating element using jQuery

I'm currently working on setting up a notification system for my website but seem to be encountering some issues that I can't quite pinpoint. Essentially, I have a link that triggers a JavaScript function upon being clicked. This function is mean ...

What is the best strategy for managing various contexts in React?

Just diving into React - I've been experimenting with using multiple contexts in my App component. Following the instructions laid out in the official guide on working with multiple contexts. Let me share my current code: App.js import React from " ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Uniform Image Sizes in Bootstrap Carousel (With One Exception)

I am encountering a JavaScript exception related to image size. I am trying to set a fixed size for the images in my carousel, allowing them to auto adjust or resize without concern for distortion or pixelation. I have experimented with max-width and widt ...

Modal shows full JSON information instead of just a single item

This is a sample of my JSON data. I am looking to showcase the content of the clicked element in a modal window. [{ "id": 1, "companyName": "test", "image": "https://mmelektronik.com.pl/w ...