I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable which is being flagged as undefined. Strangely, I am able to reference my 'scene' and 'camera' variables without any issues from within the loop. Can anyone shed light on why this is happening?

<script>
                //Variables
                var container, stats;
                var camera, scene, renderer;
                var mouseX = 0, mouseY = 0;
                var windowHalfX = window.innerWidth/2;
                var windowHalfY = window.innerHeight/2;
                init();
                animate();

                //Initialisation
                function init(){
                    container = document.createElement('div');
                    document.body.appendChild(container);
                    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
                    camera.position.z = 2;

                    //scene
                    scene = new THREE.Scene();

                    //Light
                    var ambient = new THREE.AmbientLight(0x101030);
                    scene.add(ambient);
                    var directionalLight = new THREE.DirectionalLight(0xffeedd);
                    directionalLight.position.set(1,0,1);
                    scene.add(directionalLight);

                    //Texture
                    var manager = new THREE.LoadingManager();
                    manager.onProgress = function ( item, loaded, total ) {
                        console.log("Loading: " + item, loaded, total );
                    };

                    var texture = new THREE.Texture();
                    var loader = new THREE.ImageLoader(manager);
                    loader.load('skin.jpg', function(image){
                        texture.image = image;
                        texture.needsUpdate = true;
                    });

                    //Model
                    var loader = new THREE.OBJLoader(manager);
                    loader.load('test.obj', function(object){
                        object.traverse(function(child){
                                if(child instanceof THREE.Mesh){
                                    //child.material.map = texture;
                                }
                        }); 

                        //Resize the object...
                        object.position.y = .10;
                        object.position.x += .10;

                        //Scale
                        object.scale.x = 0.5;
                        object.scale.z = 0.5;
                        object.scale.y = 0.5;

                        console.log(object);

                        scene.add(object);
                    });

                    //Renderer
                    renderer = new THREE.WebGLRenderer();
                    renderer.setSize(window.innerWidth, window.innerHeight);
                    renderer.setClearColorHex( 0xffffff, 1 );
                    container.appendChild(renderer.domElement);

                    //Event Listeners
                    //document.addEventListener('mousemove', onDocumentMouseMove, false);
                    window.addEventListener('resize', onWindowResize, false);
                }


                //Declaring Event Listeners
                function onWindowResize(){
                    windowHalfX = window.innerWidth/2;
                    windowHalfY = window.innerHeight/2;
                    camera.aspect = window.innerWidth/window.innerHeight;
                    camera.updateProjectionMatrix();
                    renderer.setSize(window.innerWidth, window.innerHeight);
                }

                function onDocumentMouseMove(event){
                    mouseX = (event.clientX - windowHalfX)/2;
                    mouseY = (event.clientY - windowHalfY)/2;
                }
                //Declaring Event Listeners

                //Animation
                function animate(){
                    requestAnimationFrame(animate);
                    render();
                }

                function render(){
                    camera.position.x += (mouseX - camera.position.x) * .05;
                    camera.position.y += (mouseY - camera.position.y) * .05;
                    camera.lookAt(scene.position);
                    renderer.render(scene, camera);
                }
            </script>

The problem lies in not being able to console.log(object) or anything at this point.

function render(){
                        camera.position.x += (mouseX - camera.position.x) * .05;
                        camera.position.y += (mouseY - camera.position.y) * .05;
                        camera.lookAt(scene.position);

                        renderer.render(scene, camera);
                    }

Answer №1

If you're new to JavaScript, understanding variable scope can be tricky. When you have:

loader.load('test.obj', function(object){

This means that the variable object is only accessible within the function where it's declared.

One solution is to create a global variable at the beginning of your script:

<script>
            //Variables
            var loadedObject = null;

Then, assign the object to this variable inside the function:

loader.load('test.obj', function(object){
    loadedObject = object;

You can now use loadedObject in your render() function. Just remember to check if it's defined before using it, as it may still be loading:

function render() {
    if ( loadedObject ) {
         // do something with it
    }

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

Designing a query feature to explore a Sequel Database utilizing a 'RETRIEVE' approach

In my index.erb, I've created a search bar with the following code: <nav> <div class="nav-wrapper"> <form> <div class="input-field"> <input id="search" type="search" placeholder="Search..." required> ...

Check the input in the text box against the selected options to validate it

Currently, I am working on an add contacts page where I am facing the challenge of displaying an error message or highlighting input as invalid if a user tries to enter a contact name that already exists. It seems like one solution could be populating a s ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

Is there a built-in event in Jquery UI tabs for when the tabs are collapsed?

Which event in jquery ui can I utilize to detect when a panel collapse has finished on the browser? I require this information to perform calculations based on the screen layout after the collapse has occurred. If I use the select or show event callbacks, ...

Altering the guardians of a three-dimensional model without compromising its original placement

I am currently utilizing the three.js library for handling 3D models, primarily in .glb format. My goal is to import a 3D model that consists of groups and meshes. I aim to move meshes between existing groups within a model without altering the visual rep ...

Fetching json data from the request in Node.js

I'm currently working on a project that involves using the request module to send an HTTP GET request to a specific URL in order to receive a JSON response. However, I've run into an issue where my function is not properly returning the body of ...

How to address critical vulnerabilities found in a Vue.js project that relies on the 'vue-svg-loader' dependency, specifically impacting 'nth-check', 'css-select', and 'svgo'?

Attempting to launch a Vue version 2 project, encountered the following error: # npm audit report nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available ...

Enhancing functionality by updating a function to accept an object as input instead of individual key:value pairs in TypeScript

I'm currently tackling a challenge with a friend's icon library component, specifically with their set() function. The issue arises when I want to invoke two functions, namely setRandomColor() and setColor(), both intended to update two values w ...

Adding and removing form fields in a table dynamically using AngularJS

I need to dynamically add multiple form fields when a button is pressed, and I want all the fields to be displayed in a table format (each field should have its own space in a <td>field</td> structure). Currently, I am facing an issue where if ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

PHP: the images uploaded are not located within the designated folder

Having trouble uploading multiple images to a folder and saving them in the database? The images are not moving to the folder, even though the code works on localhost. Here is the code snippet: var abc = 0; // Declaring and defining global incremen ...

Tips for interpreting information from a JSON array that has been stringified, looping through the data, and utilizing it effectively

I'm currently exploring Node JS packages and I need some guidance. Here is an example of the JSON data that I have: [{ "name":"SpiderMan", "description":"Superhero", "head_id":"29", "domain_name":"spiderman.com" }] I am trying to figure out how to ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

Retrieve data from the controller of the selected element on the subsequent page using AngularJS

Currently, I am in the process of developing an ecommerce platform using angularjs. In my controller, I have a list of various products structured like this: $scope.products = [ {imgLink: 'product1.jpg', name: 'Wingtip Cognac Oxford&apo ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

Issues with ng-click functionality not activating on <li> HTML elements

I've been attempting to add ng-click functionality to my list, but it's not working as expected. I've tried adding the ng-repeat directive and also without it on li elements. Here is the snippet of HTML code: <ul class="nav nav-tabs"&g ...