What is the best way to duplicate a set of objects in ThreeJS?

I am trying to develop an educational activity for my students wherein a group of objects needs to be replicated and positioned randomly in a scene. I have created a function for this purpose, but unfortunately, it only duplicates the same object instead of adding new ones. I have been attempting to clone additional objects without success. Additionally, I will need to delete these models individually at a later stage. If anyone could offer guidance on how to address these issues, I would greatly appreciate it.

Below is the code snippet:

this.addmodel = function() {
    scene.add(model);
    model.name = "model-" + scene.children.length;
    model.position.x= -20 + Math.round((Math.random() * 40));
    model.position.y= Math.round((Math.random() * 5));
    model.position.z= -17.5 + Math.round((Math.random() * 35));
    this.numOfObjects = scene.children.length;
}

Answer №1

Here is a demonstration of creating and adding multiple cube models to a scene:

function CubeModel(){
    this.mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),new THREE.MeshBasicMaterial({color:"red"}));
  this.addCubeModel = function(){
    var newCubeModel = this.mesh.clone();
    newCubeModel.name = "cube-model-" + scene.children.length;
    newCubeModel.position.x= -20 + Math.round((Math.random() * 40));
    newCubeModel.position.y= Math.round((Math.random() * 5));
    newCubeModel.position.z= -17.5 + Math.round((Math.random() * 35));
    scene.add(newCubeModel);
  }
};

var cubeModelInstance = new CubeModel();
for(var i = 0; i < 10; i++){
    cubeModelInstance.addCubeModel();
}

You can view the example on jsfiddle.

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

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

JavaScript allows for the seamless uploading of content in the background through the Share

My recent project involved implementing a method to upload files in a share extension utilizing the wkwebview and a javascript bridge. This approach handles the upload process, where each part of the file is uploaded successfully before moving on to the ne ...

React Typescript: Error - Attempting to access properties of undefined while attempting to read 'map'

I've been attempting to display user data on a card component fetched from jsonplaceholder using axios. However, I keep encountering an error message: "TypeError: Cannot read properties of undefined (reading 'map')". Despite trying various s ...

The vacant array suddenly fills up with content once it is accessed

I encountered a strange scenario where the console.log indicated that the array was empty. However, upon inspection, I found 2 elements within it. This unexpected behavior prevented the component from rendering as it believed that conversations was empty. ...

Tips on employing useState within useEffect?

Attempting to refactor my component from react.component to hooks has been a bit challenging. I am struggling to properly utilize the state variable offsetTop. It seems like the value is not being set when needed. In my first attempt: const [offsetTop, se ...

Using the React context without explicitly setting the contextType or defining a default context

Is it possible to access the closest context from a provider without having to explicitly define contextType in a component by using this.context? Alternatively, is there a way to establish a default context so that when I use this.context, I automaticall ...

Stop the page from unloading before the ajax request is made

Seeking a solution similar to this question: Reliably complete Ajax request on page unload I am in need of triggering a network request before the page closes without requiring the response value. However, simply placing it within my beforeunload handler ...

Creating interactive labels in a histogram that update based on the user's input

Currently, I have operational code in place that takes input data and generates a histogram based on set thresholds. When the code is executed, the histogram changes dynamically as the threshold slider is adjusted. However, there seems to be an issue wit ...

What methods can be utilized to avoid displaying a Bootstrap popover intermittently within an AngularJS framework?

When using the bootstrap popover in a custom AngularJS directive, I need to display an error message when the button is disabled by setting $scope.buytypeButton= {type:false}. The error message should be displayed in a popover. On the other hand, when $sco ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

What could be causing the lack of functionality for my button click in my JavaScript and HTML setup?

Currently, I am attempting to implement a functionality where I have two buttons at the top of my page. One button displays "French" by default, and when I click on the "English" button, it should replace the text with "French" using show and hide methods. ...

Prevent clicking on a div using Jquery

Imagine I have a simple click event set up for an HTML div element. When the div is clicked, it should trigger a fadeToggle effect. Inside that div, there is another nested div with its own click event. Upon clicking this inner div, it is supposed to do s ...

When attempting to download a PDF file from Flask to the client, the file appears to be

I am encountering an issue with my Flask server that sends a PDF file using the send_file function. When testing this route on Postman, I am able to view and download the PDF successfully. However, when attempting to download it through my React frontend, ...

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: https://i.sstatic.net/oSAi8.jpg Here is a snapshot of my database: https://i.sstatic.net/j5PpZ.jpg Below is my event controller class: <?php namespace App\Http\Contro ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Determining the quantity of items within a div using jQuery

Similar Question: Retrieve the count of elements inside parent div using jQuery Can you determine the total number of elements within a specific div? <div id=count"> <span></span> <span></span> <span></ ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

Is there a way to view the contents of a file uploaded from <input type="file" /> without the need to send it to a server?

Having trouble uploading a JSON file from my local disk to Chrome storage. Whenever I use the <input type="file"> tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...' ImportExport Component: ...

Why does my array become empty once it exits the useEffect scope?

const [allJobs, setAllJobs] = useState([]); useEffect(() => { axios.get('http://localhost:3002/api/jobs') .then(res => setAllJobs(res.data)); allJobs.map((job, i) => { if (job.language.toLowerCas ...