Each time the page is refreshed, the objects in Three.js load in varying positions due to the OBJMTLloader

My scene is populated with various objects:

var objectInfo = [
{"objURL":"3D/Barrel/barrel.obj", "mtlURL":"3D/Barrel/barrel.mtl","xPOS":0,"yPOS":-2,"zPOS":-260,"xROT":0,"yROT":0,"zROT":0,"scaleX":0.6,"scaleY":0.6,"scaleZ":0.6},
{"objURL":"3D/Sofa/sofa.obj", "mtlURL":"3D/Sofa/sofa.mtl","xPOS":0,"yPOS":0,"zPOS":0,"xROT":0,"yROT":4,"zROT":0,"scaleX":1,"scaleY":1,"scaleZ":1},
{"objURL":"3D/Lamp/lamp.obj", "mtlURL":"3D/Lamp/lamp.mtl","xPOS":210,"yPOS":-20,"zPOS":10,"xROT":0,"yROT":50,"zROT":0,"scaleX":1,"scaleY":1,"scaleZ":1},
];

for (var i = 0; i < objectInfo.length; i++) {

                      loader=new THREE.OBJMTLLoader();

                      loader.addEventListener('load', function (event) { //event handler for loading .obj and .mtl

                          obj = event.content;

                          var c=count(); //external counter used as i is not defined here

                          obj.position.set(objectInfo[c].xPOS,objectInfo[c].yPOS,objectInfo[c].zPOS);
                          obj.rotation.x=objectInfo[c].xROT;
                          obj.rotation.y=objectInfo[c].yROT; 
                          obj.rotation.z=objectInfo[c].zROT;

                          obj.scale.set(objectInfo[c].scaleX, objectInfo[c].scaleY, objectInfo[c].scaleZ);

                          scene.add(obj);

                          OBJS[c]=obj; 

                      });

                      loader.load(objectInfo[i].objURL,objectInfo[i].mtlURL);

 }

However, after hard refreshing the page in Chrome (F5), the objects appear in different positions. Subsequent refreshes sometimes restore the original positions. This behavior seems random.

What could be causing this issue? I've searched extensively but couldn't find a solution.

UPDATE: Attempted alternative implementation without the counter() function (still facing issues)

  for (var i = 0; i < objectInfo.length; i++) {

                      loader=new THREE.OBJMTLLoader();

                      loader.addEventListener('load', function (event) { //event handler for loading .obj and .mtl

                          obj = event.content;                      

                          var objectInfo2=objectInfo.pop();

                          obj.position.set(objectInfo2.xPOS,objectInfo2.yPOS,objectInfo2.zPOS);
                          obj.rotation.x=objectInfo2.xROT;
                          obj.rotation.y=objectInfo2.yROT; 
                          obj.rotation.z=objectInfo2.zROT;

                          obj.scale.set(objectInfo2.scaleX, objectInfo2.scaleY, objectInfo2.scaleZ);

                          scene.add(obj);

                          // OBJS[c]=obj; 

                      });

                      loader.load(objectInfo[i].objURL,objectInfo[i].mtlURL);

    }

Not only are the positions randomly changing after each refresh, but the scale and other attributes are also affected.

Answer №1

load events occur in a random sequence.

--update--

It seems like the issue is connected to the counter function call, as it assumes that the initial call is for the first object's load event callback in the array.

OBJMTLLoader features

load: function ( url, mtlurl, onLoad, onProgress, onError )

You can assign the proper index to onLoad.

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

AngularJS: default radio button selection

I'm currently working on creating a color configurator using AngularJS with radio buttons. Everything seems to be functioning properly - the data binds correctly, etc., but I'm encountering an issue setting the default color radio button as check ...

Struggling to reset the first item in an HTML select dropdown with Angular - any tips?

I am having an issue with my dropdown in a modal window. When I first open the modal, the dropdown works as expected. However, if I make a selection and then close and reopen the modal, the selected value remains instead of resetting to 'None selected ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

The compiler mistakenly infers an incorrect type while utilizing a default value for a discriminated union type

I am currently working on a simplified component: export type BaseProps = { size?: 'xs' | 'sm' | 'md' | 'lg'; } type ButtonAsButtonProps = Omit<React.ComponentPropsWithoutRef<'button'>, ' ...

Delete the value from the array and refresh the HTML with the updated total amount, or display '$' if there is no total amount

Currently, I have two inputs: debit and credit. On button click events, they update an array called 'debits'. Debit adds positive values while credit adds negative values. The next step is to sum the values in the array and assign it to a variab ...

What is the correct way to properly insert a display none attribute

I'm experiencing some alignment issues with the images in my slideshow. I used this example as a reference to create my slide: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_dots When clicking on the next image, it seems to mo ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

The event failed to initiate

I have an event that is fired when the number value changes in the <input type="number"> below: <input type="number" inputmode="numeric" pattern="[0-9]*" size="4" class="lorem" value="0" step="1"> <input type="button" class="minus" value=" ...

Modifying an image or audio using document.getElementByID("...").src=x+".png" is not effective

I'm having trouble figuring out why it's not working. I've searched online and here, but all I could find were tutorials that didn't include the variable or questions that were too specific. Can someone help me with this? <html> ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

What is the process for inserting additional information into a geoJson file?

In the "gj" object, I need to add new properties from the "dataToAdd" array. The current format of "gj" is as follows: const gj = { "type": "FeatureCollection", "features" : [ { "type": "Feature", "geometry": { ...

Change the background color of a MUI ToggleButton based on a dynamic selection

const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({ "&.Mui-selected, &.Mui-selected:hover": { backgroundColor: selectedColor, } })); const FilterTeam = (props) => { const [view, setView] = ...

Converting a multipart form data string into JSON format

Can you help me figure out how to convert a multipart form data into a JSON object in Node.js? I've been looking for the right module but haven't had any luck so far. Here is an example of my form data: ------WebKitFormBoundaryZfql9GlVvi0vwMml& ...

Trying to assign a value to 'currentStatus' using "this" on an undefined property

In my attempt to display the state of formSubmit in vue js, I've encountered an issue. My lack of familiarity with using "this" has led to errors in the code, particularly when trying to indicate the status using "this.currentStatus". This is the cod ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

Having trouble accessing PDF files on Electron framework

Despite following the advice provided in similar questions' answers, such as including webPreferences: { plugins: true } in the options when creating a BrowserWindow instance, I am still encountering issues. Every attempt to open or view a PDF ...

difficulty in making an https request

My application was developed using OFFICEjs and was functioning properly on LOCALHOST. However, last week it suddenly started throwing an error message - "XHR Error." This issue arose out of nowhere, as I hadn't made any changes to the code over the w ...

How can I eliminate the hover effect from a div element?

I am facing an issue with implementing a zoom effect on hover for my list of products. When I do a long press on a product, it works the first time but not the second time. I suspect this is because the div remains in a hover state. I want to ensure that ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...