What is the process of creating multiple entities in Three.js?

I am struggling to create a scenario where multiple objects fall from the top in my project.

My attempt at duplicating the code has not been successful.

Below is the code snippet I have been working on:

var renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myCanvas'), antialias: true});
      renderer.setClearColor(0x00ff00);
      renderer.setClearColor( 0xffffff, 0);
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      // CAMERA!
      var camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.1, 3000);
      // SCENE!
      var scene = new THREE.Scene();
      // LIGHTS!
      var light = new THREE.AmbientLight(0xffffff, 0.5)
      scene.add(light);

      var light1 = new THREE.PointLight(0xffffff, 0.5)
      scene.add(light1);
      // TYPE OF 3D SHAPE!
      var geometry = new THREE.BoxGeometry( 100, 100, 20 );

      geometry.applyMatrix( new THREE.Matrix4().makeRotationZ( Math.PI / 4 ) );
      geometry.applyMatrix( new THREE.Matrix4().makeScale( .6, 0.9, .6 ) );       // MATERIALs!
      var material = new THREE.MeshLambertMaterial({color: 0xF3FFE2});
      var mesh = new THREE.Mesh(geometry, material);
      var mesh1 = new THREE.Mesh(geometry, material);
      mesh.position.set(100, 500, -1000);
      mesh1.position.set(200, 500, -1000);

      scene.add(mesh);
      scene.add(mesh1);

      // RENDER LOOP
      color = '0x'+(Math.random()*0xFFFFFF<<0).toString(16);
      requestAnimationFrame(render);
      function render() {
        move = Math.floor((Math.random() * 2) + 1);
        mesh.translateZ(-10)
        mesh.translateY(-10)
        if (move == 1){
        mesh.material.color.setHex(color);
        }
        mesh.rotation.x += 0.005; //MOVE SHAPE
        mesh.rotation.y += 0.1;
        renderer.render(scene, camera);
        requestAnimationFrame(render);
        scene.add(mesh)
      }

I am aiming to have several objects falling from above within the three.js environment, but I can't seem to make it work as intended. Can someone provide guidance on how to achieve this using three.js?

I am relatively new to three.js and would greatly appreciate any assistance! Please note that I am not new to JavaScript.

Your help is highly appreciated! Thank you in advance for your support as I have been stuck on this particular issue for some time.

Answer №1

Check out this updated live code snippet that showcases an improved version of your code. The main concept involves using an array to handle individual objects in your scene:

for ( var i = 0; i < count; i ++ ) {

    var mesh = new THREE.Mesh(geometry, material);

    scene.add(mesh);
    objects.push(mesh);

    // setting initial transformations for each object

    mesh.position.set(- 1000 + Math.random() * 2000, 2000 * Math.random(), -1000 + Math.random() * 2000 );
    mesh.rotation.x += Math.PI * Math.random();
    mesh.rotation.y += Math.PI * Math.random();

}

Next, you can apply the same technique to update these objects within your animation loop.

Take a look at the demo here: https://jsfiddle.net/6bzfLag2/1/

Keep in mind that this method may not be optimal for a large number of objects since it requires one draw call per object. To improve performance, consider utilizing InstancedMesh, a feature recently added to the engine. Explore the example below to see how you can transform individual objects using InstancedMesh and render them with a single draw call.

Example:

Using three.js R110

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

Choose a node from descendants based on its attribute

I am working with an interface that switches between displaying different div elements. Each div element has their children arranged differently, and when the switch happens, I need to access a specific child node of the newly displayed div. However, I fin ...

Updating props in a recursive Vue 3 component proves to be a challenging task

I am facing an issue with two recursive components. The first component acts as a wrapper for the elements, while the second component represents the individual element. Wrapper Component <template> <div class="filter-tree"> &l ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

Adjusting image size according to browser dimensions

I've been struggling to resize a background image on my Square space website dynamically based on the user's browser window size. If the window width drops below a certain point, I want the image to adjust accordingly while maintaining its aspect ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

Tally the quantity of data points within jQuery Datatables

Upon navigating to my jQuery DataTable, I aim to showcase the count of Users pending activation. Typically, I would use fnGetData with (this), but since I am not triggering this on a click event and wish to count all entries in the table, I am unsure of ho ...

Tips for determining the final cost post discount entry

Calculate the final cost with discount Issue with OnChange event function CalculateDiscount() { var quantity = document.getElementById("ticket-count").innerText; var price = document.getElementById("item-price").innerText; var discount = document.getEle ...

How to transform a hyperlink into a clickable element within an absolutely positioned container

I'm currently working on a photo gallery project and using magnific popup to create it. However, I ran into an issue with the hover event on the images that displays an icon when it's hovered over, indicating that it can be clicked to view more. ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

Are there any cross-platform inter-process communication APIs available in both C++ and Javascript?

In the process of developing an app, I am faced with the challenge of passing messages between a C++ application and a Javascript web app. While I have experience writing sockets code in both languages when required, I am now looking for a higher-level me ...

Styles in makeStyles use unique css names

Instead of using the const useStyles = makeStyles to style Popover and OtherStyles separately, I want to nest them within Popover, like so: const useStyles = makeStyles({ Popover: { root: { textAlign: "center", ...

Navigate to a different web page within the body tag without changing the current URL by utilizing a hash symbol

I am working with two HTML files, index.html and about.html. My goal is to display the content of about.html within my index.html without navigating away from it. After observing many websites, I noticed that they often use #about in their URLs to dynamic ...

Show full-screen images on click using Ionic framework

Currently, I am working on developing a mobile app using the Ionic framework. I have created a layout that resembles the one shown in this Card Layout. My question is: How can I make the card image display in full screen when clicked by the user and retur ...

Find items where a certain value matches any of the values in another array and return them

I'm seeking assistance with a specific task. I have an object structured as shown below: SOMEKEY: { "key1": val1, "key2": val2 } Additionally, I have an array that contains string values like this: [stringA, stringB, stringC ...

How to target a class in jQuery that contains two specific strings

There are multiple images in my HTML, each assigned two classes. Here's a snippet of the relevant code: class = "thing other0-a" class = "thing other1-a" class = "thing other2-a" class = "thing other3-a" class = ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

Tips on leveraging state values within the makeStyles function in Material UI React

I'm in the process of building a Webpage and incorporating Material UI for the Components. Here's the code: import { makeStyles, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ container: { ...

The functionality of the calculator, created using HTML and JavaScript, is impeded on certain devices

I developed a web-based app that functions as a simple calculator for calculating freight/shipping prices to Venezuela. The app allows users to select between 1 to 4 packages, and choose different types of freight including air (normal, express) and mariti ...