Create unique color patterns for 10 randomly selected objects using Three.js

I am currently working on a function to randomly change the color of 10 objects called material. However, I am struggling with how to integrate this function into either an array or vectors. I attempted to use arrays like meshArrayX in the color(selector) function, but encountered issues where the object positions were undefined and no objects were colored at all.

var mesh, scene,
    MeshBasicMaterial = new THREE.MeshBasicMaterial({
      color: 0x000000,
      opacity: 0.3,
      transparent: true
    });
var BoxGeometry = new THREE.BoxGeometry(16, 16, 16);

function random(){
        var random = [0, 16, 32];
        var randomValue = random[Math.floor(random.length * Math.random())];
        console.log(randomValue);
}

function color(selector){
  for(var v=0; v<10; v++){
    selector.position.x = random();
    selector.position.y = random();
    selector.position.z = random();
    selector.material.color.setHex( 0x0000ff);
  }
}

var meshArrayX = [];
for (var x=0; x<3; x++) {
  var meshArrayY = [meshArrayX.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial))];
  for(var y=0; y<3; y++){
    var meshArrayZ = [meshArrayY.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial))];
    for(var z=0; z<3; z++){
      meshArrayZ.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial));
      mesh.position.x = 16*x;
      mesh.position.y = 16*y;
      mesh.position.z = 16*z;
      scene.add(mesh);


      console.log(meshArrayX.length, meshArrayY.length-1, meshArrayZ.length-1, mesh.position);
    }
  }
}
color(mesh);

Answer №1

I'm not completely clear on the question you're asking, but I'll do my best to assist you.

It seems like you're trying to create an array of 27 boxes (3x3x3), but I'm a bit confused by your code. You're using a global variable called mesh, but only adding it to the scene within the z loop.

Here's how I would approach this:

var BoxGeometry = new THREE.BoxGeometry(5, 5, 5);
var meshArray = [];
for (var x=0; x<3; x++) {
  for(var y=0; y<3; y++){
    for(var z=0; z<3; z++){
      var mesh = new THREE.Mesh(BoxGeometry, material.clone());
      meshArray.push(mesh);
      mesh.position.x = 16*x;
      mesh.position.y = 16*y;
      mesh.position.z = 16*z;
      scene.add(mesh);  
      console.log(meshArray.length, mesh.position);
    }
  }
}

It's important to note that "material.clone()" is necessary to create a new instance of material for each mesh.

For defining colors, you could use a function like this:

function color(selector){
  for(var v=0; v<10; v++){
   var pos= Math.floor((Math.random() * selector.length));

    selector[pos].material.color.setHex( 0x0000ff );
  }
}

You can then call this function with:

color(meshArray);

By calling the color function, it randomly selects 10 boxes from the array and applies a different color to them.

I hope this information proves helpful

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

Hmm, JavaScript is throwing a JSON parse error related to single quotes. But where exactly is

When using an upload php script with AS3 and now with JavaScript, I encountered a test feature that should return this if everything is okay: {"erro":"OK","msg":"","descr":"op:ini,urlArq:\/Library\/WebServer\/Documents\/www\/sintr ...

Is it possible to utilize PropTypes to indicate that a prop is of type Promise?

Using PropTypes can aid in debugging by providing warnings when expectations are not met. Additionally, they serve as a helpful tool to clearly express how a component should be used. If I have a component that requires a prop with a value that could pote ...

The HTTPS Ajax Request Google Chrome Extension

I am developing a Google Chrome extension and need to send an AJAX request to a HTTPS *REST API*. When I tested this request on an HTTP page but attempted to make the request to a HTTPS page, it did not work due to cross-domain posting restrictions. I sear ...

What could be causing the errors when trying to populate fields while using Sequelize?

My current project involves working with Sequelize on an Apollo-Server backend. While most of the process has been smooth sailing, I've hit a roadblock when it comes to refactoring my code. Specifically, I am encountering difficulties populating certa ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

What's the best way to retrieve the content of a textarea field?

After revisiting my previous inquiry, I find that this issue pertains more to JavaScript than Google App Engine. Within my form: <form name="choice_form" id="choice_form" method="post" action="/g/choicehandler" onsubmit="writeToStorage()"> <te ...

Issue with Jquery function not executing on second attempt

/** Creates a table of iTunes data in HTML format **/ var appendValues = function(songArray) { songArray.each(function() { var title = $(this).find("im\\:name").eq(0).text(); var songImage = $(this).find("im\\:image").eq(0).text(); var ...

Using Javascript to determine the frequency of a JSON array with ESLINT version 6

I'm struggling to create an algorithm that counts the occurrences while adhering to ESLint's strict standards in JavaScript. Here is my input table: [ { "id": 2, "name": "Health", "color": "0190fe" }, { "id": 3, "name": ...

Different methods for identifying errors when utilizing $.post() or $.get()

I'm curious about how to effectively manage errors when using either $.post or $.get methods. $.post(URL,data,function(data,status,xhr),dataType) $.get(URL,data,function(data,status,xhr),dataType) Is there a way to handle errors in these methods tha ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Quickly optimize your project using url-loader in Vite

Looking to process GLTF and HDR files in my Vue/Three.js project. Unfortunately, this functionality doesn't come standard with Vite. However, when using Webpack, I can easily configure the Webpack settings like so: module.exports = { module: { r ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...

Using the window.setInterval() method to add jQuery/AJAX scripts to elements at regular intervals of 60 seconds

I'm having trouble with automatically updating a div. I have a script that refreshes the page content (similar to Facebook) every minute. The issue is that this div is newly added to the page and contains some ajax/jQuery elements for effects. functi ...

Tips for effectively utilizing the mock-ajax library in conjunction with Jasmine

Currently, I have a function that requests JSON data and then modifies the DOM in the success function. To simplify my Jasmine tests, I am attempting to utilize the mock-ajax library instead of exposing private functions for mocking. Despite setting reque ...

Using gulp to compile a Vue component without the need for `require` statements

I'm currently exploring the process of constructing a component with Gulp. Right now, I am working on a Vue component that has the following structure: my-component.vue <template> <div class="foo"> </div> </template> < ...

How to target individual DOM elements using their id within an ng-repeat loop in AngularJS

In a unique scenario I find myself in, there is a need to modify the CSS within a controller. While not typically recommended, it is necessary for this specific situation as outlined below. Within an ng-repeat loop, I have a title and description housed i ...

Rotate the image as you swipe left or right with Angular's ng-swipe-left and ng-swipe-right features

I am currently utilizing angular's ng-swipe-left and ng-swipe-right to detect swipe events on touch devices. My goal is to rotate an image based on the speed and direction of the swipe while it is still in progress. However, I am facing a challenge as ...

Using JavaScript to access session data from the view in CodeIgniter

Working with CodeIgniter 2.0 Framework In my current project, I am facing a challenge where I need to access session data set up in the model from the view. Below is the code snippet that I have been testing within my view: <script type='text/ja ...

The URL is not appearing in the browser's address bar

Below is the code I am using for ajax requests: // JavaScript Document function createTeam() { var name=document.getElementById("name").value; if(name==null || name==""){ var div3 = document.getElementById("errorMessage"); var text ...