Exploring Geometry, Materials, and Mesh in Three.js on the Web

Currently delving into the world of Three.js with enthusiasm.

Here's What I Have:

In my exploration, I have implemented a for loop that generates a specific object at random positions within the scene.

Visual Reference: https://i.sstatic.net/VXdXR.png Code Snippet:

//Creating Objects
var geometry = new THREE.CylinderBufferGeometry( 0, 10, 30, 4, 1 );
var material = new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } );

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

    var mesh = new THREE.Mesh( geometry, material );
    mesh.position.x = getRandomInt(-500,500);
    mesh.position.y = getRandomInt(10, 100);
    mesh.position.z = getRandomInt(-500,500);
    mesh.updateMatrix();
    mesh.matrixAutoUpdate = false;
    scene_Main.add( mesh );
}

The Query at Hand:

I am now pondering over the idea of creating random objects with varying materials and geometries within a for loop.

Is it feasible to utilize an array to store specific geometries/materials? If so, how can I implement this array and make use of it effectively?

Proposed Array Strategy:

var geometryList = [cube, pyramid, sphere, donut, ...];
var materialList = [ .. possibilities abound here .. ];

for(var i=0; i<100; i++) {
    var mesh = new THREE.Mesh( geometryList[random[n]], materialList[random[n]] );
   ....    
}

Answer №1

The possibilities are endless when it comes to what you can accomplish. Simply fill up your materialList[] in the following manner:

for(var i=0; i<100; i++) {
    color = new THREE.Color( 0xffffff );
    color.setHex( Math.random() * 0xffffff );
    materialList.push(new THREE.MeshBasicMaterial({ color: color }));
}

Make sure that your random[n] function returns a value within the range of [0-99].

Answer №2

var materialList = [];


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

        //Generating unique material for each object
        var color = new THREE.Color( 0xffffff );
        color.setHex( Math.random() * 0xffffff );
        materialList.push(new THREE.MeshBasicMaterial({ color: color }));

        //Setting different sizes for the objects
        var geometrySize_2 = getRandomInt(5,30);

        //Creating 50 Pyramids
        if(i <= 50){

            var geometry1 = new THREE.CylinderBufferGeometry( 0, 10, 30, 4, 1 );

            var mesh = new THREE.Mesh( geometry1, materialList[i] );
            mesh.position.x = getRandomInt(-500,500);
            mesh.position.y = getRandomInt(10, 150);
            mesh.position.z = getRandomInt(-500,500);
            mesh.updateMatrix();
            mesh.matrixAutoUpdate = false;
            scene_Main.add( mesh );
        }
        //Generating 50 Cubes
        else if(i <= 100 && i>= 50){

            var geometry2 = new THREE.BoxGeometry(geometrySize_2,geometrySize_2,geometrySize_2);

            var mesh = new THREE.Mesh( geometry2, materialList[i] );
            mesh.position.x = getRandomInt(-500,500);
            mesh.position.y = getRandomInt(10, 150);
            mesh.position.z = getRandomInt(-500,500);
            mesh.updateMatrix();
            mesh.matrixAutoUpdate = false;
            scene_Main.add( mesh );
        }
        //Creating 100 Spheres
        else if(i <= 150 && i>= 50){

            var geometry3 = new THREE.SphereGeometry( 5, 32, 32 );

            var mesh = new THREE.Mesh( geometry3, materialList[i] );
            mesh.position.x = getRandomInt(-500,500);
            mesh.position.y = getRandomInt(10, 150);
            mesh.position.z = getRandomInt(-500,500);
            mesh.updateMatrix();
            mesh.matrixAutoUpdate = false;
            scene_Main.add( mesh );
        }
    }

https://i.sstatic.net/va47k.png

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

Utilizing typesafe trpc in Node.js to efficiently transfer data between routes

I have successfully implemented an end-to-end typesafe API using the T3 Stack and can access all the data and types in my Next.js app. However, I also have a Node.js backend to populate my database with. My Node.js setup is as follows: app.use( '/t ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

Utilizing Radio buttons to establish default values - a step-by-step guide

I am utilizing a Map to store the current state of my component. This component consists of three groups, each containing radio buttons. To initialize default values, I have created an array: const defaultOptions = [ { label: "Mark", value: & ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

The functionality of Angular services is not available for use in Jasmine tests

As someone who is relatively new to Jasmine Testing and the Angular framework, I find myself in a unique situation. I am currently struggling with referencing my service functions in my Jasmine tests. Here is a snippet of my Angular Service Initialization ...

Unable to start node.js server to upload file in node with express and multer

As a novice in the realm of node.js, I am attempting to create a website using Express, allowing me to upload various content. The server is currently set up locally on my Mac. Below is the code that I have written: server.js var express = require(&apos ...

Is there a table that allows users to input percentages?

Looking for help with a table that has 2 columns: "Activities" and "Average % of Time". Users need to input a % value for each activity in the "Average % of Time" column. There are 7 rows for activities. The goal is to ensure that the sum of the % values f ...

Discover and capture zip codes using javascript

Looking to extract zip codes from strings like "HONOLULU HI 96814-2317 USA" and "HONOLULU HI 96814 USA" using JavaScript. Any suggestions on how to achieve this? ...

Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when at ...

I have a `null` input value. Is there a way to compute this value in relation to a date

When the input is null, what can be done to calculate the value with date? https://i.stack.imgur.com/DmFsJ.png /* // ======================================================== * * * * * How To Calculate Input Value With Date When Input Is Null * * */ // ...

When dragging and dropping in react-flow-renderer, make sure to duplicate the node

I am working on implementing a feature where the original node remains in its position while allowing drag and drop functionality to create a new node at the drop location. The original node should stay at its initial position. When dragging a duplicate n ...

What is the process of passing data from a jQuery-AJAX function to a PHP file and how can these values be retrieved within the PHP

Here is the jQuery-AJAX function I have written: $('#request_form').submit(function(e) { var form = $(this); var stud_id = $('#stud_id').val(); var reg_date = $('#reg_date').val(); var formdata = false; var fileIn ...

Retrieve image data in its original format using AJAX

Currently, I am working on integrating Facebook with a website and I encountered a specific call in the Facebook API that posts a picture to a user's account. One of the parameters required is the raw image data. The image is stored locally on the web ...

Exploring window event handling in Typescript (angular2)

Trying to capture events on the window object from an Angular 2 application written in TypeScript. Additionally, jQuery (imported via typings) is being used. The desired events are generated by an external library included using <script> tags in ind ...

Wait for AJAX to finish before continuing the loop in Javascript

Is it possible to halt a loop until each AJAX request has returned for every iteration? for (var i = 0; i < 5; i++) { var data = "i=" + 1; var ajax = $.ajax({ url: '/ajax.php', type: 'post', dat ...

Is there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

How can I transform a CSS3D rendering plane into a floor in Three.js?

For my project, I need to create a CSS3D rendering plane that acts as a floor with a 3D cube positioned on top of the plane. I have attempted to achieve this by sharing the same scene and camera between the plane and cube in the code below. However, I face ...

Saving dynamic object expressions that are constantly re-evaluated within Angular

Hello Everyone During the development of a prototype e-commerce website, I encountered an unexpected issue today. Specifically, the challenge lies in a method designed to take user input and apply discounts based on two criteria: 1). Validation of a cor ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...