What is the best way to retrieve an object that needs to be defined within a function?

I am struggling to get my imported obj model to move using three.js. There seems to be a formatting issue where the obj object needs to be declared inside a function, making it inaccessible outside of that function even if I pre-declare a variable to point to the object. How can I access the object in this scenario?

import * as THREE from 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7938f958282a7d7c9d6d5d1c9d6">[email protected]</a>/build/three.module.js';

import { OrbitControls } from 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f18599839494b1c1dfc0c3c7dfc0">[email protected]</a>/examples/jsm/controls/OrbitControls.js';

// More import statements

    const renderer = new THREE.WebGLRenderer();
    // Additional code for setting up renderer and scene

    let house = undefined;

    // MTL and OBJ loader setup
    const mtlLoader = new MTLLoader();
    mtlLoader.load(
        '../source/MaryStanfordLifeboatHouse02.mtl',
        (materials) => {
            materials.preload();

            const objLoader = new OBJLoader()
            objLoader.setMaterials(materials)
            objLoader.load(
                '../source/MaryStanfordLifeboatHouse02.obj',
                function(object){
                    scene.add(object);
                    house = object;
                    house.rotation.x = 1/2 * Math.PI;
                    house.rotation.y =  Math.PI;
                },
                function(xhr){
                    console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
                },
                function(error){
                    console.log("Object error")
                }
            )
        },
        (xhr) => {
            console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
        },
        (error) => {
            console.log("Material Error")
        }
    )

    // Texture loader setup
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load(
        '../img/doge.jpg',
        function ( texture ) {
            scene.background = texture;
        },
        undefined,
        function ( err ) {
            console.error( 'An error occurred.' );
        }
    );

    // Animation and rendering functions
    function animate(){
        renderer.render(scene,camera);
        sLightHelper.update();
    }

    renderer.setAnimationLoop(animate);

    window.addEventListener('resize',function(){
        camera.aspect = window.innerWidth/this.window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth,window.innerHeight);
    });

Answer №1

// house.position.x += 1;

The code above is encountering an error due to premature access to the variable. It's important to remember that the model is loaded asynchronously, so you need to be mindful of this when trying to access it. An easy fix to prevent runtime errors is:

if ( house !== undefined ) house.position.x += 1;

Alternatively, you could choose to initiate animation only after all assets have finished loading.

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

Retrieve the URL with a GET request and remove a specific object

Currently, I am working on developing a CRUD (Create, Read, Update, Delete) App using Express and LowDB. So far, I have successfully implemented the create and read functions, but I am facing issues with the delete function. This is an example of what th ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

Here are the steps to calculate the duration between two dates in the specified format:

let d1 = new Date("05/20/2022 09:28:15") let d2 = new Date("05/24/2022 12:38:25") Can someone help me calculate the difference between these two dates? ...

Repeating a PHP variable within an angular scope

When working with PHP, any element prefixed with a $ is recognized as a variable. However, I encountered an issue when attempting to output an Angular statement using the following code: if(...) { echo "return $scope.id;"; } An error message indicated th ...

Authentication through Proxy and requests from nodes

I am attempting to make a get request to a website via https using the request module. However, I am behind a proxy that requires authentication. Despite my attempts to add the authentication, the connection to the site fails. I have experimented with add ...

Is it possible for Vue js to display an image from the /dist/ directory even if it is not present?

Currently, I am in the process of learning Vue.js + webpack and have started a project by following these steps: f:www\> npm install -g vue-cli f:www\> vue init webpack-simple my-project f:www\> cd my-project f:www\> npm in ...

What is the mechanism by which the useState hook in React determines the calling context?

After transitioning from using class components to functional components in React, I delved into the documentation with keen interest to understand how the useState hook functions. Upon consulting the FAQ page, it was explained that each component has an ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Is it advisable to combine ng-change with ng-blur in AngularJS?

Seeking clarification on the correct usage of AngularJS's ng-change and ng-blur from an expert. Specifically, when updating a form value. In the code snippet below, I have a dropdown where I would like to trigger overrideBusinessDec() when the user ...

The showdown between JSON and a hefty JavaScript array

Currently, I am developing a jQuery autocomplete feature that will need to handle between 10 to 20k records. The dataset is static, and I have the option to either retrieve it from a JSON file or embed it directly into the page using a single line of code ...

Identifying the action of maximizing a window using JavaScript

Similar Question: How to Detect if a Browser Window is Maximized or Minimized using Javascript Can we use javascript to identify when the browser window is maximized? ...

Unable to utilize routes in Express.JS when integrated with nginx

After setting up nginx in front of Express.JS, everything seemed to be running smoothly. However, I encountered an issue when trying to access website.com/users, which resulted in a 404 Not Found error. It appears that accessing website.com works fine, but ...

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

The button's onclick function is failing to save the record in the database

Hello everyone, I am facing an issue with the ONCLICK button functionality. I have written code to save a form to the database. In the image, there are 2 buttons: Save button (type="submit") Save and New button (type="button") The Save button is ...

Incorporate Three.JS into Meteor for enhanced functionality

Currently, I am experimenting with integrating Meteor and Three.JS. The specific meteorite package for Three.JS that I am utilizing can be found here: https://github.com/nozpheratu/three-meteor. Despite being able to perform basic functions in Three.JS, I ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Understanding how to handle the responseText in Laravel when it is returned as a JSON string

Here is the Laravel code snippet: public function validateRegisterToBidForm(Request $request){ $validationArray = $this->getValidationArray(); $this->validate($request, $validationArray); return response()->json(); }//validateRegis ...

Issue with the placement of the bottom background when viewed in responsive mode

I'm encountering an issue with the placement of a bottom white image when I switch to responsive mode. It seems to not align at the bottom of the parent ul element as expected. If possible, could you provide assistance in addressing this issue? The i ...