What is the best way to bring an array consisting of a class to life through animation in three.js?

I am currently exploring the world of three.js and experimenting with some basic concepts. One thing I have been working on is a class that generates cubes in random locations and populates an array with these cubes using a for loop. My goal is to animate all the cubes so they fall slowly at the same time. However, I've run into an issue where only the last cube added to the array seems to animate. Here is the snippet of my code:

class CubeGenerator {

  constructor() {
      this.cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
      this.cubeMaterial = new THREE.MeshLambertMaterial({
        color: 0x673612
      });
      this.cube = new THREE.Mesh(this.cubeGeometry, this.cubeMaterial);
      this.cube.position.x = Math.random() * (10 - (-10)) + (-10);
      this.cube.position.y = Math.random() * (6 - (-6)) + (-6);
      this.cube.position.z = Math.random() * (6 - (-6)) + (-6);

      scene.add(this.cube);
  }

}

var cubeArray = [];

for(var i = 0; i < 22; i++) {
  var newCube = new CubeGenerator();
  cubeArray.push(newCube);
};

var fallSpeed = 0.01;

var animateCubes = function() {
  requestAnimationFrame(animateCubes);

  cubeArray.forEach(function(cube) {
    cube.cube.position.y -= fallSpeed;
  });
  
  renderer.render(scene, camera);
};

animateCubes();

Any assistance or guidance would be highly appreciated! Thank you.

Answer №1

To ensure all box objects are animated, you must iterate through the array of boxes once more:

for (i = 0; i < randBoxes.length; i++) {
    randBoxes[i].box.position.y = newBox.box.position.y - fall_speed;
}

The issue with your existing code is that it only animates the final newBox object. This is because your initial loop stops at index 22, setting newBox to be the last item in the array.

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

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

Starting Web Server using File (file://) protocol

I'm currently using Quasar to develop a Vue SPA web app/page. For this project, the web app will only run by clicking on the index.html file generated by the Quasar packager. This package will not be distributed online or hosted on any domain. My mai ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

Tips for properly formatting objects in a JSON file with commas using nodejs

I have a client-server setup where I am sending right click coordinates from the client side to the server side and storing them in a JSON file. Each coordinate is stored as a separate object in the JSON file. This is an example of how my JSON file looks: ...

The authentication callback function fails to execute within Auth0 Lock

I'm having an issue with logging into my application using Auth0. I have integrated Auth0 Lock version 10.3.0 through a CDN link in my project and am utilizing it as shown below: let options = { disableSignupAction: true, rememberLastLogin: f ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

Unlock the power of json data traversal to derive cumulative outcomes

Our goal is to populate a table by parsing a JSON object with predefined header items. (excerpt from an answer to a previous query) var stories = {}; for (var i=0; i<QueryResults.Results.length; i++) { var result = QueryResults.Results[i], ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Unable to locate the MoreVert icon in Material UI interface

I am trying to incorporate the MoreVert icon into my application's header to display signout and settings options. I have added the MoreVert icon as shown below, and although the popup appears when clicking on the supposed location of the icon, I am u ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Crafting a dynamic bar chart with recharts for your data visualization

Is it possible to set a custom bar range in the Bar Chart made with recharts? Can we define specific start and end positions for the bars? For instance, if I have two values startPos and endPos, is there a way to create a Bar that starts at startPos and e ...

Enhance Your Website with Bootstrap 5 Slider/Carousel for Product Showcase

I am attempting to create a slider/carousel of products similar to the image shown below using Bootstrap 5: https://i.sstatic.net/7FhPw.png Here is the current code I have: <style> <!-- Temporary --> .carousel-control-next-icon { bac ...

Obtain the URL for the JavaScript code that is currently running

Can anyone help me find the URL of the JavaScript currently being executed? I am aware of using window.location.href for the current page, but that doesn't necessarily provide the path to the script that is running. Any assistance would be greatly ap ...

What is the best way to save data from a jQuery plugin to a database using ASP .NET MVC?

I have a jQuery plugin called "Slider" that displays the current price of an item. I would like to enhance it by allowing users to change prices using the jQuery slider and update them in the database. Here is the model: public class Item { public in ...

Effort to update Div element with Ajax fails to function

Looking for some assistance here. I'm attempting to update a database's entries using Ajax after submitting a form. The entries are displayed within a div. I've tried the following code to refresh only that specific div, but it doesn't ...

Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this: myVar = `Some text with ${eggs} and ${noodles} or ${pies}`; Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"? M ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...