How to load several Collada objects in THREE.js

When loading multiple car models using a loop in THREE.js, I've encountered an issue where sometimes all objects load correctly, but other times not all of them load. For instance, if the loop iterates 3 times, it may only load 2 objects at times, while other times it might load just 1 or all three objects. I've searched extensively for a solution, but haven't been able to find anything useful. Here is the code snippet:

for (var k = 1; k <= myWorld.noOfEnemies(); k++) {

                myWorld.setWorldEnemyCar(k);

                loader2.load('obj/us/us_police_car.dae', function colladaReady(collada) {
                    object3 = collada.scene;

                    object3.scale.x = object3.scale.y = object3.scale.z = 2;
                    object3.updateMatrix();
                    object3.position.x = myWorld.enemyCar.position.x;
                    object3.position.y = myWorld.enemyCar.position.y;
                    object3.position.z = myWorld.enemyCar.position.z;

                    object3.rotation.x = -(Math.PI / 2);

                    object3.rotation.z = (Math.PI / 2);
                    enemyModels.push(object3);                    
                });

            }

Additionally, there's another loader with init() and animate() functions included.

loader2.load('obj/us/us_police_car.dae', function colladaReady(collada) {
                localObject = collada.scene;

                localObject.scale.x = localObject.scale.y = localObject.scale.z = 2;
                localObject.updateMatrix();
                localObject.position.x = 0;
                localObject.position.y = 0;
                localObject.position.z = 0;

                localObject.rotation.x = -(Math.PI / 2);

                localObject.rotation.z = (Math.PI / 2);

                init();

                animate();

            });

The second piece of code works fine, but the issue with the first one remains unresolved. Hopefully, someone can provide some insight into what might be causing this inconsistency.

Answer №1

It appears that there is a notable problem when using the same collada loader instance to load multiple collada files.

Below is a code snippet that has been consistently successful for me (especially in chrome and firefox):

scene = new THREE.Scene();

// set up lighting and other elements

load('/path/someColladaModel.dae');
load("/path/someOtherColladaModel.dae");
load("/path/yetAnotherColladaModel.dae");

function load(daeLocation){
    var manager = new THREE.LoadingManager();
    manager.onProgress = function(item, loaded, total) {
        console.log(item, loaded, total);
    };

    var loader = new THREE.ColladaLoader(manager);
    loader.options.convertUpAxis = true;

    loader.load(daeLocation, function(collada) {
            dae = collada.scene;
            dae.position.set(0, 0, 0); 
            scene.add(dae);
            render();
        }, function(progress) {
            // display progress
    });
}

Take note that I am creating a new loader instance every time I load a model.

Answer №2

If you're encountering issues with an async function being used as if it were synchronous, consider crafting your own async loader to address the problem. It's crucial to ensure that the code doesn't proceed before the async function has completed its task. Remember, this issue is not specific to just three.js, but rather a common challenge in JavaScript development.

customLoader = function(files,callback){
    var counter = 0;
    var loadedObjects = new Array();
    files.forEach(function(file){
        customLoadFunction.load('obj/us/us_police_car.dae', function onColladaReady(collada) {
            loadedObjects[counter] = collada.scene;
            // Additional code for each object goes here
            counter++;
            if (counter == files.length) {
                callback(loadedObjects);
            }
        } 
    });
}

Answer №3

Encountering a similar issue, I discovered that the Collada loader is unable to handle loading multiple files simultaneously. To overcome this obstacle, I consolidated all objects into a single file. After the complete file loads, I am able to extract and utilize individual objects separately. Hopefully, this workaround proves beneficial in your situation as well.

Answer №4

When you're trying to load a identical model repeatedly, rather than calling the loader each time, it's more efficient to clone the mesh instead.

// Suppose 'queen' represents a mesh
var newQueen = queen.clone();
// Don't forget to reposition the new queen for visibility
newQueen.position.set(100,100,100); // You can adjust the coordinates as needed

Answer №5

After thorough investigation, it has been concluded that the issue at hand is a bug in the 3js collada loader. Fortunately, there is a new loader in development that aims to address this problem, though it has not been officially released as of December 2015. For those interested, the new loader can be accessed in the dev tree. Additional information can be found at https://github.com/mrdoob/three.js/issues/7388

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

Utilizing React: passing a Component as a prop and enhancing it with additional properties

My question involves a versatile component setup like the one below const Img = ({ component }) => { const image_ref = useRef() return ( <> {component ref={image_ref} } </> ) } I am exploring ways to use this compo ...

Invoking a prototype method executes the incorrect function repeatedly

I'm currently diving into the world of structures and anonymous functions in JavaScript, and after examining various codes and libraries that implement this technique, I decided to give it a shot. However, when attempting to replicate the method they ...

Adjusting the width of a nested iframe within two div containers

I am trying to dynamically change the width of a structure using JavaScript. Here is the current setup: <div id="HTMLGroupBox742928" class="HTMLGroupBox" style="width:1366px"> <div style="width:800px;"> <iframe id="notReliable_C ...

Make sure to wait for the complete loading of all content in the AJAX response before showing it on

I am currently working on a search function that sends a json request to the server for results every time a character is entered. Although this part is functioning correctly, I am trying to figure out how to add a loading class to .search-load > .conta ...

retrieve JSON object from deferred response of AJAX request

After utilizing Ajax to send an item to a SharePoint list, I aim to incorporate the jsonObject received in response into a list of items. Located in AppController.js $scope.addListItem = function(listItem){ $.when(SharePointJSOMService.addListIte ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

Issue: The GET request to a third-party API using Fetch API encountered a "TypeError: Failed to fetch" error

After conducting extensive research and investing hours into this issue, I am at the point where I need to seek assistance. I am attempting to make a GET call to a third-party Infutor API using the fetch API in my ReactJS Project. Initially, I encountered ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

What is the solution to fixing the Vue 2 error when using Node 12?

Issue with Node 12: It seems that there is an error related to the node-sass library in Node 12. Error message from Node: node-pre-gyp ERR! node -v v12.1.0 node-pre-gyp ERR! node-pre-gyp -v v0.10.3 node-pre-gyp ERR! not ok ...

Node.js assert causes mocha to hang or timeout instead of throwing an error when using assert(false)

I am facing an issue with a mocha test that I have written: describe 'sabah', → beforeEach → @sabahStrategy = _.filter(@strats, { name: 'sabah2' })[0] .strat it 'article list should be populated&ap ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

I'm having trouble getting the code to work properly after the "else" statement using both jQuery and Javascript. My head is

Being a newcomer to javascript and jquery, debugging and viewing log files seem like a challenge compared to php. Any help from experienced individuals would be greatly appreciated. Although my code mostly works fine, I'm having trouble with the if/e ...

Executing multiple MSSQL queries in a Node.js environment

Currently, I am faced with the challenge of running multiple SQL queries. The issue lies in variables going out of scope due to the asynchronous nature of node.js. I am attempting to find a solution similar to the await keyword available in C#. To clarif ...

How can I convert a Java array of arrays into JavaScript?

When working with Java, I need to create a JSON structure similar to this: [ [ timestamp , number ],[ timestamp , number ] ] This structure is necessary for displaying data on Highcharts graphs. I initially used a "LinkedList of LinkedList" format to ...

What is the best way to create a reactive prop within this Vue 3 application?

I've been developing a news application using Vue 3 along with the News API. My current focus is on implementing a search feature. Within my App.vue file, I have: <template> <TopBar @search="doSearch" /> <div class=" ...