Improving your scene with multiple cubes using Three.js

I recently came across a raycasting tutorial for threejs on a website, and the author demonstrated adding cubes to the scene in an interesting way:

geom = new THREE.CubeGeometry( 5, 5, 5 );

cubes = new THREE.Object3D();
scene.add( cubes );

for(var i = 0; i < 100; i++ ) {
        var grayness = Math.random() * 0.5 + 0.25,
                mat = new THREE.MeshBasicMaterial(),
                cube = new THREE.Mesh( geom, mat );
        mat.color.setRGB( grayness, grayness, grayness );
        cube.position.set( range * (0.5 - Math.random()), range * (0.5 - Math.random()), range * (0.5 - Math.random()) );
        cube.rotation.set( Math.random(), Math.random(), Math.random() ).multiplyScalar( 2 * Math.PI );
        cube.grayness = grayness; // *** NOTE THIS
        cubes.add( cube );
}

The concept seems clear, but it got me thinking:

Is there an advantage to adding multiple cubes to an Object3D instead of individually adding each cube to the scene?

I'm particularly interested in situations where you're utilizing raycasting and need to animate all the cubes (let's say around 200 cubes or planes) simultaneously.

Answer №1

When you add cubes to an Object3D, they are grouped together and rendered sequentially. To improve performance when rendering multiple cubes, one option is to merge them using THREE.GeometryUtils.merge(). You can learn more about this technique in the following blog post:

If you need to use raycasting with your cubes, you can still access individual faces as demonstrated in this example:

Keep in mind that for a smaller number of cubes (e.g. 200), mesh merging may not be necessary.

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

Showcasing top performers via JavaScript tabs

I have two tabs on my webpage: "Overall Leaderboard" and "Weekly Leaderboard". Each tab displays a leaderboard with different scores. When I click on the "Overall Leaderboard" tab, it shows a leaderboard with specific scores. Now, my question is how can ...

What is the most effective method to package a React application?

I am currently working on embedding a React application within a Web component's Shadow Root or an iFrame in order to create a widget for a Chatbot messenger similar to Intercom widget. The technologies I am using include: React 16.8.6 Typescript 3. ...

JavaScript Object Retrieval: [object Object]

I am currently facing an issue with my node/express app where I keep running into a problem with [object Object]. When rendering a page, I use the following code: app.get('/members', checkAuthentication, function(req, res){ res.render('m ...

Image can be centered, but unable to center div in IE7

When trying to center an element both vertically and horizontally, everything seems to be working correctly except for one issue I'm facing in IE7. I am able to center an img vertically but not a div. What style is being applied by IE to the image tha ...

What is the best way to ensure the parent element adjusts to fit its floated children, without exceeding the width of the window?

I am attempting to center a group of floating elements, but due to them being displayed in masonry style, I cannot set them as inline. It is clear that a container is necessary, but I have been unable to find information on how to achieve this: Please dis ...

Phonegap failing to trigger service method for Ajax requests

My AJAX call looks like this: $.ajax({ type: "POST", url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin", crossDomain: true, data:{ 'EmailID':EmailID, 'Password':Password}, success: ...

The error message "vue-router encountered an unexpected token import" popped

Trying to find a way to store my Vue templates in variables for routing purposes. I've set up an App.vue file with just a simple HTML title (for testing), and a main.js file with an 'import' statement that I haven't used in JavaScript ...

When using JavaScript, the output will only display the result of the final iteration of a for loop that contains

A custom node.js script was created to utilize the jimp library for fetching all image files from a specified directory (input), applying certain manipulations to them, and then saving them in another target directory (also an input) with the format filena ...

ThreeJS - Visualizing mesh as wireframe in object structure

I'm currently working on displaying a wireframe of an object file that has been loaded using OBJLoader(). Below is the snippet of code I am implementing: var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { objec ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

A Guide to Uploading Multiple Rows Using AngularJS

I am facing a challenge with submitting a form that contains multiple table rows. While I have been able to successfully send the table data to the AngularJS controller, I am struggling to figure out how to forward that data to the apiController. The form ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

Interacting with a Facebook tracking pixel as I navigate away from my website

I'm interested in implementing Facebook's pixel tracking to monitor user exits from my website, rather than entrances. I specifically want the tracking code to be triggered upon exit. The standard code provided by Facebook is as follows: <sc ...

The malfunctioning buttons are a result of embedding PHP code within a JavaScript if-query

I am experiencing an issue where my buttons are not functioning properly, preventing me from clicking on them. All variables have been correctly assigned values. Can someone assist me in resolving this? Thank you. ?> <script> ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

Automatically export SSRS reports to PDF using the default interface

In our organization, we utilize numerous custom SSRS reports that we typically run from the built-in interface. This interface allows users to set parameters and then click 'View Report' to generate a default HTML rendering of the report. A small ...

Set a variable within the ref.current.measure callback

I'm facing an issue with measuring the value of my views. To achieve this, I need to retrieve the pageX and pageY values. A snippet from one of my components: useEffect(() => { setTimeout(() => { updateElementPositions(index) }) ...

The transfer of a javascript variable into a php variable using ajax is proving to be ineffective

test.php <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> function gettingVariables(){ $.ajax({ url: 'test-data.php', type: 'GET', ...