Using ThreeJS to load and display several meshes from a .json 3D file

I downloaded a .json file from an online 3D editor and now I'm facing an issue while trying to load and create 20 instances of it, similar to this example. Sadly, my code seems to be flawed as all 20 instances are behaving as if they are the same object. I'm puzzled as to why they're not appearing as separate objects in their designated x,z coordinates.

var serverObject;
var allBrains = []
var xCenter;
var zCenter;
var spacing = .2;
var newServ;

var objectLoader = new THREE.ObjectLoader();
objectLoader.load("asset_src/model.json", function(obj) {

    //assigning a global name for future access
    serverObject = obj

    //checking the contents of the object
    obj.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                console.log(child)
            }
        })

    //was trying to add transparency this way, but ended up
    //applying it through the online editor instead
    // var cubeMaterial1 = new THREE.MeshBasicMaterial({
    //     color: 0xb7b7b7,
    //     refractionRatio: 0.98
    // });


    //Should I instantiate my mesh like this? If so, how do I ensure it receives the materials from the json file? The json includes 6 children each with a different material
    // serverObject = new THREE.Mesh( obj, cubeMaterial1 );


    //creating 20 instances of the object
    for (var i = 0; i < 20; i++) {
        xCenter = Math.cos(toRadians(i * spacing))
        zCenter = Math.sin(toRadians(i * spacing))
        serverObject.scale.set(.09, .09, .09)

        //offset is appropriate for the scale of my world
        //intended to use xCenter, zCenter but simplified for testing
        serverObject.position.set((i * .1), controls.userHeight - 1, i * .1);
        allBrains.push(serverObject)
        //Tried various ways to add the object to the scene, this was one attempt
        scene.add(allBrains[i]);

    }

    //confirming the existence of 20 meshes
    console.log(allBrains)


});

The output of my last console log appears as shown in the following image: https://i.sstatic.net/zHAVJ.png

Answer №1

Currently, you are working with a single object (serverObject) that you are duplicating and adding multiple times. However, each loop iteration only alters the same object, overwriting previous settings.

To solve this issue, you should clone your mesh using the clone() method. This way, you can make changes to the new object (the copy) independently, and each mesh will remain separate.

Another approach could be to call the objectLoader.load method within the loop to create the object multiple times from the JSON file. However, this may not be the most efficient use of resources.

Answer №2

Shoutout to @jcaor for the neat clone() solution, here is the updated code snippet:

const objLoader = new THREE.ObjectLoader();
objLoader.load("asset_src/model.json", function(object) {

    //assign a global name for future reference
    serverObject = object;

    //explore its contents
    object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                console.log(child);
            }
        });


    for (let i = 0; i < 20; i++) {
        const newObject = serverObject.clone();
        const xCenter = Math.cos(toRadians(i * spacing));
        const zCenter = Math.sin(toRadians(i * spacing));
        newObject.scale.set(.05, .05, .05);
        newObject.position.set(xCenter, controls.userHeight - 1, zCenter);
        allBrains.push(newObject);
        scene.add(allBrains[i]);

    }

    console.log(allBrains);

});

Answer №3

It seems like there may be an issue with pointers in this situation.

When working with JavaScript, variables can be thought of as pointers which is why there is no need to assign types to variables and how functions can be treated as variables in regular computer science.

In this particular scenario, the same pointer is being assigned to each slot in the array.

Here is a simplified version of the problem: obj2.foo was never altered, but due to changing obj.foo, obj2.foo also changed as the var is simply pointing to the same object.

var obj = {
  foo : 1
}
var obj2 = obj;

obj.foo = 2;

console.log(obj2.foo);

My suggestion would be to create a new object and populate it with the information from the master object, in this case "serverObject".

allBrains.push(serverObject)

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

Graph your data with a stunning Fusioncharts area range graph combined with a sleek

My goal is to create a visual representation of an area range graph with a corresponding mid line. You can view the image below for reference: https://i.sstatic.net/8KDbF.png While I have successfully incorporated the low and high values, I am encounterin ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

Take a break and resume iterating in for loops

I have developed a script that loops through items until it finds one with a value greater than the specified parameter, then stops. std::vector<AggregatedQuoteType>::iterator OrderBook::locate_value(PriceType price) { std::vector<AggregatedQu ...

Filtering an array of objects by multiple arrays of keys

My data set consists of an array of objects const Data = [ {first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer'}, {first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'en ...

The .env file is functioning properly for the current keys, but any new ones I include remain undefined

Recently, I took over a Vue application that utilizes axios. Within the dataService.js file, it retrieves URLs from a project's .env file using process.env.FOO_BAR for GET requests. The pre-existing key-value pairs such as VUE_APP_DATA_URL function p ...

Angular JS has a unique feature of a scrollable drop-up menu that allows

https://i.sstatic.net/MOUqO.pngHere is the code snippet for my Dropup component: <div class="dropup"> <button class="btn btn-primary btn-raised dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false> ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

Comparison of WebAPI Response Codes: Understanding the Difference Between 401 and

As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format: { username: myusername, password: mypa ...

Deliver the AJAX response of success to a modal in jQuery

Is there a way to send an ajax success response to a jQuery Modal (jQuery Modal Site) when clicking submit and have the modal automatically display the response? Here is my current ajax post code: $('#rincian').submit(function() { $.ajax({ ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...

The button fails to trigger the AJAX request

I've developed a form that includes a QR code generator. The QR code is generated as an SVG, and below the code is a download button that should trigger an AJAX call to my PHP script when clicked. However, the download button does not seem to initiate ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Implementing server authentication for page requests in a nodeJS and angularJS application

My application relies on passport.js for authentication. One of my main requirements is to prevent access to a specific page (e.g., '/restricted') for users who are not logged in. Currently, anyone can directly access the "localhost:3000/#/restr ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Is there a way to customize a package.json file using postinstall?

I've developed a package on npm that generates an "scss directory structure" and my goal is to include custom scripts in the package.json file located at the project's root. MY-PROJECT ├── node_modules ├── scss └── package.json ...

Customizing the direction of the Stepper component in React.js using Material UI

I'm facing an unusual challenge where I'm attempting to create a stepper component for my application. Everything is working smoothly so far, but I want the stepper to progress from right to left. Here's what I've tried: Installed i18n ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

Encountering issues with resolving dependency tree post updating node, specifically with node-sass dependency causing failure

Following the update to the latest version of Node.js, I encountered error messages when attempting to use npm audit fix --force. It appears that resolving dependency tree issues is proving to be difficult. Despite extensive research and trying various s ...